diff --git a/CHANGELOG.md b/CHANGELOG.md deleted file mode 100644 index 1248267..0000000 --- a/CHANGELOG.md +++ /dev/null @@ -1,204 +0,0 @@ -# Changelog - -All notable changes to the Electronic Document Management System (EDMS) project will be documented in this file. - -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - -## [2.0.0] - 2024-01-15 - -### 🎨 **Major Design System Overhaul** - -#### Added -- **New Standardized Components** - - `RsInput.vue`: Comprehensive input component with validation, sizing, and error states - - `RsSelect.vue`: Dropdown/select component with single/multiple selection support - - `RsTextarea.vue`: Textarea component with configurable resize and validation - - Design system documentation page at `/dms/design-system` - - Interactive component playground with live examples - - Component usage guidelines and best practices - -- **Enhanced Design System Features** - - Consistent prop structure across all Rs components (`modelValue`, `label`, `error`, `disabled`, `size`) - - Universal dark mode support via CSS variables - - Accessibility features with proper ARIA attributes - - Standardized sizing system (sm, md, lg) - - Error state handling with validation messaging - - Real-time validation and form state management - -#### Changed -- **Settings Architecture Simplification** - - Reduced from 10 to 5 core settings categories: - - 🔐 User & Access Management - - 📁 Document & Folder Settings - - 📝 Metadata & Tagging - - 📤 Upload & Storage Settings - - 📅 System Settings - - Removed categories: Search & Indexing, Integration Settings, Audit & Compliance, Workflow & Automation, UI & Branding - - Streamlined settings structure for better usability and maintenance - -- **Component Standardization** - - `DMSAccessRequestDialog.vue`: Replaced manual button styling with `RsButton` components - - Settings page: Updated key form inputs to use `RsInput`, `RsSelect`, `RsTextarea` - - Standardized modal footer patterns across all dialogs - - Consistent form validation and error handling - -- **Enhanced Component Registration** - - Added new Rs components to global component registry - - Updated export system in `pages/devtool/code-playground/index.js` - - Improved component discovery and usage - -#### Improved -- **Form Consistency** - - Unified form styling across all components - - Consistent error handling and validation states - - Standardized label and placeholder patterns - - Improved accessibility with proper form associations - -- **User Experience** - - Better visual consistency across the application - - Improved dark mode support and theme switching - - Enhanced form validation with real-time feedback - - Standardized interaction patterns - -### 📖 **Documentation Updates** - -#### Added -- **Comprehensive Design System Documentation** - - Interactive component playground at `/dms/design-system` - - Component API documentation with props and examples - - Usage guidelines and best practices - - Color system and typography scale documentation - - Accessibility standards and compliance information - -- **Enhanced Technical Guide** - - Complete design system section with component specifications - - Form component usage examples and API reference - - Color system documentation with CSS variable reference - - Typography and spacing scale definitions - - Integration patterns and best practices - -#### Updated -- **User Guide Enhancements** - - Added comprehensive Settings Administration section - - Documented simplified 5-category settings structure - - Detailed explanation of each settings category - - Best practices for settings management - - Troubleshooting guide for settings issues - -- **README Overhaul** - - Complete project overview with features and technology stack - - Design system highlights and component examples - - Comprehensive setup and installation instructions - - Development guidelines and contribution standards - - Security features and support information - -### 🔧 **Technical Improvements** - -#### Enhanced -- **CSS Architecture** - - Improved CSS variable system for theming - - Standardized component styling patterns - - Better organization of style files - - Enhanced dark mode support - -- **Form Handling** - - Consistent v-model patterns across components - - Improved validation and error state management - - Better form component composition - - Enhanced accessibility features - -- **State Management** - - Improved settings state management - - Better validation and error handling - - Enhanced form state synchronization - -### 🚨 **Breaking Changes** -- Settings API structure changed due to category reduction -- Some component prop names standardized (may affect custom implementations) -- Manual form styling replaced with Rs components (update required for custom forms) - -### 💻 **Development Experience** - -#### Improved -- **Component Development** - - Standardized component patterns for easier development - - Better TypeScript support for component props - - Improved component documentation and examples - - Enhanced development guidelines - -- **Design Consistency** - - Clear design system guidelines - - Standardized component usage patterns - - Better visual consistency across the application - - Improved maintainability - -#### Added -- **Development Tools** - - Interactive design system playground - - Component examples and usage guidelines - - Development best practices documentation - - Contributing guidelines for design system - -### 📱 **User Interface** - -#### Enhanced -- **Visual Consistency** - - Unified button styles and interactions - - Consistent form field appearance - - Standardized modal and dialog layouts - - Improved color scheme and theming - -- **Accessibility** - - Better keyboard navigation support - - Improved screen reader compatibility - - Consistent focus states and indicators - - WCAG 2.1 compliance improvements - -- **Responsive Design** - - Better mobile form interactions - - Improved tablet layout handling - - Consistent breakpoint management - - Enhanced touch interaction support - -### 🔄 **Migration Guide** - -#### For Developers -1. **Update Form Components**: Replace manual form styling with Rs components -2. **Settings Integration**: Update any settings-related code for new 5-category structure -3. **Component Usage**: Follow new Rs component patterns for consistency -4. **Styling Updates**: Remove manual Tailwind classes in favor of Rs components - -#### For Users -1. **Settings Location**: Settings now organized in 5 streamlined categories -2. **Interface Changes**: Improved form interactions and validation -3. **New Features**: Access to design system documentation and examples - -### 🎯 **Future Roadmap** -- Additional Rs components (date picker, multi-select, autocomplete) -- Enhanced animation system for micro-interactions -- Expanded accessibility features and testing -- Advanced form validation and error handling -- Component testing and documentation automation - ---- - -## [1.0.0] - 2023-12-01 - -### Initial Release -- Electronic Document Management System with hierarchical organization -- User authentication and role-based access control -- Document upload, preview, and management capabilities -- Basic settings and configuration system -- Initial UI components and styling - ---- - -**Legend:** -- 🎨 Design System -- 📖 Documentation -- 🔧 Technical -- 🚨 Breaking Changes -- 💻 Development Experience -- 📱 User Interface -- 🔄 Migration -- 🎯 Roadmap \ No newline at end of file diff --git a/README.md b/README.md index 611f1c7..7f452fe 100644 --- a/README.md +++ b/README.md @@ -1,256 +1,45 @@ -# Electronic Document Management System (EDMS) +# Nuxt 3 Minimal Starter -A modern, web-based document management system built with Nuxt.js 3 and Vue.js 3, featuring a comprehensive design system and hierarchical document organization. +Look at the [nuxt 3 documentation](https://v3.nuxtjs.org) to learn more. -## 🚀 Features +## Setup -### Core Functionality -- **Hierarchical Organization**: Cabinet → Drawer → Folder → Subfolder structure -- **Advanced Document Management**: Upload, version control, metadata management -- **Role-Based Access Control**: Granular permissions with access request workflows -- **Multi-format Document Viewer**: Built-in viewer for PDF, images, Office documents -- **Advanced Search**: Full-text search with metadata and tag filtering -- **Responsive Design**: Works seamlessly across desktop, tablet, and mobile +Make sure to install the dependencies: -### Design System -- **Standardized Components**: Complete "Rs" component library (RsButton, RsInput, RsSelect, etc.) -- **Consistent Styling**: Unified design patterns with dark/light mode support -- **Accessibility**: WCAG-compliant components with proper ARIA attributes -- **Interactive Documentation**: Design system playground at `/dms/design-system` - -### Administration -- **Streamlined Settings**: 5 core configuration categories - - 🔐 User & Access Management - - 📁 Document & Folder Settings - - 📝 Metadata & Tagging - - 📤 Upload & Storage Settings - - 📅 System Settings -- **Import/Export**: Configuration backup and transfer capabilities -- **Real-time Validation**: Form validation with dependency checking - -## 🛠️ Technology Stack - -### Frontend -- **Nuxt.js 3**: Universal Vue.js framework with SSR/SPA support -- **Vue.js 3**: Progressive framework with Composition API -- **TailwindCSS**: Utility-first CSS framework with custom component system -- **Pinia**: Modern state management with persistence -- **FormKit**: Advanced form handling with custom theming - -### Backend -- **Prisma ORM**: Type-safe database client with migrations -- **MySQL/PostgreSQL**: Relational database with comprehensive schema -- **File System Integration**: Secure file storage and management -- **JWT Authentication**: Token-based authentication with RBAC - -### Development Tools -- **TypeScript**: Type safety and enhanced development experience -- **ESLint**: Code linting with Vue.js specific rules -- **Vite**: Lightning-fast build tool and HMR - -## 📋 Setup - -### Requirements -- Node.js 18+ and npm/yarn/pnpm -- MySQL 8+ or PostgreSQL 13+ -- Modern web browser with JavaScript enabled - -### Installation - -1. **Clone Repository** ```bash -git clone https://github.com/your-repo/edms.git -cd edms -``` - -2. **Install Dependencies** -```bash -# Using npm -npm install - -# Using yarn +# yarn yarn install -# Using pnpm -pnpm install +# npm +npm install + +# pnpm +pnpm install --shamefully-hoist ``` -3. **Environment Configuration** -Create `.env` file: -```env -# Database -DATABASE_URL="mysql://username:password@localhost:3306/edms_db" +## Development Server -# Authentication -JWT_SECRET="your-jwt-secret-key-min-256-bits" -SESSION_SECRET="your-session-secret-key" +Start the development server on http://localhost:3000 -# File Storage -UPLOAD_PATH="/var/uploads/edms" -MAX_FILE_SIZE="104857600" # 100MB -ALLOWED_FILE_TYPES="pdf,doc,docx,xls,xlsx,ppt,pptx,txt,jpg,jpeg,png" - -# Application -NUXT_SECRET_KEY="your-nuxt-app-secret" -BASE_URL="http://localhost:3000" -``` - -4. **Database Setup** -```bash -# Generate Prisma client -npx prisma generate - -# Run migrations -npx prisma db push - -# Seed data (optional) -npx prisma db seed -``` - -5. **Development Server** ```bash npm run dev ``` -Access the application at `http://localhost:3000` +## Production -## 🎨 Design System - -### Component Library -The EDMS uses a standardized component library with the "Rs" prefix: - -#### Form Components -- **RsInput**: Standardized input fields with validation -- **RsSelect**: Dropdown/select with options support -- **RsTextarea**: Multi-line text input with resize controls -- **RsButton**: Buttons with multiple variants and sizes - -#### UI Components -- **RsCard**: Container component with header/body/footer -- **RsModal**: Modal dialogs with standardized structure -- **RsTable**: Data tables with sorting and filtering -- **RsDropdown**: Dropdown menus and navigation - -### Usage Examples - -```vue - - - - - - Save Changes - - - - - - - - -``` - -### Design Principles -- **🎯 Consistency**: Unified patterns across all components -- **🔧 Modularity**: Reusable and composable components -- **🌙 Dark Mode**: Universal theme support -- **📱 Responsive**: Mobile-first approach -- **♿ Accessibility**: WCAG-compliant with keyboard navigation - -## 📖 Documentation - -### Available Guides -- **[Technical Guide](docs/Technical_Guide.md)**: Comprehensive technical documentation -- **[User Guide](docs/User_Guide.md)**: End-user instructions and features -- **[Site Settings](docs/SITE_SETTINGS.md)**: Configuration and customization guide - -### Interactive Documentation -- **Design System**: Visit `/dms/design-system` for component examples -- **API Documentation**: Available in development mode -- **Component Playground**: Test components with live examples - -## 🔧 Development - -### Project Structure -``` -edms/ -├── components/ # Vue components -│ ├── dms/ # DMS-specific components -│ │ ├── dialogs/ # Modal dialogs -│ │ ├── explorer/ # Document browser -│ │ ├── search/ # Search functionality -│ │ └── viewers/ # Document preview -│ └── Rs*.vue # Design system components -├── pages/ # File-based routing -│ ├── dms/ # DMS pages -│ └── devtool/ # Admin tools -├── stores/ # Pinia state management -├── server/ # API routes and middleware -├── prisma/ # Database schema and migrations -├── assets/ # Stylesheets and assets -└── docs/ # Documentation -``` - -### Building for Production +Build the application for production: ```bash -# Build application npm run build - -# Preview production build -npm run preview - -# Generate static site (if applicable) -npm run generate ``` -## 🔐 Security Features +Locally preview production build: -- **Role-Based Access Control**: Granular permission system -- **Document-level Security**: Individual document access controls -- **Access Request Workflow**: Approval system for restricted documents -- **Audit Trail**: Comprehensive activity logging -- **File Type Validation**: Security through file type restrictions -- **Session Management**: Secure token-based authentication +```bash +npm run preview +``` -## 🤝 Contributing +Checkout the [deployment documentation](https://v3.nuxtjs.org/guide/deploy/presets) for more information. +# corradAF -1. Fork the repository -2. Create a feature branch (`git checkout -b feature/amazing-feature`) -3. Follow the design system guidelines -4. Use standardized components (Rs library) -5. Add tests for new functionality -6. Commit changes (`git commit -m 'Add amazing feature'`) -7. Push to branch (`git push origin feature/amazing-feature`) -8. Open a Pull Request - -### Development Guidelines -- Use Rs components instead of custom styling -- Follow semantic variant naming (primary, secondary, danger) -- Test in both light and dark modes -- Maintain accessibility standards -- Document new features in user/technical guides - -## 📄 License - -This project is part of the corradAF base project. See the license file for details. - -## 🆘 Support - -- **Technical Issues**: Check the [Technical Guide](docs/Technical_Guide.md) -- **User Questions**: Refer to the [User Guide](docs/User_Guide.md) -- **Component Usage**: Visit `/dms/design-system` for examples -- **Bug Reports**: Create an issue with detailed reproduction steps - ---- - -Built with ❤️ using Nuxt.js 3, Vue.js 3, and modern web technologies. +This is the base project for corradAF. diff --git a/components/RsInput.vue b/components/RsInput.vue deleted file mode 100644 index f6e0b98..0000000 --- a/components/RsInput.vue +++ /dev/null @@ -1,115 +0,0 @@ - - - - - \ No newline at end of file diff --git a/components/RsSelect.vue b/components/RsSelect.vue deleted file mode 100644 index 045b3e1..0000000 --- a/components/RsSelect.vue +++ /dev/null @@ -1,143 +0,0 @@ - - - - - \ No newline at end of file diff --git a/components/RsTextarea.vue b/components/RsTextarea.vue deleted file mode 100644 index 04ae223..0000000 --- a/components/RsTextarea.vue +++ /dev/null @@ -1,105 +0,0 @@ - - - - - \ No newline at end of file diff --git a/components/dms/dialogs/DMSAccessApprovalDialog.vue b/components/dms/dialogs/DMSAccessApprovalDialog.vue new file mode 100644 index 0000000..dc6e581 --- /dev/null +++ b/components/dms/dialogs/DMSAccessApprovalDialog.vue @@ -0,0 +1,296 @@ + + + \ No newline at end of file diff --git a/components/dms/dialogs/DMSAccessRequestDialog.vue b/components/dms/dialogs/DMSAccessRequestDialog.vue index 69435e2..67c29c1 100644 --- a/components/dms/dialogs/DMSAccessRequestDialog.vue +++ b/components/dms/dialogs/DMSAccessRequestDialog.vue @@ -1,5 +1,5 @@ diff --git a/components/dms/workflows/DMSAccessRequestTracker.vue b/components/dms/workflows/DMSAccessRequestTracker.vue new file mode 100644 index 0000000..471513d --- /dev/null +++ b/components/dms/workflows/DMSAccessRequestTracker.vue @@ -0,0 +1,435 @@ + + + + + \ No newline at end of file diff --git a/components/dms/workflows/DMSApprovalQueue.vue b/components/dms/workflows/DMSApprovalQueue.vue new file mode 100644 index 0000000..7bb13c2 --- /dev/null +++ b/components/dms/workflows/DMSApprovalQueue.vue @@ -0,0 +1,539 @@ + + + + + \ No newline at end of file diff --git a/composables/useDmsSettings.js b/composables/useDmsSettings.js new file mode 100644 index 0000000..41ba2cb --- /dev/null +++ b/composables/useDmsSettings.js @@ -0,0 +1,346 @@ +export const useDmsSettings = () => { + // Global DMS settings state + const dmsSettings = useState('dmsSettings', () => ({ + // User & Access Management + access: { + userRoles: ['Admin', 'Editor', 'Viewer', 'Uploader'], + rbacEnabled: true, + userGroups: ['HR Department', 'Finance', 'IT', 'Legal'], + permissions: { + view: true, + edit: true, + delete: false, + download: true, + share: true + }, + authentication: { + ssoEnabled: false, + mfaRequired: false, + ldapIntegration: false, + sessionTimeout: 8 + } + }, + + // Document & Folder Settings + documents: { + folderHierarchy: { + maxDepth: 5, + defaultStructure: ['Department', 'Project', 'Category', 'Year'], + folderTemplates: ['Standard', 'Project-based', 'Department-based'] + }, + namingConventions: { + autoGenerate: true, + mandatoryFields: ['title', 'department', 'date'], + pattern: '{department}_{title}_{date}' + }, + retention: { + enabled: true, + defaultDays: 2555, // 7 years + archiveBeforeDelete: true + }, + versionControl: { + enabled: true, + maxVersions: 10, + autoVersioning: true + } + }, + + // Metadata & Tagging + metadata: { + customFields: [ + { name: 'Department', type: 'dropdown', required: true }, + { name: 'Priority', type: 'select', required: false }, + { name: 'Project Code', type: 'text', required: true }, + { name: 'Review Date', type: 'date', required: false } + ], + tagging: { + predefinedTags: ['urgent', 'confidential', 'public', 'draft', 'final'], + userGeneratedTags: true, + tagSuggestions: true + }, + classification: { + autoClassification: true, + rules: ['confidential-keywords', 'department-based', 'file-type'] + } + }, + + // Workflow & Automation + workflow: { + approvalFlows: { + enabled: true, + defaultFlow: 'department-head-approval', + customFlows: ['legal-review', 'finance-approval', 'director-sign-off'] + }, + notifications: { + emailNotifications: true, + inAppNotifications: true, + uploadAlerts: true, + deadlineReminders: true + }, + automation: { + triggers: ['document-uploaded', 'approval-completed', 'deadline-reached'], + actions: ['move-to-folder', 'send-notification', 'create-task'] + } + }, + + // Upload & Storage Settings + upload: { + fileTypes: { + allowed: ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'jpg', 'png'], + blocked: ['exe', 'bat', 'cmd'] + }, + fileSizeLimit: 100, // MB + quotas: { + perUser: 5000, // MB + perGroup: 50000, // MB + perProject: 100000 // MB + }, + storage: { + type: 'local', // local, s3, azure, google + path: '/var/uploads/edms', + backupEnabled: true, + compressionEnabled: false + } + }, + + // System Settings + system: { + timezone: 'Asia/Kuala_Lumpur', + backupSchedule: 'daily', + logLevel: 'info', + maintenanceMode: false, + autoUpdates: false, + systemMonitoring: true, + performanceMetrics: true + } + })); + + // Loading state + const loading = useState('dmsSettingsLoading', () => false); + const saving = useState('dmsSettingsSaving', () => false); + + // Load DMS settings from API + const loadDmsSettings = async () => { + loading.value = true; + try { + const response = await $fetch("/api/dms/settings", { + method: "GET", + }); + + if (response && response.data) { + dmsSettings.value = { ...dmsSettings.value, ...response.data }; + console.log('[useDmsSettings] Settings loaded successfully:', response.data); + } + } catch (error) { + console.error("Error loading DMS settings:", error); + throw error; + } finally { + loading.value = false; + } + }; + + // Update DMS settings + const updateDmsSettings = async (newSettings) => { + console.log("[useDmsSettings] updateDmsSettings called with:", JSON.parse(JSON.stringify(newSettings))); + saving.value = true; + try { + const response = await $fetch("/api/dms/settings", { + method: "POST", + body: newSettings, + }); + console.log("[useDmsSettings] API response received:", JSON.parse(JSON.stringify(response))); + + if (response && response.statusCode === 200) { + // Reload settings after successful update + await loadDmsSettings(); + console.log("[useDmsSettings] Returning success from updateDmsSettings."); + return { success: true, data: response.data }; + } + + let errorMessage = "Update operation failed: No data returned from server."; + if (response && typeof response === 'object' && response !== null && 'message' in response) { + errorMessage = response.message; + } + + console.log("[useDmsSettings] Returning failure from updateDmsSettings:", errorMessage); + return { success: false, error: { message: errorMessage, details: response } }; + } catch (error) { + console.error("[useDmsSettings] Error in updateDmsSettings catch block:", error); + let detailedMessage = "An unexpected error occurred during update."; + if (error.data && error.data.message) { + detailedMessage = error.data.message; + } else if (error.message) { + detailedMessage = error.message; + } + console.log("[useDmsSettings] Returning failure (catch block) from updateDmsSettings:", detailedMessage); + return { success: false, error: { message: detailedMessage, details: error } }; + } finally { + saving.value = false; + } + }; + + // Reset settings to defaults + const resetToDefaults = async () => { + const defaultSettings = { + access: { + userRoles: ['Admin', 'Editor', 'Viewer', 'Uploader'], + rbacEnabled: true, + userGroups: ['HR Department', 'Finance', 'IT', 'Legal'], + permissions: { + view: true, + edit: true, + delete: false, + download: true, + share: true + }, + authentication: { + ssoEnabled: false, + mfaRequired: false, + ldapIntegration: false, + sessionTimeout: 8 + } + }, + documents: { + folderHierarchy: { + maxDepth: 5, + defaultStructure: ['Department', 'Project', 'Category', 'Year'], + folderTemplates: ['Standard', 'Project-based', 'Department-based'] + }, + namingConventions: { + autoGenerate: true, + mandatoryFields: ['title', 'department', 'date'], + pattern: '{department}_{title}_{date}' + }, + retention: { + enabled: true, + defaultDays: 2555, + archiveBeforeDelete: true + }, + versionControl: { + enabled: true, + maxVersions: 10, + autoVersioning: true + } + }, + metadata: { + customFields: [ + { name: 'Department', type: 'dropdown', required: true }, + { name: 'Priority', type: 'select', required: false }, + { name: 'Project Code', type: 'text', required: true }, + { name: 'Review Date', type: 'date', required: false } + ], + tagging: { + predefinedTags: ['urgent', 'confidential', 'public', 'draft', 'final'], + userGeneratedTags: true, + tagSuggestions: true + }, + classification: { + autoClassification: true, + rules: ['confidential-keywords', 'department-based', 'file-type'] + } + }, + workflow: { + approvalFlows: { + enabled: true, + defaultFlow: 'department-head-approval', + customFlows: ['legal-review', 'finance-approval', 'director-sign-off'] + }, + notifications: { + emailNotifications: true, + inAppNotifications: true, + uploadAlerts: true, + deadlineReminders: true + }, + automation: { + triggers: ['document-uploaded', 'approval-completed', 'deadline-reached'], + actions: ['move-to-folder', 'send-notification', 'create-task'] + } + }, + upload: { + fileTypes: { + allowed: ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'jpg', 'png'], + blocked: ['exe', 'bat', 'cmd'] + }, + fileSizeLimit: 100, + quotas: { + perUser: 5000, + perGroup: 50000, + perProject: 100000 + }, + storage: { + type: 'local', + path: '/var/uploads/edms', + backupEnabled: true, + compressionEnabled: false + } + }, + system: { + timezone: 'Asia/Kuala_Lumpur', + backupSchedule: 'daily', + logLevel: 'info', + maintenanceMode: false, + autoUpdates: false, + systemMonitoring: true, + performanceMetrics: true + } + }; + + return await updateDmsSettings(defaultSettings); + }; + + // Export settings to JSON + const exportSettings = () => { + const dataStr = JSON.stringify(dmsSettings.value, null, 2); + const dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(dataStr); + + const exportFileDefaultName = 'dms-settings.json'; + + const linkElement = document.createElement('a'); + linkElement.setAttribute('href', dataUri); + linkElement.setAttribute('download', exportFileDefaultName); + linkElement.click(); + }; + + // Import settings from JSON + const importSettings = (jsonData) => { + try { + const importedSettings = JSON.parse(jsonData); + dmsSettings.value = { ...dmsSettings.value, ...importedSettings }; + return { success: true }; + } catch (error) { + console.error('Error importing settings:', error); + return { success: false, error: 'Invalid JSON format' }; + } + }; + + // Get setting by category and key + const getSetting = (category, key) => { + if (dmsSettings.value[category]) { + return dmsSettings.value[category][key]; + } + return null; + }; + + // Update specific setting + const updateSetting = async (category, key, value) => { + if (dmsSettings.value[category]) { + dmsSettings.value[category][key] = value; + // Save to backend + return await updateDmsSettings(dmsSettings.value); + } + return { success: false, error: 'Category not found' }; + }; + + return { + dmsSettings: readonly(dmsSettings), + loading: readonly(loading), + saving: readonly(saving), + loadDmsSettings, + updateDmsSettings, + resetToDefaults, + exportSettings, + importSettings, + getSetting, + updateSetting + }; +}; \ No newline at end of file diff --git a/docs/DMS_SETTINGS.md b/docs/DMS_SETTINGS.md new file mode 100644 index 0000000..bf94b42 --- /dev/null +++ b/docs/DMS_SETTINGS.md @@ -0,0 +1,1019 @@ +# DMS Settings System - Comprehensive Guide + +## Overview +The Document Management System (DMS) Settings provides administrators with complete control over all aspects of the document management system. This comprehensive configuration system allows customization of user access, document handling, metadata management, workflows, upload settings, and system behavior through an intuitive web interface. + +## Table of Contents +1. [Access & Navigation](#access--navigation) +2. [Settings Categories](#settings-categories) +3. [User & Access Management](#user--access-management) +4. [Document & Folder Settings](#document--folder-settings) +5. [Metadata & Tagging](#metadata--tagging) +6. [Workflow & Automation](#workflow--automation) +7. [Upload & Storage Settings](#upload--storage-settings) +8. [System Settings](#system-settings) +9. [Settings Management](#settings-management) +10. [Import/Export Functionality](#importexport-functionality) +11. [API Integration](#api-integration) +12. [Configuration Best Practices](#configuration-best-practices) +13. [Troubleshooting](#troubleshooting) + +## Access & Navigation + +### Prerequisites +- **Administrative Privileges**: Only users with admin roles can access DMS settings +- **Browser Requirements**: Modern browser with JavaScript enabled +- **Network Access**: Stable connection to the EDMS server + +### Accessing DMS Settings +1. **Navigate to Settings**: + - Click **DMS** in the main navigation menu + - Select **Settings** from the dropdown or navigate to `/dms/settings` + - Wait for the settings interface to load + +2. **Settings Interface Layout**: + - **Left Navigation Panel**: Six main categories with color-coded icons + - **Main Content Area**: Forms and configuration options for selected category + - **Action Buttons**: Save, Export, Import, and Reset options in the header + +3. **Permission Verification**: + - System automatically verifies admin permissions + - Unauthorized users are redirected to main DMS interface + - Error messages displayed for access issues + +## Settings Categories + +The DMS settings are organized into six main categories, each with a distinct icon and color scheme: + +### 1. User & Access Management 🔐 +- **Icon**: Lock symbol (security theme) +- **Color**: Blue scheme +- **Purpose**: Configure user roles, permissions, and authentication +- **Key Features**: RBAC, SSO, MFA, session management + +### 2. Document & Folder Settings 📁 +- **Icon**: Folder symbol +- **Color**: Green scheme +- **Purpose**: Configure document organization and folder structure +- **Key Features**: Naming conventions, version control, retention policies + +### 3. Metadata & Tagging 📝 +- **Icon**: Document with pen +- **Color**: Yellow scheme +- **Purpose**: Configure custom fields, tags, and classification +- **Key Features**: Custom metadata fields, predefined tags, auto-classification + +### 4. Workflow & Automation 🔄 +- **Icon**: Circular arrows (workflow symbol) +- **Color**: Purple scheme +- **Purpose**: Configure approval flows and automation +- **Key Features**: Approval workflows, notifications, automation triggers + +### 5. Upload & Storage Settings 📤 +- **Icon**: Upload arrow +- **Color**: Orange scheme +- **Purpose**: Configure file handling and storage +- **Key Features**: File type restrictions, size limits, storage quotas + +### 6. System Settings 📅 +- **Icon**: Calendar/gear symbol +- **Color**: Gray scheme +- **Purpose**: Configure system-wide settings +- **Key Features**: Timezone, backups, monitoring, maintenance mode + +## User & Access Management + +### User Roles Configuration + +#### Default Roles +The system comes with four default user roles: +- **Admin**: Full system access and administrative privileges +- **Editor**: Create, edit, and manage documents with approval capabilities +- **Viewer**: Read-only access to assigned documents +- **Uploader**: Upload documents with basic editing capabilities + +#### Adding Custom Roles +1. **Navigate to User Roles section** +2. **Click "Add Role" button** +3. **Enter role name** in the prompt dialog +4. **Role automatically added** to the list +5. **Save settings** to persist changes + +#### Removing Roles +1. **Locate role** in the roles list +2. **Click delete button** (trash icon) next to role name +3. **Confirm deletion** (role removed from all users) +4. **Save settings** to persist changes + +### Permission Configuration + +#### Granular Permissions +Configure specific permissions for different user levels: + +- **View Documents**: + - **Default**: Enabled for all roles + - **Purpose**: Basic read access to documents + - **Impact**: Controls document visibility + +- **Edit Documents**: + - **Default**: Enabled for Admin/Editor roles + - **Purpose**: Modify document content and metadata + - **Impact**: Affects document modification capabilities + +- **Delete Documents**: + - **Default**: Disabled (Admin only) + - **Purpose**: Remove documents from system + - **Impact**: Permanent document removal access + +- **Download Documents**: + - **Default**: Enabled for most roles + - **Purpose**: Save documents locally + - **Impact**: Controls offline document access + +- **Share Documents**: + - **Default**: Enabled for Admin/Editor roles + - **Purpose**: Share documents with other users + - **Impact**: Affects collaboration capabilities + +### Authentication Configuration + +#### Single Sign-On (SSO) +- **Purpose**: Integrate with organizational authentication systems +- **Supported Providers**: LDAP, Active Directory, OAuth providers +- **Configuration**: Enable/disable SSO functionality +- **Impact**: Streamlines user authentication process + +#### Multi-Factor Authentication (MFA) +- **Purpose**: Enhanced security for sensitive environments +- **Methods**: SMS, email, authenticator apps +- **Configuration**: Require MFA for all users or specific roles +- **Impact**: Significantly improves account security + +#### LDAP Integration +- **Purpose**: Synchronize with enterprise directory services +- **Features**: User import, group synchronization, automatic provisioning +- **Configuration**: Enable/disable LDAP authentication +- **Impact**: Centralizes user management + +#### Session Management +- **Session Timeout**: Configure automatic logout (1-24 hours) +- **Default**: 8 hours +- **Security Impact**: Balances security with user convenience +- **Compliance**: Helps meet organizational security policies + +## Document & Folder Settings + +### Naming Conventions + +#### Automatic Name Generation +- **Purpose**: Standardize document naming across organization +- **Configuration**: Enable/disable automatic naming +- **Benefits**: Consistency, searchability, organization + +#### Naming Patterns +- **Default Pattern**: `{department}_{title}_{date}` +- **Available Variables**: + - `{department}`: Document department/category + - `{title}`: Document title + - `{date}`: Creation date (YYYY-MM-DD format) + - `{user}`: Document creator username + - `{category}`: Document category + - `{counter}`: Auto-incrementing number + +#### Custom Pattern Examples +- `{department}_{category}_{date}_{title}` +- `{user}_{department}_{date}_{title}` +- `DOC_{counter}_{department}_{date}` + +#### Mandatory Fields +Configure which metadata fields are required for document upload: +- **Title**: Document title (recommended) +- **Department**: Organizational unit +- **Date**: Creation or effective date +- **Category**: Document type/classification +- **Custom Fields**: Organization-specific requirements + +### Version Control + +#### Version Control Features +- **Enable/Disable**: Toggle document versioning system-wide +- **Benefits**: Track changes, prevent data loss, maintain history +- **Storage Impact**: Increased storage requirements + +#### Version Limits +- **Maximum Versions**: Configure how many versions to retain (1-50) +- **Default**: 10 versions per document +- **Storage Optimization**: Automatic cleanup of old versions +- **Performance Impact**: More versions = more storage/processing + +#### Automatic Versioning +- **Auto-versioning**: Create new version on every document modification +- **Manual Versioning**: Users manually create versions +- **Hybrid Approach**: Combine automatic and manual versioning +- **Configuration**: Enable/disable automatic version creation + +### Document Retention + +#### Retention Policies +- **Purpose**: Comply with legal and organizational requirements +- **Default Period**: 2,555 days (approximately 7 years) +- **Customization**: Configure per document type or category +- **Legal Compliance**: Meets common retention requirements + +#### Archive Before Delete +- **Purpose**: Create archive copy before permanent deletion +- **Benefits**: Data recovery, compliance, audit trail +- **Storage Impact**: Requires additional archive storage +- **Configuration**: Enable/disable archive creation + +## Metadata & Tagging + +### Custom Metadata Fields + +#### Field Types +The system supports multiple field types for custom metadata: + +- **Text**: Single-line text input + - **Use Cases**: Names, IDs, short descriptions + - **Validation**: Length limits, format requirements + - **Examples**: Employee ID, Project Code, Reference Number + +- **Dropdown**: Single selection from predefined options + - **Use Cases**: Categories, departments, status values + - **Configuration**: Define available options + - **Examples**: Department (HR, Finance, IT), Priority (High, Medium, Low) + +- **Date**: Date picker with validation + - **Use Cases**: Effective dates, expiration dates, deadlines + - **Format**: System-standard date format + - **Examples**: Contract Expiry, Review Date, Effective Date + +- **Number**: Numeric input with validation + - **Use Cases**: Amounts, quantities, scores + - **Validation**: Min/max values, decimal places + - **Examples**: Budget Amount, Quantity, Rating + +- **Multi-select**: Multiple selections from predefined options + - **Use Cases**: Tags, categories, multiple assignments + - **Configuration**: Define available options + - **Examples**: Skills, Keywords, Applicable Departments + +#### Managing Custom Fields + +##### Adding New Fields +1. **Navigate to Custom Fields section** +2. **Click "Add Custom Field" button** +3. **Configure field properties**: + - **Field Name**: Descriptive name for the field + - **Field Type**: Select from available types + - **Required**: Mark as mandatory for document upload +4. **Save changes** to apply new field + +##### Editing Existing Fields +1. **Locate field** in the custom fields list +2. **Modify field properties** as needed +3. **Required status** can be changed for existing fields +4. **Save changes** to apply modifications + +##### Removing Fields +1. **Click delete button** (trash icon) next to field +2. **Confirm deletion** (data loss warning) +3. **Field removed** from all future uploads +4. **Existing data** preserved but field no longer editable + +#### Default Custom Fields +The system includes several pre-configured custom fields: + +- **Department** (Dropdown, Required) + - Purpose: Organizational categorization + - Options: Configurable per organization + +- **Priority** (Multi-select, Optional) + - Purpose: Document priority level + - Options: High, Medium, Low, Critical + +- **Project Code** (Text, Required) + - Purpose: Project association + - Validation: Alphanumeric format + +- **Review Date** (Date, Optional) + - Purpose: Scheduled review timeline + - Format: Standard date picker + +### Tagging System + +#### Predefined Tags +- **Purpose**: Standardize document categorization +- **Configuration**: Comma-separated list of tags +- **Default Tags**: urgent, confidential, public, draft, final +- **Benefits**: Consistency, searchability, filtering + +#### Custom Tag Examples +- **By Priority**: urgent, high-priority, normal, low-priority +- **By Status**: draft, review, approved, published, archived +- **By Confidentiality**: public, internal, confidential, restricted +- **By Department**: hr, finance, legal, marketing, operations + +#### User-Generated Tags +- **Configuration**: Enable/disable user-created tags +- **Benefits**: Flexibility, user adoption, comprehensive tagging +- **Drawbacks**: Potential inconsistency, tag proliferation +- **Best Practice**: Combine with predefined tags for optimal results + +#### Tag Suggestions +- **Auto-complete**: Suggest existing tags as users type +- **Machine Learning**: Learn from user behavior (future feature) +- **Performance**: Improves tagging consistency and speed +- **Configuration**: Enable/disable intelligent suggestions + +### Auto-Classification + +#### Classification Rules +Configure automatic document classification based on: + +- **Content Keywords**: Analyze document content for specific terms +- **File Type**: Classify based on file extension or format +- **Department**: Auto-assign based on uploader's department +- **Naming Patterns**: Extract classification from filename +- **Metadata**: Use existing metadata for classification + +#### Classification Benefits +- **Consistency**: Automated classification reduces human error +- **Efficiency**: Saves time during document upload +- **Compliance**: Ensures proper categorization for regulations +- **Searchability**: Improves document discoverability + +## Workflow & Automation + +### Approval Workflows + +#### Default Approval Flow +- **Standard Flow**: "department-head-approval" +- **Process**: Document → Department Head → Approved/Rejected +- **Notification**: Automatic notifications to stakeholders +- **Timeline**: Configurable approval timeframes + +#### Custom Approval Flows +The system supports multiple pre-configured approval workflows: + +- **Legal Review**: + - **Process**: Document → Legal Department → Approval + - **Use Cases**: Contracts, policies, compliance documents + - **Timeline**: Extended review period for thorough analysis + +- **Finance Approval**: + - **Process**: Document → Finance Department → Approval + - **Use Cases**: Budgets, expenses, financial reports + - **Requirements**: Financial analysis and verification + +- **Director Sign-off**: + - **Process**: Document → Director Level → Final Approval + - **Use Cases**: Strategic documents, major policies + - **Authority**: Highest level organizational approval + +#### Workflow Configuration +- **Enable/Disable**: Toggle approval workflows system-wide +- **Default Assignment**: Set primary approval flow +- **Custom Rules**: Configure workflow triggers based on: + - Document type or category + - File size or sensitivity + - Department or user role + - Document metadata values + +### Notification System + +#### Email Notifications +- **Purpose**: Keep stakeholders informed of document activities +- **Triggers**: Upload, approval, rejection, deadline approaching +- **Configuration**: Enable/disable email notifications +- **Templates**: Customizable email templates for different events + +#### In-App Notifications +- **Real-time**: Instant notifications within the application +- **Persistence**: Notifications remain until acknowledged +- **Categories**: Document activities, system events, approval requests +- **Benefits**: Immediate awareness without email dependency + +#### Upload Alerts +- **New Documents**: Notify relevant parties of new uploads +- **Large Files**: Alert administrators of significant uploads +- **Restricted Areas**: Notifications for uploads to sensitive folders +- **Batch Uploads**: Summarized notifications for multiple uploads + +#### Deadline Reminders +- **Review Deadlines**: Remind users of pending document reviews +- **Expiration Dates**: Alert before document expiration +- **Approval Timeouts**: Notify about pending approval requests +- **Custom Deadlines**: Configurable reminder schedules + +### Automation Features + +#### Automation Triggers +Configure automatic actions based on specific events: + +- **Document Uploaded**: Trigger actions when new documents are added +- **Approval Completed**: Actions after document approval process +- **Deadline Reached**: Time-based triggers for scheduled actions +- **Status Changed**: Trigger on document status modifications +- **User Action**: Custom triggers based on user activities + +#### Automation Actions +Define actions to execute automatically: + +- **Move to Folder**: Automatically organize documents +- **Send Notification**: Alert specific users or groups +- **Create Task**: Generate workflow tasks for users +- **Update Metadata**: Automatically modify document properties +- **Generate Report**: Create summary reports of activities + +## Upload & Storage Settings + +### File Type Management + +#### Allowed File Types +Configure which file formats can be uploaded to the system: + +**Default Allowed Types**: +- **Documents**: pdf, doc, docx, txt, rtf +- **Spreadsheets**: xls, xlsx, csv +- **Presentations**: ppt, pptx +- **Images**: jpg, jpeg, png, gif, bmp +- **Archives**: zip, rar (if configured) + +**Configuration Format**: +- Comma-separated list of extensions +- Case-insensitive matching +- No dots required (system adds automatically) +- Example: `pdf, doc, docx, xls, xlsx, jpg, png` + +#### Blocked File Types +Prevent upload of potentially dangerous or inappropriate files: + +**Default Blocked Types**: +- **Executables**: exe, bat, cmd, scr +- **Scripts**: js, vbs, ps1, sh +- **System Files**: dll, sys, ini +- **Malware-prone**: com, pif, reg + +**Security Benefits**: +- Prevents malware upload +- Reduces security vulnerabilities +- Maintains system integrity +- Protects user devices + +#### MIME Type Validation +- **Purpose**: Verify file content matches extension +- **Security**: Prevents file extension spoofing +- **Implementation**: Server-side content verification +- **Benefits**: Enhanced security and file integrity + +### Storage Quotas + +#### File Size Limits +- **Maximum File Size**: Configure per-file upload limit +- **Default**: 100 MB per file +- **Range**: 1 MB to 2 GB (depending on server configuration) +- **Impact**: Affects upload performance and storage usage + +#### User Quotas +- **Per-User Limit**: Total storage allocated per user +- **Default**: 5,000 MB (5 GB) per user +- **Monitoring**: Track individual user storage consumption +- **Enforcement**: Prevent uploads when quota exceeded + +#### Group Quotas +- **Per-Group Limit**: Storage allocated to user groups/departments +- **Default**: 50,000 MB (50 GB) per group +- **Shared Storage**: Group members share allocation +- **Management**: Administrative oversight of group usage + +#### Project Quotas +- **Per-Project Limit**: Storage for specific projects or initiatives +- **Default**: 100,000 MB (100 GB) per project +- **Isolation**: Separate storage allocation for different projects +- **Tracking**: Monitor project-specific storage usage + +### Storage Configuration + +#### Storage Type +- **Local Storage**: Files stored on server filesystem +- **Cloud Storage**: Integration with cloud providers (future feature) +- **Hybrid**: Combination of local and cloud storage +- **Configuration**: Select appropriate storage backend + +#### Storage Path +- **Default Path**: `/var/uploads/edms` +- **Customization**: Configure custom storage directory +- **Permissions**: Ensure proper filesystem permissions +- **Backup Access**: Consider backup system access requirements + +#### Backup Settings +- **Automatic Backup**: Enable scheduled backup of uploaded files +- **Backup Frequency**: Configure backup schedule +- **Retention**: How long to keep backup copies +- **Storage Location**: Separate backup storage location + +#### Compression Settings +- **File Compression**: Reduce storage requirements +- **Performance Impact**: CPU usage vs. storage savings +- **File Types**: Configure which files to compress +- **Compression Level**: Balance between size and processing time + +## System Settings + +### General Configuration + +#### System Timezone +- **Purpose**: Standardize timestamps across the system +- **Default**: Asia/Kuala_Lumpur +- **Options**: All standard timezone identifiers +- **Impact**: Affects all date/time displays and logging + +**Common Timezone Options**: +- **Asia/Kuala_Lumpur**: Malaysia Standard Time (UTC+8) +- **UTC**: Coordinated Universal Time +- **America/New_York**: Eastern Time (UTC-5/-4) +- **Europe/London**: British Time (UTC+0/+1) +- **Asia/Singapore**: Singapore Time (UTC+8) + +#### Backup Schedule +Configure automated system backups: + +- **Hourly**: Maximum data protection, high resource usage +- **Daily**: Recommended for most organizations +- **Weekly**: Suitable for low-activity systems +- **Monthly**: Minimal backup frequency + +#### System Logging +- **Debug**: Detailed logging for troubleshooting +- **Info**: Standard operational logging +- **Warning**: Log potential issues and warnings +- **Error**: Log only errors and critical issues + +### System Maintenance + +#### Maintenance Mode +- **Purpose**: Disable system access during maintenance +- **Impact**: Users cannot access the system +- **Notification**: Display maintenance message to users +- **Use Cases**: System updates, database maintenance, security patches + +#### Automatic Updates +- **System Updates**: Automatically apply system updates +- **Security Patches**: Automatic security patch installation +- **Feature Updates**: Include new feature releases +- **Configuration**: Enable/disable automatic updates + +#### System Monitoring +- **Performance Metrics**: Track system performance +- **Resource Usage**: Monitor CPU, memory, and storage +- **User Activity**: Track user behavior and system usage +- **Alerts**: Automatic alerts for system issues + +#### Performance Metrics +- **Response Times**: Monitor API and page load times +- **Database Performance**: Track query execution times +- **File Operations**: Monitor upload/download performance +- **User Experience**: Track user interaction metrics + +## Settings Management + +### Save & Load Operations + +#### Automatic Saving +- **Real-time Updates**: Changes saved immediately when modified +- **Background Process**: Saves occur without interrupting user workflow +- **Error Handling**: Graceful handling of save failures +- **Visual Feedback**: Loading indicators during save operations + +#### Loading States +- **Initial Load**: Display loading spinner when page loads +- **Save Operations**: Show saving indicator during updates +- **Error States**: Clear error messages if operations fail +- **Success Confirmation**: Green confirmation messages on successful saves + +#### Data Validation +- **Client-side**: Immediate validation feedback +- **Server-side**: Comprehensive validation on save +- **Error Messages**: Clear, actionable error descriptions +- **Required Fields**: Validation of mandatory settings + +### Error Handling + +#### Common Error Scenarios +- **Network Issues**: Connection problems during save +- **Validation Errors**: Invalid configuration values +- **Permission Errors**: Insufficient privileges for changes +- **Server Errors**: Backend processing issues + +#### Error Recovery +- **Retry Mechanisms**: Automatic retry for transient failures +- **Fallback Values**: Default settings if load fails +- **User Guidance**: Clear instructions for error resolution +- **Support Contact**: Escalation path for persistent issues + +### Success Feedback + +#### Confirmation Messages +- **Save Success**: "Settings saved successfully!" +- **Auto-dismiss**: Messages disappear after 3 seconds +- **Visual Design**: Green background with checkmark icon +- **Non-intrusive**: Don't block user workflow + +#### Visual Indicators +- **Active Tab**: Highlighted current settings category +- **Modified Fields**: Visual indication of unsaved changes +- **Loading States**: Spinners and progress indicators +- **Status Icons**: Success, error, and warning indicators + +## Import/Export Functionality + +### Export Settings + +#### Export Process +1. **Click Export Button**: Located in settings header +2. **Generate JSON**: System creates comprehensive settings export +3. **Download File**: Browser downloads `dms-settings.json` +4. **Backup Storage**: Store export file securely + +#### Export Content +The exported JSON includes: +- Complete settings configuration +- All custom fields and their definitions +- User roles and permission settings +- Predefined tags and classification rules +- System configuration options +- Timestamp of export creation + +#### Export Benefits +- **Backup**: Protect against configuration loss +- **Migration**: Transfer settings between environments +- **Version Control**: Track configuration changes over time +- **Rollback**: Restore previous configurations if needed + +### Import Settings + +#### Import Process +1. **Select JSON File**: Click import button and choose file +2. **File Validation**: System validates JSON format and content +3. **Preview Changes**: Display what will be imported (future feature) +4. **Apply Settings**: Import settings and update database +5. **Confirmation**: Success message with change summary + +#### Import Validation +- **JSON Format**: Verify file is valid JSON +- **Schema Validation**: Ensure settings structure is correct +- **Value Validation**: Check individual setting values +- **Compatibility**: Verify settings are compatible with current version + +#### Import Safety +- **Backup Creation**: Automatic backup before import +- **Rollback Option**: Ability to revert to previous settings +- **Merge Strategy**: How to handle existing vs. imported settings +- **Conflict Resolution**: Handle conflicting configuration values + +### Settings Migration + +#### Environment Transfer +- **Development to Production**: Deploy tested configurations +- **Staging Environment**: Test settings before production +- **Multi-tenant**: Share configurations across tenants +- **Branch Environments**: Maintain different configurations + +#### Version Compatibility +- **Forward Compatibility**: Newer exports work with older systems +- **Backward Compatibility**: Older exports work with newer systems +- **Migration Scripts**: Automatic schema updates when needed +- **Deprecation Handling**: Graceful handling of removed settings + +## API Integration + +### Settings API Endpoints + +#### GET `/api/dms/settings` +**Purpose**: Retrieve current DMS settings + +**Response Format**: +```json +{ + "statusCode": 200, + "message": "Success", + "data": { + "access": { /* access management settings */ }, + "documents": { /* document settings */ }, + "metadata": { /* metadata configuration */ }, + "workflow": { /* workflow settings */ }, + "upload": { /* upload configuration */ }, + "system": { /* system settings */ } + } +} +``` + +**Features**: +- Returns complete settings structure +- Provides default values if settings don't exist +- Handles database connection errors gracefully +- Transforms database format to frontend structure + +#### POST `/api/dms/settings` +**Purpose**: Update DMS settings + +**Request Format**: +```json +{ + "access": { + "userRoles": ["Admin", "Editor", "Viewer"], + "rbacEnabled": true, + "permissions": { + "view": true, + "edit": true, + "delete": false + } + }, + /* other setting categories */ +} +``` + +**Response Format**: +```json +{ + "statusCode": 200, + "message": "Settings updated successfully", + "data": { /* updated settings */ } +} +``` + +**Features**: +- Accepts partial or complete settings updates +- Validates all input data +- Transforms frontend format to database structure +- Creates settings record if none exists + +### Data Transformation + +#### Frontend to Database +The API handles complex data transformations: + +**Array to String Conversion**: +- `userRoles: ["Admin", "Editor"]` → `userRoles: "Admin,Editor"` +- `predefinedTags: ["urgent", "public"]` → `taggingPredefinedTags: "urgent,public"` + +**Nested Object Flattening**: +- `access.permissions.view: true` → `permissionView: true` +- `upload.quotas.perUser: 5000` → `uploadQuotaPerUser: 5000` + +**JSON Serialization**: +- `customFields: [{}]` → `metadataCustomFields: JSON.stringify([{}])` + +#### Database to Frontend +Reverse transformations for data retrieval: + +**String to Array Conversion**: +- `userRoles: "Admin,Editor"` → `userRoles: ["Admin", "Editor"]` + +**Object Restructuring**: +- `permissionView: true` → `access.permissions.view: true` + +**JSON Parsing**: +- `metadataCustomFields: "{}"` → `customFields: JSON.parse("{}")` + +### Error Handling + +#### Validation Errors +- **Required Fields**: Missing mandatory settings +- **Data Types**: Invalid data type for setting value +- **Range Validation**: Values outside acceptable ranges +- **Format Validation**: Invalid format for specific settings + +#### Database Errors +- **Connection Issues**: Database connectivity problems +- **Query Failures**: SQL execution errors +- **Transaction Rollback**: Ensure data consistency +- **Constraint Violations**: Database constraint errors + +#### Response Errors +```json +{ + "statusCode": 400, + "message": "Validation error", + "errors": [ + { + "field": "uploadFileSizeLimit", + "message": "File size limit must be between 1 and 2000 MB" + } + ] +} +``` + +## Configuration Best Practices + +### Security Configuration + +#### Access Control +- **Principle of Least Privilege**: Grant minimum necessary permissions +- **Role-Based Access**: Use roles rather than individual permissions +- **Regular Review**: Periodically audit user roles and permissions +- **Documentation**: Maintain documentation of role definitions + +#### Authentication Settings +- **Strong Passwords**: Enforce password complexity requirements +- **Session Timeouts**: Balance security with user convenience +- **Multi-Factor Authentication**: Enable for sensitive environments +- **Regular Updates**: Keep authentication systems updated + +#### File Security +- **File Type Restrictions**: Block potentially dangerous file types +- **Size Limits**: Prevent resource exhaustion attacks +- **Virus Scanning**: Implement file scanning (external integration) +- **Content Validation**: Verify file content matches extension + +### Performance Optimization + +#### Storage Management +- **Quota Planning**: Set realistic quotas based on usage patterns +- **File Compression**: Enable for appropriate file types +- **Archive Policies**: Implement automated archiving +- **Cleanup Procedures**: Regular cleanup of temporary files + +#### Database Optimization +- **Index Management**: Ensure proper database indexing +- **Query Optimization**: Monitor and optimize slow queries +- **Connection Pooling**: Configure database connection pools +- **Backup Strategy**: Regular database backups and testing + +#### System Resources +- **Memory Management**: Monitor system memory usage +- **CPU Utilization**: Track processing requirements +- **Disk Space**: Monitor storage usage and growth +- **Network Bandwidth**: Consider file transfer requirements + +### Operational Excellence + +#### Monitoring & Alerting +- **Performance Metrics**: Track key system metrics +- **Error Monitoring**: Alert on system errors and failures +- **Usage Analytics**: Monitor user activity and system usage +- **Capacity Planning**: Predict future resource requirements + +#### Backup & Recovery +- **Regular Backups**: Implement comprehensive backup strategy +- **Recovery Testing**: Regularly test backup recovery procedures +- **Disaster Recovery**: Plan for disaster recovery scenarios +- **Documentation**: Maintain recovery procedure documentation + +#### Change Management +- **Testing Environment**: Test configuration changes before production +- **Change Documentation**: Document all configuration changes +- **Rollback Procedures**: Maintain ability to rollback changes +- **Version Control**: Track configuration versions over time + +### Compliance & Governance + +#### Data Retention +- **Legal Requirements**: Comply with legal retention requirements +- **Industry Standards**: Follow industry-specific guidelines +- **Data Classification**: Classify data based on sensitivity +- **Audit Trail**: Maintain comprehensive audit logs + +#### Privacy Protection +- **Data Minimization**: Collect only necessary metadata +- **Access Logging**: Log all data access activities +- **Anonymization**: Remove personal data when appropriate +- **Consent Management**: Track user consent for data processing + +## Troubleshooting + +### Common Issues + +#### Settings Not Saving +**Symptoms**: +- Changes appear but revert after page refresh +- Error messages during save operations +- Loading indicators that never complete + +**Troubleshooting Steps**: +1. **Check Network Connection**: Verify stable internet connectivity +2. **Browser Console**: Check for JavaScript errors +3. **Clear Cache**: Clear browser cache and reload page +4. **Try Different Browser**: Test with alternative browser +5. **Check Permissions**: Verify administrative access +6. **Server Status**: Confirm server is operational + +**Common Causes**: +- Network connectivity issues +- Server-side validation errors +- Database connection problems +- Insufficient user permissions +- Browser compatibility issues + +#### Settings Not Loading +**Symptoms**: +- Blank settings page or loading indefinitely +- Error messages on page load +- Missing configuration options + +**Troubleshooting Steps**: +1. **Refresh Page**: Simple page refresh may resolve issue +2. **Check URL**: Verify correct settings page URL +3. **Clear Browser Data**: Clear cache, cookies, and storage +4. **Disable Extensions**: Temporarily disable browser extensions +5. **Check Server Logs**: Review server error logs +6. **Database Connectivity**: Verify database is accessible + +#### Import/Export Failures +**Symptoms**: +- Export downloads empty or corrupted files +- Import fails with validation errors +- Settings don't apply after import + +**Troubleshooting Steps**: +1. **File Format**: Verify JSON file format is correct +2. **File Size**: Check if file exceeds browser limits +3. **Content Validation**: Validate JSON structure manually +4. **Backup First**: Always backup before importing +5. **Partial Import**: Try importing smaller setting sections +6. **Contact Support**: Escalate persistent issues + +### Performance Issues + +#### Slow Loading +**Symptoms**: +- Settings page takes long time to load +- Slow response to setting changes +- Timeouts during save operations + +**Optimization Steps**: +1. **Network Speed**: Check internet connection speed +2. **Server Performance**: Monitor server resource usage +3. **Database Optimization**: Check database performance +4. **Browser Performance**: Close unnecessary tabs/applications +5. **Clear Cache**: Regular cache clearing +6. **Update Browser**: Use latest browser version + +#### Memory Issues +**Symptoms**: +- Browser becomes unresponsive +- Out of memory errors +- System slowdown during settings operations + +**Resolution Steps**: +1. **Close Tabs**: Reduce browser tab count +2. **Restart Browser**: Fresh browser session +3. **Check RAM**: Monitor system memory usage +4. **Reduce Complexity**: Simplify configuration changes +5. **Browser Update**: Ensure browser is updated +6. **System Restart**: Restart computer if necessary + +### Error Resolution + +#### Validation Errors +**Common Validation Issues**: +- Invalid file size limits (outside 1-2000 MB range) +- Malformed email addresses for notifications +- Invalid timezone identifiers +- Empty required fields + +**Resolution**: +1. **Read Error Messages**: Carefully review validation messages +2. **Check Ranges**: Verify values are within acceptable ranges +3. **Format Validation**: Ensure proper format for fields +4. **Required Fields**: Complete all mandatory fields +5. **Save Incrementally**: Save settings in smaller sections + +#### Permission Errors +**Symptoms**: +- "Access Denied" messages +- Settings page redirect to main interface +- Missing administrative options + +**Resolution**: +1. **Verify Role**: Confirm administrative privileges +2. **Contact Admin**: Request permission elevation +3. **Role Assignment**: Check role assignment accuracy +4. **System Restart**: Logout and login again +5. **Cache Clear**: Clear browser authentication cache + +### Support & Escalation + +#### Documentation Resources +- **Technical Guide**: Comprehensive system documentation +- **User Guide**: End-user documentation +- **API Documentation**: Developer integration guides +- **Change Log**: System update and change history + +#### Contact Procedures +- **System Administrator**: Internal IT support contact +- **Help Desk**: Organizational support procedures +- **Vendor Support**: External support if applicable +- **Community Forums**: User community resources + +#### Information to Provide +When seeking support, include: +- **Error Messages**: Exact text of error messages +- **Steps to Reproduce**: Detailed reproduction steps +- **Browser Information**: Browser type and version +- **System Configuration**: Relevant system details +- **Screenshots**: Visual documentation of issues +- **Log Files**: Relevant system or browser logs + +This comprehensive guide covers all aspects of the DMS Settings system, providing administrators with the knowledge needed to effectively configure and manage the document management system. \ No newline at end of file diff --git a/docs/SITE_SETTINGS.md b/docs/SITE_SETTINGS.md index eed0bcc..22716d0 100644 --- a/docs/SITE_SETTINGS.md +++ b/docs/SITE_SETTINGS.md @@ -1,161 +1,656 @@ -# Site Settings Feature +# Site Settings System - Comprehensive Guide ## Overview -The Site Settings feature allows administrators to customize the appearance and branding of the application through a user-friendly interface. All settings are globally applied across the entire application including SEO, meta tags, and visual elements. +The Site Settings system provides administrators with comprehensive control over the visual appearance, branding, and global configuration of the Electronic Document Management System (EDMS). This system allows complete customization of the application's look and feel, SEO settings, and theme management through an intuitive web interface. -## Features +## Table of Contents +1. [System Integration](#system-integration) +2. [Features Overview](#features-overview) +3. [Accessing Site Settings](#accessing-site-settings) +4. [Configuration Categories](#configuration-categories) +5. [Basic Information Settings](#basic-information-settings) +6. [Branding & Visual Identity](#branding--visual-identity) +7. [SEO & Meta Tag Management](#seo--meta-tag-management) +8. [Theme System Integration](#theme-system-integration) +9. [Advanced Customization](#advanced-customization) +10. [API Integration](#api-integration) +11. [Technical Implementation](#technical-implementation) +12. [Best Practices](#best-practices) +13. [Troubleshooting](#troubleshooting) + +## System Integration + +### EDMS Ecosystem +The Site Settings system is fully integrated with the EDMS ecosystem and works alongside: +- **DMS Settings**: Document management configuration (separate system) +- **User Management**: Role-based access control for settings access +- **Theme System**: Dynamic theme switching and custom theme support +- **Component Library**: Rs component system integration +- **Global State**: Pinia store management for reactive updates + +### Global Impact +Site settings affect the entire application including: +- **Header and Navigation**: Site logo, name, and branding elements +- **Loading Screens**: Custom loading logos and branding +- **Document Viewer**: Consistent branding across all interfaces +- **Authentication Pages**: Login page branding and styling +- **SEO Elements**: Meta tags, Open Graph, and social media integration +- **Theme Application**: Global color schemes and visual styling + +## Features Overview + +### Core Capabilities +- **Complete Branding Control**: Logos, site name, and visual identity +- **Theme Management**: Built-in themes plus custom theme support +- **SEO Optimization**: Comprehensive meta tag and social media optimization +- **Custom Styling**: CSS injection and custom theme file support +- **Real-time Preview**: Live preview of changes before applying +- **Global Integration**: Settings applied across entire application +- **Backup & Restore**: Export/import configuration for backup and migration + +### Administrative Features +- **Role-Based Access**: Only administrators can modify site settings +- **Validation System**: Comprehensive validation for all settings +- **File Upload Management**: Secure file upload for logos and assets +- **Version Control**: Track changes and maintain configuration history +- **Multi-Environment Support**: Different configurations for different environments + +## Accessing Site Settings + +### Prerequisites +- **Administrative Privileges**: User must have admin role +- **Modern Browser**: Chrome 70+, Firefox 65+, Safari 12+, Edge 79+ +- **JavaScript Enabled**: Required for interactive functionality +- **Network Access**: Stable connection for file uploads and saves + +### Navigation Path +1. **Main Menu**: Navigate to **Pentadbiran** (Administration) +2. **Configuration Section**: Select **Konfigurasi** (Configuration) +3. **Site Settings**: Choose **Site Settings** from the submenu +4. **Alternative Access**: Direct URL navigation to `/admin/site-settings` + +### Interface Layout +- **Tabbed Interface**: Basic Info, Branding, SEO, Advanced settings +- **Live Preview Panel**: Real-time preview of changes +- **Action Buttons**: Save, Reset, Export, Import functionality +- **Validation Feedback**: Immediate feedback on invalid settings +- **Loading States**: Visual feedback during save operations + +## Configuration Categories ### 1. Basic Information -- **Site Name**: Customize the application name displayed globally in: - - Header and sidebar - - Browser title and meta tags - - SEO and Open Graph tags - - Loading screen - - All pages and components -- **Site Description**: Set a description used for: - - SEO meta descriptions - - Open Graph descriptions - - Twitter Card descriptions -- **Theme Selection**: Choose from available themes: - - Standard themes (from themeList.js) - - Accessibility themes (from themeList2.js) - - Custom themes added to theme.css +- **Site Name**: Application name displayed globally +- **Site Description**: Meta description for SEO and social sharing +- **Font Configuration**: Typography settings and font selection +- **Display Options**: Show/hide site name in header and other locations ### 2. Branding -- **Site Logo**: Upload a custom logo displayed in: - - Header (horizontal layout) - - Sidebar (vertical layout) - - Loading screen - - Login page - - Any component using site settings -- **Favicon**: Upload a custom favicon displayed in: - - Browser tabs - - Bookmarks - - Mobile home screen icons +- **Site Logo**: Main application logo for headers and navigation +- **Loading Logo**: Branded loading screen logo +- **Favicon**: Browser tab icon and bookmark icon +- **Login Logo**: Dedicated branding for authentication pages -### 3. Advanced Settings -- **Custom CSS**: Add custom CSS injected into document head -- **Custom Theme File**: Upload CSS files saved to `/assets/style/css/` -- **Add Custom Theme to theme.css**: Directly add themes to the main theme.css file +### 3. SEO & Social Media +- **Meta Tags**: Title, description, keywords, author information +- **Open Graph**: Facebook and social media sharing optimization +- **Twitter Cards**: Twitter-specific meta tag configuration +- **Analytics Integration**: Google Analytics, Tag Manager, Facebook Pixel -## How to Access +### 4. Advanced Settings +- **Custom CSS**: Global CSS injection for advanced styling +- **Custom Themes**: Upload and manage custom theme files +- **Theme Editor**: Direct editing of theme.css file +- **Developer Tools**: Advanced configuration options -1. Navigate to **Pentadbiran** → **Konfigurasi** → **Site Settings** -2. Use the tabbed interface: - - **Basic Info**: Site name, description, and theme selection - - **Branding**: Logo and favicon uploads - - **Advanced**: Custom CSS and theme management -3. Use the **Live Preview** panel to see changes in real-time -4. Click **Save Changes** to apply your settings +## Basic Information Settings -## Technical Implementation +### Site Name Configuration +- **Purpose**: Define the application name displayed throughout the system +- **Default Value**: "corradAF" (customizable) +- **Global Impact**: Updates header, page titles, meta tags, loading screens +- **Font Size Control**: Adjustable font size (12-36px range) +- **Character Limit**: Recommended maximum of 50 characters for optimal display -### Database Schema -The settings are stored in the `site_settings` table with the following fields: -- `siteName`, `siteDescription` -- `siteLogo`, `siteFavicon` -- `selectedTheme` - Selected theme name -- `customCSS`, `customThemeFile` -- Legacy fields maintained for backward compatibility +**Display Locations**: +- Header navigation (primary logo area) +- Browser page titles (prefixed to page names) +- Loading screen branding +- SEO meta tags and social sharing +- Authentication page headers -### API Endpoints -- `GET /api/devtool/config/site-settings` - Retrieve current settings -- `POST /api/devtool/config/site-settings` - Update settings -- `POST /api/devtool/config/upload-file` - Upload files (logos, themes) -- `POST /api/devtool/config/add-custom-theme` - Add custom theme to theme.css +### Site Description +- **Purpose**: Provide descriptive text for SEO and social media sharing +- **SEO Impact**: Used as meta description tag for search engines +- **Social Sharing**: Appears in social media link previews +- **Character Limit**: Recommended 150-160 characters for optimal SEO +- **Multi-language Support**: Single description applies globally -### File Upload Locations -- **Logo and Favicon files**: Saved to `public/uploads/site-settings/` -- **Theme CSS files**: Saved to `assets/style/css/` directory -- **Custom themes**: Added directly to `assets/style/css/base/theme.css` +### Typography Configuration +- **Font Selection**: Choose from available system fonts +- **Font Source**: Local fonts vs. web fonts (Google Fonts integration) +- **Font Size Controls**: Configurable sizes for different elements +- **Global Application**: Typography changes apply system-wide -### Composable -The `useSiteSettings()` composable provides: -- `siteSettings` - Reactive settings object -- `loadSiteSettings()` - Load settings from API -- `updateSiteSettings()` - Update settings -- `setTheme()` - Set theme using existing theme system -- `getCurrentTheme()` - Get current theme -- `applyThemeSettings()` - Apply theme changes to DOM -- `updateGlobalMeta()` - Update global meta tags and SEO -- `addCustomThemeToFile()` - Add custom theme to theme.css +## Branding & Visual Identity -### Global Integration -The site settings are globally integrated across: +### Logo Management System -#### Header Component -- Uses site settings for logo and name display -- Theme selection dropdown uses same system as site settings -- Synced with site settings theme selection +#### Site Logo (Primary) +- **Usage**: Main application logo in header and navigation +- **Recommended Dimensions**: 200x60px (maximum) +- **Supported Formats**: PNG, JPG, SVG (vector preferred) +- **File Size Limit**: 5MB maximum +- **Responsive Behavior**: Automatic scaling for different screen sizes +- **Fallback**: System default logo if custom logo fails to load -#### Loading Component -- Uses site logo if available, fallback to default -- Displays site name in loading screen +#### Loading Logo +- **Usage**: Branded loading screens and splash pages +- **Recommended Dimensions**: 100x100px (square preferred) +- **Animation Support**: Static images only (CSS animations can be added) +- **Multiple Screens**: Applied to all loading states throughout application +- **Brand Consistency**: Should complement primary site logo -#### App.vue -- Global meta tags updated from site settings -- Title, description, and favicon managed globally -- Theme initialization from site settings +#### Favicon Configuration +- **Usage**: Browser tab icons, bookmarks, mobile home screen icons +- **Required Format**: ICO format preferred (PNG acceptable) +- **Dimensions**: 16x16, 32x32, 48x48px (multi-size ICO recommended) +- **Mobile Icons**: Apple touch icons and Android home screen support +- **Browser Compatibility**: Cross-browser favicon support -#### SEO and Meta Tags -- Document title updated globally -- Meta descriptions for SEO -- Open Graph tags for social sharing -- Twitter Card tags -- Favicon and apple-touch-icon +#### Login Page Logo +- **Usage**: Dedicated branding for authentication and login pages +- **Design Consideration**: Can be different from main site logo for branding flexibility +- **Recommended Dimensions**: 250x80px maximum +- **Security Context**: Appears on security-sensitive pages +- **Brand Trust**: Important for user trust and brand recognition -### Theme System Integration -- Integrates with existing theme system (themeList.js, themeList2.js) -- Theme selection in header dropdown synced with site settings -- Custom themes can be added directly to theme.css -- Backward compatibility with existing theme structure +### File Upload System +- **Secure Upload**: File validation and virus scanning +- **Storage Location**: `public/uploads/site-settings/` directory +- **Backup Integration**: Uploaded files included in system backups +- **Version Control**: Maintain previous versions of uploaded assets +- **CDN Support**: Compatible with content delivery networks -### Custom Theme Structure -Custom themes added to theme.css should follow this structure: +## SEO & Meta Tag Management + +### Search Engine Optimization + +#### Basic SEO Settings +- **SEO Title**: Custom title for search engine results +- **Meta Description**: Description displayed in search results +- **Meta Keywords**: Keyword tags (legacy but still supported) +- **Meta Author**: Content author information +- **Canonical URL**: Preferred URL for content indexing + +#### Advanced SEO Configuration +- **Robots Meta Tag**: Control search engine crawling behavior + - Default: "index, follow" (allow indexing and link following) + - Options: noindex, nofollow, noarchive, nosnippet +- **Structured Data**: Schema.org markup for rich snippets +- **XML Sitemap**: Automatic sitemap generation and submission +- **Page Speed Optimization**: Settings that impact page load times + +### Social Media Integration + +#### Open Graph (Facebook) +- **og:title**: Social media sharing title +- **og:description**: Social media sharing description +- **og:image**: Image displayed in social media previews +- **og:type**: Content type (website, article, etc.) +- **og:url**: Canonical URL for social sharing + +#### Twitter Cards +- **twitter:card**: Card type (summary, summary_large_image, app, player) +- **twitter:title**: Twitter-specific sharing title +- **twitter:description**: Twitter-specific sharing description +- **twitter:image**: Twitter preview image +- **twitter:creator**: Twitter handle of content creator + +### Analytics & Tracking + +#### Google Analytics Integration +- **Tracking ID**: Google Analytics measurement ID (GA4 format) +- **Enhanced Ecommerce**: Advanced tracking for document interactions +- **Custom Events**: Track document downloads, views, searches +- **Privacy Compliance**: GDPR and privacy regulation compliance + +#### Google Tag Manager +- **Container ID**: GTM container identifier +- **Custom Variables**: Document metadata as GTM variables +- **Event Tracking**: Advanced event tracking through GTM +- **Third-party Integration**: Easy integration with other analytics tools + +#### Facebook Pixel +- **Pixel ID**: Facebook advertising pixel identifier +- **Conversion Tracking**: Track document interactions as conversions +- **Custom Audiences**: Build audiences based on document engagement +- **Privacy Controls**: Respect user privacy preferences + +## Theme System Integration + +### Built-in Theme Support + +#### Standard Themes +The system includes several pre-built themes from `themeList.js`: +- **biasa**: Default neutral theme with balanced colors +- **terang**: Light theme with bright, clean aesthetics +- **gelap**: Dark theme for reduced eye strain +- **biru**: Blue-dominant professional theme +- **hijau**: Green nature-inspired theme + +#### Accessibility Themes +Special themes from `themeList2.js` for enhanced accessibility: +- **high-contrast**: High contrast for visual impairments +- **large-text**: Increased font sizes for readability +- **color-blind**: Color-blind friendly color palettes +- **low-vision**: Optimized for users with low vision + +### Custom Theme Development + +#### Theme Structure +Custom themes follow CSS custom property structure: ```css -html[data-theme="your-theme-name"] { +html[data-theme="custom-theme-name"] { --color-primary: 255, 0, 0; --color-secondary: 0, 255, 0; --color-success: 0, 255, 0; --color-info: 0, 0, 255; --color-warning: 255, 255, 0; --color-danger: 255, 0, 0; - /* Add your theme variables here */ + --color-light: 248, 249, 250; + --color-dark: 33, 37, 41; + /* Additional custom properties */ } ``` -## Default Values -If no settings are configured, the system uses these defaults: -- Site Name: "corradAF" -- Site Description: "corradAF Base Project" -- Selected Theme: "biasa" -- Logo: Default corradAF logo -- Favicon: Default favicon +#### Color Variable System +- **RGB Values**: Colors defined as RGB triplets for alpha transparency support +- **Semantic Naming**: Colors named by purpose rather than appearance +- **Component Integration**: Variables used throughout Rs component system +- **Dark Mode Support**: Automatic dark mode variants -## Migration Notes -- Legacy color fields (primaryColor, secondaryColor, etc.) are maintained for backward compatibility -- `themeMode` field is mapped to `selectedTheme` for compatibility -- Existing installations will automatically use default values -- Theme selection integrates with existing theme dropdown in header +#### Theme File Management +- **Upload Location**: Custom themes saved to `assets/style/css/` +- **Integration Method**: Direct injection into `theme.css` file +- **Validation**: CSS syntax validation before integration +- **Backup**: Automatic backup before theme modifications -## Notes -- Changes are applied immediately in the preview -- Theme changes affect the entire application -- Custom CSS is injected into the document head -- Theme files are saved to `/assets/style/css/` for proper integration -- File uploads are validated for type and size -- Settings persist across browser sessions -- Site name and description updates are reflected globally and immediately -- All meta tags and SEO elements are automatically updated -- Logo changes are reflected in all components that use site settings +### Theme Switching Mechanism +- **Real-time Application**: Themes applied immediately without page refresh +- **Header Integration**: Theme selector synchronized with site settings +- **User Preferences**: Individual user theme preferences (if enabled) +- **Default Theme**: System-wide default theme setting -### Important Notes -- Changes are applied immediately in the preview -- Theme changes affect the entire application -- Custom CSS is injected into the document head -- Theme files are saved to `/assets/style/css/` for proper integration -- File uploads are validated for type and size -- Settings persist across browser sessions -- Site name and description updates are reflected globally and immediately -- All meta tags and SEO elements are automatically updated -- Logo changes are reflected in all components that use site settings \ No newline at end of file +## Advanced Customization + +### Custom CSS Injection + +#### Global CSS Override +- **Injection Point**: CSS inserted into document `` element +- **Priority**: Custom CSS has high specificity to override defaults +- **Validation**: Basic CSS syntax validation +- **Performance**: Minification and optimization of injected CSS + +#### Best Practices for Custom CSS +- **Specificity**: Use appropriate CSS specificity for overrides +- **Performance**: Minimize custom CSS for better performance +- **Maintenance**: Document custom CSS changes for future reference +- **Testing**: Test across different browsers and devices + +#### CSS Framework Integration +- **TailwindCSS Compatibility**: Custom CSS works alongside TailwindCSS +- **Component System**: Respect Rs component styling patterns +- **Responsive Design**: Ensure custom CSS is responsive +- **Dark Mode**: Consider dark mode implications + +### Custom Theme File Upload + +#### File Requirements +- **Format**: Standard CSS files (.css extension) +- **Size Limit**: 1MB maximum file size +- **Encoding**: UTF-8 encoding required +- **Syntax**: Valid CSS syntax required + +#### Integration Process +1. **File Upload**: Secure file upload to server +2. **Validation**: CSS syntax and security validation +3. **Integration**: Append to main theme.css file +4. **Backup**: Create backup of previous theme.css +5. **Application**: Theme immediately available for selection + +#### Security Considerations +- **Content Filtering**: Remove potentially dangerous CSS +- **Path Restrictions**: Prevent access to restricted file paths +- **Size Limits**: Prevent resource exhaustion attacks +- **Validation**: Comprehensive CSS validation + +## API Integration + +### Site Settings API Endpoints + +#### GET `/api/devtool/config/site-settings` +**Purpose**: Retrieve current site settings configuration + +**Response Format**: +```json +{ + "statusCode": 200, + "message": "Success", + "data": { + "siteName": "Custom EDMS", + "siteDescription": "Enterprise Document Management System", + "siteLogo": "/uploads/site-settings/logo.png", + "siteFavicon": "/uploads/site-settings/favicon.ico", + "selectedTheme": "professional-blue", + "customCSS": ".custom-header { background: #blue; }", + "seoTitle": "EDMS - Document Management", + "seoDescription": "Comprehensive document management solution", + "seoKeywords": "document, management, enterprise", + "seoGoogleAnalytics": "GA-XXXXXXXXX-X" + } +} +``` + +#### POST `/api/devtool/config/site-settings` +**Purpose**: Update site settings configuration + +**Request Format**: +```json +{ + "siteName": "Updated EDMS Name", + "siteDescription": "Updated description", + "selectedTheme": "dark-professional", + "customCSS": ".updated-styles { color: red; }", + "seoTitle": "Updated SEO Title" +} +``` + +**Features**: +- Partial updates supported (only changed fields required) +- Automatic validation of all input data +- File path validation for security +- Database persistence with timestamps + +#### POST `/api/devtool/config/upload-file` +**Purpose**: Secure file upload for logos and assets + +**Request Format**: Multipart form data with file and metadata + +**Response Format**: +```json +{ + "statusCode": 200, + "message": "File uploaded successfully", + "data": { + "filename": "uploaded-logo.png", + "path": "/uploads/site-settings/logo.png", + "size": 15420, + "type": "image/png" + } +} +``` + +**Security Features**: +- File type validation (images only for logos) +- File size limits enforcement +- Virus scanning integration +- Secure file storage with proper permissions + +#### POST `/api/devtool/config/add-custom-theme` +**Purpose**: Add custom theme directly to theme.css file + +**Request Format**: +```json +{ + "themeName": "custom-corporate", + "themeCSS": "html[data-theme=\"custom-corporate\"] { --color-primary: 0, 100, 200; }" +} +``` + +**Features**: +- CSS validation before integration +- Automatic backup of existing theme.css +- Immediate availability after integration +- Rollback capability if integration fails + +### Composable Integration + +#### useSiteSettings() Composable +The `useSiteSettings()` composable provides reactive state management: + +```javascript +const { + siteSettings, // Reactive settings object + loading, // Loading state + loadSiteSettings, // Load settings from API + updateSiteSettings, // Update settings + setTheme, // Apply theme changes + getCurrentTheme, // Get current theme + applyThemeSettings, // Apply theme to DOM + updateGlobalMeta, // Update meta tags + addCustomThemeToFile // Add custom theme +} = useSiteSettings(); +``` + +#### Real-time Updates +- **Reactive State**: Changes immediately reflected in UI +- **Global Sync**: Updates synchronized across all components +- **Meta Tag Updates**: SEO meta tags updated dynamically +- **Theme Application**: Theme changes applied without page refresh + +## Technical Implementation + +### Database Schema +Settings stored in `site_settings` table with comprehensive field structure: + +```sql +CREATE TABLE site_settings ( + settingID INT PRIMARY KEY AUTO_INCREMENT, + siteName VARCHAR(255) DEFAULT 'corradAF', + siteNameFontSize INT DEFAULT 18, + siteDescription TEXT, + siteLogo VARCHAR(500), + siteLoadingLogo VARCHAR(500), + siteFavicon VARCHAR(500), + siteLoginLogo VARCHAR(500), + showSiteNameInHeader BOOLEAN DEFAULT TRUE, + customCSS LONGTEXT, + themeMode VARCHAR(100) DEFAULT 'biasa', + customThemeFile VARCHAR(500), + currentFont VARCHAR(100), + fontSource VARCHAR(100), + seoTitle VARCHAR(255), + seoDescription TEXT, + seoKeywords TEXT, + seoAuthor VARCHAR(255), + seoOgImage VARCHAR(500), + seoTwitterCard VARCHAR(100) DEFAULT 'summary_large_image', + seoCanonicalUrl VARCHAR(500), + seoRobots VARCHAR(100) DEFAULT 'index, follow', + seoGoogleAnalytics VARCHAR(255), + seoGoogleTagManager VARCHAR(255), + seoFacebookPixel VARCHAR(255), + settingCreatedDate DATETIME DEFAULT CURRENT_TIMESTAMP, + settingModifiedDate DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP +); +``` + +### File System Integration +- **Upload Directory**: `public/uploads/site-settings/` +- **Theme Directory**: `assets/style/css/` +- **Backup Directory**: `backups/site-settings/` +- **Permission Management**: Proper file system permissions +- **Cleanup Procedures**: Automatic cleanup of unused files + +### Global Integration Points + +#### Header Component +- **Logo Display**: Dynamic logo from site settings +- **Site Name**: Configurable site name display +- **Theme Selector**: Synchronized theme selection +- **Brand Colors**: Applied from theme settings + +#### App.vue Global Configuration +- **Meta Tags**: Dynamically updated from settings +- **Title Management**: Global title prefix from site name +- **Theme Initialization**: Theme applied on app startup +- **Favicon**: Dynamic favicon from settings + +#### Loading Components +- **Branded Loading**: Custom loading logo +- **Brand Colors**: Theme colors in loading screens +- **Consistent Experience**: Uniform branding across all loading states + +## Best Practices + +### Branding Guidelines + +#### Logo Design +- **Vector Format**: Use SVG for scalability when possible +- **Optimization**: Optimize file sizes for web performance +- **Consistency**: Maintain consistent branding across all logos +- **Accessibility**: Ensure sufficient contrast for accessibility compliance + +#### Color Schemes +- **Brand Consistency**: Align with organizational brand guidelines +- **Accessibility**: Meet WCAG contrast requirements +- **Cultural Sensitivity**: Consider cultural color associations +- **Dark Mode Support**: Provide appropriate dark mode variants + +### SEO Optimization + +#### Content Strategy +- **Unique Descriptions**: Unique meta descriptions for better SEO +- **Keyword Research**: Use relevant keywords in meta tags +- **Regular Updates**: Keep SEO content current and relevant +- **Performance**: Optimize for page load speed + +#### Technical SEO +- **Structured Data**: Implement appropriate schema markup +- **Mobile Optimization**: Ensure mobile-friendly configuration +- **Page Speed**: Monitor and optimize loading times +- **Security**: Implement HTTPS and security headers + +### Performance Considerations + +#### File Optimization +- **Image Compression**: Compress logos and images appropriately +- **CSS Minification**: Minify custom CSS for better performance +- **Caching Strategy**: Implement appropriate caching headers +- **CDN Integration**: Consider CDN for static assets + +#### Theme Performance +- **Minimal CSS**: Keep custom themes lightweight +- **Variable Usage**: Use CSS custom properties efficiently +- **Browser Compatibility**: Test across different browsers +- **Fallback Support**: Provide fallbacks for older browsers + +### Security Best Practices + +#### File Upload Security +- **File Type Validation**: Strict file type checking +- **Size Limits**: Appropriate file size restrictions +- **Virus Scanning**: Implement virus scanning for uploads +- **Path Traversal**: Prevent directory traversal attacks + +#### CSS Security +- **Content Filtering**: Filter potentially dangerous CSS +- **XSS Prevention**: Prevent CSS-based XSS attacks +- **Input Validation**: Validate all CSS input thoroughly +- **Sanitization**: Sanitize user-provided CSS content + +## Troubleshooting + +### Common Issues + +#### Settings Not Saving +**Symptoms**: +- Changes revert after page refresh +- Error messages during save operations +- Loading indicators that don't complete + +**Resolution Steps**: +1. **Check Permissions**: Verify administrative access +2. **Network Issues**: Confirm stable internet connection +3. **Browser Console**: Check for JavaScript errors +4. **Server Status**: Verify server is operational +5. **Database Connection**: Check database connectivity + +#### Logos Not Displaying +**Symptoms**: +- Broken image icons instead of logos +- Default logos showing instead of custom ones +- Images not loading properly + +**Resolution Steps**: +1. **File Path**: Verify correct file paths in settings +2. **File Permissions**: Check server file permissions +3. **File Format**: Ensure supported image formats +4. **File Size**: Check if files exceed size limits +5. **Browser Cache**: Clear browser cache and reload + +#### Theme Not Applying +**Symptoms**: +- Theme selection not taking effect +- Colors not changing as expected +- Custom themes not available + +**Resolution Steps**: +1. **CSS Validation**: Check for CSS syntax errors +2. **Theme File**: Verify theme file integration +3. **Browser Compatibility**: Test with different browsers +4. **Cache Issues**: Clear browser and server cache +5. **CSS Conflicts**: Check for CSS specificity issues + +### Performance Issues + +#### Slow Loading +**Causes**: +- Large logo files +- Excessive custom CSS +- Network connectivity issues +- Server performance problems + +**Optimization**: +1. **Image Optimization**: Compress logo files +2. **CSS Optimization**: Minimize custom CSS +3. **Caching**: Implement proper caching strategies +4. **CDN**: Use content delivery networks +5. **Server Optimization**: Monitor server performance + +#### Memory Issues +**Symptoms**: +- Browser becoming unresponsive +- High memory usage +- Slow interface response + +**Resolution**: +1. **File Size**: Reduce logo file sizes +2. **CSS Efficiency**: Optimize CSS selectors +3. **Browser Update**: Use latest browser versions +4. **System Resources**: Monitor system memory +5. **Cache Management**: Regular cache clearing + +### Support Resources + +#### Documentation +- **Technical Guide**: Comprehensive system documentation +- **User Guide**: End-user documentation +- **API Documentation**: Developer integration guides +- **Change Log**: System updates and changes + +#### Contact Support +- **Internal IT**: Contact system administrators +- **Help Desk**: Organizational support procedures +- **Community**: User forums and knowledge bases +- **Vendor Support**: External support options + +#### Information to Provide +When reporting issues: +- **Error Messages**: Exact error text +- **Browser Information**: Browser type and version +- **Steps to Reproduce**: Detailed reproduction steps +- **Screenshots**: Visual documentation of issues +- **System Details**: Relevant configuration information + +This comprehensive guide provides complete coverage of the Site Settings system, enabling administrators to effectively customize and manage the visual appearance and global configuration of the EDMS application. \ No newline at end of file diff --git a/docs/Technical_Guide.md b/docs/Technical_Guide.md index b1e491b..4fb3c27 100644 --- a/docs/Technical_Guide.md +++ b/docs/Technical_Guide.md @@ -9,25 +9,28 @@ 6. [Development Environment](#development-environment) 7. [Component Structure](#component-structure) 8. [API & Data Management](#api--data-management) -9. [Security & Authentication](#security--authentication) -10. [Deployment](#deployment) -11. [Maintenance & Monitoring](#maintenance--monitoring) -12. [Extension & Customization](#extension--customization) +9. [DMS Settings System](#dms-settings-system) +10. [Site Settings Integration](#site-settings-integration) +11. [Security & Authentication](#security--authentication) +12. [Deployment](#deployment) +13. [Maintenance & Monitoring](#maintenance--monitoring) +14. [Extension & Customization](#extension--customization) ## System Overview -The Electronic Document Management System (EDMS) is a modern web application built with Nuxt.js 3 and Vue.js 3, designed to provide a comprehensive document management solution for organizations. The system implements a hierarchical document organization structure with role-based access control (RBAC) and supports integration with external authentication providers like Authentik. +The Electronic Document Management System (EDMS) is a modern web application built with Nuxt.js 3 and Vue.js 3, designed to provide a comprehensive document management solution for organizations. The system implements a hierarchical document organization structure with role-based access control (RBAC) and supports integration with external authentication providers. ### Key Technical Features - **Modern Frontend**: Vue.js 3 with Composition API and script setup syntax - **SSR/SPA Support**: Nuxt.js 3 for optimal performance and SEO -- **Database**: Prisma ORM with MySQL/PostgreSQL support and migrations -- **Styling**: TailwindCSS with custom component system +- **Database**: Prisma ORM with MySQL support and comprehensive schema +- **Styling**: TailwindCSS with custom Rs component system - **State Management**: Pinia for reactive state management with persistence - **Authentication**: Flexible authentication with JWT tokens and RBAC - **File Management**: Server-side file handling with metadata and versioning - **Real-time Features**: Vue reactivity for live updates and notifications - **Responsive Design**: Mobile-first approach with adaptive layouts +- **Configurable System**: Comprehensive settings management for DMS and site configuration ## Architecture @@ -35,12 +38,13 @@ The Electronic Document Management System (EDMS) is a modern web application bui ``` ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │ Frontend │ │ Backend │ │ Database │ -│ (Nuxt.js) │◄──►│ (Server API) │◄──►│ (MySQL/PG) │ +│ (Nuxt.js) │◄──►│ (Server API) │◄──►│ (MySQL) │ │ │ │ │ │ │ │ • Vue.js 3 │ │ • Prisma ORM │ │ • User Data │ │ • TailwindCSS │ │ • File System │ │ • Documents │ │ • Pinia Store │ │ • Authentication│ │ • Permissions │ -│ • Components │ │ • API Routes │ │ • Audit Logs │ +│ • Rs Components │ │ • API Routes │ │ • Audit Logs │ +│ • Settings UI │ │ • Settings API │ │ • DMS Settings │ └─────────────────┘ └─────────────────┘ └─────────────────┘ │ │ │ │ ┌─────────────────┐ │ @@ -55,12 +59,14 @@ The Electronic Document Management System (EDMS) is a modern web application bui ### Application Flow 1. **Authentication**: User authenticates via configured authentication provider 2. **Authorization**: System validates user permissions against RBAC rules -3. **Navigation**: User navigates document hierarchy with tree-based structure -4. **Data Fetching**: Pinia store manages API calls with caching and error handling -5. **Rendering**: Vue components render UI with reactive updates -6. **File Operations**: Server handles secure file upload/download/preview -7. **Access Control**: System enforces granular document permissions -8. **Audit Trail**: All actions are logged for compliance and security +3. **Configuration Loading**: System loads DMS and site settings from database +4. **Navigation**: User navigates document hierarchy with access level tabs +5. **Data Fetching**: Pinia store manages API calls with caching and error handling +6. **Rendering**: Vue components render UI with reactive updates +7. **File Operations**: Server handles secure file upload/download/preview +8. **Access Control**: System enforces granular document permissions +9. **Audit Trail**: All actions are logged for compliance and security +10. **Settings Management**: Administrators configure system behavior through settings UI ## Technology Stack @@ -136,832 +142,715 @@ The Electronic Document Management System (EDMS) is a modern web application bui model user { userID Int @id @default(autoincrement()) userSecretKey String? @db.VarChar(255) - userUsername String? @unique @db.VarChar(255) + userUsername String? @db.VarChar(255) userPassword String? @db.VarChar(255) userFullName String? @db.VarChar(255) - userEmail String? @unique @db.VarChar(255) + userEmail String? @db.VarChar(255) userPhone String? @db.VarChar(255) userStatus String? @db.VarChar(255) userCreatedDate DateTime? @default(now()) @db.DateTime(0) - userModifiedDate DateTime? @updatedAt @db.DateTime(0) + userModifiedDate DateTime? @db.DateTime(0) // Relationships + audit audit[] userrole userrole[] - accessRequests AccessRequest[] - permissions AccessPermission[] - documents Document[] @relation("DocumentCreator") - cabinets Cabinet[] @relation("CabinetCreator") - drawers Drawer[] @relation("DrawerCreator") - folders Folder[] @relation("FolderCreator") - subfolders Subfolder[] @relation("SubfolderCreator") } model role { roleID Int @id @default(autoincrement()) - roleName String @unique @db.VarChar(255) - roleDescription String? @db.Text - rolePermissions Json? // Flexible permissions structure - roleCreatedDate DateTime @default(now()) @db.DateTime(0) - roleModifiedDate DateTime @updatedAt @db.DateTime(0) + roleName String? @db.VarChar(255) + roleDescription String? @db.VarChar(255) + roleStatus String? @db.VarChar(255) + roleCreatedDate DateTime? @db.DateTime(0) + roleModifiedDate DateTime? @db.DateTime(0) userrole userrole[] - permissions AccessPermission[] +} + +model userrole { + userRoleID Int @id @default(autoincrement()) + userRoleUserID Int @default(0) + userRoleRoleID Int @default(0) + userRoleCreatedDate DateTime @db.DateTime(0) + + role role @relation(fields: [userRoleRoleID], references: [roleID]) + user user @relation(fields: [userRoleUserID], references: [userID]) } ``` -#### Document Hierarchy +#### Organization Structure ```prisma -// Cabinet → Drawer → Folder → Subfolder → Document - -model Cabinet { - id Int @id @default(autoincrement()) - name String @db.VarChar(255) - description String? @db.Text - metadata Json? // Flexible metadata storage - createdAt DateTime @default(now()) @db.DateTime(0) - updatedAt DateTime @updatedAt @db.DateTime(0) - createdBy Int - status String @default("active") @db.VarChar(50) +model organization { + org_id Int @id @default(autoincrement()) + org_name String @unique @db.VarChar(255) + org_address1 String? @db.VarChar(255) + org_address2 String? @db.VarChar(255) + org_postcode Int? + org_state String? @db.VarChar(100) + org_country String? @db.VarChar(100) + org_active Int? - user user @relation("CabinetCreator", fields: [createdBy], references: [userID]) - drawers Drawer[] - permissions AccessPermission[] - - @@index([createdBy]) - @@index([status]) + departments department[] } -model Document { - id Int @id @default(autoincrement()) - name String @db.VarChar(255) - description String? @db.Text - fileSize Int @default(0) - fileType String @db.VarChar(100) - fileExtension String @db.VarChar(20) - filePath String @db.VarChar(500) - thumbnailPath String? @db.VarChar(500) - checksum String? @db.VarChar(64) - version Int @default(1) - isTemplate Boolean @default(false) - isPublic Boolean @default(false) - metadata Json? // Custom metadata fields - tags String? @db.Text - folderId Int? - subfolderId Int? - createdAt DateTime @default(now()) @db.DateTime(0) - updatedAt DateTime @updatedAt @db.DateTime(0) - createdBy Int - status String @default("active") @db.VarChar(50) +model department { + dp_id Int @id @default(autoincrement()) + dp_name String @db.VarChar(255) + org_id Int - folder Folder? @relation("FolderDocuments", fields: [folderId], references: [id], onDelete: SetNull) - subfolder Subfolder? @relation("SubfolderDocuments", fields: [subfolderId], references: [id], onDelete: SetNull) - user user @relation("DocumentCreator", fields: [createdBy], references: [userID]) - accessRequests AccessRequest[] - permissions AccessPermission[] - versions DocumentVersion[] + organization organization @relation(fields: [org_id], references: [org_id]) + cabinets cabinets[] + users sys_user[] +} + +model cabinets { + cb_id Int @id @default(autoincrement()) + cb_name String @unique @db.VarChar(255) + cb_parent_id Int? + cb_private Int? @default(0) + cb_owner Int? + dp_id Int? + created_at DateTime? @db.DateTime(0) + modified_at DateTime? @db.DateTime(0) - @@index([folderId]) - @@index([subfolderId]) - @@index([createdBy]) - @@index([fileType]) - @@index([status]) - @@fulltext([name, description, tags]) + department department? @relation(fields: [dp_id], references: [dp_id]) } ``` -#### Access Control & Workflow +#### Site Settings Configuration ```prisma -model AccessPermission { - id Int @id @default(autoincrement()) - userId Int? - roleId Int? - documentId Int? - cabinetId Int? - drawerId Int? - folderId Int? - subfolderId Int? - permissionLevel String @db.VarChar(50) // view, download, print, edit, full, admin - conditions Json? // Additional permission conditions - createdAt DateTime @default(now()) @db.DateTime(0) - updatedAt DateTime @updatedAt @db.DateTime(0) - expiresAt DateTime? @db.DateTime(0) - createdBy Int? - - user user? @relation(fields: [userId], references: [userID], onDelete: SetNull) - role role? @relation(fields: [roleId], references: [roleID], onDelete: SetNull) - document Document? @relation(fields: [documentId], references: [id], onDelete: Cascade) - cabinet Cabinet? @relation(fields: [cabinetId], references: [id], onDelete: Cascade) - drawer Drawer? @relation(fields: [drawerId], references: [id], onDelete: Cascade) - folder Folder? @relation(fields: [folderId], references: [id], onDelete: Cascade) - subfolder Subfolder? @relation(fields: [subfolderId], references: [id], onDelete: Cascade) - - @@index([userId]) - @@index([roleId]) - @@index([documentId]) - @@index([expiresAt]) +model site_settings { + settingID Int @id @default(autoincrement()) + siteName String? @default("corradAF") @db.VarChar(255) + siteNameFontSize Int? @default(18) + siteDescription String? @db.Text + siteLogo String? @db.VarChar(500) + siteLoadingLogo String? @db.VarChar(500) + siteFavicon String? @db.VarChar(500) + siteLoginLogo String? @db.VarChar(500) + showSiteNameInHeader Boolean? @default(true) + customCSS String? @db.LongText + themeMode String? @default("biasa") @db.VarChar(100) + customThemeFile String? @db.VarChar(500) + currentFont String? @db.VarChar(100) + fontSource String? @db.VarChar(100) + seoTitle String? @db.VarChar(255) + seoDescription String? @db.Text + seoKeywords String? @db.Text + seoAuthor String? @db.VarChar(255) + seoOgImage String? @db.VarChar(500) + seoTwitterCard String? @default("summary_large_image") @db.VarChar(100) + seoCanonicalUrl String? @db.VarChar(500) + seoRobots String? @default("index, follow") @db.VarChar(100) + seoGoogleAnalytics String? @db.VarChar(255) + seoGoogleTagManager String? @db.VarChar(255) + seoFacebookPixel String? @db.VarChar(255) + settingCreatedDate DateTime? @default(now()) @db.DateTime(0) + settingModifiedDate DateTime? @default(now()) @db.DateTime(0) } +``` -model AccessRequest { - id Int @id @default(autoincrement()) - documentId Int - userId Int - requestedLevel String @db.VarChar(50) // view, download, print, edit, full - duration String? @db.VarChar(50) // 7d, 14d, 30d, 60d, 90d, permanent - justification String? @db.Text - status String @default("pending") @db.VarChar(50) // pending, approved, rejected, expired - responseNote String? @db.Text - requestedAt DateTime @default(now()) @db.DateTime(0) - respondedAt DateTime? @db.DateTime(0) - respondedBy Int? - expiresAt DateTime? @db.DateTime(0) +#### DMS Settings Configuration +```prisma +model dms_settings { + settingID Int @id @default(autoincrement()) - document Document @relation(fields: [documentId], references: [id], onDelete: Cascade) - user user @relation(fields: [userId], references: [userID]) + // User & Access Management + userRoles String? @db.Text + rbacEnabled Boolean? @default(true) + userGroups String? @db.Text + permissionView Boolean? @default(true) + permissionEdit Boolean? @default(true) + permissionDelete Boolean? @default(false) + permissionDownload Boolean? @default(true) + permissionShare Boolean? @default(true) + ssoEnabled Boolean? @default(false) + mfaRequired Boolean? @default(false) + ldapIntegration Boolean? @default(false) + sessionTimeout Int? @default(8) - @@index([documentId]) - @@index([userId]) - @@index([status]) + // Document & Folder Settings + folderMaxDepth Int? @default(5) + folderDefaultStructure String? @db.Text + folderTemplates String? @db.Text + namingAutoGenerate Boolean? @default(true) + namingMandatoryFields String? @db.Text + namingPattern String? @default("{department}_{title}_{date}") @db.VarChar(255) + retentionEnabled Boolean? @default(true) + retentionDefaultDays Int? @default(2555) + retentionArchiveBeforeDelete Boolean? @default(true) + versionControlEnabled Boolean? @default(true) + versionControlMaxVersions Int? @default(10) + versionControlAutoVersioning Boolean? @default(true) + + // Metadata & Tagging + metadataCustomFields String? @db.LongText + taggingPredefinedTags String? @db.Text + taggingUserGeneratedTags Boolean? @default(true) + taggingTagSuggestions Boolean? @default(true) + classificationAutoEnabled Boolean? @default(true) + classificationRules String? @db.Text + + // Workflow & Automation + workflowApprovalEnabled Boolean? @default(true) + workflowDefaultFlow String? @default("department-head-approval") @db.VarChar(255) + workflowCustomFlows String? @db.Text + notificationEmail Boolean? @default(true) + notificationInApp Boolean? @default(true) + notificationUploadAlerts Boolean? @default(true) + notificationDeadlineReminders Boolean? @default(true) + automationTriggers String? @db.Text + automationActions String? @db.Text + + // Upload & Storage Settings + uploadAllowedFileTypes String? @db.Text + uploadBlockedFileTypes String? @db.Text + uploadFileSizeLimit Int? @default(100) + uploadQuotaPerUser Int? @default(5000) + uploadQuotaPerGroup Int? @default(50000) + uploadQuotaPerProject Int? @default(100000) + storageType String? @default("local") @db.VarChar(100) + storagePath String? @default("/var/uploads/edms") @db.VarChar(500) + storageBackupEnabled Boolean? @default(true) + storageCompressionEnabled Boolean? @default(false) + + // System Settings + systemTimezone String? @default("Asia/Kuala_Lumpur") @db.VarChar(100) + systemBackupSchedule String? @default("daily") @db.VarChar(100) + systemLogLevel String? @default("info") @db.VarChar(100) + systemMaintenanceMode Boolean? @default(false) + systemAutoUpdates Boolean? @default(false) + systemMonitoring Boolean? @default(true) + systemPerformanceMetrics Boolean? @default(true) + + settingCreatedDate DateTime? @default(now()) @db.DateTime(0) + settingModifiedDate DateTime? @default(now()) @db.DateTime(0) +} +``` + +#### Audit Trail +```prisma +model audit { + auditID Int @id @default(autoincrement()) + auditIP String? @db.VarChar(255) + auditURL String? @db.VarChar(255) + auditURLMethod String? @db.VarChar(255) + auditURLPayload String? @db.Text + auditCreatedDate DateTime? @default(now()) @db.DateTime(0) + auditAction String? @db.VarChar(255) + auditDetails String? @db.Text + auditUserID Int? + auditUsername String? @db.VarChar(255) + + user user? @relation(fields: [auditUserID], references: [userID]) } ``` ## Installation & Setup ### Prerequisites -- Node.js 18+ and npm/yarn/pnpm +- Node.js 18+ with npm/yarn/pnpm - MySQL 8.0+ or PostgreSQL 13+ - Git for version control -- Optional: Docker for containerized deployment -### Installation Steps - -1. **Clone Repository** +### Environment Configuration +Create a `.env` file in the project root: ```bash -git clone -cd edms -``` - -2. **Install Dependencies** -```bash -# Using npm -npm install - -# Using yarn -yarn install - -# Using pnpm -pnpm install -``` - -3. **Environment Configuration** -Create `.env` file: -```env # Database Configuration DATABASE_URL="mysql://username:password@localhost:3306/edms_db" -# For PostgreSQL: DATABASE_URL="postgresql://username:password@localhost:5432/edms_db" -# Authentication -JWT_SECRET="your-jwt-secret-key-min-256-bits" -SESSION_SECRET="your-session-secret-key" - -# External Authentication (Optional) -AUTHENTIK_BASE_URL="https://auth.yourdomain.com" -AUTHENTIK_CLIENT_ID="your-client-id" -AUTHENTIK_CLIENT_SECRET="your-client-secret" +# Authentication Settings +JWT_SECRET="your-super-secret-jwt-key" +AUTH_PROVIDER="local" # or "authentik", "ldap" # File Storage UPLOAD_PATH="/var/uploads/edms" -TEMP_PATH="/var/tmp/edms" -MAX_FILE_SIZE="104857600" # 100MB in bytes -ALLOWED_FILE_TYPES="pdf,doc,docx,xls,xlsx,ppt,pptx,txt,jpg,jpeg,png,gif" +MAX_FILE_SIZE="100" # MB -# Application Configuration -NUXT_SECRET_KEY="your-nuxt-app-secret" -BASE_URL="http://localhost:3000" -NODE_ENV="development" - -# Security -CORS_ORIGIN="http://localhost:3000" -RATE_LIMIT_MAX="100" # requests per window -RATE_LIMIT_WINDOW="15" # minutes - -# Monitoring & Logging -LOG_LEVEL="info" -LOG_FILE="/var/log/edms/app.log" +# Application Settings +NUXT_SECRET_KEY="your-nuxt-secret-key" +NUXT_PUBLIC_API_BASE="/api" ``` -4. **Database Setup** +### Database Setup ```bash +# Install dependencies +npm install + # Generate Prisma client npx prisma generate -# Run database migrations +# Apply database migrations npx prisma db push # Seed initial data (optional) npx prisma db seed - -# View database in Prisma Studio (optional) -npx prisma studio ``` -5. **Development Server** +### Development Server ```bash # Start development server npm run dev -# Access application at http://localhost:3000 +# Access application +# http://localhost:3000 ``` -## Development Environment +## Component Structure -### Project Structure +### Frontend Architecture ``` -edms/ -├── components/ # Vue components -│ ├── dms/ # DMS-specific components -│ │ ├── explorer/ # Document explorer interface -│ │ ├── dialogs/ # Modal dialogs and forms -│ │ ├── viewers/ # Document preview components -│ │ └── navigation/ # Tree and breadcrumb navigation -│ ├── layouts/ # Layout components -│ ├── formkit/ # FormKit custom components -│ └── [Rs*].vue # Reusable UI components (RsButton, RsCard, etc.) -├── pages/ # Nuxt pages (file-based routing) -│ ├── dms/ # DMS-related pages -│ ├── dashboard/ # Dashboard and analytics -│ ├── login/ # Authentication pages -│ └── index.vue # Homepage -├── stores/ # Pinia state stores -│ ├── dms.js # Document management store -│ ├── auth.js # Authentication store -│ └── app.js # Global application store -├── middleware/ # Route middleware -│ ├── auth.js # Authentication middleware -│ └── rbac.js # Role-based access control -├── layouts/ # Nuxt layouts -│ ├── default.vue # Default application layout -│ └── auth.vue # Authentication layout -├── server/ # Server-side code -│ ├── api/ # API routes -│ └── middleware/ # Server middleware -├── prisma/ # Database configuration -│ ├── schema.prisma # Database schema -│ └── migrations/ # Database migrations -├── public/ # Static assets -├── assets/ # Build-time assets -├── plugins/ # Nuxt plugins -├── composables/ # Vue composables -└── utils/ # Utility functions +pages/ +├── dms/ +│ ├── index.vue # Main DMS interface with access level tabs +│ ├── settings.vue # Comprehensive DMS settings management +│ └── erd.vue # Entity Relationship Diagram viewer +├── index.vue # Dashboard/landing page +└── [...other pages] + +components/ +├── dms/ +│ └── explorer/ +│ └── DMSExplorer.vue # Document management interface +├── Rs/ # Reusable component system +│ ├── RsButton.vue +│ ├── RsCard.vue +│ ├── RsInput.vue +│ └── [...other components] +└── layouts/ + └── Breadcrumb.vue # Navigation breadcrumb component + +composables/ +├── useDmsSettings.js # DMS settings state management +├── useSiteSettings.js # Site configuration management +└── [...other composables] + +stores/ +├── dms.js # DMS-specific Pinia store +└── [...other stores] ``` -### Component Architecture +### Rs Component System +The EDMS uses a custom component library (Rs components) for consistent UI: +- **RsButton**: Standardized button component with variants +- **RsCard**: Card container with header/body/footer slots +- **RsInput**: Form input components with validation +- **RsModal**: Modal dialog components +- **RsTable**: Data table components with sorting/filtering -#### Core EDMS Components -1. **DMSExplorer.vue**: Main document browser with tree navigation, content views, and details panel -2. **DMSTreeView.vue**: Recursive tree navigation for hierarchical structure -3. **DMSDocumentViewer.vue**: Multi-format document viewer with zoom and controls -4. **DMSAccessRequestDialog.vue**: Access request form with approval workflow -5. **DMSUploadDialog.vue**: File upload interface with metadata assignment +## API & Data Management -#### Custom UI Components (Rs Prefix) -- **RsButton.vue**: Standardized button component with variants -- **RsCard.vue**: Container component with consistent styling -- **RsModal.vue**: Modal dialog base component -- **RsInput.vue**: Standardized input field component -- **RsSelect.vue**: Standardized dropdown/select component -- **RsTextarea.vue**: Standardized textarea component -- **RsTable.vue**: Data table with sorting and filtering -- **RsDropdown.vue**: Dropdown menu component - -## Design System - -### Overview -The EDMS implements a comprehensive design system built on a standardized component library with the "Rs" prefix (Reusable System). This ensures consistency, maintainability, and accessibility across the entire application. - -### Design Principles -- **🎯 Consistency**: All components follow unified design patterns and naming conventions -- **🔧 Modularity**: Components are reusable and composable for complex interfaces -- **🌙 Dark Mode**: Universal support for both light and dark themes via CSS variables -- **📱 Responsive**: Mobile-first approach with adaptive layouts -- **♿ Accessibility**: WCAG-compliant with proper ARIA attributes and keyboard navigation - -### Component Library - -#### Form Components - -##### RsInput.vue -```vue - +### API Route Structure +``` +server/api/ +├── dms/ +│ └── settings.js # DMS configuration API +├── devtool/ +│ └── config/ +│ ├── site-settings.js # Site settings API +│ ├── upload-file.js # File upload handling +│ └── add-custom-theme.js # Theme management +└── [...other API routes] ``` -**Props:** -- `modelValue`: String/Number - Input value -- `label`: String - Field label -- `placeholder`: String - Placeholder text -- `type`: String - Input type (text, email, password, etc.) -- `required`: Boolean - Required field indicator -- `error`: String - Error message -- `size`: String - Size variant (sm, md, lg) -- `disabled`: Boolean - Disabled state +### DMS Settings API +The DMS settings API provides comprehensive configuration management: -##### RsSelect.vue -```vue - -``` +#### GET `/api/dms/settings` +Retrieves current DMS settings with automatic defaults if none exist. -**Props:** -- `modelValue`: String/Number/Array - Selected value(s) -- `options`: Array - Options list (objects with value/label or simple strings) -- `label`: String - Field label -- `placeholder`: String - Placeholder text -- `multiple`: Boolean - Multiple selection support -- `required`: Boolean - Required field indicator -- `error`: String - Error message -- `disabled`: Boolean - Disabled state - -##### RsTextarea.vue -```vue - -``` - -**Props:** -- `modelValue`: String - Textarea content -- `label`: String - Field label -- `placeholder`: String - Placeholder text -- `rows`: Number - Number of visible rows -- `resize`: String - Resize behavior (none, both, horizontal, vertical) -- `required`: Boolean - Required field indicator -- `error`: String - Error message -- `disabled`: Boolean - Disabled state - -#### UI Components - -##### RsButton.vue -```vue - - Button Text - -``` - -**Variants:** -- `primary`: Blue primary button -- `secondary`: Gray secondary button -- `info`: Blue info button -- `success`: Green success button -- `warning`: Yellow warning button -- `danger`: Red danger button -- `primary-outline`: Outlined primary button -- `secondary-outline`: Outlined secondary button -- `primary-text`: Text-only primary button - -**Sizes:** -- `sm`: Small button (padding: 0.25rem 0.75rem) -- `md`: Medium button (padding: 0.5rem 1rem) -- `lg`: Large button (padding: 0.75rem 1.25rem) - -##### RsCard.vue -```vue - - - - - -``` - -##### RsModal.vue -```vue - - - - - -``` - -**Sizes:** -- `sm`: 300px width -- `md`: 500px width -- `lg`: 800px width -- `xl`: 1000px width -- `full`: Full screen width - -### Color System - -The design system uses CSS custom properties for consistent theming: - -```css -:root { - /* Primary Colors */ - --color-primary: 59 130 246; /* Blue */ - --color-secondary: 100 116 139; /* Gray */ - --color-info: 14 165 233; /* Sky Blue */ - --color-success: 34 197 94; /* Green */ - --color-warning: 251 191 36; /* Yellow */ - --color-danger: 239 68 68; /* Red */ - - /* Background Colors */ - --bg-1: 248 250 252; /* Light Gray */ - --bg-2: 255 255 255; /* White */ - - /* Text Colors */ - --text-color: 15 23 42; /* Slate 900 */ - --text-muted: 100 116 139; /* Slate 500 */ - - /* Border Colors */ - --border-color: 226 232 240; /* Slate 200 */ - --fk-border-color: 209 213 219; /* Gray 300 */ -} -``` - -### Typography Scale - -```css -/* Font Sizes */ -.text-xs { font-size: 0.75rem; } /* 12px */ -.text-sm { font-size: 0.875rem; } /* 14px */ -.text-base { font-size: 1rem; } /* 16px */ -.text-lg { font-size: 1.125rem; } /* 18px */ -.text-xl { font-size: 1.25rem; } /* 20px */ -.text-2xl { font-size: 1.5rem; } /* 24px */ -.text-3xl { font-size: 1.875rem; } /* 30px */ - -/* Font Weights */ -.font-light { font-weight: 300; } -.font-normal { font-weight: 400; } -.font-medium { font-weight: 500; } -.font-semibold { font-weight: 600; } -.font-bold { font-weight: 700; } -``` - -### Spacing Scale - -```css -/* Spacing (padding/margin) */ -.p-1 { padding: 0.25rem; } /* 4px */ -.p-2 { padding: 0.5rem; } /* 8px */ -.p-3 { padding: 0.75rem; } /* 12px */ -.p-4 { padding: 1rem; } /* 16px */ -.p-6 { padding: 1.5rem; } /* 24px */ -.p-8 { padding: 2rem; } /* 32px */ -``` - -### Usage Guidelines - -#### ✅ Best Practices -1. **Always use Rs components** for UI elements instead of custom styling -2. **Use semantic variants** (primary, secondary, danger) rather than color names -3. **Follow consistent spacing** using the predefined scale -4. **Use CSS variables** for colors instead of hardcoded values -5. **Test in both themes** (light and dark mode) -6. **Maintain accessibility** with proper labels and ARIA attributes - -#### ❌ Anti-patterns -1. **Don't use manual Tailwind classes** for buttons (e.g., `px-4 py-2 bg-blue-500`) -2. **Don't create custom input styling** without extending Rs components -3. **Don't hardcode colors** or spacing values -4. **Don't mix different component styling approaches** -5. **Don't forget dark mode** support in custom components - -### FormKit Integration - -The design system integrates with FormKit for advanced form handling: - -```javascript -// FormKit theme configuration -export default { - global: { - label: "formkit-label-global", - outer: "formkit-outer-global", - wrapper: "formkit-wrapper-global", - }, - button: { - wrapper: "formkit-wrapper-button", - input: "formkit-input-button", - }, - text: { - label: "formkit-outer-text", - inner: "formkit-inner-text", - input: "formkit-input-text", +**Response Structure:** +```json +{ + "statusCode": 200, + "message": "Success", + "data": { + "access": { + "userRoles": ["Admin", "Editor", "Viewer", "Uploader"], + "rbacEnabled": true, + "userGroups": ["HR Department", "Finance", "IT", "Legal"], + "permissions": { + "view": true, + "edit": true, + "delete": false, + "download": true, + "share": true + }, + "authentication": { + "ssoEnabled": false, + "mfaRequired": false, + "ldapIntegration": false, + "sessionTimeout": 8 + } + }, + "documents": { + "folderHierarchy": { + "maxDepth": 5, + "defaultStructure": ["Department", "Project", "Category", "Year"], + "folderTemplates": ["Standard", "Project-based", "Department-based"] + }, + "namingConventions": { + "autoGenerate": true, + "mandatoryFields": ["title", "department", "date"], + "pattern": "{department}_{title}_{date}" + }, + "retention": { + "enabled": true, + "defaultDays": 2555, + "archiveBeforeDelete": true + }, + "versionControl": { + "enabled": true, + "maxVersions": 10, + "autoVersioning": true + } + }, + "metadata": { + "customFields": [ + {"name": "Department", "type": "dropdown", "required": true}, + {"name": "Priority", "type": "select", "required": false} + ], + "tagging": { + "predefinedTags": ["urgent", "confidential", "public", "draft", "final"], + "userGeneratedTags": true, + "tagSuggestions": true + }, + "classification": { + "autoClassification": true, + "rules": ["confidential-keywords", "department-based", "file-type"] + } + }, + "workflow": { + "approvalFlows": { + "enabled": true, + "defaultFlow": "department-head-approval", + "customFlows": ["legal-review", "finance-approval", "director-sign-off"] + }, + "notifications": { + "emailNotifications": true, + "inAppNotifications": true, + "uploadAlerts": true, + "deadlineReminders": true + }, + "automation": { + "triggers": ["document-uploaded", "approval-completed", "deadline-reached"], + "actions": ["move-to-folder", "send-notification", "create-task"] + } + }, + "upload": { + "fileTypes": { + "allowed": ["pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "txt", "jpg", "png"], + "blocked": ["exe", "bat", "cmd"] + }, + "fileSizeLimit": 100, + "quotas": { + "perUser": 5000, + "perGroup": 50000, + "perProject": 100000 + }, + "storage": { + "type": "local", + "path": "/var/uploads/edms", + "backupEnabled": true, + "compressionEnabled": false + } + }, + "system": { + "timezone": "Asia/Kuala_Lumpur", + "backupSchedule": "daily", + "logLevel": "info", + "maintenanceMode": false, + "autoUpdates": false, + "systemMonitoring": true, + "performanceMetrics": true + } } } ``` -### Component Registration +#### POST `/api/dms/settings` +Updates DMS settings with validation and automatic database creation. -All Rs components are globally registered via the component index: +**Request Body:** Complete or partial settings object +**Response:** Success confirmation with updated data +### Data Transformation +The API handles transformation between frontend structure and database format: +- **Arrays to Strings**: Converts arrays like `userRoles` to comma-separated strings for database storage +- **Nested Objects**: Flattens nested frontend structure to database columns +- **Type Conversion**: Handles boolean/integer conversions between frontend and database +- **Default Values**: Provides sensible defaults for undefined settings + +## DMS Settings System + +### Overview +The DMS Settings system provides comprehensive configuration management for all aspects of the document management system. Administrators can customize user access, document handling, metadata management, workflows, upload settings, and system configuration through an intuitive web interface. + +### Settings Categories + +#### 1. User & Access Management +- **User Roles**: Define custom roles (Admin, Editor, Viewer, Uploader, etc.) +- **RBAC Configuration**: Enable/disable role-based access control +- **User Groups**: Organize users into departments or teams +- **Permissions**: Granular control over view, edit, delete, download, and share permissions +- **Authentication**: SSO, MFA, and LDAP integration settings +- **Session Management**: Configure session timeout periods + +#### 2. Document & Folder Settings +- **Folder Hierarchy**: Configure maximum depth and default structure +- **Naming Conventions**: Automatic name generation with customizable patterns +- **Document Retention**: Set retention policies and archive settings +- **Version Control**: Enable versioning with configurable version limits +- **Folder Templates**: Predefined folder structures for different use cases + +#### 3. Metadata & Tagging +- **Custom Fields**: Define custom metadata fields with types (text, dropdown, date, etc.) +- **Tagging System**: Manage predefined tags and user-generated tags +- **Tag Suggestions**: Enable intelligent tag suggestions +- **Auto-Classification**: Configure automatic document classification rules + +#### 4. Workflow & Automation +- **Approval Flows**: Configure document approval workflows +- **Notifications**: Email and in-app notification settings +- **Automation Triggers**: Define triggers for automated actions +- **Custom Workflows**: Create department-specific approval processes + +#### 5. Upload & Storage Settings +- **File Type Restrictions**: Allowed and blocked file types +- **Size Limits**: Maximum file size and storage quotas +- **Storage Configuration**: Local storage or cloud storage settings +- **Backup Settings**: Automatic backup and compression options + +#### 6. System Settings +- **Timezone Configuration**: System-wide timezone settings +- **Backup Schedules**: Automated backup frequency +- **Monitoring**: System monitoring and performance metrics +- **Maintenance Mode**: Enable/disable maintenance mode +- **Logging**: Configure system log levels + +### Settings Interface Features + +#### Tabbed Navigation +- **Organized Categories**: Six main categories with intuitive icons +- **Active Indicators**: Visual feedback for the current tab +- **Color-Coded Icons**: Each category has a distinct color scheme + +#### Form Management +- **Real-time Updates**: Changes are reflected immediately in the UI +- **Validation**: Client-side and server-side validation +- **Loading States**: Visual feedback during save operations +- **Error Handling**: Comprehensive error messages with auto-dismiss + +#### Dynamic Fields +- **Add/Remove Roles**: Dynamic management of user roles +- **Custom Field Builder**: Add/remove custom metadata fields with type selection +- **Array Management**: Tag lists and file type lists with comma-separated input + +#### Import/Export Functionality +- **JSON Export**: Export complete settings as JSON for backup +- **JSON Import**: Import settings from backup files +- **Settings Migration**: Easy transfer between environments + +#### Reset to Defaults +- **One-Click Reset**: Reset all settings to default values +- **Confirmation Dialog**: Prevent accidental resets +- **Selective Reset**: Reset individual categories (future enhancement) + +### Implementation Details + +#### Composable Pattern ```javascript -// pages/devtool/code-playground/index.js -export { - RsAlert, - RsBadge, - RsButton, - RsCard, - RsInput, - RsModal, - RsSelect, - RsTextarea, - RsTable, - // ... other components -}; +// useDmsSettings.js provides: +const { + dmsSettings, // Reactive settings object + loading, // Loading state + saving, // Saving state + loadDmsSettings, // Load from API + updateDmsSettings, // Save to API + resetToDefaults, // Reset functionality + exportSettings, // Export as JSON + importSettings, // Import from JSON + getSetting, // Get individual setting + updateSetting // Update individual setting +} = useDmsSettings(); ``` -### Design System Documentation +#### Database Integration +- **Automatic Creation**: Settings table created automatically if not exists +- **Upsert Operations**: Update existing or create new settings +- **Default Values**: Sensible defaults for all configuration options +- **Data Transformation**: Automatic conversion between frontend and database formats -Access the interactive design system documentation at `/dms/design-system` to: -- View all components with live examples -- Test different variants and states -- Copy code snippets for implementation -- Understand usage guidelines and best practices +#### Error Handling +- **API Errors**: Graceful handling of network and server errors +- **Validation Errors**: Client-side validation with user-friendly messages +- **Fallback Values**: Default settings if API fails +- **Retry Mechanisms**: Automatic retry for failed operations -### Future Enhancements +## Site Settings Integration -Planned design system improvements: -- **Animation Library**: Consistent micro-interactions and transitions -- **Icon System**: Standardized icon library with consistent sizing -- **Layout Components**: Grid and flexbox utilities -- **Advanced Form Components**: Date pickers, multi-select, autocomplete -- **Data Visualization**: Chart and graph components -- **Notification System**: Toast and alert components +### Comprehensive Branding System +The site settings system allows complete customization of the application appearance: -## API & Data Management +#### Basic Configuration +- **Site Name**: Global application name with font size control +- **Site Description**: SEO and meta tag descriptions +- **Theme Selection**: Choose from standard and accessibility themes -### Server API Routes +#### Branding Assets +- **Site Logo**: Custom logo for header and sidebar +- **Loading Logo**: Branding for loading screens +- **Favicon**: Custom browser icon +- **Login Logo**: Dedicated login page branding -#### Document Management -```javascript -// server/api/dms/documents/[id].get.js -export default defineEventHandler(async (event) => { - const id = getRouterParam(event, 'id') - // Fetch document with access control -}) +#### Advanced Customization +- **Custom CSS**: Inject custom styles globally +- **Custom Themes**: Upload and manage custom theme files +- **Font Configuration**: Custom font selection and sources -// server/api/dms/upload.post.js -export default defineEventHandler(async (event) => { - // Handle file upload with validation -}) +#### SEO Integration +- **Meta Tags**: Complete SEO meta tag management +- **Open Graph**: Social media sharing optimization +- **Twitter Cards**: Twitter-specific meta tags +- **Analytics**: Google Analytics and Tag Manager integration -// server/api/dms/search.get.js -export default defineEventHandler(async (event) => { - const query = getQuery(event) - // Perform document search -}) -``` - -#### Access Control -```javascript -// server/api/dms/access-request.post.js -export default defineEventHandler(async (event) => { - // Process access requests -}) - -// server/api/dms/permissions/[id].get.js -export default defineEventHandler(async (event) => { - // Get user permissions for item -}) -``` - -### Data Validation - -#### Prisma Schema Validation -- Field constraints and types -- Relationship integrity -- Index optimization - -#### Frontend Validation -```javascript -// FormKit validation rules -const documentValidation = { - title: 'required|length:3,255', - description: 'length:0,1000', - fileType: 'required|in:pdf,doc,docx,xls,xlsx,jpg,png', - accessLevel: 'required|in:public,private,personal' -} -``` +### Global Application Integration +Site settings are integrated throughout the application: +- **Header Component**: Dynamic logo and name display +- **Loading Screen**: Branded loading experience +- **Document Title**: Dynamic page titles +- **Theme System**: Synchronized theme selection ## Security & Authentication -### Authentication Flow -1. **User Login**: Redirect to Authentik -2. **Token Exchange**: Receive JWT token -3. **Token Validation**: Verify on each request -4. **Session Management**: Store in secure cookie -5. **Token Refresh**: Automatic renewal +### Authentication Methods +- **Local Authentication**: Username/password with bcrypt hashing +- **JWT Tokens**: Secure token-based authentication +- **Session Management**: Configurable session timeouts +- **Multi-Factor Authentication**: Optional MFA support +- **LDAP Integration**: Enterprise directory integration +- **SSO Support**: Single Sign-On capabilities -### Authorization Levels -- **System Admin**: Full system access -- **Department Admin**: Department-wide permissions -- **Document Owner**: Full access to owned documents -- **User**: Access based on granted permissions +### Authorization & RBAC +- **Role-Based Access Control**: Granular permission system +- **Dynamic Permissions**: Configurable permission sets +- **Resource-Level Security**: Document-level access control +- **Access Request Workflow**: Formal access request process +- **Audit Trail**: Comprehensive activity logging -### File Security -- **Path Traversal Protection**: Validate file paths -- **File Type Validation**: Whitelist allowed formats -- **Size Limits**: Prevent large file uploads -- **Virus Scanning**: Optional integration -- **Access Logging**: Track file access - -### Data Protection -- **SQL Injection Prevention**: Parameterized queries via Prisma -- **XSS Protection**: Input sanitization -- **CSRF Protection**: Token validation -- **Secure Headers**: Security-focused HTTP headers +### Data Security +- **Input Validation**: Server-side validation for all inputs +- **SQL Injection Prevention**: Prisma ORM parameter binding +- **XSS Protection**: Content Security Policy and input sanitization +- **File Upload Security**: File type validation and virus scanning +- **Encryption**: Data encryption at rest and in transit ## Deployment -### Production Build +### Production Environment ```bash # Build for production npm run build -# Generate static files (if needed) -npm run generate +# Start production server +npm run start -# Preview production build -npm run preview -``` - -### Environment Configuration - -#### Production Environment Variables -```env +# Environment configuration NODE_ENV=production -DATABASE_URL="mysql://prod_user:password@db.server:3306/edms_prod" +DATABASE_URL="mysql://user:pass@host:port/db" NUXT_SECRET_KEY="production-secret-key" -BASE_URL="https://dms.jkr-kotabharu.gov.my" ``` -#### Docker Deployment +### Docker Deployment ```dockerfile FROM node:18-alpine - WORKDIR /app COPY package*.json ./ RUN npm ci --only=production - COPY . . RUN npm run build - EXPOSE 3000 -CMD ["npm", "run", "start"] +CMD ["npm", "start"] ``` -### Nginx Configuration -```nginx -server { - listen 80; - server_name dms.jkr-kotabharu.gov.my; - - location / { - proxy_pass http://localhost:3000; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - } - - location /uploads/ { - alias /var/www/uploads/; - expires 1y; - } -} +### Database Migrations +```bash +# Apply schema changes +npx prisma db push + +# Generate migration files +npx prisma migrate dev --name init + +# Apply migrations in production +npx prisma migrate deploy ``` ## Maintenance & Monitoring ### Database Maintenance -```sql --- Regular maintenance queries -OPTIMIZE TABLE document; -ANALYZE TABLE access_permission; +- **Backup Strategies**: Automated database backups +- **Performance Monitoring**: Query optimization and indexing +- **Data Retention**: Configurable document retention policies +- **Archive Management**: Automated archiving of old documents --- Cleanup old access requests -DELETE FROM access_request -WHERE status = 'rejected' -AND requested_at < DATE_SUB(NOW(), INTERVAL 30 DAY); -``` +### System Monitoring +- **Performance Metrics**: Configurable system monitoring +- **Error Tracking**: Comprehensive error logging +- **Audit Logs**: User activity and system event logging +- **Health Checks**: API endpoint health monitoring -### Backup Strategy -- **Database Backups**: Daily automated backups -- **File Storage Backups**: Incremental file backups -- **Configuration Backups**: Version control for configs - -### Monitoring -- **Application Performance**: Response times, error rates -- **Database Performance**: Query performance, connection counts -- **File Storage**: Disk usage, file integrity -- **Security Events**: Failed logins, access violations - -### Logging -```javascript -// Server-side logging -import { createLogger } from 'winston' - -const logger = createLogger({ - level: 'info', - format: winston.format.json(), - transports: [ - new winston.transports.File({ filename: 'error.log', level: 'error' }), - new winston.transports.File({ filename: 'combined.log' }) - ] -}) -``` +### Update Management +- **Automated Updates**: Optional automatic system updates +- **Version Control**: Database schema versioning +- **Rollback Procedures**: Safe rollback mechanisms +- **Testing Procedures**: Comprehensive testing protocols ## Extension & Customization -### Adding New Document Types -1. Update Prisma schema with new file types -2. Add validation rules for the file type -3. Implement viewer component for the format -4. Update upload dialog to support the type - -### Custom Access Control -1. Extend AccessPermission model -2. Implement custom permission logic -3. Update UI to reflect new permissions -4. Add admin interface for permission management - -### Integration Points -- **External Authentication**: LDAP/Active Directory -- **Document Processing**: OCR, text extraction -- **Workflow Systems**: Approval workflows -- **Notification Systems**: Email/SMS notifications -- **Analytics**: Document usage analytics +### Custom Components +The Rs component system allows easy customization: +```vue + +``` ### API Extensions +Add custom API endpoints: ```javascript -// Custom API endpoint example -// server/api/custom/analytics.get.js +// server/api/custom/endpoint.js export default defineEventHandler(async (event) => { - // Custom analytics logic - return { - totalDocuments: count, - storageUsed: size, - activeUsers: userCount - } -}) + // Custom logic here + return { message: "Custom API response" }; +}); ``` ### Theme Customization -```javascript -// tailwind.config.js extensions -module.exports = { - theme: { - extend: { - colors: { - primary: { - 50: '#eff6ff', - 500: '#3b82f6', - 900: '#1e3a8a' - } - } - } - } +Create custom themes: +```css +html[data-theme="custom-theme"] { + --color-primary: 255, 0, 0; + --color-secondary: 0, 255, 0; + /* Custom variables */ } ``` ---- +### Plugin Development +Extend functionality with Nuxt plugins: +```javascript +// plugins/custom-plugin.client.js +export default defineNuxtPlugin(() => { + // Client-side plugin logic +}); +``` -**Document Version**: 2.0 -**Last Updated**: December 2024 -**System Version**: EDMS v1.0 -**Technology Stack**: Nuxt.js 3, Vue.js 3, Prisma, TailwindCSS -**Database**: MySQL/PostgreSQL -**Authentication**: JWT with optional external providers \ No newline at end of file +### Settings Extensions +The DMS settings system is designed for extensibility: +- **Custom Setting Categories**: Add new configuration sections +- **Validation Rules**: Custom validation for settings +- **Setting Computed Properties**: Derived settings based on other values +- **Setting Watchers**: React to setting changes automatically + +This technical guide provides comprehensive coverage of the EDMS system architecture, implementation details, and customization options. The system is designed for scalability, maintainability, and extensibility while providing a robust document management solution. \ No newline at end of file diff --git a/docs/User_Guide.md b/docs/User_Guide.md index 466eb36..cf0d07c 100644 --- a/docs/User_Guide.md +++ b/docs/User_Guide.md @@ -4,13 +4,13 @@ 1. [Introduction](#introduction) 2. [Getting Started](#getting-started) 3. [Navigation](#navigation) -4. [Document Organization](#document-organization) -5. [Working with Documents](#working-with-documents) -6. [Access Control](#access-control) -7. [Search and Filtering](#search-and-filtering) -8. [Document Viewer](#document-viewer) -9. [My Documents](#my-documents) -10. [Settings Administration](#settings-administration) +4. [DMS Interface](#dms-interface) +5. [Access Level System](#access-level-system) +6. [Document Organization](#document-organization) +7. [Working with Documents](#working-with-documents) +8. [DMS Settings (Administrators)](#dms-settings-administrators) +9. [Search and Filtering](#search-and-filtering) +10. [Document Viewer](#document-viewer) 11. [Troubleshooting](#troubleshooting) ## Introduction @@ -18,9 +18,10 @@ The Electronic Document Management System (EDMS) is a modern web-based platform designed to efficiently organize, store, and manage digital documents in organizational environments. The system provides a secure, hierarchical structure for document storage with comprehensive role-based access control and advanced document management capabilities. ### Key Features -- **Hierarchical Organization**: Documents are organized in a Cabinet → Drawer → Folder → Subfolder structure +- **Access Level Organization**: Documents categorized as All, Public, Private, and Personal with color-coded tabs +- **Hierarchical Structure**: Documents organized in a Cabinet → Drawer → Folder → Subfolder structure - **Multiple View Modes**: List, Grid, and Details views for browsing documents -- **Access Control**: Public, Private, and Personal document categories with granular permission management +- **Advanced Settings Management**: Comprehensive configuration system for administrators - **Document Viewer**: Built-in viewer supporting multiple file formats (PDF, images, text files, spreadsheets) - **Search Functionality**: Advanced search across document titles, descriptions, and metadata - **Upload Management**: Drag-and-drop file upload with comprehensive metadata assignment @@ -55,27 +56,32 @@ The main dashboard provides: ### Main Navigation Menu Access the EDMS through the main navigation menu: - **Dashboard**: System overview and quick access to recent items -- **DMS**: Main document management interface -- **My Documents**: Personal document collection and workspace -- **Upload Document**: Dedicated document upload interface +- **DMS**: Main document management interface with access level tabs +- **DMS Settings**: Administrative configuration panel (admin only) +- **ERD**: Entity Relationship Diagram viewer for system structure ### EDMS Interface Layout -The EDMS interface consists of three main areas: +The EDMS interface consists of several main areas: -1. **Tree Navigation (Left Panel)** +1. **Access Level Tabs (Top)** + - **All Documents**: Complete view of all accessible documents (blue folder icon) + - **Public**: Documents available to all users (green unlock icon) + - **Private**: Restricted documents requiring special permissions (red lock icon) + - **Personal**: Individual user documents (purple user icon) + +2. **Tree Navigation (Left Panel - when available)** - Hierarchical view of cabinets, drawers, and folders - Expandable/collapsible folder structure - Color-coded access indicators for different permission levels - Lock icons for restricted items requiring special access -2. **Content Area (Center)** +3. **Content Area (Center)** - Document listing with multiple view modes (List, Grid, Details) - Breadcrumb navigation showing current location - Search and filter tools for finding documents - View mode controls and sorting options - - Document tabs for filtering by access type -3. **Details Panel (Optional Right Panel)** +4. **Details Panel (Optional Right Panel)** - Document properties and metadata information - Quick actions and document tools - Access control information and permissions @@ -87,6 +93,82 @@ The EDMS interface consists of three main areas: - Helps maintain orientation in deep folder structures - Displays full path from root to current location +## DMS Interface + +### Access Level Tabs +The main DMS interface features a modern tabbed design for easy navigation between different document categories: + +#### All Documents Tab +- **Icon**: Blue folder icon +- **Purpose**: Shows all documents you have permission to access +- **Color Scheme**: Blue theme with active indicator +- **Use Case**: Comprehensive view for finding any accessible document + +#### Public Tab +- **Icon**: Green unlock icon +- **Purpose**: Displays documents accessible to all system users +- **Color Scheme**: Green theme indicating open access +- **Use Case**: Company policies, public announcements, shared resources + +#### Private Tab +- **Icon**: Red lock icon +- **Purpose**: Shows restricted documents requiring special permissions +- **Color Scheme**: Red theme indicating restricted access +- **Use Case**: Confidential documents, sensitive information, executive files + +#### Personal Tab +- **Icon**: Purple user icon +- **Purpose**: Displays your personal documents and private workspace +- **Color Scheme**: Purple theme indicating personal ownership +- **Use Case**: Individual workspace, draft documents, personal files + +### Visual Design Features +- **Active Tab Indicators**: Current tab highlighted with "Active" badge +- **Hover Effects**: Smooth transitions when hovering over tabs +- **Loading States**: Visual feedback during system operations +- **Error Handling**: Clear error messages with retry options + +## Access Level System + +### Understanding Access Levels + +#### Public Documents +- **Accessibility**: Visible and accessible to all system users +- **Visual Indicator**: Green color theme with unlock icon +- **Permissions**: No special permissions or approvals required +- **Best For**: + - Company policies and procedures + - Public announcements + - Shared templates and forms + - General information documents + +#### Private Documents +- **Accessibility**: Restricted access requiring specific permissions +- **Visual Indicator**: Red color theme with lock icon +- **Permissions**: May require access request and approval workflow +- **Best For**: + - Confidential business information + - HR records and sensitive data + - Financial documents + - Executive communications + - Legal documents + +#### Personal Documents +- **Accessibility**: Documents owned and controlled by individual users +- **Visual Indicator**: Purple color theme with user icon +- **Permissions**: Full control over sharing and access +- **Best For**: + - Individual workspace documents + - Draft documents before publication + - Personal notes and references + - Work-in-progress files + +### Access Level Switching +- Click any access level tab to filter documents by that category +- Visual feedback shows which tab is currently active +- Document count may vary between tabs based on your permissions +- Some tabs may be empty if no documents exist in that category + ## Document Organization ### Hierarchical Structure @@ -106,8 +188,9 @@ Documents are organized in a four-level hierarchy designed for maximum flexibili ### Visual Indicators The system uses color coding and icons to indicate access levels: - **Green**: Public documents (open access for all users) -- **Blue**: Personal documents (owned by you) +- **Blue**: All accessible documents (comprehensive view) - **Red**: Private documents (restricted access) +- **Purple**: Personal documents (owned by you) - **Lock Icon**: Documents you cannot currently access - **Template Icon**: Document templates available for use @@ -117,7 +200,7 @@ The system uses color coding and icons to indicate access levels: #### Single File Upload 1. Navigate to the desired location in the hierarchy -2. Click the "Upload" button or use the dedicated "Upload Document" page +2. Click the "Upload" button or use the dedicated upload interface 3. Select file(s) using the file picker or drag-and-drop interface 4. Fill in comprehensive document metadata: - Document title and description @@ -136,16 +219,17 @@ The system uses color coding and icons to indicate access levels: 5. Review and confirm successful uploads ### Document Metadata -For each document, you can specify comprehensive metadata: +For each document, you can specify comprehensive metadata based on system configuration: - **Title**: Descriptive document name/title - **Description**: Brief summary of document content and purpose - **Keywords**: Search terms for improved discoverability (comma-separated) -- **Category**: Document type (Technical Specification, Contract, Report, Policy, etc.) +- **Category**: Document type (configurable in DMS settings) - **Status**: Current state (Draft, Under Review, Approved, Archived, etc.) - **Department**: Responsible department or team - **Access Level**: Determines who can view and interact with the document - **Retention Period**: How long the document should be retained - **Version**: Document version number and change notes +- **Custom Fields**: Additional metadata fields as configured by administrators ### Viewing Documents 1. Click on any document to view its details and metadata @@ -158,392 +242,218 @@ For each document, you can specify comprehensive metadata: - **Move Documents**: Drag and drop to reorganize into different locations - **Delete Documents**: Remove documents with confirmation and audit trail - **Copy Documents**: Duplicate documents to multiple locations -- **Version Control**: Track document versions and view change history +- **Version Control**: Track document versions and view change history (if enabled) - **Share Documents**: Generate sharing links and manage access permissions -## Access Control - -### Understanding Access Levels - -#### Public Documents -- Visible and accessible to all system users -- No special permissions or approvals required -- Green color indicator for easy identification -- Suitable for general information and policies - -#### Private Documents -- Restricted access requiring specific permissions -- Red color indicator with lock icon -- May require access request and approval workflow -- Ideal for sensitive or confidential information - -#### Personal Documents -- Documents owned and controlled by individual users -- Blue color indicator showing ownership -- Full control over sharing and permissions -- Private workspace for individual document management - -### Requesting Access -When you encounter a private document you cannot access: - -1. **Identify Restricted Item**: Look for red color coding and lock icon -2. **Initiate Access Request**: Click the "Request Access" button -3. **Complete Request Form**: - - **Document Information**: Pre-filled with document title and file details - - **Access Type**: Choose appropriate permission level: - - View Only: Read-only access to document content - - Download: View and download permissions for offline access - - Print: View and print permissions for physical copies - - Full Access: Complete access rights including editing - - **Access Duration**: Select appropriate timeframe: - - 7 days, 14 days, 30 days, 60 days, 90 days, or Permanent - - **Justification**: Detailed explanation of why access is needed (required field) -4. **Submit Request**: Click "Submit Request" to send for approval -5. **Monitor Status**: Track request status and wait for approval from document owner or administrator - -### Access Request Status -- **Pending**: Request submitted and awaiting review by approvers -- **Approved**: Access granted for specified duration and permission level -- **Rejected**: Request denied with explanation from approver -- **Expired**: Previously approved access has reached its expiration date - -## Search and Filtering - -### Basic Search -1. Use the search box in the top navigation bar -2. Enter keywords, document titles, or content descriptions -3. Press Enter or click the search icon to execute search -4. Results display with matching documents and highlighted search terms -5. Refine results using additional filters and sorting options - -### Advanced Search Options -- **Filter by Type**: Documents, folders, cabinets, or specific file formats -- **Filter by Category**: Technical, Administrative, Financial, HR, etc. -- **Filter by Date Range**: Creation date, modification date, or access date -- **Filter by Owner**: Documents by specific users or departments -- **Filter by Access Level**: Public, private, personal, or template documents -- **Filter by Status**: Draft, approved, archived, or under review -- **Filter by File Format**: PDF, Word, Excel, images, etc. - -### Search Tips for Better Results -- Use quotation marks for exact phrase matching -- Combine multiple keywords with spaces for broader results -- Search includes document titles, descriptions, metadata, and content (where supported) -- Use wildcards (*) for partial word matching -- Utilize Boolean operators (AND, OR, NOT) for complex searches - -### Document Tabs for Quick Filtering -Filter documents by category using convenient tabs: -- **All**: Display all accessible documents in current location -- **Public**: Show only public documents available to all users -- **Private**: Display private documents you have access to -- **Personal**: Show your personal documents and workspace items - -## Document Viewer - -### Supported File Formats -The built-in document viewer supports multiple formats: -- **PDF Documents**: Full preview with zoom, navigation, and text selection -- **Images**: JPG, PNG, GIF, BMP with zoom and pan functionality -- **Text Files**: TXT, RTF with formatted preview and search -- **Microsoft Office**: DOC, DOCX, XLS, XLSX, PPT, PPTX (basic preview) -- **Other Formats**: Download option provided for unsupported formats - -### Viewer Features and Controls -- **Zoom Controls**: Zoom in/out from 25% to 400% for optimal readability -- **Page Navigation**: Navigate through multi-page documents with thumbnails -- **Full Screen Mode**: Maximize viewer for immersive document experience -- **Download Function**: Save document locally for offline access -- **Print Support**: Print document directly from viewer interface -- **Search in Document**: Find specific text within document content -- **Rotation Controls**: Rotate document pages for better viewing - -### Viewer Interface Controls -- **Zoom Options**: 25%, 50%, 75%, 100%, 125%, 150%, 200%, Fit to Width, Fit to Page -- **Navigation**: Previous/Next page buttons, page number input, thumbnail sidebar -- **View Options**: Single page, continuous scroll, two-page spread -- **Tools**: Text selection, annotation tools (if enabled), measurement tools -- **Close**: Return to document list or previous view - -## My Documents - -### Personal Document Workspace -The "My Documents" section provides a personalized workspace showing: -- Documents you've created and own -- Documents you've recently accessed or modified -- Documents shared with you by other users -- Recent document activity and version history -- Personal folders and organizational structure - -### Organization and Management Features -- **Quick Search**: Search specifically within your personal documents -- **Sort Options**: Sort by name, date created, date modified, file type, or size -- **View Modes**: Switch between list, grid, or detailed view layouts -- **Bulk Actions**: Select and manage multiple documents simultaneously -- **Folder Creation**: Create personal folders for document organization -- **Favorites**: Mark frequently used documents for quick access - -### Personal Document Statistics and Insights -View comprehensive information about your document usage: -- Total number of documents owned and accessible -- Storage space used and available quota -- Recent upload activity and document creation trends -- Document categories and type distribution -- Most accessed documents and usage patterns - -## Settings Administration +## DMS Settings (Administrators) ### Overview -The EDMS Settings module provides administrators with comprehensive control over system configuration and behavior. Access to settings is restricted to users with administrative privileges and affects system-wide operations. +Administrators have access to comprehensive DMS settings through the **DMS Settings** page, allowing complete customization of the document management system behavior. -### Accessing Settings -1. Navigate to **DMS** → **Settings** from the main navigation menu -2. Select a settings category from the left sidebar navigation -3. Configure settings within each category using standardized form components -4. Save changes to apply configurations across the system +### Accessing DMS Settings +1. Navigate to **DMS** → **Settings** in the main menu +2. Requires administrative privileges to access +3. Settings are organized into six main categories with tabbed navigation ### Settings Categories -The EDMS settings are organized into 5 core categories for streamlined administration: +#### 1. User & Access Management 🔐 +- **User Roles**: Define and manage custom user roles (Admin, Editor, Viewer, Uploader, etc.) +- **Access Permissions**: Configure granular permissions for view, edit, delete, download, and share +- **Authentication Settings**: + - Enable/disable Single Sign-On (SSO) + - Require Multi-Factor Authentication (MFA) + - LDAP/Active Directory integration + - Session timeout configuration (1-24 hours) -#### 🔐 User & Access Management -Configure user permissions, roles, and authentication settings: +#### 2. Document & Folder Settings 📁 +- **Naming Conventions**: + - Auto-generate document names + - Configure naming patterns (e.g., `{department}_{title}_{date}`) + - Set mandatory fields for document metadata +- **Version Control**: + - Enable/disable document versioning + - Set maximum number of versions to retain + - Configure automatic versioning behavior -**User Roles & Permissions** -- Define user roles (Admin, Editor, Viewer, Uploader) -- Set granular permissions for each role: - - View Documents: Read-only access to document content - - Edit Documents: Modify document metadata and properties - - Delete Documents: Remove documents with audit trail - - Download Documents: Save documents for offline access - - Share Documents: Generate sharing links and manage access -- Manage user groups by department or project -- Enable Role-Based Access Control (RBAC) system-wide +#### 3. Metadata & Tagging 📝 +- **Custom Metadata Fields**: + - Add/remove custom fields (text, dropdown, date, number, multi-select) + - Set required fields for document uploads + - Configure field types and validation rules +- **Tagging System**: + - Manage predefined tags (urgent, confidential, public, draft, final, etc.) + - Enable/disable user-generated tags + - Configure tag suggestions and auto-completion -**Authentication Settings** -- Single Sign-On (SSO) integration with external providers -- Multi-Factor Authentication (MFA) enforcement -- LDAP/Active Directory integration for enterprise environments -- Session timeout configuration (1-24 hours) -- Password policies and security requirements +#### 4. Workflow & Automation 🔄 +- **Approval Workflows**: + - Enable/disable approval workflows + - Configure default approval flow (department-head-approval, legal-review, etc.) + - Set up custom approval processes +- **Notifications**: + - Email notifications for document activities + - In-app notifications and alerts + - Upload alerts and deadline reminders -#### 📁 Document & Folder Settings -Configure document organization and structure: +#### 5. Upload & Storage Settings 📤 +- **File Type Management**: + - Allowed file types (pdf, doc, docx, xls, xlsx, ppt, pptx, txt, jpg, png, etc.) + - Blocked file types (exe, bat, cmd, etc.) + - Configure MIME type validation +- **Storage Quotas**: + - Maximum file size limit (MB) + - Per-user storage quota + - Per-group storage quota + - Per-project storage quota -**Folder Hierarchy** -- Set maximum folder depth (1-10 levels) -- Choose default folder structure templates: - - Standard: General-purpose organization - - Project-based: Project-focused hierarchy - - Department-based: Organizational structure alignment - - Custom: User-defined structure -- Configure folder creation permissions and restrictions - -**Document Naming Conventions** -- Enable automatic document name generation -- Define mandatory metadata fields for document creation -- Set naming patterns using variables: - - `{department}`: Document department/owner - - `{title}`: Document title or name - - `{date}`: Creation or upload date - - `{project}`: Project code or identifier - - `{category}`: Document category/type - -**Document Retention & Version Control** -- Enable document retention policies with configurable retention periods -- Set automatic archiving before deletion -- Configure version control system: - - Maximum versions to retain (1-50) - - Automatic versioning on document updates - - Version history tracking and comparison tools - -#### 📝 Metadata & Tagging -Configure document metadata and classification: - -**Custom Metadata Fields** -Define custom fields for enhanced document organization: -- Field types: Text, Dropdown, Date, Number, Multi-select -- Required field enforcement for document uploads -- Department-specific metadata schemas -- Dynamic field validation and formatting rules - -**Predefined Metadata Fields** -- Department: Organizational unit assignment -- Priority: Document importance level (Low, Medium, High, Critical) -- Project Code: Project or initiative identifier -- Review Date: Scheduled review or expiration date - -**Tagging System** -- Configure predefined tags: urgent, confidential, public, draft, final -- Enable user-generated tags for flexible categorization -- Tag suggestion system for consistent tagging -- Auto-classification based on: - - Keyword recognition in document content - - Department-based classification rules - - File type and format analysis - -#### 📤 Upload & Storage Settings -Configure file upload restrictions and storage management: - -**File Type Management** -- **Allowed File Types**: Specify permitted file formats - - Default: pdf, doc, docx, xls, xlsx, ppt, pptx, txt, jpg, png - - Configurable list for organizational requirements -- **Blocked File Types**: Prevent potentially harmful files - - Default: exe, bat, cmd (executable files) - - Customizable blacklist for security compliance - -**File Size & Storage Quotas** -- Maximum file size per upload (typically 100MB) -- User storage quotas (default: 5GB per user) -- Group storage quotas (default: 50GB per group) -- Project storage quotas (default: 100GB per project) -- System-wide storage monitoring and alerts - -**Storage Configuration** -- Storage type selection (Local, AWS S3, Azure, Google Cloud) -- Storage path configuration for file organization -- Backup settings and automated backup scheduling -- Compression settings for storage optimization - -#### 📅 System Settings -Configure global system behavior and preferences: - -**General System Configuration** -- **System Timezone**: Set default timezone for timestamps - - Options: Asia/Kuala_Lumpur, UTC, America/New_York, Europe/London - - Affects document timestamps, scheduling, and user interface -- **Backup Schedule**: Configure automated system backups - - Options: Hourly, Daily, Weekly, Monthly - - Affects data protection and recovery capabilities -- **Log Level**: Set system logging verbosity - - Options: Debug, Info, Warning, Error - - Affects troubleshooting and system monitoring - -**System Monitoring & Maintenance** -- **Maintenance Mode**: Enable system-wide maintenance mode - - Displays maintenance message to users - - Restricts access during system updates -- **Automatic Updates**: Configure automatic system updates - - Security patches and feature updates - - Scheduled during low-usage periods -- **System Monitoring**: Enable performance monitoring - - Track system performance metrics - - Monitor user activity and system health - - Generate usage reports and analytics +#### 6. System Settings 📅 +- **General Configuration**: + - System timezone (Asia/Kuala_Lumpur, UTC, etc.) + - Backup schedule (hourly, daily, weekly, monthly) + - System log level (debug, info, warning, error) +- **System Maintenance**: + - Enable/disable maintenance mode + - Configure automatic updates + - System monitoring and performance metrics ### Settings Management Features -#### Import/Export Configuration -- **Export Settings**: Save current configuration as JSON file - - Backup settings before major changes - - Transfer settings between environments - - Documentation and compliance purposes -- **Import Settings**: Load configuration from JSON file - - Restore previous configurations - - Deploy settings across multiple systems - - Standardize configurations across environments +#### Save & Load Settings +- **Auto-save**: Settings are saved immediately when modified +- **Loading States**: Visual feedback during save operations +- **Error Handling**: Clear error messages if save fails +- **Success Confirmation**: Confirmation messages with auto-dismiss + +#### Import/Export Functionality +- **Export Settings**: Download complete settings as JSON file for backup +- **Import Settings**: Upload JSON file to restore settings +- **Settings Migration**: Easy transfer between environments +- **Backup Management**: Regular backups of configuration #### Reset to Defaults -- **Category Reset**: Reset individual setting categories to default values -- **System Reset**: Reset entire system configuration to factory defaults -- **Selective Reset**: Choose specific settings to reset while preserving others +- **One-click Reset**: Reset all settings to system defaults +- **Confirmation Dialog**: Prevents accidental resets +- **Selective Reset**: Reset individual setting categories (future enhancement) +- **Default Values**: Sensible defaults for all configuration options -#### Settings Validation -- **Real-time Validation**: Form validation prevents invalid configurations -- **Dependency Checking**: Settings are validated for interdependencies -- **Conflict Resolution**: System identifies and resolves setting conflicts -- **Preview Mode**: Test settings before applying system-wide +#### Dynamic Field Management +- **Add Custom Fields**: Create new metadata fields with validation +- **Remove Fields**: Delete unused custom fields +- **Reorder Fields**: Arrange custom fields in preferred order +- **Field Types**: Support for text, dropdown, date, number, and multi-select fields -### Best Practices for Settings Management +### Configuration Best Practices -#### Security Considerations -- Regularly review user permissions and access levels -- Enable MFA for administrative accounts -- Use strong session timeout values for security -- Regularly audit user roles and group memberships +#### Security Settings +- Enable MFA for sensitive environments +- Configure appropriate session timeouts +- Set up proper user roles and permissions +- Regularly review access control settings #### Storage Management -- Monitor storage quotas and usage patterns -- Implement retention policies for compliance -- Regular backup verification and testing -- Plan for storage scaling based on usage growth +- Set realistic file size limits based on storage capacity +- Configure appropriate quotas for users and groups +- Enable compression for large files when possible +- Set up regular backup schedules -#### System Performance -- Monitor log levels to balance debugging needs with performance -- Schedule maintenance during off-peak hours -- Regular cleanup of temporary files and old versions -- Performance monitoring for system optimization +#### Workflow Optimization +- Configure approval workflows based on organizational structure +- Enable relevant notifications to keep users informed +- Set up appropriate retention policies +- Configure automatic tagging rules for efficiency -#### Documentation & Compliance -- Document all configuration changes with justification -- Maintain change logs for audit purposes -- Regular export of settings for backup and documentation -- Review settings for compliance with organizational policies +## Search and Filtering -### Troubleshooting Settings Issues +### Search Functionality +- **Global Search**: Search across all accessible documents +- **Tab-Specific Search**: Search within specific access level tabs +- **Keyword Search**: Search document titles, descriptions, and metadata +- **Advanced Filters**: Filter by date, document type, department, etc. -#### Common Settings Problems -- **Permission Conflicts**: Resolve conflicting role assignments -- **Upload Failures**: Check file type restrictions and size limits -- **Authentication Issues**: Verify SSO and authentication settings -- **Storage Problems**: Monitor quotas and storage allocation +### Search Tips +- Use quotation marks for exact phrase searches +- Combine multiple keywords for more specific results +- Use the predefined tags for quick filtering +- Take advantage of custom metadata fields for precise searches -#### Settings Recovery -- Use exported settings files to restore configurations -- Reset specific categories if issues persist -- Contact system administrator for complex configuration issues -- Review audit logs for recent configuration changes +## Document Viewer + +### Supported File Types +The built-in document viewer supports: +- **PDF Documents**: Full PDF viewing with zoom and navigation +- **Microsoft Office**: Word, Excel, PowerPoint documents +- **Images**: JPG, PNG, GIF, and other common image formats +- **Text Files**: Plain text, CSV, and other text-based formats + +### Viewer Features +- **Zoom Controls**: Zoom in/out for better readability +- **Page Navigation**: Navigate through multi-page documents +- **Full Screen Mode**: Distraction-free document viewing +- **Download Option**: Download documents for offline access +- **Print Support**: Direct printing from the viewer ## Troubleshooting -### Common Issues and Solutions +### Common Issues -#### Cannot Access Document -- **Check Access Level**: Verify document permissions and look for lock icons -- **Request Access**: Use the access request feature for private documents -- **Contact Administrator**: Reach out for urgent access needs or system issues -- **Verify Account Status**: Ensure your user account is active and properly configured +#### Documents Not Loading +1. Check your internet connection +2. Verify you have permission to access the document +3. Try refreshing the page or switching tabs +4. Contact administrator if the issue persists -#### Upload Problems -- **File Size Limits**: Check maximum file size restrictions (typically 50MB) -- **File Format Support**: Ensure file format is supported by the system -- **Network Connection**: Verify stable internet connection for large uploads -- **Upload Permissions**: Confirm you have upload permissions for the target location -- **Browser Issues**: Try clearing cache or using a different browser +#### Upload Failures +1. Check file size limits (configured in DMS settings) +2. Verify file type is allowed (check blocked file types in settings) +3. Ensure you have upload permissions in current location +4. Try uploading one file at a time if bulk upload fails -#### Search Not Working Properly -- **Check Spelling**: Verify search terms are spelled correctly -- **Try Alternative Keywords**: Use different or broader search terms -- **Clear Active Filters**: Remove any filters that might be limiting results -- **Refresh Application**: Reload the page to reset search functionality -- **Check Indexing Status**: Some documents may take time to be indexed for search +#### Search Not Working +1. Clear browser cache and cookies +2. Try different search terms or keywords +3. Check if you're searching in the correct access level tab +4. Verify documents exist in the location you're searching -#### Document Viewer Issues -- **Browser Compatibility**: Ensure you're using a supported modern browser -- **Enable JavaScript**: Verify JavaScript is enabled in browser settings -- **Clear Browser Cache**: Clear cache and cookies to resolve display issues -- **Plugin Requirements**: Install any required browser plugins for specific file types -- **Download Alternative**: Use download option if viewer is not functioning +#### Access Denied Errors +1. Verify you have appropriate permissions for the document/folder +2. Check if the document is in the correct access level category +3. Request access from document owner or administrator +4. Contact administrator if permissions seem incorrect -### Getting Help and Support -- **Contact IT Support**: Reach out to technical support for system issues -- **Check System Status**: Verify overall system availability and maintenance schedules -- **User Training**: Request additional training sessions for advanced features -- **Documentation**: Refer to technical guide for detailed system information -- **Community Resources**: Access user forums and knowledge bases if available +### Performance Issues -### Best Practices for Optimal System Use -1. **Systematic Organization**: Create and maintain clear, logical folder structures -2. **Descriptive Naming**: Use meaningful, descriptive document titles and filenames -3. **Regular Maintenance**: Periodically review and clean up outdated documents -4. **Backup Strategy**: Keep local copies of critical documents as backup -5. **Consistent Conventions**: Follow organizational naming and filing conventions -6. **Metadata Accuracy**: Keep document metadata current and accurate -7. **Access Control Respect**: Follow organizational policies for document sharing and access -8. **Version Management**: Use version control features to track document changes -9. **Security Awareness**: Be mindful of document sensitivity and appropriate access levels -10. **Regular Updates**: Stay informed about system updates and new features +#### Slow Loading +1. Check internet connection speed +2. Clear browser cache and temporary files +3. Close unnecessary browser tabs +4. Contact administrator about server performance + +#### Browser Compatibility +- Use modern browsers (Chrome 70+, Firefox 65+, Safari 12+, Edge 79+) +- Enable JavaScript in browser settings +- Update browser to latest version +- Disable conflicting browser extensions + +### Getting Help + +#### Contact Information +- **System Administrator**: Contact your IT department +- **User Support**: Check internal documentation or help desk +- **Technical Issues**: Report to system administrator with: + - Error messages (exact text) + - Steps to reproduce the issue + - Browser and version information + - Screenshots if applicable + +#### Best Practices +- **Regular Backups**: Keep local copies of important documents +- **Organize Properly**: Use consistent naming and folder structures +- **Tag Documents**: Use relevant tags for easy searching +- **Stay Updated**: Keep track of system updates and new features +- **Follow Security**: Use strong passwords and follow access control policies + +This user guide provides comprehensive coverage of the EDMS interface and functionality, designed to help users effectively navigate and utilize the document management system. The system is designed for ease of use while providing powerful document management capabilities. --- diff --git a/navigation/index.js b/navigation/index.js index 494a709..52b99f3 100644 --- a/navigation/index.js +++ b/navigation/index.js @@ -4,30 +4,61 @@ export default [ "description": "Document Management System", "child": [ { - "title": "ERD", - "path": "/dms/erd", - "icon": "material-symbols:database-sharp", - "child": [], - "meta": {} - }, - { - "title": "Document Management", + "title": "Document Explorer", "path": "/dms", "icon": "ic:outline-folder", "child": [], "meta": {} }, { - "title": "Access Requests", - "path": "/dms/access-requests", - "icon": "ic:outline-security", + "title": "Admin Dashboard", + "path": "/dms/admin-dashboard", + "icon": "material-symbols:dashboard", + "child": [], + "meta": { + "auth": { + "role": ["admin", "superadmin"] + } + } + }, + { + "title": "Access Management", + "path": "/dms/access-management", + "icon": "ic:baseline-security", + "child": [], + "meta": { + "auth": { + "role": ["admin", "superadmin"] + } + } + }, + { + "title": "Role Management", + "path": "/dms/role-management", + "icon": "mdi:account-key", + "child": [], + "meta": { + "auth": { + "role": ["superadmin"] + } + } + }, + { + "title": "Switch Role", + "path": "/dms/switch-roles", + "icon": "ic:outline-swap-horiz", "child": [] }, { "title": "Settings", "path": "/dms/settings", "icon": "ic:outline-settings", - "child": [] + "child": [], + "meta": { + "auth": { + "role": ["admin", "superadmin"] + } + } } ], "meta": {} @@ -99,7 +130,7 @@ export default [ "meta": { "auth": { "role": [ - "Developer" + "superadmin" ] } } diff --git a/pages/devtool/code-playground/index.js b/pages/devtool/code-playground/index.js index c03c820..fc98745 100644 --- a/pages/devtool/code-playground/index.js +++ b/pages/devtool/code-playground/index.js @@ -8,14 +8,11 @@ import RsCollapseItem from "../../../components/RsCollapseItem.vue"; import RsDropdown from "../../../components/RsDropdown.vue"; import RsDropdownItem from "../../../components/RsDropdownItem.vue"; import RsFieldset from "../../../components/RsFieldset.vue"; -import RsInput from "../../../components/RsInput.vue"; import RsModal from "../../../components/RsModal.vue"; import RsProgressBar from "../../../components/RsProgressBar.vue"; -import RsSelect from "../../../components/RsSelect.vue"; import RsTab from "../../../components/RsTab.vue"; import RsTabItem from "../../../components/RsTabItem.vue"; import RsTable from "../../../components/RsTable.vue"; -import RsTextarea from "../../../components/RsTextarea.vue"; import RsWizard from "../../../components/RsWizard.vue"; export { @@ -29,13 +26,10 @@ export { RsDropdown, RsDropdownItem, RsFieldset, - RsInput, RsModal, RsProgressBar, - RsSelect, RsTab, RsTabItem, RsTable, - RsTextarea, RsWizard, }; diff --git a/pages/dms/access-management.vue b/pages/dms/access-management.vue new file mode 100644 index 0000000..400838a --- /dev/null +++ b/pages/dms/access-management.vue @@ -0,0 +1,236 @@ + + + + + \ No newline at end of file diff --git a/pages/dms/admin-dashboard.vue b/pages/dms/admin-dashboard.vue new file mode 100644 index 0000000..b1b1f4d --- /dev/null +++ b/pages/dms/admin-dashboard.vue @@ -0,0 +1,541 @@ + + + + + \ No newline at end of file diff --git a/pages/dms/check-role.vue b/pages/dms/check-role.vue new file mode 100644 index 0000000..dff13c5 --- /dev/null +++ b/pages/dms/check-role.vue @@ -0,0 +1,127 @@ + + + + + \ No newline at end of file diff --git a/pages/dms/design-system.vue b/pages/dms/design-system.vue deleted file mode 100644 index 48bca0c..0000000 --- a/pages/dms/design-system.vue +++ /dev/null @@ -1,277 +0,0 @@ - - - - - \ No newline at end of file diff --git a/pages/dms/index.vue b/pages/dms/index.vue index 2b9a359..9576981 100644 --- a/pages/dms/index.vue +++ b/pages/dms/index.vue @@ -1,8 +1,9 @@ @@ -167,34 +146,195 @@ onMounted(() => { @@ -211,16 +351,81 @@ onMounted(() => { height: 100%; } -.explorer-container { +.content-area { min-height: 0; + overflow: hidden; } -/* Ensure smooth transitions */ -.tabs-header button { - transition: all 0.2s ease; +.dms-content { + height: 100%; } -.tabs-header button:hover { +.access-tabs { + flex-shrink: 0; +} + +.access-tab { + position: relative; + overflow: hidden; +} + +.access-tab:hover { transform: translateY(-1px); } + +.access-tab.active { + transform: translateY(-2px); + box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); +} + +/* Dynamic color classes */ +.bg-blue-100 { background-color: rgb(219 234 254); } +.text-blue-700 { color: rgb(29 78 216); } +.border-blue-200 { border-color: rgb(191 219 254); } +.text-blue-600 { color: rgb(37 99 235); } +.bg-blue-100 { background-color: rgb(219 234 254); } +.text-blue-800 { color: rgb(30 64 175); } + +.bg-green-100 { background-color: rgb(220 252 231); } +.text-green-700 { color: rgb(21 128 61); } +.border-green-200 { border-color: rgb(187 247 208); } +.text-green-600 { color: rgb(22 163 74); } +.text-green-800 { color: rgb(22 101 52); } + +.bg-red-100 { background-color: rgb(254 226 226); } +.text-red-700 { color: rgb(185 28 28); } +.border-red-200 { border-color: rgb(254 202 202); } +.text-red-600 { color: rgb(220 38 38); } +.text-red-800 { color: rgb(153 27 27); } + +.bg-purple-100 { background-color: rgb(243 232 255); } +.text-purple-700 { color: rgb(126 34 206); } +.border-purple-200 { border-color: rgb(233 213 255); } +.text-purple-600 { color: rgb(147 51 234); } +.text-purple-800 { color: rgb(107 33 168); } + +/* Dark mode colors */ +.dark .bg-blue-900\/20 { background-color: rgba(30, 58, 138, 0.2); } +.dark .text-blue-300 { color: rgb(147 197 253); } +.dark .border-blue-800 { border-color: rgb(30 64 175); } +.dark .text-blue-400 { color: rgb(96 165 250); } +.dark .bg-blue-900\/30 { background-color: rgba(30, 58, 138, 0.3); } + +.dark .bg-green-900\/20 { background-color: rgba(20, 83, 45, 0.2); } +.dark .text-green-300 { color: rgb(134 239 172); } +.dark .border-green-800 { border-color: rgb(22 101 52); } +.dark .text-green-400 { color: rgb(74 222 128); } +.dark .bg-green-900\/30 { background-color: rgba(20, 83, 45, 0.3); } + +.dark .bg-red-900\/20 { background-color: rgba(127, 29, 29, 0.2); } +.dark .text-red-300 { color: rgb(252 165 165); } +.dark .border-red-800 { border-color: rgb(153 27 27); } +.dark .text-red-400 { color: rgb(248 113 113); } +.dark .bg-red-900\/30 { background-color: rgba(127, 29, 29, 0.3); } + +.dark .bg-purple-900\/20 { background-color: rgba(88, 28, 135, 0.2); } +.dark .text-purple-300 { color: rgb(196 181 253); } +.dark .border-purple-800 { border-color: rgb(107 33 168); } +.dark .text-purple-400 { color: rgb(168 85 247); } +.dark .bg-purple-900\/30 { background-color: rgba(88, 28, 135, 0.3); } \ No newline at end of file diff --git a/pages/dms/role-management.vue b/pages/dms/role-management.vue new file mode 100644 index 0000000..d3dc971 --- /dev/null +++ b/pages/dms/role-management.vue @@ -0,0 +1,585 @@ + + + + + \ No newline at end of file diff --git a/pages/dms/settings.vue b/pages/dms/settings.vue index 713252f..797fe9f 100644 --- a/pages/dms/settings.vue +++ b/pages/dms/settings.vue @@ -1,5 +1,5 @@