Compare commits

..

1 Commits
main ... prod

Author SHA1 Message Date
1047e5826d add all untracked and modified files 2025-05-29 16:14:53 +08:00
29 changed files with 16580 additions and 12209 deletions

70
.gitignore vendored
View File

@ -8,48 +8,14 @@ dist
# Node dependencies
node_modules
# Package manager files
package-lock.json
pnpm-lock.yaml
# Logs
*.log
logs/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Coverage directory used by tools like istanbul
coverage/
*.lcov
# nyc test coverage
.nyc_output
# Misc
.DS_Store
.fleet
.idea
# Editor directories and files
.vscode/settings.json
.vscode/launch.json
.vscode/extensions.json
*.swp
*.swo
*~
# OS generated files
Thumbs.db
ehthumbs.db
Desktop.ini
# Local env files
.env
.env.*
@ -57,39 +23,3 @@ Desktop.ini
# Uploads directory
public/uploads/
# Development and testing files
test-*.md
fixes-*.md
debug-*.md
*-debug.*
*-test.*
# Temporary files
*.tmp
*.temp
.tmp/
.temp/
# Database files
*.sqlite
*.sqlite3
*.db
# IDE and editor files
.project
.classpath
.settings/
*.sublime-*
.brackets.json
*.code-workspace
# Backup files
*.bak
*.backup
*~
.#*
# Documentation drafts (keep main docs)
draft-*.md
notes-*.md

3
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,3 @@
{
"vue3snippets.enable-compile-vue-file-on-did-save-code": true
}

211
README.md
View File

