diff --git a/PHASE-3-IMPLEMENTATION-SUMMARY.md b/PHASE-3-IMPLEMENTATION-SUMMARY.md new file mode 100644 index 0000000..35f92c5 --- /dev/null +++ b/PHASE-3-IMPLEMENTATION-SUMMARY.md @@ -0,0 +1,191 @@ +# Phase 3: Collections & Environment Management - Implementation Summary + +## ✅ Completed Features + +### 1. Collections Sidebar with Tree View +- **File**: `components/api-platform/CollectionsSidebar.vue` +- **Features**: + - Collapsible collections with tree structure + - Request management within collections + - Quick actions: Edit, Delete, Add Request + - Recent requests section (last 5) + - Responsive design with mobile support + +### 2. Collection Management +- **File**: `components/api-platform/CreateCollectionModal.vue` +- **Features**: + - Create new collections with name and description + - Modal-based interface + - Form validation + +### 3. Save/Load Request Functionality +- **File**: `components/api-platform/SaveRequestModal.vue` +- **Features**: + - Save current request to any collection + - Auto-populate request name + - Create collections on-the-fly + - Complete request data preservation (params, headers, auth, body) + +### 4. Environment Management +- **File**: `components/api-platform/EnvironmentSelector.vue` +- **File**: `components/api-platform/EnvironmentModal.vue` +- **Features**: + - Environment dropdown selector + - Full environment CRUD operations + - Variable management per environment + - Visual indicators for variable count + +### 5. Variable Substitution System +- **File**: `composables/useVariableSubstitution.js` +- **Features**: + - Template syntax: `{{variableName}}` + - Complete request processing (URL, headers, params, auth, body) + - Real-time variable detection and validation + - Visual indicators in UI + +### 6. Persistence Layer +- **Storage**: localStorage +- **Features**: + - Automatic saving of collections and environments + - Persistent data across browser sessions + - JSON-based storage format + +## 🎯 User Interface Enhancements + +### Main Layout Updates +- **File**: `pages/api-platform/index.vue` +- Added collections sidebar toggle +- Environment selector in top bar +- Save request button +- Responsive layout adjustments + +### Request Builder Enhancements +- **File**: `components/api-platform/RequestBuilder.vue` +- Variable detection in URL field +- Variable preview panel +- Current environment indicator +- Integrated variable substitution + +### Global State Management +- **File**: `composables/useApiPlatform.js` +- Added UI state management +- Collections and environments state +- Modal management + +## 🔧 Technical Implementation + +### Variable Substitution Flow +1. User enters `{{variableName}}` in any field +2. System detects variables and shows indicators +3. On request send, variables are substituted with environment values +4. Visual feedback shows which variables are resolved + +### Data Structure + +#### Collections +```javascript +{ + id: timestamp, + name: "Collection Name", + description: "Optional description", + requests: [ + { + id: timestamp, + name: "Request Name", + method: "GET", + url: "{{baseUrl}}/api/endpoint", + params: [...], + headers: [...], + auth: {...}, + body: {...}, + createdAt: "ISO string" + } + ], + createdAt: "ISO string" +} +``` + +#### Environments +```javascript +{ + id: timestamp, + name: "Environment Name", + variables: [ + { + key: "baseUrl", + value: "https://api.example.com" + } + ] +} +``` + +## 🚀 Usage Examples + +### 1. Creating an Environment +1. Click environment settings icon +2. Create new environment (e.g., "Production") +3. Add variables: + - `baseUrl`: `https://api.production.com` + - `apiKey`: `prod-key-123` + +### 2. Using Variables in Requests +- URL: `{{baseUrl}}/users` +- Headers: `Authorization: Bearer {{apiKey}}` +- System automatically substitutes values when sending + +### 3. Saving Requests to Collections +1. Configure your request +2. Click "Save" button +3. Choose or create collection +4. Request is saved with all current settings + +### 4. Loading Saved Requests +1. Open collections sidebar +2. Browse collections +3. Click on any saved request +4. Request loads with all original settings + +## 📁 File Structure +``` +components/api-platform/ +├── CollectionsSidebar.vue # Main collections interface +├── CreateCollectionModal.vue # Collection creation +├── EnvironmentSelector.vue # Environment dropdown +├── EnvironmentModal.vue # Environment management +├── SaveRequestModal.vue # Request saving +└── RequestBuilder.vue # Enhanced with variables + +composables/ +├── useApiPlatform.js # Global state management +└── useVariableSubstitution.js # Variable processing + +pages/api-platform/ +└── index.vue # Main layout with sidebar +``` + +## ✨ Key Benefits + +1. **Organized Workflow**: Collections help organize related requests +2. **Environment Management**: Easy switching between dev/staging/prod +3. **Variable Substitution**: DRY principle for common values +4. **Persistent Storage**: Work survives browser restarts +5. **Team Collaboration**: Exportable collections (future feature) +6. **Professional UX**: Modern interface with visual feedback + +## 🔄 Integration with Existing Features + +- ✅ Fully compatible with existing request/response system +- ✅ Works with all authentication methods +- ✅ Integrates with notification system +- ✅ Maintains all existing functionality +- ✅ No breaking changes to existing components + +## 🎯 Phase 3 Goals - Status + +- ✅ Collections sidebar with tree view +- ✅ Save/Load requests to collections +- ✅ Environment selector dropdown +- ✅ Variable substitution ({{baseUrl}}) +- ✅ Persistence layer (localStorage) + +**Phase 3 is now complete and ready for use!** \ No newline at end of file diff --git a/docs/Current Implementation Analysis (first g.ini b/docs/Current Implementation Analysis (first g.ini new file mode 100644 index 0000000..35cb967 --- /dev/null +++ b/docs/Current Implementation Analysis (first g.ini @@ -0,0 +1,79 @@ +Current Implementation Analysis (first generation) +✅ Features Currently Implemented: +✅ HTTP Methods - Full support (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS) +✅ URL Input - With auto-protocol fixing (google.com → https://google.com) +✅ Query Parameters - Key-value UI with checkboxes +✅ Custom Headers - Key-value UI with checkboxes +✅ Basic Authentication - Bearer Token, Basic Auth, API Key (header/query) +✅ Raw Body Input - Basic textarea with JSON detection +✅ URL-encoded Body - Key-value form +✅ Response Viewer - Body and Headers tabs +✅ Response Timing - Shows ms and bytes +✅ Status Badges - Color-coded status indicators +✅ Loading States - Button loading, proper UX +✅ Error Handling - Network errors, timeouts, invalid URLs +✅ Notifications - Success/error toasts +✅ Request History - In-memory tracking +✅ Responsive Layout - Fixed viewport constraints +⚠️ Partially Implemented: +⚠️ Collections - Data structure exists but no UI/persistence +⚠️ Environments - Data structure exists but no UI/persistence +⚠️ Form-data Body - Basic structure but no file uploads +⚠️ JSON Editor - Basic textarea, no beautify/minify +❌ Missing Critical Features: +❌ OAuth2 Flow - Complete authorization flow +❌ File Uploads - Form-data with file input +❌ Code Generation - curl, axios, fetch snippets +❌ Response Export - JSON, CSV download +❌ Test Scripts - pm.test-like functionality +❌ Import/Export - Postman collections, OpenAPI +❌ Environment Variables - {{variable}} substitution +❌ Response Timeline - Performance waterfall +❌ Cookies Tab - Cookie management +❌ Test Results Tab - Script execution results +❌ JSON Beautify/Copy - Formatting tools +❌ GraphQL Support - Query editor +❌ XML/HTML Support - Syntax highlighting +❌ Collections Sidebar - Tree view, organization +❌ Environment Selector - Dropdown switcher + +🚀 Phase-by-Phase Implementation Roadmap + +Phase 2: Enhanced Body Types & JSON Tools +Goal: Complete the request body functionality +Missing Components: +Form-data with File Upload +JSON Beautify/Minify/Copy buttons +Raw body type selector (JSON, XML, Text, HTML) +Syntax highlighting for JSON/XML +Implementation Plan: +Add file input to form-data +Add JSON formatting toolbar +Add body type sub-selector +Integrate Monaco or Ace editor + +Phase 3: Collections & Environment Management +Goal: Persistent data management +Missing Components: +Collections sidebar with tree view +Save/Load requests to collections +Environment selector dropdown +Variable substitution ({{baseUrl}}) +Persistence layer (localStorage/backend) + +Phase 4: Advanced Features +Goal: Power user functionality +Missing Components: +OAuth2 complete flow +Code generation modal +Import/Export functionality +Test scripts tab with execution +Response export options + +Phase 5: Enhanced Response Viewer +Goal: Better analysis tools +Missing Components: +Timeline tab with waterfall +Cookies tab with management +Test Results tab +Response search/filter \ No newline at end of file diff --git a/pages/BF-PRF/AS/DETAIL/[id]/index.vue b/pages/BF-PRF/AS/DETAIL/[id]/index.vue new file mode 100644 index 0000000..81c6af4 --- /dev/null +++ b/pages/BF-PRF/AS/DETAIL/[id]/index.vue @@ -0,0 +1,674 @@ + + + \ No newline at end of file diff --git a/pages/BF-PRF/AS/LIST/index.vue b/pages/BF-PRF/AS/LIST/index.vue new file mode 100644 index 0000000..00a279a --- /dev/null +++ b/pages/BF-PRF/AS/LIST/index.vue @@ -0,0 +1,337 @@ + + + \ No newline at end of file diff --git a/server/api/analyze-asnaf.post.ts b/server/api/analyze-asnaf.post.ts new file mode 100644 index 0000000..2034b0e --- /dev/null +++ b/server/api/analyze-asnaf.post.ts @@ -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; // 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 => { + const body = await readBody(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.' + }; + */ +}); \ No newline at end of file