@ -1,214 +1,45 @@
# corradAF - Corrad Application Framework
# Nuxt 3 Minimal Starter
Welcome to **corradAF**, a comprehensive Nuxt.js template designed for rapid application development. This framework provides a solid foundation with essential development tools, authentication system, and modern UI components.
Look at the [nuxt 3 documentation](https://v3.nuxtjs.org) to learn more.
## 🚀 Features
## Setup
- **🔐 Complete Authentication System** - Login, Register, Password Recovery, Logout
- **👥 User Management** - User and role management with CRUD operations
- **🛠️ Development Tools Suite** - Comprehensive set of dev tools for rapid development
- **🎨 Modern UI Components** - Built with TailwindCSS and custom components
- **📱 Responsive Design** - Mobile-first approach with modern UX patterns
- **🔧 API Management** - Built-in API endpoint design and testing tools
- **📝 Content Management** - Dynamic content and template management
- **🎯 Menu Configuration** - Easy navigation structure management
- **💻 Code Playground** - In-browser code testing and prototyping
- **🗄️ ORM Integration** - Database schema management tools
- **⚙️ Configuration Management** - System settings and environment setup
## 🛠️ Development Tools Included
### User Management
- User CRUD operations
- Role-based access control
- Permission management
### Menu Editor
- Dynamic navigation configuration
- Hierarchical menu structure
- Permission-based menu visibility
### API Editor
- Design and test API endpoints
- Interactive API documentation
- Request/response testing
### Content Editor
- Dynamic content management
- Template editing
- Content versioning
### Code Playground
- Real-time code testing
- Multiple language support
- Instant preview
### ORM Tools
- Database schema management
- Query builder interface
- Migration tools
### Configuration
- Environment variable management
- System settings
- Feature toggles
## 📋 Prerequisites
- Node.js 18+
- Yarn (preferred) or npm
- Database (PostgreSQL/MySQL recommended)
## 🚀 Quick Start
### 1. Clone the Template
Make sure to install the dependencies:
```bash
git clone https://git.sena.my/corrad-software/corrad-af-2024.git your-project-name
cd your-project-name
```
### 2. Install Dependencies
```bash
# Using yarn (recommended)
# yarn
yarn install
# Or using npm
# npm
npm install
# pnpm
pnpm install --shamefully-hoist
```
### 3. Environment Setup
## Development Server
Start the development server on http://localhost:3000
```bash
# Copy environment template
cp .env.example .env
# Edit your environment variables
nano .env
npm run dev
```
Configure your database connection and other environment variables in the `.env` file.
## Production
### 4. Database Setup
Build the application for production:
```bash
# Run database migrations and generate Prisma client
yarn prisma
# Or manually
npx prisma db pull && npx prisma generate
npm run build
```
### 5. Start Development Server
Locally preview production build:
```bash
yarn dev
npm run preview
```
Your application will be available at `http://localhost:3000`
Checkout the [deployment documentation](https://v3.nuxtjs.org/guide/deploy/presets) for more information.
# corradAF
## 📁 Project Structure
```
├── assets/ # Static assets (images, styles)
├── components/ # Vue components
├── composables/ # Vue composables
├── layouts/ # Application layouts
├── middleware/ # Route middleware
├── navigation/ # Navigation configuration
├── pages/ # Application pages
│ ├── devtool/ # Development tools
│ ├── dashboard/ # Main dashboard
│ ├── login/ # Authentication pages
│ ├── register/ # User registration
│ └── ...
├── plugins/ # Nuxt plugins
├── prisma/ # Database schema and migrations
├── public/ # Public static files
├── server/ # Server-side API
├── stores/ # Pinia stores
└── templates/ # Template files
```
## 🔧 Configuration
### Database
Configure your database connection in the `.env` file:
```env
DATABASE_URL="postgresql://username:password@localhost:5432/database_name"
```
### Authentication
Set up JWT secrets and authentication settings:
```env
JWT_SECRET="your-super-secret-jwt-key"
AUTH_ORIGIN="http://localhost:3000"
```
## 🎨 Customization
### Theme Configuration
Customize colors, fonts, and spacing in:
- `tailwind.config.js` - TailwindCSS configuration
- `app.config.js` - Application-specific settings
### Adding New Development Tools
1. Create a new page in `pages/devtool/your-tool/`
2. Add navigation entry in the navigation configuration
3. Implement your tool's functionality
## 📖 Documentation
- [Nuxt 3 Documentation](https://nuxt.com/docs)
- [TailwindCSS Documentation](https://tailwindcss.com/docs)
- [Prisma Documentation](https://www.prisma.io/docs)
- [FormKit Documentation](https://formkit.com/)
## 🚀 Deployment
### Build for Production
```bash
yarn build
```
### Preview Production Build
```bash
yarn preview
```
### Environment Variables for Production
Ensure all environment variables are properly set in your production environment:
- `DATABASE_URL`
- `JWT_SECRET`
- `AUTH_ORIGIN`
- `NUXT_SECRET_KEY`
## 🤝 Contributing
1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request
## 📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
## 🆘 Support
For support and questions:
- Create an issue in the repository
- Check existing documentation
- Review the development tools included in the framework
---
**Built with ❤️ using Nuxt 3, TailwindCSS, and modern web technologies.**
This is the base project for corradAF.

155
SETUP.md
View File

@ -1,155 +0,0 @@
# corradAF Setup Guide
This guide will help you set up the corradAF framework template for your new project.
## 🚀 Quick Setup
### 1. Environment Configuration
Create a `.env` file in your project root with the following variables:
```env
# Database Configuration
DATABASE_URL="postgresql://username:password@localhost:5432/database_name"
# Authentication
JWT_SECRET="your-super-secret-jwt-key-change-this-in-production"
AUTH_ORIGIN="http://localhost:3000"
# Application
NUXT_SECRET_KEY="your-nuxt-secret-key-for-session-encryption"
APP_NAME="Your Application Name"
APP_URL="http://localhost:3000"
# Email Configuration (Optional)
MAIL_HOST="smtp.example.com"
MAIL_PORT="587"
MAIL_USERNAME="your-email@example.com"
MAIL_PASSWORD="your-email-password"
MAIL_FROM_ADDRESS="noreply@yourapp.com"
MAIL_FROM_NAME="Your App Name"
# Development
NODE_ENV="development"
NUXT_HOST="localhost"
NUXT_PORT="3000"
```
### 2. Database Setup
corradAF uses Prisma as the ORM. Follow these steps:
1. **Configure your database URL** in the `.env` file
2. **Run database setup**:
```bash
yarn prisma
# This runs: npx prisma db pull && npx prisma generate && nuxt dev
```
### 3. First Run
```bash
# Install dependencies
yarn install
# Start development server
yarn dev
```
## 🔧 Development Tools Access
After setup, you can access these development tools:
- **User Management**: `/devtool/user-management/user`
- **Menu Editor**: `/devtool/menu-editor`
- **API Editor**: `/devtool/api-editor`
- **Content Editor**: `/devtool/content-editor`
- **Code Playground**: `/devtool/code-playground`
- **ORM Tools**: `/devtool/orm`
- **Configuration**: `/devtool/config`
## 🎨 Customization
### Update Branding
1. **App Name**: Update in `.env` file (`APP_NAME`)
2. **Colors**: Modify `tailwind.config.js`
3. **Logo**: Replace files in `public/` directory
4. **Favicon**: Replace `public/favicon.ico`
### Navigation Structure
Edit the navigation configuration in `navigation/` directory to customize menus.
### Authentication
The authentication system is ready to use with:
- User registration at `/register`
- Login at `/login`
- Password recovery at `/forgot-password`
## 📦 Production Deployment
### Environment Variables
Ensure these production environment variables are set:
```env
NODE_ENV="production"
DATABASE_URL="your-production-database-url"
JWT_SECRET="your-production-jwt-secret"
AUTH_ORIGIN="https://yourdomain.com"
NUXT_SECRET_KEY="your-production-secret-key"
```
### Build Commands
```bash
# Build for production
yarn build
# Preview production build locally
yarn preview
```
## 🛠️ Extending the Framework
### Adding New Development Tools
1. Create new page in `pages/devtool/your-tool/`
2. Add navigation entry
3. Implement functionality
### Custom Components
Add your custom components in `components/` directory following the existing structure.
### API Endpoints
Create server routes in `server/api/` directory.
## 🐛 Troubleshooting
### Common Issues
1. **Database Connection Issues**: Verify DATABASE_URL in `.env`
2. **Authentication Problems**: Check JWT_SECRET configuration
3. **Build Errors**: Ensure all dependencies are installed with `yarn install`
4. **Port Conflicts**: Change NUXT_PORT in `.env` file
### Getting Help
- Check the main README.md for detailed documentation
- Review existing development tools for implementation examples
- Create issues in the repository for bugs or feature requests
## 📝 Next Steps
After setup:
1. Customize the dashboard welcome page with your project branding
2. Set up your project-specific features
3. Configure authentication and user roles
4. Start building your application features
Happy coding with corradAF! 🚀

View File

@ -225,74 +225,6 @@ html[data-theme="oren"] {
--tw-shadow: #e5eaf2;
}
html[data-theme="purplian"] {
/* Core colors */
--color-primary: 145, 54, 136; /* #913688 - Main Purple */
--color-secondary: 165, 94, 156; /* #a55e9c - Lighter Purple */
--color-accent: 241, 235, 245; /* #f1ebf5 - Very soft purple */
/* Status colors */
--color-success: 67, 160, 71; /* #43a047 - Modern green */
--color-info: 41, 121, 255; /* #2979ff - Bright blue */
--color-warning: 255, 145, 0; /* #ff9100 - Vibrant orange */
--color-danger: 229, 57, 53; /* #e53935 - Refined red */
/* Basic UI colors */
--text-color: 60, 60, 67; /* #3c3c43 - Dark gray text */
--border-color: 232, 232, 235; /* #e8e8eb - Light gray border */
--bg-1: 250, 250, 253; /* #fafafd - Almost white background */
--bg-2: 255, 255, 255; /* #ffffff - Pure white background */
/* Sidebar colors with interactive states */
--sidebar: 145, 54, 136; /* #913688 - Purple sidebar */
--sidebar-menu: 120, 40, 110; /* #78286e - Darker Purple for menu */
--sidebar-text: 255, 255, 255; /* White Text */
--sidebar-hover-bg: 165, 94, 156; /* #a55e9c - Lighter purple for hover */
--sidebar-active-bg: 100, 30, 90; /* #641e5a - Darker purple for active state */
--sidebar-selected-bg: 185, 114, 176; /* #b972b0 - Highlight purple for selected */
--sidebar-indicator: 255, 255, 255; /* #ffffff - White indicator line */
--sidebar-active-text: 255, 236, 249; /* #ffecf9 - Brighter white for active text */
--sidebar-item-spacing: 2px; /* Spacing between sidebar items */
--sidebar-item-radius: 8px; /* Rounded corners for items */
/* Header styles */
--header: 250, 250, 253; /* #fafafd - Light header */
--header-text: 60, 60, 67; /* #3c3c43 - Dark text for header */
--header-active-text: 145, 54, 136; /* #913688 - Purple for active header items */
--header-hover-bg: 241, 235, 245; /* #f1ebf5 - Very soft purple for hover */
--header-border: 232, 232, 235; /* #e8e8eb - Light border under header */
/* UI Element Colors */
--scroll-color: 220, 220, 225; /* #dcdce1 - Light gray scrollbar */
--scroll-hover-color: 145, 54, 136; /* #913688 - Purple on hover */
--fk-border-color: 232, 232, 235; /* #e8e8eb - Light gray border */
--fk-placeholder-color: 150, 150, 155; /* #96969b - Medium gray placeholder */
--fk-focus-border: 145, 54, 136; /* #913688 - Purple border on focus */
--fk-hover-border: 165, 94, 156; /* #a55e9c - Lighter purple on hover */
--box-shadow: rgba(0, 0, 0, 0.05) 0px 1px 2px,
rgba(0, 0, 0, 0.04) 0px 0px 1px;
--cp-bg: 255, 255, 255; /* White Background */
/* Interactive elements */
--btn-hover-bg: 241, 235, 245; /* #f1ebf5 - Very soft purple for button hover */
--active-tab-border: 145, 54, 136; /* #913688 - Purple border for active tab */
--focus-ring: 185, 114, 176, 0.4; /* #b972b0 - Focus outline with opacity */
/* UI Settings */
--rounded-box: 0.4rem;
--rounded-btn: 0.375rem;
--rounded-badge: 1.9rem;
--animation-btn: 0.2s;
--animation-input: 0.2s;
--btn-text-case: capitalize;
--btn-focus-scale: 0.98;
--padding-btn: 0.6rem 1.2rem;
--border-btn: 1px;
--tab-border: 1px;
--tab-radius: 0.5rem;
--tw-shadow: rgba(0, 0, 0, 0.05);
}
html[data-theme="LZS"] {
--color-primary: 0, 90, 173; /* #005AAD - Blue */
--color-secondary: 141, 199, 61; /* #8DC73D - Green */
@ -334,4 +266,3 @@ html[data-theme="LZS"] {
--focus-ring: 255, 242, 0, 0.5; /* Yellow focus ring */
--tw-shadow: #e5eaf2;
}

View File

@ -1,11 +0,0 @@
# Development files
*.md
!README.md
# Logs
*.log
# Testing
test/
tests/
*.test.js

View File

@ -1,37 +0,0 @@
# CORRAD AF CLI Tool
🚀 **The fastest way to bootstrap your next project with CORRAD Application Framework**
## Quick Start
```bash
npx corradaf
```
## Features
- ✨ Beautiful ASCII welcome screen
- 🔐 Public/Internal project modes
- ⚙️ Automatic environment setup
- 🤖 Cursor AI rules integration
- 📦 Automatic dependency installation
- 🗄️ Prisma database setup
- 🎯 IDE auto-detection
## Usage
1. Run the CLI tool
2. Choose project type (Public/Internal)
3. Enter project name
4. Configure environment variables
5. Enjoy your new CORRAD AF project!
## Requirements
- Node.js 14+
- Git
- Internet connection
## License
MIT

View File

@ -1,684 +0,0 @@
#!/usr/bin/env node
console.log('🚀 Starting CORRAD AF CLI...');
const { execSync, spawn } = require('child_process');
const fs = require('fs');
const path = require('path');
const inquirer = require('inquirer');
const figlet = require('figlet');
const ora = require('ora');
const chalk = require('chalk');
const boxen = require('boxen');
const gradient = require('gradient-string');
const https = require('https');
const http = require('http');
// Function to fetch content from URL
function fetchFromUrl(url) {
return new Promise((resolve, reject) => {
const client = url.startsWith('https') ? https : http;
const urlObj = new URL(url);
const options = {
hostname: urlObj.hostname,
port: urlObj.port,
path: urlObj.pathname + urlObj.search,
method: 'GET'
};
const req = client.request(options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
if (res.statusCode === 200) {
resolve(data);
} else {
reject(new Error(`HTTP ${res.statusCode}: ${res.statusMessage}`));
}
});
});
req.on('error', (err) => {
reject(err);
});
req.end();
});
}
// Helper function to run shell commands with proper quoting
function runCommand(command, options = {}) {
try {
console.log(chalk.gray(`Running: ${command}`));
execSync(command, { stdio: 'inherit', ...options });
return true;
} catch (error) {
console.error(chalk.red(`Error: ${error.message}`));
return false;
}
}
// Helper function to properly quote project names with spaces
function escapeProjectName(projectName) {
// Use double quotes for Windows and Unix compatibility
return `"${projectName}"`;
}
// Helper function to run async commands
function runCommandAsync(command, args = [], options = {}) {
return new Promise((resolve, reject) => {
const child = spawn(command, args, { stdio: 'inherit', ...options });
child.on('close', (code) => {
if (code === 0) {
resolve(code);
} else {
reject(new Error(`Command failed with exit code ${code}`));
}
});
});
}
// Create progress bar animation
function createProgressBar(message, duration = 3000) {
return new Promise((resolve) => {
const spinner = ora({
text: message,
spinner: {
interval: 100,
frames: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
}
}).start();
let progress = 0;
const interval = setInterval(() => {
progress += 10;
spinner.text = `${message} ${progress}%`;
if (progress >= 100) {
clearInterval(interval);
spinner.succeed(chalk.green('✓ Setup complete!'));
resolve();
}
}, duration / 10);
});
}
// Clear screen and display ASCII art
function displayHeader() {
clearScreen();
// Show ASCII "CORRAD AF" with gradient
const asciiText = figlet.textSync('CORRAD AF', {
font: 'Big',
horizontalLayout: 'default',
verticalLayout: 'default'
});
console.log(gradient.rainbow(asciiText));
console.log(boxen(
chalk.white.bold('🚀 Welcome to CORRAD Application Framework CLI\n') +
chalk.gray('The fastest way to bootstrap your next project'),
{
padding: 1,
margin: 1,
borderStyle: 'round',
borderColor: 'cyan'
}
));
}
// Clear screen and position cursor at top
function clearScreen() {
console.clear();
process.stdout.write('\x1b[H');
}
// Check if current directory has project files
function hasProjectFiles() {
const projectFiles = ['package.json', '.git', 'node_modules', 'src', 'pages', 'components'];
return projectFiles.some(file => fs.existsSync(file));
}
// Parse .env.example file and extract variables
function parseEnvExample(content) {
const lines = content.split('\n');
const envVars = [];
for (const line of lines) {
const trimmed = line.trim();
if (trimmed && !trimmed.startsWith('#') && trimmed.includes('=')) {
const [key, ...valueParts] = trimmed.split('=');
const value = valueParts.join('=').replace(/['"]/g, '');
const description = extractComment(line);
envVars.push({
key: key.trim(),
defaultValue: value.trim(),
description: description
});
}
}
return envVars;
}
// Extract comment from env line
function extractComment(line) {
const commentMatch = line.match(/#\s*(.+)$/);
return commentMatch ? commentMatch[1].trim() : '';
}
// Create default .env.example file if it doesn't exist
function createDefaultEnvExample() {
const defaultEnvContent = `# Database Configuration
DATABASE_URL="mysql://username:password@localhost:3306/database_name" # Your MySQL connection string
# Authentication
JWT_SECRET="your-super-secret-jwt-key-change-this-in-production" # Secret key for JWT tokens
AUTH_ORIGIN="http://localhost:3000" # Allowed origin for authentication
# Application
NUXT_SECRET_KEY="your-nuxt-secret-key-for-session-encryption" # Nuxt secret key
APP_NAME="Your Application Name" # Your application name
APP_URL="http://localhost:3000" # Your application URL
# Email Configuration (Optional)
MAIL_HOST="smtp.example.com" # SMTP server host
MAIL_PORT="587" # SMTP server port
MAIL_USERNAME="your-email@example.com" # SMTP username
MAIL_PASSWORD="your-email-password" # SMTP password
MAIL_FROM_ADDRESS="noreply@yourapp.com" # From email address
MAIL_FROM_NAME="Your App Name" # From name
# Development
NODE_ENV="development" # Environment (development, production)
NUXT_HOST="localhost" # Nuxt host
NUXT_PORT="3000" # Nuxt port
`;
fs.writeFileSync('.env.example', defaultEnvContent);
return defaultEnvContent;
}
// Check if environment is properly configured
function isEnvConfigured() {
if (!fs.existsSync('.env')) {
return false;
}
const envContent = fs.readFileSync('.env', 'utf-8');
// Check if DATABASE_URL is properly set (not empty or default)
const dbUrlMatch = envContent.match(/DATABASE_URL\s*=\s*["'](.+?)["']/);
if (!dbUrlMatch) return false;
const dbUrl = dbUrlMatch[1];
return dbUrl && !dbUrl.includes('username:password');
}
// Main CLI function
async function main() {
try {
// Show the header once at the beginning
displayHeader();
// Check for existing project files
const hasFiles = hasProjectFiles();
// Step 2: Ask about project setup
console.log(chalk.cyan.bold('\n📦 Project Setup'));
if (hasFiles) {
console.log(chalk.yellow('⚠️ Existing project files detected in current directory'));
}
const setupChoices = hasFiles ? [
{ name: 'Pull latest updates from CORRAD AF repository', value: 'pull' },
{ name: 'Start completely new project (will overwrite existing)', value: 'new' },
{ name: 'Cancel setup', value: 'cancel' }
] : [
{ name: 'Start new project by cloning CORRAD AF repository', value: 'new' },
{ name: 'Cancel setup', value: 'cancel' }
];
const { setupAction } = await inquirer.prompt([
{
type: 'list',
name: 'setupAction',
message: 'What would you like to do?',
choices: setupChoices,
default: 0
}
]);
if (setupAction === 'cancel') {
console.log(chalk.yellow('👋 Setup cancelled. Goodbye!'));
process.exit(0);
}
// Display header again for consistency
displayHeader();
// Get project name (only for new projects)
let projectName = path.basename(process.cwd());
if (setupAction === 'new') {
const { inputProjectName } = await inquirer.prompt([
{
type: 'input',
name: 'inputProjectName',
message: 'Enter your project name:',
default: 'my-corradaf-project',
validate: function(input) {
if (input.trim().length === 0) {
return 'Project name cannot be empty';
}
// Check for invalid characters
if (/[<>:"/\\|?*]/.test(input)) {
return 'Project name contains invalid characters';
}
return true;
}
}
]);
projectName = inputProjectName;
}
// Display header again for consistency
displayHeader();
// Step 3: Ask about environment setup
console.log(chalk.cyan.bold('\n🔐 Environment Setup'));
const { envSetupType } = await inquirer.prompt([
{
type: 'list',
name: 'envSetupType',
message: 'How would you like to set up your environment?',
choices: [
{
name: chalk.green('🔧 Manual Setup') + chalk.gray(' - Configure environment later'),
value: 'manual'
},
{
name: chalk.blue('🔗 Import from URL') + chalk.gray(' - Paste a configuration URL'),
value: 'url'
}
],
default: 0
}
]);
// Display header again for consistency
displayHeader();
// Step 4: Ask about Cursor rules
console.log(chalk.cyan.bold('\n⚙ Development Tools'));
const { useCursorRules } = await inquirer.prompt([
{
type: 'list',
name: 'useCursorRules',
message: 'Do you want to apply the optimized Cursor AI rules for better code assistance?',
choices: [
{ name: 'Yes, apply Cursor AI rules (recommended)', value: true },
{ name: 'No, skip Cursor rules', value: false }
],
default: 0
}
]);
// Display header again for consistency
displayHeader();
// Step 5: Show loading screen and setup project
console.log(chalk.cyan.bold('\n🚀 Setting up your project...'));
if (setupAction === 'new') {
// Clone the repository with proper escaping
const cloneSpinner = ora('Cloning CORRAD AF template...').start();
const escapedProjectName = escapeProjectName(projectName);
const success = runCommand(`git clone https://git.sena.my/corrad-software/corrad-af-2024.git ${escapedProjectName}`, { stdio: 'pipe' });
if (!success) {
cloneSpinner.fail('Failed to clone repository');
process.exit(1);
}
cloneSpinner.succeed('Repository cloned successfully');
// Change to project directory
process.chdir(projectName);
} else {
// Pull latest updates
const pullSpinner = ora('Pulling latest updates...').start();
const success = runCommand('git pull origin main', { stdio: 'pipe' });
if (!success) {
pullSpinner.fail('Failed to pull updates');
console.log(chalk.yellow('⚠️ You may need to resolve conflicts manually'));
} else {
pullSpinner.succeed('Updates pulled successfully');
}
}
// Remove .git folder (user will init themselves later) - only for new projects
if (setupAction === 'new') {
const gitSpinner = ora('Cleaning up repository...').start();
try {
if (fs.existsSync('.git')) {
if (process.platform === 'win32') {
runCommand('rmdir /s /q .git', { stdio: 'pipe' });
} else {
runCommand('rm -rf .git', { stdio: 'pipe' });
}
}
gitSpinner.succeed('Repository cleaned up');
} catch (error) {
gitSpinner.warn('Repository cleanup skipped');
}
}
// Setup environment file
if (envSetupType === 'url') {
// Display header for consistency
displayHeader();
const { envUrl } = await inquirer.prompt([
{
type: 'input',
name: 'envUrl',
message: 'Enter the URL for your environment configuration:',
validate: function(input) {
if (!input.trim() || !input.startsWith('http')) {
return 'Please enter a valid URL (starting with http:// or https://)';
}
return true;
}
}
]);
const envSpinner = ora('Fetching environment configuration from URL...').start();
try {
// Fetch .env content from provided URL
const envContent = await fetchFromUrl(envUrl);
const processedContent = envContent.replace(/\${projectName}/g, projectName);
fs.writeFileSync('.env', processedContent);
envSpinner.succeed('Environment configuration imported successfully');
// Run Prisma commands if the env is properly configured
if (isEnvConfigured()) {
const prismaSpinner = ora('Setting up Prisma database...').start();
if (fs.existsSync('prisma/schema.prisma')) {
const prismaSuccess = runCommand('npx prisma generate', { stdio: 'pipe' });
if (prismaSuccess) {
prismaSpinner.succeed('Prisma database configured');
} else {
prismaSpinner.fail('Prisma setup failed - please check your DATABASE_URL');
}
} else {
prismaSpinner.warn('No Prisma schema found - skipping database setup');
}
}
} catch (error) {
envSpinner.fail('Failed to fetch environment configuration');
console.log(chalk.yellow(`⚠️ Unable to access URL: ${error.message}`));
console.log(chalk.gray('Creating a basic .env file you can edit later...'));
// Create basic .env file from .env.example
try {
let exampleContent;
if (fs.existsSync('.env.example')) {
exampleContent = fs.readFileSync('.env.example', 'utf8');
} else {
exampleContent = createDefaultEnvExample();
}
fs.copyFileSync('.env.example', '.env');
console.log(chalk.green('✓ Basic environment file created'));
console.log(chalk.yellow('⚠️ Please edit the .env file and configure your DATABASE_URL before running Prisma commands'));
} catch (error) {
console.log(chalk.red(`Error creating .env file: ${error.message}`));
}
}
} else {
// Manual environment setup
const envSpinner = ora('Setting up environment files...').start();
try {
// Create or ensure .env.example exists
if (!fs.existsSync('.env.example')) {
createDefaultEnvExample();
}
// Copy .env.example to .env without filling in values
fs.copyFileSync('.env.example', '.env');
envSpinner.succeed('Environment files created');
console.log(chalk.green('✓ Created .env file from .env.example'));
console.log(chalk.yellow('⚠️ Please edit the .env file and configure your DATABASE_URL before running Prisma commands'));
} catch (error) {
envSpinner.fail('Failed to set up environment');
console.log(chalk.red(`Error: ${error.message}`));
}
}
// Setup Cursor rules
if (useCursorRules) {
const cursorSpinner = ora('Applying Cursor AI rules...').start();
const cursorRules = `# CORRAD AF Cursor Rules
# These rules optimize Cursor AI for working with the CORRAD Application Framework
### Behaviour rules
- You are an agent - please keep going until the user's query is completely resolved, before ending your turn and yielding back to the user. Only terminate your turn when you are sure that the problem is solved.
- If you are not sure about file content or codebase structure pertaining to the user's request, use your tools to read files and gather the relevant information: do NOT guess or make up an answer.
- You MUST plan extensively before each function call, and reflect extensively on the outcomes of the previous function calls. DO NOT do this entire process by making function calls only, as this can impair your ability to solve the problem and think insightfully.
### Coding rules
You are a Senior Full Stack Developer and an Expert in Vue, NuxtJS, JavaScript, TypeScript, HTML, SCSS and modern UI/UX frameworks (e.g., TailwindCSS, NuxtUI, Vuetify). You are thoughtful, give nuanced answers, and are brilliant at reasoning. You carefully provide accurate, factual, thoughtful answers, and are a genius at reasoning.
- Follow the user's requirements carefully & to the letter.
- First think step-by-step - describe your plan for what to build in pseudocode, written out in great detail.
- Confirm, then write code!
- Always write correct, best practice, KISS, DRY, SOLID, YAGNI principles, bug free, fully functional and working code.
- Avoid creating very large Vue components. When possible, extract functionality into separate sub-components.
- When working on an existing project, adapt to the existing conventions. If there's not enough context in the prompt to know what the conventions in the current project are, you MUST proactively read other files to find out.
- When asked to do something / create some kind of code, first read code of the same kind in the project so you know what's the project's syntax and practices.
- Before creating types or interfaces, first search through the project as the required types might already exist.
- Before creating migrations on backend, check what the correct command is in the package.json. After creation, check if the created migration contains only the added fields, otherwise remove the rest as the generator may add garbage.
- Focus on easy and readability code, over being performant.
- Fully implement all requested functionality.
- Leave NO todo's, placeholders or missing pieces.
- Ensure code is complete! Verify thoroughly finalised.
- Include all required imports, and ensure proper naming of key components.
- Be concise Minimize any other prose.
- If you think there might not be a correct answer, you say so.
- If you do not know the answer, say so, instead of guessing.
- When you want to show different options to solve an issue, do so WITHOUT implementing every option. First ask the user which one they would prefer.
- Every non-code part of your response should be written using Markdown, for better legibility.
- When using frameworks / UI libraries, you may use context7 to check the documentation on what components to use for the required task and how to use them correctly.
- IMPORTANT #1: Limit yourself to what you were asked to do. DO NOT REFACTOR / REWRITE code unless asked to. Instead, you MAY emit any recommendations you have at the end of your message (or you may do it at the start, and ask for confirmation, if you feel convenient).
- IMPORTANT #2: The user is a software engineer. Focus on what he asked you to change. Do not fix or change things that haven't been asked you to.
- IMPORTANT #3: Every change you implement must be carefuly though, and the implementation MUST BE ROBUST, unless specified otherwise by the user.
## CORRAD AF Framework Specific Rules
You are an expert in Nuxt 3, Vue 3, TypeScript, TailwindCSS, and the CORRAD AF framework.
Code Style Preferences:
- Use Composition API with <script setup>
- Prefer TypeScript for type safety
- Use TailwindCSS for styling
- Follow CORRAD AF patterns from llms.txt
Key Conventions:
- Use \`navigateTo()\` instead of \`router.push()\`
- Use \`definePageMeta()\` for page configuration
- Use \`ref()\` and \`reactive()\` for Vue 3 reactivity
- Prefer composables over mixins
- Use middleware for route protection
Framework Patterns:
- Follow the component templates in llms.txt
- Use rs-card, rs-button components
- Implement proper error handling
- Follow the API endpoint patterns
- Use Prisma for database operations
Security:
- Always validate inputs
- Use proper authentication patterns
- Implement RBAC where needed
- Follow security best practices from llms.txt
`;
fs.writeFileSync('.cursorrules', cursorRules);
cursorSpinner.succeed('Cursor AI rules applied');
}
// Show fancy loading progress
await createProgressBar('Installing dependencies and setting up project', 4000);
// Install dependencies
const yarnSpinner = ora('Installing dependencies with Yarn...').start();
const yarnSuccess = runCommand('yarn install', { stdio: 'pipe' });
if (!yarnSuccess) {
yarnSpinner.fail('Failed to install dependencies with Yarn');
console.log(chalk.yellow('Trying with npm as fallback...'));
const npmSpinner = ora('Installing dependencies with npm...').start();
const npmSuccess = runCommand('npm install', { stdio: 'pipe' });
if (!npmSuccess) {
npmSpinner.fail('Failed to install dependencies');
console.log(chalk.red('❌ Please install dependencies manually after setup'));
} else {
npmSpinner.succeed('Dependencies installed with npm');
}
} else {
yarnSpinner.succeed('Dependencies installed with Yarn');
}
// Display header again for consistency at the end
displayHeader();
// Step 6: Success message and next steps
const prismaNotes = isEnvConfigured() ?
'' :
chalk.yellow('\n⚠ Important: Edit your .env file and configure your DATABASE_URL before running:\n') +
chalk.gray(' npx prisma generate\n');
const nextSteps = setupAction === 'new' ? [
` cd ${projectName}`,
' git init # Initialize git repository',
' # Edit your .env file with proper configuration',
' npx prisma generate # Generate Prisma client after configuring DATABASE_URL',
' yarn dev # Start development server',
' yarn build # Build for production',
' yarn start # Start production server'
] : [
' # Edit your .env file with proper configuration',
' npx prisma generate # Generate Prisma client after configuring DATABASE_URL',
' yarn dev # Start development server',
' yarn build # Build for production',
' yarn start # Start production server'
];
console.log('\n' + boxen(
chalk.green.bold('🎉 Project setup completed successfully!\n\n') +
chalk.white(`Project: ${chalk.cyan.bold(projectName)}\n`) +
chalk.white(`Action: ${chalk.yellow.bold(setupAction === 'new' ? 'New Project' : 'Updated Existing')}\n`) +
chalk.white(`Location: ${chalk.gray(process.cwd())}\n`) +
prismaNotes +
chalk.white.bold('Next steps:\n') +
nextSteps.map(step => chalk.gray(step)).join('\n'),
{
padding: 1,
margin: 1,
borderStyle: 'round',
borderColor: 'green'
}
));
// Ask if user wants to open in IDE
const { openIDE } = await inquirer.prompt([
{
type: 'list',
name: 'openIDE',
message: 'Would you like to open the project in your IDE now?',
choices: [
{ name: 'Yes, open in IDE', value: true },
{ name: 'No, I will open it manually', value: false }
],
default: 0
}
]);
if (openIDE) {
console.log(chalk.cyan('Opening project in IDE...'));
// Try different IDE commands
const ideCommands = ['code .', 'cursor .', 'webstorm .', 'idea .'];
let ideOpened = false;
for (const cmd of ideCommands) {
try {
execSync(cmd, { stdio: 'pipe' });
console.log(chalk.green(`✓ Opened in IDE with: ${cmd}`));
ideOpened = true;
break;
} catch (error) {
// Try next IDE
}
}
if (!ideOpened) {
console.log(chalk.yellow('Could not detect IDE. Please open the project manually.'));
}
}
// Step 7: Auto close after showing final message
console.log(chalk.gray('\n👋 CLI setup complete. You can now continue in your IDE terminal.'));
console.log(chalk.gray('This terminal will close in 3 seconds...'));
setTimeout(() => {
process.exit(0);
}, 3000);
} catch (error) {
if (error.isTtyError) {
console.error(chalk.red('❌ This CLI requires an interactive terminal.'));
} else {
console.error(chalk.red('❌ Setup failed:'), error.message);
}
process.exit(1);
}
}
// Handle Ctrl+C gracefully
process.on('SIGINT', () => {
console.log(chalk.yellow('\n\n👋 Setup cancelled by user. Goodbye!'));
process.exit(0);
});
// Handle uncaught exceptions
process.on('uncaughtException', (error) => {
console.error('❌ Uncaught Exception:', error);
process.exit(1);
});
// Handle unhandled promise rejections
process.on('unhandledRejection', (reason, promise) => {
console.error('❌ Unhandled Rejection at:', promise, 'reason:', reason);
process.exit(1);
});
// Run the CLI
console.log('📦 Calling main function...');
main().catch((error) => {
console.error('❌ Main function error:', error);
process.exit(1);
});

View File

@ -1,39 +0,0 @@
{
"name": "corradaf",
"version": "1.0.2",
"description": "CLI tool to quickly set up CORRAD Application Framework projects",
"main": "index.js",
"bin": {
"corradaf": "./index.js"
},
"scripts": {
"start": "node index.js"
},
"keywords": [
"corradaf",
"cli",
"project-setup",
"nuxt",
"vue",
"framework",
"template"
],
"dependencies": {
"boxen": "^5.1.2",
"chalk": "^4.1.2",
"figlet": "^1.8.1",
"gradient-string": "^2.0.2",
"inquirer": "^8.2.6",
"ora": "^5.4.1"
},
"author": "Corrad Team",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://git.sena.my/corrad-software/corrad-af-2024.git"
},
"homepage": "https://git.sena.my/corrad-software/corrad-af-2024",
"engines": {
"node": ">=14.0.0"
}
}

View File

@ -12,49 +12,16 @@ const refreshPage = () => {
window.location.reload(true);
};
// Fast loading logo - fetch during SSR to prevent hydration flash
const { data: quickLoadingData } = await useLazyFetch("/api/devtool/config/loading-logo", {
default: () => ({
data: {
siteLoadingLogo: '',
siteName: 'Loading...'
}
}),
transform: (response) => response.data || {
siteLoadingLogo: '',
siteName: 'Loading...'
}
});
const loadingLogoSrc = computed(() => {
// First priority: Quick loading data if available
if (quickLoadingData.value?.siteLoadingLogo) {
return quickLoadingData.value.siteLoadingLogo;
}
// Second priority: Full site settings if loaded
if (!siteSettingsLoading.value && siteSettings.value.siteLoadingLogo) {
return siteSettings.value.siteLoadingLogo;
}
// Fallback: Default logo
return '/img/logo/corradAF-logo.svg';
return 'http://localhost:3003/uploads/site-settings/loading-logo.png';
});
// Get site name with fallback
const getSiteName = () => {
// First priority: Quick loading data
if (quickLoadingData.value?.siteName) {
return quickLoadingData.value.siteName;
if (siteSettingsLoading.value) {
return 'Loading Logo';
}
// Second priority: Full site settings
if (!siteSettingsLoading.value && siteSettings.value.siteName) {
return siteSettings.value.siteName;
}
// Fallback
return 'Loading...';
return siteSettings.value?.siteName || 'Loading Logo';
};
</script>

View File

@ -1,135 +1,36 @@
export default function () {
return [
{
theme: "biru",
theme: "biasa",
colors: [
{
name: "primary",
value: "0, 102, 204", // Strong blue
value: "243, 88, 106",
},
{
name: "secondary",
value: "51, 153, 255", // Lighter blue
value: "240, 122, 37",
},
{
name: "accent",
value: "255, 204, 0", // Gold
},
{
name: "background",
value: "240, 248, 255", // Alice blue
},
{
name: "text",
value: "0, 0, 0", // Black
value: "243, 244, 246",
},
],
},
{
theme: "merah",
theme: "gelap",
colors: [
{
name: "primary",
value: "204, 0, 0", // Strong red
value: "243, 88, 106",
},
{
name: "secondary",
value: "255, 102, 102", // Lighter red
value: "240, 122, 37",
},
{
name: "accent",
value: "255, 255, 153", // Light yellow
},
{
name: "background",
value: "255, 240, 240", // Very light pink
},
{
name: "text",
value: "0, 0, 0", // Black
},
],
},
{
theme: "ungu",
colors: [
{
name: "primary",
value: "75, 0, 130", // Indigo
},
{
name: "secondary",
value: "138, 43, 226", // Blue violet
},
{
name: "accent",
value: "255, 215, 0", // Gold
},
{
name: "background",
value: "240, 248, 255", // Alice blue
},
{
name: "text",
value: "0, 0, 0", // Black
},
],
},
{
theme: "oren",
colors: [
{
name: "primary",
value: "255, 103, 0", // Dark orange
},
{
name: "secondary",
value: "255, 159, 64", // Lighter orange
},
{
name: "accent",
value: "0, 128, 128", // Teal
},
{
name: "background",
value: "255, 250, 240", // Floral white
},
{
name: "text",
value: "0, 0, 0", // Black
},
],
},
{
theme: "purplian",
colors: [
{
name: "primary",
value: "145, 54, 136", // #913688 - Main Purple
},
{
name: "secondary",
value: "165, 94, 156", // #a55e9c - Lighter Purple
},
{
name: "accent",
value: "241, 235, 245", // #f1ebf5 - Very soft purple
},
{
name: "background",
value: "250, 250, 253", // #fafafd - Almost white
},
{
name: "text",
value: "60, 60, 67", // #3c3c43 - Dark gray text
},
{
name: "surface",
value: "255, 255, 255", // #ffffff - Pure white
},
{
name: "highlight",
value: "225, 207, 235", // #e1cfeb - Very soft purple highlight
value: "15, 23, 42",
},
],
},
@ -148,16 +49,7 @@ export default function () {
name: "accent",
value: "255, 242, 0", // #FFF200 - Yellow
},
{
name: "background",
value: "245, 250, 255", // Very light blue background
},
{
name: "text",
value: "0, 0, 0", // Black
},
],
},
];
}

View File

@ -1,53 +1,102 @@
export default function () {
return [
{
theme: "biasa",
theme: "biru",
colors: [
{
name: "primary",
value: "243, 88, 106",
value: "0, 102, 204", // Strong blue
},
{
name: "secondary",
value: "240, 122, 37",
value: "51, 153, 255", // Lighter blue
},
{
name: "accent",
value: "243, 244, 246",
value: "255, 204, 0", // Gold
},
{
name: "background",
value: "240, 248, 255", // Alice blue
},
{
name: "text",
value: "0, 0, 0", // Black
},
],
},
{
theme: "gelap",
theme: "merah",
colors: [
{
name: "primary",
value: "243, 88, 106",
value: "204, 0, 0", // Strong red
},
{
name: "secondary",
value: "240, 122, 37",
value: "255, 102, 102", // Lighter red
},
{
name: "accent",
value: "15, 23, 42",
value: "255, 255, 153", // Light yellow
},
{
name: "background",
value: "255, 240, 240", // Very light pink
},
{
name: "text",
value: "0, 0, 0", // Black
},
],
},
{
theme: "purplian",
theme: "ungu",
colors: [
{
name: "primary",
value: "145, 54, 136", // #913688 - Main Purple
value: "75, 0, 130", // Indigo
},
{
name: "secondary",
value: "165, 94, 156", // #a55e9c - Lighter Purple
value: "138, 43, 226", // Blue violet
},
{
name: "accent",
value: "241, 235, 245", // #f1ebf5 - Very soft purple
value: "255, 215, 0", // Gold
},
{
name: "background",
value: "240, 248, 255", // Alice blue
},
{
name: "text",
value: "0, 0, 0", // Black
},
],
},
{
theme: "oren",
colors: [
{
name: "primary",
value: "255, 103, 0", // Dark orange
},
{
name: "secondary",
value: "255, 159, 64", // Lighter orange
},
{
name: "accent",
value: "0, 128, 128", // Teal
},
{
name: "background",
value: "255, 250, 240", // Floral white
},
{
name: "text",
value: "0, 0, 0", // Black
},
],
},
@ -66,8 +115,15 @@ export default function () {
name: "accent",
value: "255, 242, 0", // #FFF200 - Yellow
},
{
name: "background",
value: "245, 250, 255", // Very light blue background
},
{
name: "text",
value: "0, 0, 0", // Black
},
],
},
];
}

View File

@ -0,0 +1,295 @@
import { ref, computed } from 'vue';
// Define interface for the asnaf profile (keep for type reference)
interface AsnafProfile {
id: string;
nama: string;
idNumber: string;
kategori: string;
status: string;
tarikhDaftar: string;
alamat: string;
telefon: string;
email: string;
gender: string;
maritalStatus: string;
birthDate: string;
occupation: string;
monthlyIncome: string;
otherIncome: string;
totalIncome: string;
spouse: {
name: string;
idNumber: string;
} | null;
dependents: Array<{
name: string;
age: number;
relationship: string;
}>;
documents: Array<{
name: string;
size: string;
url: string;
}>;
analysis: {
hadKifayahPercentage: string;
suggestedCategory: string;
status: string;
familyCategory: string;
asnafCategory: string;
};
}
// Mock data for Asnaf profiles (LIST page)
const asnafProfiles = ref<AsnafProfile[]>([
{
id: '1',
nama: 'Ahmad Bin Abdullah',
idNumber: 'MYKAD001',
kategori: 'Fakir',
status: 'Aktif',
tarikhDaftar: '2023-01-15',
alamat: '123 Jalan Merdeka',
telefon: '012-3456789',
email: 'ahmad@example.com',
gender: 'Lelaki',
maritalStatus: 'Berkahwin',
birthDate: '1988-01-01',
occupation: 'Buruh',
monthlyIncome: '1200.00',
otherIncome: '300.00',
totalIncome: '1500.00',
spouse: { name: 'Aminah binti Yusof', idNumber: '900202-14-5678' },
dependents: [
{ name: 'Muhammad bin Ahmad', age: 10, relationship: 'Anak' },
{ name: 'Fatimah binti Ahmad', age: 8, relationship: 'Anak' }
],
documents: [
{ name: 'Salinan Kad Pengenalan', size: '1.2 MB', url: '#' },
{ name: 'Slip Gaji', size: '850 KB', url: '#' },
{ name: 'Surat Pengesahan Pendapatan', size: '1.5 MB', url: '#' }
],
analysis: {
hadKifayahPercentage: '65.25%',
suggestedCategory: 'Miskin',
status: 'Layak (Miskin)',
familyCategory: 'Miskin (50-100% Had Kifayah)',
asnafCategory: 'Miskin'
}
},
{
id: '2',
nama: 'Siti Binti Ali',
idNumber: 'MYKAD002',
kategori: 'Miskin',
status: 'Aktif',
tarikhDaftar: '2023-02-20',
alamat: '456 Jalan Harmoni',
telefon: '019-8765432',
email: 'siti@example.com',
gender: 'Perempuan',
maritalStatus: 'Bujang',
birthDate: '1990-05-12',
occupation: 'Kerani',
monthlyIncome: '1500.00',
otherIncome: '0.00',
totalIncome: '1500.00',
spouse: null,
dependents: [],
documents: [
{ name: 'Salinan Kad Pengenalan', size: '1.1 MB', url: '#' }
],
analysis: {
hadKifayahPercentage: '80.00%',
suggestedCategory: 'Miskin',
status: 'Layak (Miskin)',
familyCategory: 'Miskin (50-100% Had Kifayah)',
asnafCategory: 'Miskin'
}
},
{
id: '3',
nama: 'Lim Ah Beng',
idNumber: 'MYKAD003',
kategori: 'Mualaf',
status: 'Dalam Semakan',
tarikhDaftar: '2023-03-10',
alamat: '789 Jalan Sejahtera',
telefon: '011-1234567',
email: 'lim@example.com',
gender: 'Lelaki',
maritalStatus: 'Bujang',
birthDate: '1985-09-09',
occupation: 'Peniaga',
monthlyIncome: '2000.00',
otherIncome: '200.00',
totalIncome: '2200.00',
spouse: null,
dependents: [],
documents: [],
analysis: {
hadKifayahPercentage: '55.00%',
suggestedCategory: 'Miskin',
status: 'Dalam Semakan',
familyCategory: 'Miskin (50-100% Had Kifayah)',
asnafCategory: 'Mualaf'
}
},
{
id: '4',
nama: 'Raju A/L Muthu',
idNumber: 'MYKAD004',
kategori: 'Fi-sabilillah',
status: 'Tidak Aktif',
tarikhDaftar: '2022-12-05',
alamat: '101 Jalan Damai',
telefon: '013-9876543',
email: 'raju@example.com',
gender: 'Lelaki',
maritalStatus: 'Berkahwin',
birthDate: '1975-11-23',
occupation: 'Guru',
monthlyIncome: '2500.00',
otherIncome: '0.00',
totalIncome: '2500.00',
spouse: { name: 'Saraswathy a/p Maniam', idNumber: '750101-10-1234' },
dependents: [],
documents: [],
analysis: {
hadKifayahPercentage: '110.00%',
suggestedCategory: 'Tidak Layak',
status: 'Tidak Layak',
familyCategory: 'Non-FM (>100% Had Kifayah)',
asnafCategory: 'Fi-sabilillah'
}
},
{
id: '5',
nama: 'Aminah Binti Kassim',
idNumber: 'MYKAD005',
kategori: 'Gharimin',
status: 'Aktif',
tarikhDaftar: '2023-04-01',
alamat: '202 Jalan Ceria',
telefon: '014-2345678',
email: 'aminah@example.com',
gender: 'Perempuan',
maritalStatus: 'Janda',
birthDate: '1982-03-15',
occupation: 'Peniaga',
monthlyIncome: '1800.00',
otherIncome: '100.00',
totalIncome: '1900.00',
spouse: null,
dependents: [
{ name: 'Ali bin Kassim', age: 12, relationship: 'Anak' }
],
documents: [],
analysis: {
hadKifayahPercentage: '70.00%',
suggestedCategory: 'Miskin',
status: 'Layak (Miskin)',
familyCategory: 'Miskin (50-100% Had Kifayah)',
asnafCategory: 'Gharimin'
}
},
{
id: '6',
nama: 'John Doe Anak Luta',
idNumber: 'MYKAD006',
kategori: 'Ibnu Sabil',
status: 'Dalam Semakan',
tarikhDaftar: '2023-05-12',
alamat: '303 Jalan Gembira',
telefon: '016-3456789',
email: 'john@example.com',
gender: 'Lelaki',
maritalStatus: 'Bujang',
birthDate: '1995-07-07',
occupation: 'Penganggur',
monthlyIncome: '0.00',
otherIncome: '0.00',
totalIncome: '0.00',
spouse: null,
dependents: [],
documents: [],
analysis: {
hadKifayahPercentage: '30.00%',
suggestedCategory: 'Fakir',
status: 'Dalam Semakan',
familyCategory: 'Fakir (0-49% Had Kifayah)',
asnafCategory: 'Ibnu Sabil'
}
}
]);
// Mock detail data for a profile (DETAIL page)
const mockProfileDetail: AsnafProfile = asnafProfiles.value[0];
// Get profile by ID for detail page
function getProfileById(id: string): AsnafProfile | undefined {
return asnafProfiles.value.find((p) => p.id === id);
}
export const useAsnafMockData = () => {
// Computed statistics
const statistics = computed(() => {
const total = asnafProfiles.value.length;
const active = asnafProfiles.value.filter(p => p.status === 'Aktif').length;
const inactive = asnafProfiles.value.filter(p => p.status === 'Tidak Aktif').length;
const review = asnafProfiles.value.filter(p => p.status === 'Dalam Semakan').length;
return {
total,
active,
inactive,
review
};
});
// Filter profiles by search and filters
const filterProfiles = (search = '', statusFilter = 'All', categoryFilter = 'All'): AsnafProfile[] => {
return asnafProfiles.value.filter(profile => {
// Search by name or ID
const matchesSearch = search === '' ||
profile.nama.toLowerCase().includes(search.toLowerCase()) ||
profile.id.toLowerCase().includes(search.toLowerCase()) ||
profile.idNumber.includes(search);
// Filter by status
const matchesStatus = statusFilter === 'All' || profile.status === statusFilter;
// Filter by category
const matchesCategory = categoryFilter === 'All' || profile.kategori === categoryFilter;
return matchesSearch && matchesStatus && matchesCategory;
});
};
// Categories
const categories = [
'Fakir',
'Miskin',
'Mualaf',
'Fi-sabilillah',
'Gharimin',
'Ibnu Sabil'
];
// Statuses
const statuses = [
'Aktif',
'Tidak Aktif',
'Dalam Semakan'
];
return {
asnafProfiles,
statistics,
getProfileById,
filterProfiles,
categories,
statuses
};
};

161
docs/SITE_SETTINGS.md Normal file
View File

@ -0,0 +1,161 @@
# Site Settings Feature
## 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.
## Features
### 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
### 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
### 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
## How to Access
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
## Technical Implementation
### 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
### 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
### 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`
### 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
### Global Integration
The site settings are globally integrated across:
#### 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
#### Loading Component
- Uses site logo if available, fallback to default
- Displays site name in loading screen
#### App.vue
- Global meta tags updated from site settings
- Title, description, and favicon managed globally
- Theme initialization from site settings
#### 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
### 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
### Custom Theme Structure
Custom themes added to theme.css should follow this structure:
```css
html[data-theme="your-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 */
}
```
## 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
## 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
## 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
### 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

122
fixes-summary.md Normal file
View File

@ -0,0 +1,122 @@
# Fixes Implemented ✅
## 1. Header Title Not Showing Issue 🔧
**Problem**: Site name not appearing in header even when toggle is enabled
**Root Cause**: Header component only showed site name in horizontal layout (`v-else` condition), but most of the time the layout is vertical
**Fixes Applied**:
- ✅ Added site name display to both vertical AND horizontal header layouts
- ✅ Enhanced site settings loading in Header component's `onMounted` hook
- ✅ Added immediate watchers to sync toggle changes with global site settings
- ✅ Added debug info panel to troubleshoot site settings state
**Files Modified**:
- `components/layouts/Header.vue` - Added site name to vertical layout
- `pages/devtool/config/site-settings/index.vue` - Enhanced watchers and debugging
## 2. Button Styling Standardization 🎨
**Problem**: Inconsistent button styling across tabs
**Standardization Applied**:
- ✅ All upload buttons: `variant="outline" size="sm"`
- ✅ Save Changes button: `variant="primary" size="sm"`
- ✅ Reset button: `variant="outline" size="sm"`
- ✅ Apply Font button: `variant="outline" size="sm"` (changed from primary)
**Consistent Button Pattern**:
```vue
<rs-button variant="outline" size="sm">
<Icon name="ic:outline-[icon]" class="mr-1" />
Action Text
</rs-button>
```
**Files Modified**:
- `pages/devtool/config/site-settings/index.vue` - Standardized Apply Font button
## 3. Site Settings Description Padding 📝
**Problem**: "Configure your platform's branding, appearance, SEO, and functionality" text had improper padding for two lines
**Fix Applied**:
- ✅ Added `leading-relaxed` class for better line height
- ✅ Improved text readability and spacing
**Before**:
```vue
<p>Configure your platform's branding, appearance, SEO, and functionality.</p>
```
**After**:
```vue
<p class="leading-relaxed">Configure your platform's branding, appearance, SEO, and functionality.</p>
```
**Files Modified**:
- `pages/devtool/config/site-settings/index.vue` - Enhanced info card description
## Additional Improvements 🚀
### Enhanced Toggle Functionality
- ✅ Real-time toggle updates without requiring save
- ✅ Immediate sync between settings page and global state
- ✅ Both header and sidemenu respect the toggle setting
### Debug Information
- ✅ Added debug panel in live preview showing:
- Current site name
- Toggle state (Yes/No)
- Font size in pixels
- ✅ Helps troubleshoot configuration issues
### Header Logic Improvements
- ✅ Site name now shows in both vertical and horizontal layouts
- ✅ Proper font size scaling in sidemenu (65% of header size)
- ✅ Automatic site settings loading on component mount
## Testing Verification ✅
**Header Display Test**:
1. ✅ Site name appears in vertical layout (default)
2. ✅ Site name appears in horizontal layout
3. ✅ Toggle OFF hides name in both layouts
4. ✅ Toggle ON shows name in both layouts
5. ✅ Font size applies correctly
6. ✅ Changes are immediate
**Button Consistency Test**:
1. ✅ All upload buttons use outline variant
2. ✅ Save button uses primary variant
3. ✅ Reset button uses outline variant
4. ✅ All buttons have consistent size (sm)
5. ✅ Icons are properly positioned with mr-1
**Description Styling Test**:
1. ✅ Text has proper line height for readability
2. ✅ Padding appears natural for two-line content
3. ✅ Dark mode compatibility maintained
## Files Changed Summary 📁
1. **components/layouts/Header.vue**
- Added site name to vertical layout
- Enhanced site settings loading
- Improved responsive layout handling
2. **pages/devtool/config/site-settings/index.vue**
- Standardized button variants and sizes
- Added debug information panel
- Enhanced toggle watching and real-time updates
- Improved description line height
- Fixed immediate change application
## Next Steps 🎯
1. Test the site settings page at `/devtool/config/site-settings`
2. Verify header displays site name when toggle is enabled
3. Check that all buttons follow consistent styling
4. Confirm description text has proper spacing
5. Use debug panel to troubleshoot any remaining issues

589
llms.txt
View File

@ -1,589 +0,0 @@
# corradAF Framework - LLM Interaction Guide
## Metadata
- **Framework Name**: corradAF (Corrad Application Framework)
- **Framework Version**: 1.0.0
- **License**: MIT License
- **Base Technology**: Nuxt 3, Vue 3, TypeScript/JavaScript
- **UI Framework**: TailwindCSS with custom components
- **Database ORM**: Prisma
- **Supported Languages**: English (primary), multi-language ready
- **Input Format**: Text, Markdown, JSON for API specifications
- **Output Format**: Vue SFC components, TypeScript/JavaScript, JSON configurations
## Framework Overview
### Introduction:
corradAF is a comprehensive Nuxt.js template designed for rapid application development. It provides a complete development tools suite, authentication system, and modern UI components. This document defines interaction patterns for LLMs working with the corradAF framework.
### Core Architecture:
- **Frontend**: Nuxt 3 with Vue 3 Composition API
- **Styling**: TailwindCSS with custom component library
- **State Management**: Pinia stores
- **Authentication**: JWT-based with middleware protection
- **Database**: Prisma ORM with PostgreSQL (configurable)
- **Development Tools**: Built-in suite for rapid development
## Content Structure Guidelines
### File Organization:
```
├── pages/ # Route pages (Nuxt auto-routing)
├── components/ # Reusable Vue components
├── composables/ # Vue composables for shared logic
├── layouts/ # Application layouts
├── middleware/ # Route middleware (auth, permissions)
├── server/api/ # Server-side API endpoints
├── stores/ # Pinia state management
├── assets/ # Static assets and styles
├── public/ # Public static files
├── prisma/ # Database schema and migrations
└── devtool/ # Development tools pages
```
### Component Naming Conventions:
- **Pages**: Use kebab-case for file names (e.g., `user-management.vue`)
- **Components**: Use PascalCase for component names (e.g., `UserCard.vue`)
- **Composables**: Prefix with `use` (e.g., `useUserManagement.js`)
- **Stores**: Use camelCase with descriptive names (e.g., `userStore.js`)
## Writing Guidelines for LLMs
### Controlled Vocabulary:
- Use `navigateTo()` instead of `router.push()` for navigation (Nuxt 3 pattern)
- Use `definePageMeta()` for page configuration
- Use `ref()` and `reactive()` for Vue 3 Composition API
- Use `composables` instead of `mixins` for shared logic
- Use `middleware` for route protection and validation
### Grammar Rules:
- **Sentence Length**: Maximum 20 words for code comments
- **Active Voice**: Prefer active voice in documentation
- **Function Names**: Use camelCase with descriptive verbs
- **Variable Names**: Use camelCase with clear, descriptive nouns
### Code Style Guidelines:
- **Vue SFC Structure**: `<script setup>`, `<template>`, `<style>` order
- **Import Order**: Vue imports, Nuxt imports, local imports, type imports
- **Function Declaration**: Use `function` keyword for named functions, arrow functions for callbacks
- **Async/Await**: Prefer async/await over promises for better readability
## Component Templates
### Standard Vue SFC Component Template:
```vue
<script setup>
// Imports
import { ref, computed, onMounted } from 'vue'
// Props and emits
const props = defineProps({
modelValue: {
type: [String, Number, Boolean],
default: null
}
})
const emit = defineEmits(['update:modelValue', 'change'])
// Reactive data
const isLoading = ref(false)
const data = ref([])
// Computed properties
const processedData = computed(() => {
return data.value.filter(item => item.active)
})
// Methods
function handleUpdate(value) {
emit('update:modelValue', value)
emit('change', value)
}
// Lifecycle
onMounted(async () => {
await loadData()
})
async function loadData() {
isLoading.value = true
try {
// Load data logic
} catch (error) {
console.error('Error loading data:', error)
} finally {
isLoading.value = false
}
}
</script>
<template>
<div class="component-wrapper">
<!-- Component content -->
</div>
</template>
<style scoped>
/* Component-specific styles */
</style>
```
### Page Component Template:
```vue
<script setup>
definePageMeta({
title: "Page Title",
middleware: ["auth"], // Add middleware as needed
requiresAuth: true,
breadcrumb: [
{
name: "Dashboard",
path: "/dashboard",
},
{
name: "Current Page",
path: "/current-page",
},
],
})
// Page-specific logic
</script>
<template>
<div class="page-container">
<LayoutsBreadcrumb />
<!-- Page content -->
</div>
</template>
```
### Development Tool Page Template:
```vue
<script setup>
definePageMeta({
title: "Tool Name",
middleware: ["auth", "dev-tools"],
requiresAuth: true,
layout: "devtool",
breadcrumb: [
{
name: "Dashboard",
path: "/dashboard",
},
{
name: "Development Tools",
path: "/devtool",
},
{
name: "Tool Name",
path: "/devtool/tool-name",
},
],
})
// Tool-specific functionality
const toolData = ref([])
const isLoading = ref(false)
// CRUD operations
async function createItem(data) {
// Implementation
}
async function updateItem(id, data) {
// Implementation
}
async function deleteItem(id) {
// Implementation
}
</script>
<template>
<div class="devtool-container space-y-6">
<div class="flex justify-between items-center">
<h1 class="text-2xl font-bold text-primary">Tool Name</h1>
<rs-button variant="primary" @click="createNew">
<Icon name="mdi:plus" size="18" />
Add New
</rs-button>
</div>
<!-- Tool interface -->
</div>
</template>
```
## API Endpoint Templates
### Server API Route Template:
```typescript
export default defineEventHandler(async (event) => {
// Validate authentication
const user = await requireUserSession(event)
// Handle different HTTP methods
const method = getMethod(event)
if (method === 'GET') {
// GET logic
return { data: [] }
}
if (method === 'POST') {
// POST logic
const body = await readBody(event)
// Validate input
if (!body.name) {
throw createError({
statusCode: 400,
statusMessage: 'Name is required'
})
}
// Process request
return { success: true, data: body }
}
// Handle other methods
throw createError({
statusCode: 405,
statusMessage: 'Method not allowed'
})
})
```
### API Response Format:
```json
{
"success": true,
"data": {},
"message": "Operation completed successfully",
"meta": {
"timestamp": "2024-01-01T00:00:00Z",
"version": "1.0.0"
}
}
```
### Error Response Format:
```json
{
"success": false,
"error": {
"code": "VALIDATION_ERROR",
"message": "Invalid input provided",
"details": {}
},
"meta": {
"timestamp": "2024-01-01T00:00:00Z",
"version": "1.0.0"
}
}
```
## Database Schema Patterns
### Prisma Model Template:
```prisma
model User {
id String @id @default(cuid())
email String @unique
name String?
role Role @default(USER)
isActive Boolean @default(true)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
// Relations
profile UserProfile?
posts Post[]
@@map("users")
}
model UserProfile {
id String @id @default(cuid())
userId String @unique
avatar String?
bio String?
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@map("user_profiles")
}
enum Role {
USER
ADMIN
DEVELOPER
}
```
## TailwindCSS and Styling Guidelines
### Component Styling Patterns:
- **Cards**: Use `rs-card` component or `bg-white rounded-lg shadow-sm border`
- **Buttons**: Use `rs-button` component with variants (primary, secondary, danger)
- **Forms**: Use FormKit components with TailwindCSS utilities
- **Grid Layouts**: Use `grid grid-cols-{n} gap-{size}` for responsive layouts
- **Spacing**: Use consistent spacing scale (4, 6, 8, 12, 16, 24)
### Color Scheme:
- **Primary**: `text-primary`, `bg-primary`
- **Secondary**: `text-secondary`, `bg-secondary`
- **Success**: `text-green-600`, `bg-green-100`
- **Warning**: `text-yellow-600`, `bg-yellow-100`
- **Danger**: `text-red-600`, `bg-red-100`
## Authentication and Security Patterns
### Route Protection:
```javascript
// middleware/auth.js
export default defineNuxtRouteMiddleware((to, from) => {
const { $auth } = useNuxtApp()
if (!$auth.user) {
return navigateTo('/login')
}
})
// middleware/dev-tools.js
export default defineNuxtRouteMiddleware((to, from) => {
const { $auth } = useNuxtApp()
if (!$auth.user?.isDeveloper) {
throw createError({
statusCode: 403,
statusMessage: 'Access forbidden'
})
}
})
```
### API Security:
```typescript
// server/utils/auth.ts
export async function requireUserSession(event) {
const token = getCookie(event, 'auth-token') || getHeader(event, 'authorization')
if (!token) {
throw createError({
statusCode: 401,
statusMessage: 'Authentication required'
})
}
try {
const user = await verifyJWT(token)
return user
} catch (error) {
throw createError({
statusCode: 401,
statusMessage: 'Invalid token'
})
}
}
```
## Development Tools Integration
### Adding New Development Tools:
1. Create page in `pages/devtool/tool-name/`
2. Add navigation entry in navigation configuration
3. Implement CRUD operations
4. Add proper middleware and permissions
5. Follow established UI patterns
### Tool Configuration Template:
```javascript
// devtool configuration
export const toolConfig = {
name: 'Tool Name',
description: 'Tool description',
icon: 'mdi:tool-icon',
path: '/devtool/tool-name',
permissions: ['developer', 'admin'],
features: [
'create',
'read',
'update',
'delete',
'export',
'import'
]
}
```
## Input/Output Specifications for Code Generation
### Request Format for Component Generation:
```json
{
"task": "component_generation",
"type": "vue_component",
"specifications": {
"name": "UserCard",
"props": ["user", "showActions"],
"events": ["edit", "delete"],
"features": ["responsive", "accessible"],
"styling": "tailwindcss"
}
}
```
### Response Format:
```json
{
"success": true,
"generated_code": "<!-- Vue component code -->",
"file_path": "components/UserCard.vue",
"dependencies": ["vue", "@nuxt/icon"],
"usage_example": "<UserCard :user=\"user\" @edit=\"handleEdit\" />",
"explanation": "Generated a responsive user card component with edit and delete actions."
}
```
## Error Handling Patterns
### Frontend Error Handling:
```javascript
// composables/useErrorHandler.js
export const useErrorHandler = () => {
const handleError = (error, context = '') => {
console.error(`Error in ${context}:`, error)
// Show user-friendly message
const { $toast } = useNuxtApp()
$toast.error('An error occurred. Please try again.')
// Log to monitoring service if available
if (process.env.NODE_ENV === 'production') {
// Log to external service
}
}
return { handleError }
}
```
### API Error Handling:
```typescript
// server/utils/errorHandler.ts
export function handleAPIError(error: unknown) {
if (error instanceof ValidationError) {
throw createError({
statusCode: 400,
statusMessage: 'Validation failed',
data: error.details
})
}
if (error instanceof DatabaseError) {
throw createError({
statusCode: 500,
statusMessage: 'Database operation failed'
})
}
// Generic error
throw createError({
statusCode: 500,
statusMessage: 'Internal server error'
})
}
```
## Testing Patterns
### Component Testing Template:
```javascript
// tests/components/UserCard.test.js
import { mount } from '@vue/test-utils'
import UserCard from '~/components/UserCard.vue'
describe('UserCard', () => {
const mockUser = {
id: '1',
name: 'John Doe',
email: 'john@example.com'
}
it('renders user information correctly', () => {
const wrapper = mount(UserCard, {
props: { user: mockUser }
})
expect(wrapper.text()).toContain('John Doe')
expect(wrapper.text()).toContain('john@example.com')
})
it('emits edit event when edit button is clicked', async () => {
const wrapper = mount(UserCard, {
props: { user: mockUser, showActions: true }
})
await wrapper.find('[data-test="edit-button"]').trigger('click')
expect(wrapper.emitted('edit')).toBeTruthy()
expect(wrapper.emitted('edit')[0]).toEqual([mockUser])
})
})
```
## Ethical Guidelines and Security Considerations
### Security Best Practices:
- **Input Validation**: Always validate and sanitize user inputs
- **SQL Injection Prevention**: Use Prisma ORM parameterized queries
- **XSS Prevention**: Use Vue's built-in template sanitization
- **CSRF Protection**: Implement CSRF tokens for state-changing operations
- **Authentication**: Use secure JWT implementation with proper expiration
- **Authorization**: Implement role-based access control (RBAC)
### Ethical Considerations:
- **Accessibility**: Follow WCAG 2.1 guidelines for component generation
- **Privacy**: Implement data protection and GDPR compliance patterns
- **Bias Prevention**: Ensure generated content is inclusive and unbiased
- **Performance**: Generate efficient code that doesn't compromise user experience
### Data Handling:
- **Encryption**: Use encryption for sensitive data storage
- **Logging**: Log security events without exposing sensitive information
- **Audit Trail**: Maintain audit logs for critical operations
- **Data Retention**: Implement proper data retention and deletion policies
## Performance Guidelines
### Code Generation Best Practices:
- **Lazy Loading**: Use dynamic imports for large components
- **Tree Shaking**: Write code that supports tree shaking
- **Bundle Size**: Consider bundle size impact in generated code
- **Caching**: Implement appropriate caching strategies
- **Database Queries**: Use efficient Prisma queries with proper relations
### Optimization Patterns:
```javascript
// Lazy component loading
const LazyComponent = defineAsyncComponent(() => import('~/components/HeavyComponent.vue'))
// Efficient data fetching
const { data, pending, error } = await useLazyFetch('/api/data', {
key: 'unique-key',
server: false // Client-side only if needed
})
// Computed optimization
const expensiveComputation = computed(() => {
return useMemo(() => heavyOperation(props.data), [props.data])
})
```
---
This document serves as a comprehensive guide for LLMs working with the corradAF framework. It ensures consistent code generation, proper architecture patterns, and adherence to best practices for security, performance, and maintainability.

View File

@ -1,88 +1,126 @@
export default [
{
"header": "Utama",
"description": "",
"child": [
header: "Utama",
description: "",
child: [
{
"title": "Dashboard",
"path": "/dashboard",
"icon": "ic:outline-dashboard",
"child": [],
"meta": {}
}
title: "Dashboard",
path: "/dashboard",
icon: "ic:outline-dashboard",
child: [],
meta: {},
},
{
title: "Notes",
path: "/notes",
icon: "",
child: [],
},
{
title: "Metabase",
path: "/metabase",
icon: "",
child: [],
},
],
"meta": {}
meta: {},
},
{
"header": "Pentadbiran",
"description": "Urus aplikasi anda",
"child": [
header: "BF-PRF",
description: "Profiling",
child: [
{
"title": "Konfigurasi",
"icon": "ic:outline-settings",
"child": [
title: "Asnaf",
icon: "mdi:account-group",
child: [
{
"title": "Persekitaran",
"path": "/devtool/config/environment"
title: "Senarai Asnaf",
path: "/BF-PRF/AS/LIST",
icon: "mdi:format-list-bulleted",
},
{
"title": "Site Settings",
"path": "/devtool/config/site-settings"
}
]
},
{
"title": "Penyunting Menu",
"icon": "ci:menu-alt-03",
"path": "/devtool/menu-editor",
"child": []
},
{
"title": "Urus Pengguna",
"path": "/devtool/user-management",
"icon": "ph:user-circle-gear",
"child": [
{
"title": "Senarai Pengguna",
"path": "/devtool/user-management/user",
"icon": "",
"child": []
title: "Pendaftaran Pantas (Single)",
path: "/BF-PRF/AS/FR/01",
icon: "mdi:account-plus",
},
{
"title": "Senarai Peranan",
"path": "/devtool/user-management/role",
"icon": "",
"child": []
}
]
},
{
"title": "Kandungan",
"icon": "mdi:pencil-ruler",
"child": [
{
"title": "Penyunting",
"path": "/devtool/content-editor"
title: "Pendaftaran Lengkap",
path: "/BF-PRF/AS/FR/02",
icon: "mdi:account-multiple-plus",
},
{
"title": "Templat",
"path": "/devtool/content-editor/template"
}
]
{ title: "Kemaskini", path: "/BF-PRF/AS/UP/01", icon: "mdi:pencil" },
],
},
{
"title": "Penyunting API",
"path": "/devtool/api-editor",
"icon": "material-symbols:api-rounded",
"child": []
}
],
"meta": {
"auth": {
"role": [
"Developer"
]
}
}
}
]
},
{
header: "Pentadbiran",
description: "Urus aplikasi anda",
child: [
{
title: "Konfigurasi",
icon: "ic:outline-settings",
child: [
{
title: "Persekitaran",
path: "/devtool/config/environment",
},
{
title: "Site Settings",
path: "/devtool/config/site-settings",
},
],
},
{
title: "Penyunting Menu",
icon: "ci:menu-alt-03",
path: "/devtool/menu-editor",
child: [],
},
{
title: "Urus Pengguna",
path: "/devtool/user-management",
icon: "ph:user-circle-gear",
child: [
{
title: "Senarai Pengguna",
path: "/devtool/user-management/user",
icon: "",
child: [],
},
{
title: "Senarai Peranan",
path: "/devtool/user-management/role",
icon: "",
child: [],
},
],
},
{
title: "Kandungan",
icon: "mdi:pencil-ruler",
child: [
{
title: "Penyunting",
path: "/devtool/content-editor",
},
{
title: "Templat",
path: "/devtool/content-editor/template",
},
],
},
{
title: "Penyunting API",
path: "/devtool/api-editor",
icon: "material-symbols:api-rounded",
child: [],
},
],
meta: {
auth: {
role: ["Developer"],
},
},
},
];

View File

@ -1,29 +1,4 @@
{
"name": "corrad-af",
"version": "1.0.0",
"description": "Corrad Application Framework - A comprehensive Nuxt.js template for rapid application development",
"author": "Corrad Team",
"license": "MIT",
"keywords": [
"nuxt",
"vue",
"typescript",
"tailwindcss",
"template",
"framework",
"development-tools",
"admin-panel",
"cms",
"authentication"
],
"repository": {
"type": "git",
"url": "https://git.sena.my/corrad-software/corrad-af-2024.git"
},
"bugs": {
"url": "https://git.sena.my/corrad-software/corrad-af-2024/issues"
},
"homepage": "https://git.sena.my/corrad-software/corrad-af-2024",
"private": true,
"scripts": {
"build": "nuxt build",
@ -31,8 +6,7 @@
"generate": "nuxt generate",
"preview": "nuxt preview",
"postinstall": "nuxt prepare",
"prisma": "yarn prisma:generate && nuxt dev",
"prisma:generate": "npx prisma db pull && npx prisma generate"
"prisma": "npx prisma db pull && npx prisma generate && nuxt dev"
},
"devDependencies": {
"@nuxtjs/tailwindcss": "^6.8.0",

View File

@ -0,0 +1,674 @@
<script setup>
import { ref, computed, onMounted } from 'vue';
import { useAsnafMockData } from '~/composables/useAsnafMockData';
import { useToast } from 'vue-toastification';
const route = useRoute();
const toast = useToast();
const { getProfileById } = useAsnafMockData();
const profile = ref(null);
const loading = ref(true);
const isLoadingAnalysis = ref(false);
const confirmDelete = ref(false);
const activeTab = ref('personal');
// Load profile data
onMounted(async () => {
const id = route.params.id;
loading.value = true;
const fetchedProfile = getProfileById(id);
if (fetchedProfile) {
profile.value = { ...fetchedProfile, analysis: null };
loading.value = false;
} else {
toast.error('Profil tidak dijumpai');
navigateTo('/BF-PRF/AS/LIST');
loading.value = false;
}
});
// New function to be called by a button
async function fetchAIAnalysis() {
if (!profile.value) {
toast.error('Profil data tidak tersedia untuk analisis.');
return;
}
isLoadingAnalysis.value = true;
try {
const requestBody = {
monthlyIncome: profile.value.monthlyIncome,
otherIncome: profile.value.otherIncome,
totalIncome: profile.value.totalIncome,
occupation: profile.value.occupation,
maritalStatus: profile.value.maritalStatus,
dependents: profile.value.dependents,
// Add other fields you want to send for analysis here
};
const analysisResponse = await $fetch('/api/analyze-asnaf', {
method: 'POST',
body: requestBody,
});
if (profile.value) {
profile.value.analysis = analysisResponse;
}
} catch (error) {
console.error("Error fetching AI Analysis from /api/analyze-asnaf:", error);
toast.error('Gagal memuat analisis AI dari server.');
if (profile.value) {
profile.value.analysis = {
hadKifayahPercentage: 'Ralat',
kategoriAsnaf: 'Ralat Server',
kategoriKeluarga: 'Ralat Server',
cadanganKategori: 'Ralat Server',
statusKelayakan: 'Ralat Server',
cadanganBantuan: [{ nama: 'Tidak dapat memuat cadangan bantuan', peratusan: 'Ralat' }],
ramalanJangkaMasaPulih: 'Ralat Server',
rumusan: 'Ralat Server'
};
}
} finally {
isLoadingAnalysis.value = false;
}
}
// Computed status color
const statusColor = computed(() => {
if (!profile.value) return '';
switch (profile.value.status) {
case 'Aktif': return 'success';
case 'Tidak Aktif': return 'danger';
case 'Dalam Semakan': return 'warning';
default: return 'secondary';
}
});
// Computed category color
const categoryColor = computed(() => {
if (!profile.value) return '';
switch (profile.value.kategori) {
case 'Fakir': return 'danger';
case 'Miskin': return 'warning';
case 'Mualaf': return 'info';
case 'Fi-sabilillah': return 'primary';
case 'Gharimin': return 'secondary';
case 'Ibnu Sabil': return 'success';
default: return 'primary';
}
});
// Page metadata
definePageMeta({
title: "Maklumat Asnaf",
middleware: ["auth"],
requiresAuth: true,
breadcrumb: [
{
name: "Dashboard",
path: "/",
},
{
name: "BF-PRF",
path: "/BF-PRF",
},
{
name: "Asnaf",
path: "/BF-PRF/AS",
},
{
name: "Senarai",
path: "/BF-PRF/AS/LIST",
},
{
name: "Maklumat",
path: "/BF-PRF/AS/DETAIL",
},
],
});
// Navigation functions
function navigateToList() {
navigateTo('/BF-PRF/AS/LIST');
}
function navigateToEdit() {
navigateTo(`/BF-PRF/AS/UP/01?id=${profile.value.id}`);
}
function handleDelete() {
confirmDelete.value = true;
}
function confirmDeleteProfile() {
toast.success('Profil telah dipadamkan');
navigateTo('/BF-PRF/AS/LIST');
confirmDelete.value = false;
}
function cancelDelete() {
confirmDelete.value = false;
}
</script>
<template>
<div class="space-y-6">
<LayoutsBreadcrumb />
<!-- Loading state -->
<div v-if="loading" class="flex justify-center items-center py-20">
<div class="text-center">
<Loading />
<p class="mt-4 text-gray-600">Memuat maklumat asnaf...</p>
</div>
</div>
<div v-else>
<!-- Header with actions -->
<div class="flex flex-col md:flex-row md:justify-between md:items-center gap-4 mb-6">
<div class="flex items-center gap-3">
<h1 class="text-2xl font-bold text-primary">{{ profile.nama }}</h1>
<rs-badge :variant="statusColor">{{ profile.status }}</rs-badge>
<rs-badge :variant="categoryColor">{{ profile.kategori }}</rs-badge>
</div>
<div class="flex items-center gap-2">
<rs-button variant="secondary-outline" @click="navigateToList">
<Icon name="mdi:arrow-left" size="18" class="mr-1" />
Kembali
</rs-button>
<rs-button variant="primary" @click="navigateToEdit">
<Icon name="mdi:pencil" size="18" class="mr-1" />
Kemaskini
</rs-button>
<rs-button variant="danger" @click="handleDelete">
<Icon name="mdi:delete" size="18" class="mr-1" />
Padam
</rs-button>
</div>
</div>
<!-- Profile Overview -->
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-6">
<!-- Profile Photo and Basic Info -->
<rs-card class="lg:col-span-1">
<div class="p-6 flex flex-col items-center">
<div class="w-32 h-32 rounded-full bg-gray-200 flex items-center justify-center mb-4 overflow-hidden">
<Icon name="mdi:account" size="64" class="text-gray-400" />
</div>
<h2 class="text-xl font-semibold text-center">{{ profile.nama }}</h2>
<p class="text-gray-500 text-center mb-4">{{ profile.id }}</p>
<div class="w-full text-center">
<rs-badge :variant="categoryColor" class="mb-2">{{ profile.kategori }}</rs-badge>
<p class="text-sm text-gray-600">Didaftarkan pada {{ new Date(profile.tarikhDaftar).toLocaleDateString('ms-MY') }}</p>
</div>
</div>
</rs-card>
<!-- Personal Information -->
<rs-card class="lg:col-span-2">
<template #header>
<div class="px-4 py-3">
<h3 class="text-lg font-semibold text-primary flex items-center">
<Icon name="mdi:account-details" size="20" class="mr-2" />
Maklumat Peribadi
</h3>
</div>
</template>
<template #body>
<div class="p-4">
<div class="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-4">
<div>
<h4 class="text-sm font-medium text-gray-500">No. Kad Pengenalan</h4>
<p>{{ profile.idNumber }}</p>
</div>
<div>
<h4 class="text-sm font-medium text-gray-500">Jantina</h4>
<p>{{ profile.gender }}</p>
</div>
<div>
<h4 class="text-sm font-medium text-gray-500">Tarikh Lahir</h4>
<p>{{ new Date(profile.birthDate).toLocaleDateString('ms-MY') }}</p>
</div>
<div>
<h4 class="text-sm font-medium text-gray-500">Status Perkahwinan</h4>
<p>{{ profile.maritalStatus }}</p>
</div>
<div>
<h4 class="text-sm font-medium text-gray-500">Pekerjaan</h4>
<p>{{ profile.occupation }}</p>
</div>
<div>
<h4 class="text-sm font-medium text-gray-500">Pendapatan Bulanan</h4>
<p>RM {{ profile.monthlyIncome }}</p>
</div>
</div>
</div>
</template>
</rs-card>
<!-- Contact Information -->
<rs-card class="lg:col-span-3">
<template #header>
<div class="px-4 py-3">
<h3 class="text-lg font-semibold text-primary flex items-center">
<Icon name="mdi:contacts" size="20" class="mr-2" />
Maklumat Perhubungan
</h3>
</div>
</template>
<template #body>
<div class="p-4">
<div class="grid grid-cols-1 md:grid-cols-3 gap-x-6 gap-y-4">
<div>
<h4 class="text-sm font-medium text-gray-500">Alamat</h4>
<p>{{ profile.alamat || 'Tiada' }}</p>
</div>
<div>
<h4 class="text-sm font-medium text-gray-500">No. Telefon</h4>
<p>{{ profile.telefon }}</p>
</div>
<div>
<h4 class="text-sm font-medium text-gray-500">Emel</h4>
<p>{{ profile.email }}</p>
</div>
</div>
</div>
</template>
</rs-card>
</div>
<!-- Tabbed Details -->
<rs-card>
<template #header>
<div class="px-4 py-3 border-b">
<div class="flex overflow-x-auto space-x-4">
<button
@click="activeTab = 'personal'"
class="py-2 px-1 border-b-2 font-medium text-sm whitespace-nowrap transition-colors"
:class="activeTab === 'personal' ? 'border-primary text-primary' : 'border-transparent text-gray-500 hover:text-gray-700'"
>
<Icon name="mdi:account-group" size="18" class="mr-1" />
Maklumat Keluarga
</button>
<button
@click="activeTab = 'income'"
class="py-2 px-1 border-b-2 font-medium text-sm whitespace-nowrap transition-colors"
:class="activeTab === 'income' ? 'border-primary text-primary' : 'border-transparent text-gray-500 hover:text-gray-700'"
>
<Icon name="mdi:cash" size="18" class="mr-1" />
Maklumat Pendapatan
</button>
<button
@click="activeTab = 'aid'"
class="py-2 px-1 border-b-2 font-medium text-sm whitespace-nowrap transition-colors"
:class="activeTab === 'aid' ? 'border-primary text-primary' : 'border-transparent text-gray-500 hover:text-gray-700'"
>
<Icon name="mdi:gift" size="18" class="mr-1" />
Maklumat Bantuan
</button>
<button
@click="activeTab = 'documents'"
class="py-2 px-1 border-b-2 font-medium text-sm whitespace-nowrap transition-colors"
:class="activeTab === 'documents' ? 'border-primary text-primary' : 'border-transparent text-gray-500 hover:text-gray-700'"
>
<Icon name="mdi:file-document" size="18" class="mr-1" />
Dokumen
</button>
<button
@click="activeTab = 'analysis'"
class="py-2 px-1 border-b-2 font-medium text-sm whitespace-nowrap transition-colors"
:class="activeTab === 'analysis' ? 'border-primary text-primary' : 'border-transparent text-gray-500 hover:text-gray-700'"
>
<Icon name="mdi:chart-bar" size="18" class="mr-1" />
Analisis Data
</button>
</div>
</div>
</template>
<template #body>
<!-- Family Information Tab -->
<div v-if="activeTab === 'personal'" class="p-6">
<div v-if="profile.spouse" class="mb-8">
<h3 class="text-lg font-semibold text-primary mb-4">Maklumat Pasangan</h3>
<div class="bg-gray-50 p-4 rounded-lg">
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<h4 class="text-sm font-medium text-gray-500">Nama</h4>
<p>{{ profile.spouse.name }}</p>
</div>
<div>
<h4 class="text-sm font-medium text-gray-500">No. Kad Pengenalan</h4>
<p>{{ profile.spouse.idNumber }}</p>
</div>
</div>
</div>
</div>
<div>
<h3 class="text-lg font-semibold text-primary mb-4">Tanggungan</h3>
<div v-if="profile.dependents && profile.dependents.length > 0">
<div class="overflow-x-auto">
<table class="min-w-full divide-y divide-gray-200">
<thead>
<tr>
<th class="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Bil.</th>
<th class="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Nama</th>
<th class="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Umur</th>
<th class="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Hubungan</th>
</tr>
</thead>
<tbody class="bg-white divide-y divide-gray-200">
<tr v-for="(dependent, index) in profile.dependents" :key="index" class="hover:bg-gray-50">
<td class="px-6 py-4 whitespace-nowrap">{{ index + 1 }}</td>
<td class="px-6 py-4 whitespace-nowrap">{{ dependent.name }}</td>
<td class="px-6 py-4 whitespace-nowrap">{{ dependent.age }}</td>
<td class="px-6 py-4 whitespace-nowrap">{{ dependent.relationship }}</td>
</tr>
</tbody>
</table>
</div>
</div>
<div v-else class="bg-gray-50 p-6 rounded-lg text-center">
<Icon name="mdi:account-off" size="48" class="text-gray-400 mb-2" />
<p class="text-gray-500">Tiada tanggungan</p>
</div>
</div>
</div>
<!-- Income Information Tab -->
<div v-if="activeTab === 'income'" class="p-6">
<div class="grid grid-cols-1 md:grid-cols-3 gap-6">
<rs-card>
<div class="p-4 text-center">
<div class="mb-2">
<Icon name="mdi:cash-multiple" size="36" class="text-primary" />
</div>
<p class="text-sm text-gray-500">Pendapatan Bulanan</p>
<p class="text-xl font-bold text-primary">RM {{ profile.monthlyIncome }}</p>
</div>
</rs-card>
<rs-card>
<div class="p-4 text-center">
<div class="mb-2">
<Icon name="mdi:cash-plus" size="36" class="text-primary" />
</div>
<p class="text-sm text-gray-500">Pendapatan Lain</p>
<p class="text-xl font-bold text-primary">RM {{ profile.otherIncome }}</p>
</div>
</rs-card>
<rs-card>
<div class="p-4 text-center">
<div class="mb-2">
<Icon name="mdi:cash-register" size="36" class="text-primary" />
</div>
<p class="text-sm text-gray-500">Jumlah Pendapatan</p>
<p class="text-xl font-bold text-primary">RM {{ profile.totalIncome }}</p>
</div>
</rs-card>
</div>
<div class="mt-6">
<h3 class="text-lg font-semibold text-primary mb-4">Butiran Pendapatan</h3>
<div class="bg-gray-50 p-4 rounded-lg">
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<h4 class="text-sm font-medium text-gray-500">Pekerjaan</h4>
<p>{{ profile.occupation }}</p>
</div>
<div>
<h4 class="text-sm font-medium text-gray-500">Pendapatan Bulanan</h4>
<p>RM {{ profile.monthlyIncome }}</p>
</div>
<div>
<h4 class="text-sm font-medium text-gray-500">Pendapatan Lain</h4>
<p>RM {{ profile.otherIncome }}</p>
</div>
<div>
<h4 class="text-sm font-medium text-gray-500">Jumlah Pendapatan</h4>
<p>RM {{ profile.totalIncome }}</p>
</div>
</div>
</div>
</div>
</div>
<!-- Aid Information Tab -->
<div v-if="activeTab === 'aid'" class="p-6">
<div class="bg-gray-50 p-6 rounded-lg text-center">
<Icon name="mdi:gift-off" size="48" class="text-gray-400 mb-2" />
<p class="text-gray-500">Tiada maklumat bantuan</p>
</div>
</div>
<!-- Documents Tab -->
<div v-if="activeTab === 'documents'" class="p-6">
<h3 class="text-lg font-semibold text-primary mb-4">Dokumen Sokongan</h3>
<div v-if="profile.documents && profile.documents.length > 0">
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
<div v-for="(doc, index) in profile.documents" :key="index" class="border rounded-lg overflow-hidden">
<div class="bg-gray-50 p-4 flex items-center">
<Icon name="mdi:file-document" size="24" class="text-primary mr-3" />
<div>
<h4 class="font-medium">{{ doc.name }}</h4>
<p class="text-sm text-gray-500">{{ doc.size }}</p>
</div>
</div>
<div class="p-3 flex justify-end">
<rs-button variant="primary-text" size="sm">
<Icon name="mdi:download" size="16" class="mr-1" />
Muat Turun
</rs-button>
<rs-button variant="secondary-text" size="sm">
<Icon name="mdi:eye" size="16" class="mr-1" />
Papar
</rs-button>
</div>
</div>
</div>
</div>
<div v-else class="bg-gray-50 p-6 rounded-lg text-center">
<Icon name="mdi:file-document-off" size="48" class="text-gray-400 mb-2" />
<p class="text-gray-500">Tiada dokumen</p>
</div>
</div>
<!-- Analysis Tab -->
<div v-if="activeTab === 'analysis'" class="p-6">
<!-- Button to trigger AI Analysis -->
<div v-if="!profile.analysis && !isLoadingAnalysis" class="text-center mb-6">
<rs-button variant="primary" @click="fetchAIAnalysis" size="lg">
<Icon name="mdi:brain" size="20" class="mr-2" />
Jalankan Analisis AI
</rs-button>
<p class="text-sm text-gray-500 mt-2">Klik untuk mendapatkan penilaian berdasarkan data profil.</p>
</div>
<!-- Loading State for AI Analysis -->
<div v-if="isLoadingAnalysis" class="text-center py-10">
<Loading />
<p class="mt-4 text-gray-600">Analisis AI sedang dijalankan...</p>
<p class="text-sm text-gray-500">Sila tunggu sebentar.</p>
</div>
<!-- Display Analysis Results -->
<div v-if="profile.analysis && !isLoadingAnalysis" class="grid grid-cols-1 lg:grid-cols-3 gap-6">
<!-- AI Analysis Main Column (takes 2/3 on lg screens) -->
<div class="lg:col-span-2 space-y-6">
<!-- Card 1: Analisis Had Kifayah & Kelayakan -->
<rs-card>
<template #header>
<h3 class="text-lg font-semibold text-primary p-4 border-b">Analisis Had Kifayah & Kelayakan (AI)</h3>
</template>
<template #body>
<div class="p-4 space-y-4">
<div>
<h4 class="text-sm font-medium text-gray-500 mb-1">Peratusan Had Kifayah</h4>
<div v-if="profile.analysis.hadKifayahPercentage === 'N/A' || profile.analysis.hadKifayahPercentage === 'Ralat'" class="text-gray-500">
{{ profile.analysis.hadKifayahPercentage }}
</div>
<div v-else class="relative pt-1">
<div class="overflow-hidden h-4 text-xs flex rounded bg-gray-200">
<div
:style="{ width: profile.analysis.hadKifayahPercentage }"
:class="{
'bg-red-500': parseInt(profile.analysis.hadKifayahPercentage) < 60,
'bg-yellow-500': parseInt(profile.analysis.hadKifayahPercentage) >= 60 && parseInt(profile.analysis.hadKifayahPercentage) < 80,
'bg-green-500': parseInt(profile.analysis.hadKifayahPercentage) >= 80 && parseInt(profile.analysis.hadKifayahPercentage) <= 100,
'bg-blue-500': parseInt(profile.analysis.hadKifayahPercentage) > 100
}"
class="shadow-none flex flex-col text-center whitespace-nowrap text-white justify-center"
>
{{ profile.analysis.hadKifayahPercentage }}
</div>
</div>
</div>
</div>
<div>
<h4 class="text-sm font-medium text-gray-500">Kategori Asnaf (AI)</h4>
<p>{{ profile.analysis.kategoriAsnaf }}</p>
</div>
<div>
<h4 class="text-sm font-medium text-gray-500">Kategori Keluarga (AI)</h4>
<p>{{ profile.analysis.kategoriKeluarga }}</p>
</div>
<div>
<h4 class="text-sm font-medium text-gray-500">Cadangan Kategori (AI)</h4>
<p>{{ profile.analysis.cadanganKategori }}</p>
</div>
<div>
<h4 class="text-sm font-medium text-gray-500">Status Kelayakan (AI)</h4>
<p>{{ profile.analysis.statusKelayakan }}</p>
</div>
</div>
</template>
</rs-card>
<!-- Card 2: Cadangan & Rumusan AI -->
<rs-card>
<template #header>
<h3 class="text-lg font-semibold text-primary p-4 border-b">Cadangan & Rumusan (AI)</h3>
</template>
<template #body>
<div class="p-4 space-y-4">
<div>
<h4 class="text-sm font-medium text-gray-500">Cadangan Bantuan (AI)</h4>
<ul v-if="profile.analysis.cadanganBantuan && profile.analysis.cadanganBantuan.length > 0" class="list-disc list-inside space-y-1 mt-1">
<li v-for="(bantuan, index) in profile.analysis.cadanganBantuan" :key="index" class="text-gray-700">
{{ bantuan.nama }}
<span v-if="bantuan.peratusan && bantuan.peratusan !== 'Ralat'" class="font-semibold text-blue-600">({{ bantuan.peratusan }})</span>
<span v-else-if="bantuan.peratusan === 'Ralat'" class="text-red-500 text-xs">({{ bantuan.peratusan }})</span>
</li>
</ul>
<p v-else class="text-gray-500 mt-1">Tiada cadangan bantuan spesifik.</p>
</div>
<div>
<h4 class="text-sm font-medium text-gray-500">Ramalan Jangka Masa Taraf Hidup Pulih (AI)</h4>
<p>{{ profile.analysis.ramalanJangkaMasaPulih }}</p>
</div>
<div>
<h4 class="text-sm font-medium text-gray-500">Rumusan Keseluruhan (AI)</h4>
<div class="mt-1 p-3 bg-blue-50 border-l-4 border-blue-500 rounded-r-md">
<p class="whitespace-pre-line text-gray-700 text-sm">{{ profile.analysis.rumusan }}</p>
</div>
</div>
</div>
</template>
</rs-card>
</div>
<!-- Original Data Column (takes 1/3 on lg screens) -->
<div class="lg:col-span-1">
<rs-card>
<template #header>
<h3 class="text-lg font-semibold text-gray-700 p-4 border-b">Ringkasan Profil (Data Asal)</h3>
</template>
<template #body>
<div class="p-4 space-y-3">
<div>
<h4 class="text-sm font-medium text-gray-500">Jenis Kategori (Asal)</h4>
<rs-badge :variant="categoryColor" class="mt-1">{{ profile.kategori }}</rs-badge>
</div>
<div>
<h4 class="text-sm font-medium text-gray-500">Status Semasa (Asal)</h4>
<rs-badge :variant="statusColor" class="mt-1">{{ profile.status }}</rs-badge>
</div>
<div>
<h4 class="text-sm font-medium text-gray-500">Jumlah Pendapatan (Asal)</h4>
<p>RM {{ profile.totalIncome }}</p>
</div>
<div>
<h4 class="text-sm font-medium text-gray-500">Jumlah Tanggungan (Asal)</h4>
<p>{{ profile.dependents.length }} orang</p>
</div>
</div>
</template>
</rs-card>
</div>
</div>
</div>
</template>
</rs-card>
</div>
<!-- Delete Confirmation Modal -->
<rs-modal v-model="confirmDelete">
<template #header>
<div class="flex items-center">
<Icon name="mdi:alert-circle" size="24" class="text-red-500 mr-2" />
<h3 class="text-lg font-medium">Padam Profil</h3>
</div>
</template>
<template #default>
<div class="p-4">
<p class="mb-4">Adakah anda pasti ingin memadam profil ini?</p>
<p class="text-sm text-gray-500 mb-2">Nama: <span class="font-medium">{{ profile?.nama }}</span></p>
<p class="text-sm text-gray-500">ID: <span class="font-medium">{{ profile?.id }}</span></p>
</div>
</template>
<template #footer>
<div class="flex justify-end gap-2">
<rs-button variant="secondary-outline" @click="cancelDelete">
Batal
</rs-button>
<rs-button variant="danger" @click="confirmDeleteProfile">
Padam
</rs-button>
</div>
</template>
</rs-modal>
</div>
</template>

View File

@ -0,0 +1,337 @@
<script setup>
import { ref, computed, onMounted } from 'vue';
import { useAsnafMockData } from '~/composables/useAsnafMockData';
definePageMeta({
title: "Senarai Asnaf",
middleware: ["auth"],
requiresAuth: true,
breadcrumb: [
{
name: "Dashboard",
path: "/",
},
{
name: "BF-PRF",
path: "/BF-PRF",
},
{
name: "Asnaf",
path: "/BF-PRF/AS",
},
{
name: "Senarai",
path: "/BF-PRF/AS/LIST",
},
],
});
// Get asnaf data from the composable
const { asnafProfiles, statistics, filterProfiles, categories, statuses } = useAsnafMockData();
// Table reactivity control
const tableKey = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const totalProfiles = ref(0);
const isLoading = ref(false);
// Search and filter variables
const searchQuery = ref('');
const selectedStatus = ref('All');
const selectedCategory = ref('All');
// Table data and fields
const tableData = computed(() => {
return filterProfiles(searchQuery.value, selectedStatus.value, selectedCategory.value);
});
const tableFields = [
{ field: 'no', label: 'No.' },
{ field: 'id', label: 'ID' },
{ field: 'nama', label: 'Nama' },
{ field: 'idNumber', label: 'No. ID' },
{ field: 'kategori', label: 'Kategori' },
{ field: 'status', label: 'Status' },
{ field: 'tindakan', label: 'Tindakan' }
];
// Generate table field and data mapping
const formattedTableData = computed(() => {
return tableData.value.map((profile, index) => ({
no: index + 1,
id: profile.id,
nama: profile.nama,
idNumber: profile.idNumber,
kategori: profile.kategori,
status: profile.status,
tindakan: profile.id
}));
});
// Helper functions
function getBadgeVariantForCategory(category) {
switch (category) {
case 'Fakir': return 'danger';
case 'Miskin': return 'warning';
case 'Mualaf': return 'info';
case 'Fi-sabilillah': return 'primary';
case 'Gharimin': return 'secondary';
case 'Ibnu Sabil': return 'success';
default: return 'primary';
}
}
function getBadgeVariantForStatus(status) {
switch (status) {
case 'Aktif': return 'success';
case 'Tidak Aktif': return 'danger';
case 'Dalam Semakan': return 'warning';
default: return 'secondary';
}
}
function navigateToDetail(id) {
console.log("Attempting to navigate to detail for ID:", id);
if (id) {
navigateTo(`/BF-PRF/AS/DETAIL/${id}`);
} else {
console.error("Navigation failed: ID is undefined or null");
}
}
function navigateToRegistration() {
navigateTo('/BF-PRF/AS/FR/01');
}
// Pagination
const handlePageChange = (newPage) => {
currentPage.value = newPage;
fetchProfiles();
};
// Fetch data
async function fetchProfiles() {
isLoading.value = true;
// Simulate API delay
await new Promise(resolve => setTimeout(resolve, 500));
totalProfiles.value = tableData.value.length;
isLoading.value = false;
tableKey.value++; // Force table re-render
}
// Lifecycle hooks
onMounted(() => {
fetchProfiles();
});
</script>
<template>
<div class="space-y-6">
<LayoutsBreadcrumb />
<!-- Header -->
<div class="flex justify-between items-center">
<h1 class="text-2xl font-bold text-primary">Senarai Asnaf</h1>
<rs-button
variant="primary"
class="flex items-center gap-2"
@click="navigateToRegistration"
>
<Icon name="mdi:plus" size="18" />
<span>Tambah Asnaf</span>
</rs-button>
</div>
<!-- Statistics Cards -->
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
<rs-card class="transition-all duration-300 hover:shadow-lg">
<div class="p-4 flex items-center gap-4">
<div class="p-4 flex justify-center items-center bg-blue-100 rounded-xl">
<Icon name="mdi:account-group" size="24" class="text-primary" />
</div>
<div>
<span class="block text-2xl font-bold text-primary">{{ statistics.total }}</span>
<span class="text-sm text-gray-600">Jumlah Asnaf</span>
</div>
</div>
</rs-card>
<rs-card class="transition-all duration-300 hover:shadow-lg">
<div class="p-4 flex items-center gap-4">
<div class="p-4 flex justify-center items-center bg-green-100 rounded-xl">
<Icon name="mdi:check-circle" size="24" class="text-green-600" />
</div>
<div>
<span class="block text-2xl font-bold text-green-600">{{ statistics.active }}</span>
<span class="text-sm text-gray-600">Aktif</span>
</div>
</div>
</rs-card>
<rs-card class="transition-all duration-300 hover:shadow-lg">
<div class="p-4 flex items-center gap-4">
<div class="p-4 flex justify-center items-center bg-yellow-100 rounded-xl">
<Icon name="mdi:clock-time-four" size="24" class="text-yellow-600" />
</div>
<div>
<span class="block text-2xl font-bold text-yellow-600">{{ statistics.review }}</span>
<span class="text-sm text-gray-600">Dalam Semakan</span>
</div>
</div>
</rs-card>
<rs-card class="transition-all duration-300 hover:shadow-lg">
<div class="p-4 flex items-center gap-4">
<div class="p-4 flex justify-center items-center bg-red-100 rounded-xl">
<Icon name="mdi:close-circle" size="24" class="text-red-600" />
</div>
<div>
<span class="block text-2xl font-bold text-red-600">{{ statistics.inactive }}</span>
<span class="text-sm text-gray-600">Tidak Aktif</span>
</div>
</div>
</rs-card>
</div>
<!-- Search and Filters -->
<rs-card>
<div class="p-4">
<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Carian</label>
<div class="relative rounded-md shadow-sm">
<div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<Icon name="mdi:magnify" size="18" class="text-gray-400" />
</div>
<input
v-model="searchQuery"
type="text"
class="block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-primary focus:border-primary"
placeholder="Cari dengan nama atau ID..."
/>
</div>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Status</label>
<select
v-model="selectedStatus"
class="block w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-primary focus:border-primary"
>
<option value="All">Semua Status</option>
<option v-for="status in statuses" :key="status" :value="status">
{{ status }}
</option>
</select>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Kategori</label>
<select
v-model="selectedCategory"
class="block w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-primary focus:border-primary"
>
<option value="All">Semua Kategori</option>
<option v-for="category in categories" :key="category" :value="category">
{{ category }}
</option>
</select>
</div>
</div>
</div>
</rs-card>
<!-- Data Table -->
<rs-card>
<template #header>
<div class="px-4 py-3 flex items-center justify-between">
<h2 class="text-lg font-semibold text-primary">Senarai Asnaf</h2>
<span class="text-sm text-gray-500">
{{ tableData.length }} asnaf dijumpai
</span>
</div>
</template>
<template #body>
<div v-if="isLoading && tableData.length === 0" class="py-8 text-center">
<div class="flex justify-center">
<Icon name="mdi:loading" size="2rem" class="text-blue-500 animate-spin" />
</div>
<p class="mt-2 text-gray-600">Memuat data...</p>
</div>
<rs-table
v-else
class="mt-4"
:key="tableKey"
:data="formattedTableData"
:columns="tableFields"
:pageSize="pageSize"
:showNoColumn="true"
:options="{
variant: 'default',
hover: true,
striped: true,
bordered: true
}"
:current-page="currentPage"
:total-items="totalProfiles"
@page-change="handlePageChange"
>
<template v-slot:no="data">
{{ data.text }}
</template>
<template v-slot:id="data">
{{ data.text }}
</template>
<template v-slot:nama="data">
<div class="font-medium">{{ data.text }}</div>
</template>
<template v-slot:idNumber="data">
{{ data.text }}
</template>
<template v-slot:kategori="data">
<rs-badge :variant="getBadgeVariantForCategory(data.text)">{{ data.text }}</rs-badge>
</template>
<template v-slot:status="data">
<rs-badge :variant="getBadgeVariantForStatus(data.text)">
{{ data.text }}
</rs-badge>
</template>
<template v-slot:tindakan="data">
<div class="flex gap-2">
<rs-button
variant="primary"
size="sm"
class="!px-2 !py-1"
@click="() => {
navigateToDetail(data.value.tindakan);
}"
>
<Icon name="mdi:eye" size="1rem" class="mr-1" />
Lihat
</rs-button>
</div>
</template>
</rs-table>
<!-- Empty State -->
<div v-if="!isLoading && tableData.length === 0" class="text-center py-8">
<div class="flex justify-center mb-4">
<Icon name="mdi:magnify" size="4rem" class="text-gray-400" />
</div>
<h3 class="text-lg font-medium text-gray-500">Tiada Profil Ditemui</h3>
<p class="text-gray-500 mt-2">Sila cuba carian lain atau reset penapis.</p>
</div>
</template>
</rs-card>
</div>
</template>

View File

@ -11,305 +11,328 @@ definePageMeta({
],
});
// Framework information
const frameworkInfo = ref({
name: "corradAF",
version: "1.0.0",
description: "Corrad Application Framework - A comprehensive Nuxt.js template for rapid application development",
features: [
"Authentication System",
"User Management",
"Role-based Access Control",
"Development Tools Suite",
"API Management",
"Menu Configuration",
"Content Management",
"Code Playground",
"ORM Integration",
"Responsive Design"
]
// Data baru untuk lapangan terbang teratas
const topAirports = ref([
{
rank: 1,
name: "Lapangan Terbang Antarabangsa Kuala Lumpur (KLIA)",
visitors: 62000000,
},
{
rank: 2,
name: "Lapangan Terbang Antarabangsa Kota Kinabalu",
visitors: 9000000,
},
{ rank: 3, name: "Lapangan Terbang Antarabangsa Penang", visitors: 8000000 },
{ rank: 4, name: "Lapangan Terbang Antarabangsa Kuching", visitors: 5500000 },
{
rank: 5,
name: "Lapangan Terbang Antarabangsa Langkawi",
visitors: 3000000,
},
]);
// Data baru untuk kad ringkasan pantas
const quickSummary = ref([
{ title: "Jumlah Pelawat", value: "10.5 Juta", icon: "ic:outline-people" },
{
title: "Pendapatan Pelancongan",
value: "RM 86.14 Bilion",
icon: "ic:outline-attach-money",
},
{
title: "Tempoh Penginapan Purata",
value: "6.1 Hari",
icon: "ic:outline-hotel",
},
{
title: "Kepuasan Pelancong",
value: "92%",
icon: "ic:outline-sentiment-satisfied",
},
]);
// Data Pelawat Malaysia
const visitorData = ref([
{
name: "Pelawat Tempatan",
data: [5000000, 5500000, 6000000, 6500000, 7000000, 7500000],
},
{
name: "Pelawat Asing",
data: [3000000, 3500000, 4000000, 4500000, 5000000, 5500000],
},
]);
// Data Pelawat Asing mengikut Negeri
const foreignVisitorsByState = ref([
{ state: "Selangor", visitors: 1500000 },
{ state: "Pulau Pinang", visitors: 1200000 },
{ state: "Johor", visitors: 1000000 },
{ state: "Sabah", visitors: 800000 },
{ state: "Sarawak", visitors: 600000 },
{ state: "Melaka", visitors: 500000 },
{ state: "Kedah", visitors: 400000 },
{ state: "Negeri Sembilan", visitors: 300000 },
{ state: "Perak", visitors: 250000 },
{ state: "Terengganu", visitors: 200000 },
{ state: "Kelantan", visitors: 150000 },
{ state: "Pahang", visitors: 100000 },
{ state: "Perlis", visitors: 50000 },
]);
// Lapangan Terbang Keberangkatan Teratas
const departureData = ref([
{ airport: "JFK", departures: 1500 },
{ airport: "LHR", departures: 1200 },
{ airport: "CDG", departures: 1000 },
{ airport: "DXB", departures: 800 },
{ airport: "SIN", departures: 600 },
]);
// Data Pelancong Berulang
const repeatVisitorsData = ref([
{ category: "1-2 kali", percentage: 45 },
{ category: "3-5 kali", percentage: 30 },
{ category: "6-10 kali", percentage: 15 },
{ category: ">10 kali", percentage: 10 },
]);
// Data Negara Asal Pelancong Asing Teratas
const topVisitorCountries = ref([
{ country: "Singapura", visitors: 1500000 },
{ country: "Indonesia", visitors: 1200000 },
{ country: "China", visitors: 1000000 },
{ country: "Thailand", visitors: 800000 },
{ country: "India", visitors: 600000 },
]);
const chartOptionsVisitors = computed(() => ({
chart: { height: 350, type: "line" },
stroke: { curve: "smooth", width: 2 },
xaxis: { categories: ["2018", "2019", "2020", "2021", "2022", "2023"] },
yaxis: { title: { text: "Bilangan Pelawat" } },
}));
const chartOptionsForeignVisitors = computed(() => ({
chart: { type: "bar" },
plotOptions: { bar: { horizontal: true } },
xaxis: { categories: foreignVisitorsByState.value.map((item) => item.state) },
}));
const chartOptionsDeparture = computed(() => ({
chart: { type: "bar" },
plotOptions: { bar: { horizontal: true } },
xaxis: { categories: departureData.value.map((item) => item.airport) },
}));
const chartOptionsRepeatVisitors = computed(() => ({
chart: { type: "pie" },
labels: repeatVisitorsData.value.map((item) => item.category),
responsive: [
{
breakpoint: 480,
options: {
chart: {
width: 200,
},
legend: {
position: "bottom",
},
},
},
],
}));
const chartOptionsTopCountries = computed(() => ({
chart: { type: "bar" },
plotOptions: {
bar: { horizontal: false, columnWidth: "55%", endingShape: "rounded" },
},
dataLabels: { enabled: false },
stroke: { show: true, width: 2, colors: ["transparent"] },
xaxis: { categories: topVisitorCountries.value.map((item) => item.country) },
yaxis: { title: { text: "Bilangan Pelawat" } },
fill: { opacity: 1 },
tooltip: {
y: {
formatter: function (val) {
return val.toLocaleString() + " pelawat";
},
},
},
}));
onMounted(() => {
// Sebarang logik yang diperlukan semasa pemasangan
});
// Development tools available
const devTools = ref([
{
title: "User Management",
description: "Manage users and roles with comprehensive CRUD operations",
icon: "mdi:account-group",
path: "/devtool/user-management/user",
color: "blue"
},
{
title: "Menu Editor",
description: "Configure navigation menus and application structure",
icon: "mdi:menu",
path: "/devtool/menu-editor",
color: "green"
},
{
title: "API Editor",
description: "Design and test API endpoints with interactive tools",
icon: "mdi:api",
path: "/devtool/api-editor",
color: "purple"
},
{
title: "Content Editor",
description: "Manage dynamic content and templates",
icon: "mdi:file-document-edit",
path: "/devtool/content-editor",
color: "orange"
},
{
title: "Code Playground",
description: "Test and prototype code snippets in real-time",
icon: "mdi:code-braces",
path: "/devtool/code-playground",
color: "indigo"
},
{
title: "ORM Tools",
description: "Database schema management and query tools",
icon: "mdi:database",
path: "/devtool/orm",
color: "red"
},
{
title: "Configuration",
description: "System settings and environment configuration",
icon: "mdi:cog",
path: "/devtool/config",
color: "gray"
}
]);
// Quick stats
const quickStats = ref([
{ title: "Dev Tools", value: "7", icon: "mdi:tools" },
{ title: "Components", value: "50+", icon: "mdi:view-grid" },
{ title: "Auth System", value: "Ready", icon: "mdi:shield-check" },
{ title: "Framework", value: "Nuxt 3", icon: "mdi:nuxt" }
]);
// Getting started steps
const gettingStarted = ref([
{
step: 1,
title: "Clone Repository",
description: "Clone this template to start your new project",
command: "git clone <repository-url> your-project-name"
},
{
step: 2,
title: "Install Dependencies",
description: "Install all required packages",
command: "yarn install"
},
{
step: 3,
title: "Configure Environment",
description: "Set up your environment variables and database",
command: "cp .env.example .env"
},
{
step: 4,
title: "Start Development",
description: "Run the development server",
command: "yarn dev"
}
]);
function navigateToTool(path) {
navigateTo(path);
}
function getColorClasses(color) {
const colorMap = {
blue: 'bg-blue-100 text-blue-600 hover:bg-blue-200',
green: 'bg-green-100 text-green-600 hover:bg-green-200',
purple: 'bg-purple-100 text-purple-600 hover:bg-purple-200',
orange: 'bg-orange-100 text-orange-600 hover:bg-orange-200',
indigo: 'bg-indigo-100 text-indigo-600 hover:bg-indigo-200',
red: 'bg-red-100 text-red-600 hover:bg-red-200',
gray: 'bg-gray-100 text-gray-600 hover:bg-gray-200'
};
return colorMap[color] || 'bg-gray-100 text-gray-600 hover:bg-gray-200';
}
</script>
<template>
<div class="space-y-8">
<div>
<LayoutsBreadcrumb />
<!-- Welcome Header -->
<div class="text-center py-12 bg-gradient-to-br from-primary/10 to-secondary/10 rounded-2xl">
<div class="max-w-4xl mx-auto px-6">
<h1 class="text-4xl md:text-6xl font-bold text-primary mb-4">
Welcome to {{ frameworkInfo.name }}
</h1>
<p class="text-xl text-gray-600 mb-6">
{{ frameworkInfo.description }}
</p>
<div class="flex justify-center gap-4">
<rs-badge variant="primary" class="text-sm px-4 py-2">
v{{ frameworkInfo.version }}
</rs-badge>
<rs-badge variant="secondary" class="text-sm px-4 py-2">
Nuxt 3 Ready
</rs-badge>
</div>
</div>
</div>
<!-- Quick Stats -->
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
<!-- Kad Ringkasan Pantas -->
<div class="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-4 gap-6">
<rs-card
v-for="(stat, index) in quickStats"
v-for="(item, index) in quickSummary"
:key="index"
class="transition-all duration-300 hover:shadow-lg"
>
<div class="p-6 flex items-center gap-4">
<div class="p-4 bg-primary/20 rounded-2xl">
<Icon :name="stat.icon" size="24" class="text-primary" />
<div class="pt-5 pb-3 px-5 flex items-center gap-4">
<div
class="p-5 flex justify-center items-center bg-primary/20 rounded-2xl transition-all duration-300 hover:bg-primary/30"
>
<Icon class="text-primary text-3xl" :name="item.icon"></Icon>
</div>
<div>
<span class="block text-2xl font-bold text-primary">{{ stat.value }}</span>
<span class="text-sm text-gray-600">{{ stat.title }}</span>
<div class="flex-1 truncate">
<span class="block font-bold text-2xl leading-tight text-primary">
{{ item.value }}
</span>
<span class="text-sm font-medium text-gray-600">
{{ item.title }}
</span>
</div>
</div>
</rs-card>
</div>
<!-- Development Tools -->
<div>
<h2 class="text-2xl font-bold text-primary mb-6">Development Tools</h2>
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
<rs-card
v-for="(tool, index) in devTools"
:key="index"
class="transition-all duration-300 hover:shadow-lg cursor-pointer group"
@click="navigateToTool(tool.path)"
>
<div class="p-6">
<div class="flex items-start gap-4 mb-4">
<div
:class="getColorClasses(tool.color)"
class="p-3 rounded-xl transition-all duration-300"
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
<!-- Gambaran Keseluruhan Pelawat Malaysia -->
<rs-card class="col-span-1 lg:col-span-2">
<template #header>
<h2 class="text-xl font-bold text-primary">
Gambaran Keseluruhan Pelawat
</h2>
</template>
<template #body>
<client-only>
<VueApexCharts
width="100%"
height="350"
type="line"
:options="chartOptionsVisitors"
:series="visitorData"
></VueApexCharts>
</client-only>
</template>
</rs-card>
<!-- Pelawat Asing mengikut Negeri -->
<rs-card>
<template #header>
<h2 class="text-lg font-semibold text-primary">
Pelawat Asing mengikut Negeri
</h2>
</template>
<template #body>
<client-only>
<VueApexCharts
width="100%"
height="300"
type="bar"
:options="chartOptionsForeignVisitors"
:series="[
{ data: foreignVisitorsByState.map((item) => item.visitors) },
]"
></VueApexCharts>
</client-only>
</template>
</rs-card>
<!-- Pelancong Berulang -->
<rs-card>
<template #header>
<h2 class="text-lg font-semibold text-primary">
Kekerapan Lawatan Pelancong
</h2>
</template>
<template #body>
<client-only>
<VueApexCharts
width="100%"
height="300"
type="pie"
:options="chartOptionsRepeatVisitors"
:series="repeatVisitorsData.map((item) => item.percentage)"
></VueApexCharts>
</client-only>
</template>
</rs-card>
</div>
<!-- Negara Asal Pelancong Asing Teratas -->
<rs-card class="mb-6">
<template #header>
<h2 class="text-xl font-bold text-primary">
Negara Asal Pelancong Asing Teratas
</h2>
</template>
<template #body>
<client-only>
<VueApexCharts
width="100%"
height="350"
type="bar"
:options="chartOptionsTopCountries"
:series="[
{
name: 'Pelawat',
data: topVisitorCountries.map((item) => item.visitors),
},
]"
></VueApexCharts>
</client-only>
</template>
</rs-card>
<rs-card class="mb-6">
<template #header>
<h2 class="text-xl font-bold text-primary">
Lapangan Terbang Teratas dengan Pelawat Terbanyak
</h2>
</template>
<template #body>
<div class="overflow-x-auto">
<table class="min-w-full divide-y divide-gray-200">
<thead class="bg-gray-50">
<tr>
<th
class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
>
Kedudukan
</th>
<th
class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
>
Nama Lapangan Terbang
</th>
<th
class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
>
Jumlah Pelawat
</th>
</tr>
</thead>
<tbody class="bg-white divide-y divide-gray-200">
<tr
v-for="airport in topAirports"
:key="airport.rank"
class="hover:bg-gray-50 transition-colors duration-200"
>
<Icon :name="tool.icon" size="24" />
</div>
<div class="flex-1">
<h3 class="font-semibold text-lg text-gray-800 group-hover:text-primary transition-colors">
{{ tool.title }}
</h3>
</div>
</div>
<p class="text-gray-600 text-sm leading-relaxed">
{{ tool.description }}
</p>
<div class="mt-4 flex items-center text-primary text-sm font-medium group-hover:gap-2 transition-all">
<span>Open Tool</span>
<Icon name="mdi:arrow-right" size="16" class="ml-1 group-hover:ml-2 transition-all" />
</div>
</div>
</rs-card>
</div>
</div>
<!-- Framework Features -->
<div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
<!-- Features List -->
<rs-card>
<div class="p-6">
<h3 class="text-xl font-bold text-primary mb-4 flex items-center gap-2">
<Icon name="mdi:star" size="20" />
Framework Features
</h3>
<div class="grid grid-cols-1 md:grid-cols-2 gap-3">
<div
v-for="(feature, index) in frameworkInfo.features"
:key="index"
class="flex items-center gap-2 text-sm"
>
<Icon name="mdi:check-circle" size="16" class="text-green-500" />
<span>{{ feature }}</span>
</div>
</div>
<td class="px-6 py-4 whitespace-nowrap font-medium">
{{ airport.rank }}
</td>
<td class="px-6 py-4 whitespace-nowrap">{{ airport.name }}</td>
<td
class="px-6 py-4 whitespace-nowrap font-semibold text-primary"
>
{{ airport.visitors.toLocaleString() }}
</td>
</tr>
</tbody>
</table>
</div>
</rs-card>
<!-- Getting Started -->
<rs-card>
<div class="p-6">
<h3 class="text-xl font-bold text-primary mb-4 flex items-center gap-2">
<Icon name="mdi:rocket-launch" size="20" />
Getting Started
</h3>
<div class="space-y-4">
<div
v-for="(step, index) in gettingStarted"
:key="index"
class="border-l-2 border-primary/20 pl-4"
>
<div class="flex items-center gap-2 mb-1">
<span class="w-6 h-6 bg-primary text-white rounded-full flex items-center justify-center text-xs font-bold">
{{ step.step }}
</span>
<h4 class="font-semibold text-gray-800">{{ step.title }}</h4>
</div>
<p class="text-sm text-gray-600 mb-2">{{ step.description }}</p>
<code class="text-xs bg-gray-100 px-2 py-1 rounded block font-mono">
{{ step.command }}
</code>
</div>
</div>
</div>
</rs-card>
</div>
<!-- Documentation Links -->
<rs-card>
<div class="p-6">
<h3 class="text-xl font-bold text-primary mb-4 flex items-center gap-2">
<Icon name="mdi:book-open" size="20" />
Documentation & Resources
</h3>
<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
<a
href="https://nuxt.com/docs"
target="_blank"
class="flex items-center gap-3 p-4 bg-gray-50 rounded-xl hover:bg-gray-100 transition-colors"
>
<Icon name="mdi:nuxt" size="24" class="text-green-500" />
<div>
<div class="font-semibold">Nuxt 3 Docs</div>
<div class="text-sm text-gray-600">Official documentation</div>
</div>
</a>
<a
href="https://tailwindcss.com/docs"
target="_blank"
class="flex items-center gap-3 p-4 bg-gray-50 rounded-xl hover:bg-gray-100 transition-colors"
>
<Icon name="mdi:tailwind" size="24" class="text-blue-500" />
<div>
<div class="font-semibold">Tailwind CSS</div>
<div class="text-sm text-gray-600">Utility-first CSS</div>
</div>
</a>
<a
href="https://github.com"
target="_blank"
class="flex items-center gap-3 p-4 bg-gray-50 rounded-xl hover:bg-gray-100 transition-colors"
>
<Icon name="mdi:github" size="24" class="text-gray-700" />
<div>
<div class="font-semibold">Source Code</div>
<div class="text-sm text-gray-600">View on GitHub</div>
</div>
</a>
</div>
</div>
</template>
</rs-card>
</div>
</template>

View File

@ -5,7 +5,7 @@ definePageMeta({
requiresAuth: true,
});
const { $swal } = useNuxtApp();
const { $swal, $toast } = useNuxtApp();
const { siteSettings, updateSiteSettings, applyThemeSettings, updateGlobalMeta } = useSiteSettings();
// Reactive data
@ -139,7 +139,7 @@ const loadSettings = async () => {
}
} catch (error) {
console.error("Error loading settings:", error);
alert("Failed to load site settings");
$toast.error("Failed to load site settings");
} finally {
loading.value = false;
}
@ -148,7 +148,7 @@ const loadSettings = async () => {
// Save settings
const saveSettings = async () => {
if (!validateForm()) {
alert("Please fix the validation errors");
$toast.error("Please fix the validation errors");
return;
}
@ -160,7 +160,7 @@ const saveSettings = async () => {
if (result && result.success) {
originalSettings.value = { ...settings.value };
alert("Settings saved successfully");
$toast.success("Settings saved successfully");
// Apply changes
// applyChanges(); // Temporarily commented out to isolate the error source
@ -175,7 +175,7 @@ const saveSettings = async () => {
console.error("[SiteSettingsPage] 'result' from updateSiteSettings was undefined.");
}
alert(errorMsg);
$toast.error(errorMsg);
if (result && result.error && result.error.details) {
console.error("[SiteSettingsPage] Save settings error details:", result.error.details);
@ -189,7 +189,7 @@ const saveSettings = async () => {
// This catch block is for unexpected errors during the saveSettings execution itself,
// or if updateSiteSettings somehow re-throws an error not caught by its own try-catch.
console.error("Critical error saving settings:", error);
alert("A critical error occurred. Failed to save settings.");
$toast.error("A critical error occurred. Failed to save settings.");
} finally {
saving.value = false;
}
@ -220,7 +220,7 @@ const applyFontFromSource = () => {
}
}
alert('Font applied successfully');
$toast.success('Font applied successfully');
}
};
@ -241,7 +241,7 @@ const uploadFile = async (file, type) => {
return response.data.url;
} catch (error) {
console.error(`Error uploading ${type}:`, error);
alert(`Failed to upload ${type}`);
$toast.error(`Failed to upload ${type}`);
return null;
}
};
@ -253,7 +253,7 @@ const handleLogoUpload = async (event) => {
const url = await uploadFile(file, 'logo');
if (url) {
settings.value.siteLogo = url;
alert('Logo uploaded successfully');
$toast.success('Logo uploaded successfully');
}
}
};
@ -264,7 +264,7 @@ const handleLoadingLogoUpload = async (event) => {
const url = await uploadFile(file, 'loading-logo');
if (url) {
settings.value.siteLoadingLogo = url;
alert('Loading logo uploaded successfully');
$toast.success('Loading logo uploaded successfully');
}
}
};
@ -275,7 +275,7 @@ const handleFaviconUpload = async (event) => {
const url = await uploadFile(file, 'favicon');
if (url) {
settings.value.siteFavicon = url;
alert('Favicon uploaded successfully');
$toast.success('Favicon uploaded successfully');
}
}
};
@ -286,7 +286,7 @@ const handleLoginLogoUpload = async (event) => {
const url = await uploadFile(file, 'login-logo');
if (url) {
settings.value.siteLoginLogo = url;
alert('Login logo uploaded successfully');
$toast.success('Login logo uploaded successfully');
}
}
};
@ -295,14 +295,14 @@ const handleCSSUpload = async (event) => {
const file = event.target.files[0];
if (file) {
if (!file.name.endsWith('.css')) {
alert('Please upload a valid CSS file');
$toast.error('Please upload a valid CSS file');
return;
}
const reader = new FileReader();
reader.onload = (e) => {
settings.value.customCSS = e.target.result;
alert('CSS file loaded successfully');
$toast.success('CSS file loaded successfully');
};
reader.readAsText(file);
}
@ -314,7 +314,7 @@ const handleOgImageUpload = async (event) => {
const url = await uploadFile(file, 'og-image');
if (url) {
settings.value.seoOgImage = url;
alert('OG image uploaded successfully');
$toast.success('OG image uploaded successfully');
}
}
};
@ -332,7 +332,7 @@ const resetSettings = () => {
settings.value = { ...originalSettings.value };
errors.value = {};
applyChanges();
alert('Settings reset to last saved state');
$toast.info('Settings reset to last saved state');
};
// Check for changes
@ -364,7 +364,7 @@ const applyGoogleFont = (font) => {
settings.value.fontSource = googleFontUrl;
settings.value.currentFont = font.name;
applyFontFromSource();
alert(`${font.name} font applied successfully`);
$toast.success(`${font.name} font applied successfully`);
// Reset the dropdown after selection
selectedGoogleFont.value = '';
}
@ -451,7 +451,7 @@ watch(() => settings.value.showSiteNameInHeader, (newValue) => {
<div v-else>
<!-- Tab Navigation -->
<div class="border-b border-gray-200 dark:border-gray-700 mb-8">
<nav class="flex space-x-4" role="tablist">
<nav class="flex space-x-8" role="tablist">
<button
v-for="tab in [
{ id: 'basic', name: 'Basic', icon: 'ic:outline-info' },
@ -466,7 +466,7 @@ watch(() => settings.value.showSiteNameInHeader, (newValue) => {
activeTab === tab.id
? 'border-primary text-primary bg-primary/5'
: 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 dark:text-gray-400 dark:hover:text-gray-300',
'whitespace-nowrap py-2 px-2 border-b-2 font-medium text-sm flex items-center space-x-2 rounded-t-lg transition-all duration-200'
'whitespace-nowrap py-3 px-3 border-b-2 font-medium text-sm flex items-center space-x-2 rounded-t-lg transition-all duration-200'
]"
:aria-selected="activeTab === tab.id"
role="tab"

49
pages/metabase/index.vue Normal file
View File

@ -0,0 +1,49 @@
<template>
<div>
<LayoutsBreadcrumb />
<section class="flex flex-col h-screen">
<div class="mb-4 flex-shrink-0">
<h3>Metabase</h3>
<p>
Metabase is a powerful data visualization and analytics tool that allows you to
create and share dashboards, reports, and visualizations with your team.
</p>
</div>
<div v-if="pending" class="flex justify-center items-center flex-1">
<div class="text-lg">Loading Metabase dashboard...</div>
</div>
<div v-else-if="error" class="flex justify-center items-center flex-1">
<div class="text-red-500">Error loading dashboard: {{ error.message }}</div>
</div>
<iframe
v-else
:src="iframeUrl"
frameborder="0"
width="100%"
class="flex-1"
allowtransparency
/>
</section>
</div>
</template>
<script setup>
// Fetch the JWT token from our server API
const { data: tokenData, pending, error } = await useFetch("/api/metabase/token");
const iframeUrl = computed(() => {
if (tokenData.value?.token && tokenData.value?.siteUrl) {
return (
tokenData.value.siteUrl +
"/embed/dashboard/" +
tokenData.value.token +
"#bordered=true&titled=true"
);
}
return "";
});
</script>
<style lang="scss" scoped></style>

30
pages/notes/index.vue Normal file
View File

@ -0,0 +1,30 @@
<script setup>
definePageMeta({
title: "Notes",
middleware: ["auth"],
requiresAuth: true,
});
</script>
<template>
<div>
<LayoutsBreadcrumb />
<rs-card>
<template #header>
<div>
Notes
</div>
</template>
<template #body>
<div>
Content for Notes
</div>
</template>
</rs-card>
</div>
</template>
<style scoped>
/* Add your styles here */
</style>

View File

@ -99,14 +99,3 @@ model site_settings {
settingModifiedDate DateTime? @db.DateTime(0)
siteLoginLogo String? @db.VarChar(500)
}
model ticket {
ticketId Int @id @default(autoincrement())
title String
description String
dueDate DateTime
priority String @default("medium")
status String @default("pending")
createdAt DateTime @default(now())
updatedAt DateTime
}

View File

@ -0,0 +1,124 @@
import { defineEventHandler, readBody } from 'h3';
// Define an interface for the expected request body (subset of AsnafProfile)
interface AsnafAnalysisRequest {
monthlyIncome: string;
otherIncome: string;
totalIncome: string;
occupation: string;
maritalStatus: string;
dependents: Array<any>; // Or a more specific type if you have one for dependents
// Add any other fields you deem necessary for OpenAI to analyze
}
interface AidSuggestion {
nama: string;
peratusan: string;
}
// Define an interface for the expected OpenAI response structure (and our API response)
interface AsnafAnalysisResponse {
hadKifayahPercentage: string;
kategoriAsnaf: string;
kategoriKeluarga: string;
cadanganKategori: string;
statusKelayakan: string;
cadanganBantuan: AidSuggestion[];
ramalanJangkaMasaPulih: string;
rumusan: string;
}
export default defineEventHandler(async (event): Promise<AsnafAnalysisResponse> => {
const body = await readBody<AsnafAnalysisRequest>(event);
// --- Placeholder for Actual OpenAI API Call ---
// In a real application, you would:
// 1. Retrieve your OpenAI API key securely (e.g., from environment variables)
const openAIApiKey = process.env.OPENAI_API_KEY;
if (!openAIApiKey) {
console.error('OpenAI API key not configured. Please set OPENAI_API_KEY in your .env file.');
throw createError({ statusCode: 500, statusMessage: 'OpenAI API key not configured' });
}
// 2. Construct the prompt for OpenAI using the data from `body`.
// IMPORTANT: Sanitize or carefully construct any data from `body` included in the prompt to prevent prompt injection.
const prompt = `You are an expert Zakat administrator. Based on the following applicant data: monthlyIncome: ${body.monthlyIncome}, totalIncome: ${body.totalIncome}, occupation: ${body.occupation}, maritalStatus: ${body.maritalStatus}, dependents: ${body.dependents.length}.
Return JSON with keys: hadKifayahPercentage, kategoriAsnaf, kategoriKeluarga, cadanganKategori, statusKelayakan, cadanganBantuan, ramalanJangkaMasaPulih, rumusan.
For 'cadanganBantuan', provide a JSON array of objects, where each object has a 'nama' (string, name of the aid) and 'peratusan' (string, e.g., '85%', representing suitability). Suggest 2-3 most relevant aid types.
Example for cadanganBantuan: [{"nama": "Bantuan Kewangan Bulanan", "peratusan": "90%"}, {"nama": "Bantuan Makanan Asas", "peratusan": "75%"}].
Full JSON Example: {"hadKifayahPercentage": "75%", ..., "cadanganBantuan": [{"nama": "Bantuan Kewangan Bulanan", "peratusan": "90%"}], ...}`;
// Adjust the prompt to be more detailed and specific to your needs and desired JSON output structure.
// 3. Make the API call to OpenAI
try {
const openAIResponse = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${openAIApiKey}`,
},
body: JSON.stringify({
model: 'gpt-3.5-turbo', // Or your preferred model like gpt-4
messages: [{ role: 'user', content: prompt }],
// For more consistent JSON output, consider using a model version that officially supports JSON mode if available
// and set response_format: { type: "json_object" }, (check OpenAI documentation for model compatibility)
}),
});
if (!openAIResponse.ok) {
const errorData = await openAIResponse.text();
console.error('OpenAI API Error details:', errorData);
throw createError({ statusCode: openAIResponse.status, statusMessage: `Failed to get analysis from OpenAI: ${openAIResponse.statusText}` });
}
const openAIData = await openAIResponse.json();
// Parse the content from the response - structure might vary slightly based on OpenAI model/API version
// It's common for the JSON string to be in openAIData.choices[0].message.content
if (openAIData.choices && openAIData.choices[0] && openAIData.choices[0].message && openAIData.choices[0].message.content) {
const analysisResult = JSON.parse(openAIData.choices[0].message.content) as AsnafAnalysisResponse;
return analysisResult;
} else {
console.error('OpenAI response structure not as expected:', openAIData);
throw createError({ statusCode: 500, statusMessage: 'Unexpected response structure from OpenAI' });
}
} catch (error) {
console.error('Error during OpenAI API call or parsing:', error);
// Avoid exposing detailed internal errors to the client if they are not createError objects
if (typeof error === 'object' && error !== null && 'statusCode' in error) {
// We can infer error has statusCode here, but to be super safe with TS:
const e = error as { statusCode: number };
if (e.statusCode) throw e;
}
throw createError({ statusCode: 500, statusMessage: 'Internal server error during AI analysis' });
}
// --- End of Actual OpenAI API Call ---
// The simulated response below this line should be REMOVED once the actual OpenAI call is implemented and working.
/*
console.log('Received for analysis in server route:', body);
await new Promise(resolve => setTimeout(resolve, 2000)); // Simulate API delay
const totalIncomeNumeric = parseFloat(body.totalIncome);
let percentage = '50%';
if (totalIncomeNumeric < 1000) percentage = '30%';
else if (totalIncomeNumeric < 2000) percentage = '65%';
else if (totalIncomeNumeric < 3000) percentage = '85%';
else percentage = '110%';
return {
hadKifayahPercentage: percentage,
kategoriAsnaf: 'Simulated - Miskin',
kategoriKeluarga: 'Simulated - Miskin (50-100% HK)',
cadanganKategori: 'Simulated - Miskin',
statusKelayakan: 'Simulated - Layak (Miskin)',
cadanganBantuan: [
{ nama: 'Simulated - Bantuan Kewangan Bulanan', peratusan: '80%' },
{ nama: 'Simulated - Bantuan Pendidikan Anak', peratusan: '65%' }
],
ramalanJangkaMasaPulih: 'Simulated - 6 bulan',
rumusan: 'Simulated - Pemohon memerlukan perhatian segera.'
};
*/
});

View File

@ -1,44 +0,0 @@
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
export default defineEventHandler(async (event) => {
const method = getMethod(event);
try {
if (method === "GET") {
// Get only the loading logo and site name for faster loading
const settings = await prisma.site_settings.findFirst({
select: {
siteLoadingLogo: true,
siteName: true,
},
orderBy: { settingID: "desc" },
});
return {
statusCode: 200,
message: "Success",
data: {
siteLoadingLogo: settings?.siteLoadingLogo || '',
siteName: settings?.siteName || 'corradAF',
},
};
}
return {
statusCode: 405,
message: "Method not allowed",
};
} catch (error) {
console.error("Loading logo API error:", error);
return {
statusCode: 500,
message: "Internal server error",
error: error.message,
};
} finally {
await prisma.$disconnect();
}
});

121
test-site-settings.md Normal file
View File

@ -0,0 +1,121 @@
# Site Settings Features Test Guide
## Features Implemented ✅
### 1. Font Size Stepper for Site Name
**Location**: Site Settings > Appearance Tab > Site Name Styling
**Test Steps**:
1. Navigate to `/devtool/config/site-settings`
2. Click on the "Appearance" tab
3. Locate the "Site Name Font Size" section
4. Use the stepper buttons (+/-) to change the font size (12px - 36px)
5. Observe the live preview showing the size change
6. Check the current size indicator showing the exact pixel value
**Expected Results**:
- Font size changes in real-time in the preview
- Size indicator updates with current pixel value
- Header and sidemenu site name reflect the new size after saving
### 2. Google Fonts Suggestions Dropdown
**Location**: Site Settings > Appearance Tab > Font Configuration
**Test Steps**:
1. In the same "Appearance" tab, scroll to "Font Configuration"
2. Open the "Popular Google Fonts" dropdown
3. Select a font (e.g., "Inter", "Poppins", "Roboto")
4. Verify the font is applied immediately
5. Check that a success toast notification appears
6. Verify the "Current Font" section updates
**Expected Results**:
- Dropdown contains 15 popular Google Fonts
- Font applies immediately when selected
- Success notification shows: "[Font Name] font applied successfully"
- Current font section shows the new font name and Google Fonts URL
- Dropdown resets after selection
### 3. Show Site Name in Header Toggle
**Location**: Site Settings > Basic Tab
**Test Steps**:
1. Go to the "Basic" tab
2. Locate the "Show site name in header" toggle
3. Toggle it OFF
4. Navigate to any other page
5. Check the header - site name should be hidden
6. Return to settings and toggle it ON
7. Check the header - site name should be visible again
**Expected Results**:
- When OFF: Site name is hidden in both header and sidemenu
- When ON: Site name is visible in both header and sidemenu
- Changes apply immediately without needing to save
### 4. Consistent UI Components
**Verification Points**:
- Uses `rs-button` components with proper variants (primary, outline)
- Uses `rs-card` components for layout
- Consistent spacing and typography
- Uses `FontSizeStepper` component with proper props
- Proper dark mode support
- Icons from Iconify (`ic:` prefix)
**Design Patterns Used**:
- Border rounded containers with proper padding
- Gray borders with dark mode variants
- Consistent form input styling
- Proper spacing with Tailwind classes
- Live preview sidebar with real-time updates
## Database Fields Added ✅
- `siteNameFontSize` (Int, default: 18) - Already existed in Prisma schema
- Field is properly handled in API endpoints
- Synced with global site settings composable
## API Integration ✅
- All settings are saved to `/api/devtool/config/site-settings`
- Font size is included in the POST request body
- Settings load correctly on page refresh
- Changes persist across browser sessions
## Components Updated ✅
1. **pages/devtool/config/site-settings/index.vue**
- Added font size stepper
- Added Google Fonts dropdown
- Enhanced live preview
- Added visual feedback
2. **components/layouts/Header.vue**
- Applied dynamic font sizing
- Respects show/hide toggle
3. **components/layouts/sidemenu/index.vue**
- Applied scaled font sizing
- Respects show/hide toggle
4. **composables/useSiteSettings.js**
- Added siteNameFontSize field
- Maintains global state consistency
## Testing Checklist ✅
- [ ] Font size stepper works (12px - 36px range)
- [ ] Font size preview updates in real-time
- [ ] Font size applies to header site name
- [ ] Font size applies to sidemenu site name (scaled)
- [ ] Google Fonts dropdown has 15 options
- [ ] Google Font selection applies immediately
- [ ] Font source URL updates when Google Font selected
- [ ] Show/hide toggle works for header
- [ ] Show/hide toggle works for sidemenu
- [ ] Live preview sidebar reflects all changes
- [ ] Settings save and persist correctly
- [ ] Dark mode compatibility
- [ ] Mobile responsiveness
- [ ] Toast notifications appear for font changes
- [ ] All UI components follow design system

23869
yarn.lock

File diff suppressed because it is too large Load Diff