InfraForge Docs

InfraNotes Module · v0.37.15

Welcome

Select a document from the sidebar to read it.

Financial Analytics Module - Frontend Implementation Guide

Overview

This guide provides comprehensive documentation for integrating with the Financial Analytics Module API. It includes all available endpoints, required payloads, response structures, and practical implementation examples.

Base URL and Authentication

Base URL: https://your-api-domain.com

Environment Variables for Frontend:

const API_CONFIG = {
  baseURL: process.env.REACT_APP_API_BASE_URL || 'https://api.yourdomain.com',
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  }
}

Authentication:

  • All endpoints require authentication via JWT token in Authorization header
  • Header format: Authorization: Bearer <jwt_token>
  • User ID is automatically extracted from the JWT token context

Table of Contents

  1. Document Management
  2. Transaction Analytics
  3. Budget Management
  4. Financial Goals
  5. Cash Flow Management
  6. Financial Planning
  7. Category Management
  8. Scenario Planning
  9. UI Visualization Components
  10. Error Handling
  11. Common Data Types

Document Management

Upload Financial Document

Endpoint: POST /api/documents

Purpose: Upload and process financial documents (bank statements, CSV files)

Request Type: multipart/form-data

Request Payload:

const formData = new FormData();
formData.append('file', fileObject); // File object from input
formData.append('dataSource', 'personal_banking'); // or 'business_banking', 'credit_card', 'investment'

Response:

{
  "id": "uuid",
  "fileName": "statement.csv",
  "contentType": "text/csv",
  "fileSize": 12543,
  "processStatus": "processing", // "pending", "processing", "completed", "failed"
  "processedAt": null,
  "createdAt": "2024-01-15T10:30:00Z",
  "updatedAt": "2024-01-15T10:30:00Z",
  "retentionDate": "2025-01-15T10:30:00Z",
  "dataSource": "personal_banking"
}

Implementation Example:

const uploadDocument = async (file, dataSource = 'personal_banking') => {
  const formData = new FormData();
  formData.append('file', file);
  formData.append('dataSource', dataSource);
  
  try {
    const response = await fetch('/api/documents', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`
      },
      body: formData
    });
    
    if (!response.ok) throw new Error('Upload failed');
    return await response.json();
  } catch (error) {
    throw new Error(`Upload failed: ${error.message}`);
  }
};

List Documents

Endpoint: GET /api/documents

Query Parameters:

  • limit (optional): Number of documents to return (default: 20)
  • offset (optional): Number of documents to skip (default: 0)
  • status (optional): Filter by process status
  • dataSource (optional): Filter by data source

Request:

const params = new URLSearchParams({
  limit: '20',
  offset: '0',
  status: 'completed',
  dataSource: 'personal_banking'
});

const response = await fetch(`/api/documents?${params}`, {
  headers: { 'Authorization': `Bearer ${token}` }
});

Response:

{
  "documents": [
    {
      "id": "uuid",
      "fileName": "statement.csv",
      "contentType": "text/csv",
      "fileSize": 12543,
      "processStatus": "completed",
      "processedAt": "2024-01-15T10:35:00Z",
      "createdAt": "2024-01-15T10:30:00Z",
      "updatedAt": "2024-01-15T10:35:00Z",
      "retentionDate": "2025-01-15T10:30:00Z",
      "dataSource": "personal_banking"
    }
  ],
  "total": 1
}

Get Document Details

Endpoint: GET /api/documents/{id}

Response: Single document object (same structure as above)

Get Document Transactions

Endpoint: GET /api/documents/{id}/transactions

Response:

{
  "transactions": [
    {
      "id": "uuid",
      "transactionDate": "2024-01-15T00:00:00Z",
      "description": "GROCERY STORE PURCHASE",
      "amount": "-45.67",
      "transactionType": "expense",
      "categoryId": "uuid",
      "merchantName": "Local Grocery",
      "isRecurring": false
    }
  ],
  "total": 25
}

Delete Document

Endpoint: DELETE /api/documents/{id}

Response: 204 No Content


Transaction Analytics

Get Analytics Summary

Endpoint: GET /api/analytics/summary

Query Parameters:

  • startDate (optional): ISO date string
  • endDate (optional): ISO date string
  • period (optional): "weekly", "monthly", "quarterly", "yearly"

Request:

const params = new URLSearchParams({
  startDate: '2024-01-01',
  endDate: '2024-01-31',
  period: 'monthly'
});

const response = await fetch(`/api/analytics/summary?${params}`, {
  headers: { 'Authorization': `Bearer ${token}` }
});

Response:

{
  "totalIncome": "5000.00",
  "totalExpenses": "3250.45",
  "netCashFlow": "1749.55",
  "transactionCount": 87,
  "averageTransactionAmount": "91.95",
  "period": "monthly",
  "periodStart": "2024-01-01T00:00:00Z",
  "periodEnd": "2024-01-31T23:59:59Z",
  "topCategories": [
    {
      "categoryId": "uuid",
      "categoryName": "Groceries",
      "amount": "456.78",
      "percentage": 14.05
    }
  ],
  "trends": {
    "incomeGrowth": "5.2",
    "expenseGrowth": "2.1",
    "savingsRate": "34.9"
  }
}

Endpoint: GET /api/analytics/trends

Query Parameters:

  • trendType (optional): "increasing", "decreasing", "spike", "dip"
  • entityType (optional): "category", "merchant", "overall"
  • startDate (optional): ISO date string
  • endDate (optional): ISO date string
  • minSignificance (optional): Minimum significance score (0-1)
  • limit (optional): Number of trends to return

Response:

{
  "trends": [
    {
      "id": "uuid",
      "trendType": "increasing",
      "entityType": "category",
      "entityId": "uuid",
      "entityName": "Dining Out",
      "periodStart": "2024-01-01T00:00:00Z",
      "periodEnd": "2024-01-31T23:59:59Z",
      "previousAmount": "234.56",
      "currentAmount": "345.67",
      "percentChange": "47.35",
      "significanceScore": 0.87,
      "createdAt": "2024-01-15T10:30:00Z"
    }
  ],
  "total": 5
}

Get Recurring Transactions

Endpoint: GET /api/analytics/recurring

Response:

{
  "recurringTransactions": [
    {
      "id": "uuid",
      "merchantName": "Netflix",
      "categoryName": "Entertainment",
      "averageAmount": "15.99",
      "frequency": "monthly",
      "confidence": 0.95,
      "lastOccurrence": "2024-01-15T00:00:00Z",
      "nextPredicted": "2024-02-15T00:00:00Z",
      "occurrenceCount": 12
    }
  ],
  "total": 8
}

Budget Management

Create Budget

Endpoint: POST /api/planning/budgets

Request Payload:

{
  "name": "Monthly Household Budget",
  "description": "Family budget for monthly expenses",
  "totalAmount": "4500.00",
  "period": "monthly", // "weekly", "monthly", "quarterly", "yearly", "custom"
  "startDate": "2024-01-01T00:00:00Z",
  "endDate": "2024-12-31T23:59:59Z", // Optional for recurring budgets
  "isActive": true,
  "autoRenew": true,
  "notifyThreshold": 80, // Notify when 80% of budget is used
  "includeRecurring": true,
  "categories": [
    {
      "categoryId": "uuid",
      "categoryName": "Groceries",
      "amount": "600.00"
    },
    {
      "categoryId": "uuid",
      "categoryName": "Utilities",
      "amount": "300.00"
    }
  ]
}

Response:

{
  "id": "uuid",
  "name": "Monthly Household Budget",
  "description": "Family budget for monthly expenses",
  "totalAmount": "4500.00",
  "period": "monthly",
  "startDate": "2024-01-01T00:00:00Z",
  "endDate": "2024-12-31T23:59:59Z",
  "isActive": true,
  "autoRenew": true,
  "notifyThreshold": 80,
  "includeRecurring": true,
  "createdAt": "2024-01-15T10:30:00Z",
  "updatedAt": "2024-01-15T10:30:00Z"
}

List Budgets

Endpoint: GET /api/planning/budgets

Query Parameters:

  • name (optional): Filter by budget name
  • period (optional): Filter by budget period
  • isActive (optional): Filter by active status
  • startDateFrom (optional): Filter budgets starting from date
  • startDateTo (optional): Filter budgets starting before date
  • includeInactive (optional): Include inactive budgets
  • limit (optional): Number of budgets to return
  • offset (optional): Number of budgets to skip

Response:

{
  "budgets": [
    {
      "id": "uuid",
      "name": "Monthly Household Budget",
      "description": "Family budget for monthly expenses",
      "totalAmount": "4500.00",
      "period": "monthly",
      "startDate": "2024-01-01T00:00:00Z",
      "endDate": "2024-12-31T23:59:59Z",
      "isActive": true,
      "autoRenew": true,
      "notifyThreshold": 80,
      "includeRecurring": true,
      "createdAt": "2024-01-15T10:30:00Z",
      "updatedAt": "2024-01-15T10:30:00Z"
    }
  ],
  "total": 3
}

Get Budget Progress

Endpoint: GET /api/planning/budgets/{id}/progress

Response:

{
  "budgetId": "uuid",
  "periodStart": "2024-01-01T00:00:00Z",
  "periodEnd": "2024-01-31T23:59:59Z",
  "currentAmount": "2340.55",
  "remainingAmount": "2159.45",
  "percentUsed": "52.01",
  "isOverBudget": false,
  "categories": [
    {
      "categoryId": "uuid",
      "categoryName": "Groceries",
      "allocated": "600.00",
      "spent": "234.56",
      "remaining": "365.44",
      "percentUsed": "39.09"
    }
  ],
  "updatedAt": "2024-01-15T10:30:00Z"
}

Update Budget

Endpoint: PUT /api/planning/budgets/{id}

Request Payload: Same structure as Create Budget (excluding categories)

Add Budget Category

Endpoint: POST /api/planning/budgets/{id}/categories

Request Payload:

{
  "categoryId": "uuid",
  "categoryName": "Transportation",
  "amount": "450.00"
}

Delete Budget

Endpoint: DELETE /api/planning/budgets/{id}

Response: 204 No Content


Financial Goals

Create Financial Goal

Endpoint: POST /api/v1/goals

Request Payload:

{
  "name": "Emergency Fund",
  "description": "Build emergency fund for 6 months of expenses",
  "goalType": "emergency_fund", // "saving", "debt_payoff", "investment", "expense_reduction", "income_increase", "emergency_fund", "custom"
  "targetAmount": "25000.00",
  "startDate": "2024-01-01T00:00:00Z",
  "targetDate": "2024-12-31T23:59:59Z",
  "priority": "high", // "low", "medium", "high"
  "categoryId": "uuid", // Optional
  "isPublic": false,
  "isRecurring": false,
  "recurrencePattern": "" // Optional: for recurring goals
}

Response:

{
  "id": "uuid",
  "userId": "uuid",
  "name": "Emergency Fund",
  "description": "Build emergency fund for 6 months of expenses",
  "goalType": "emergency_fund",
  "targetAmount": "25000.00",
  "currentAmount": "0.00",
  "startDate": "2024-01-01T00:00:00Z",
  "targetDate": "2024-12-31T23:59:59Z",
  "status": "active",
  "priority": "high",
  "categoryId": "uuid",
  "isPublic": false,
  "isRecurring": false,
  "recurrencePattern": "",
  "createdAt": "2024-01-15T10:30:00Z",
  "updatedAt": "2024-01-15T10:30:00Z"
}

List Goals

Endpoint: GET /api/v1/goals

Query Parameters:

  • status (optional): "active", "achieved", "cancelled", "on_hold"
  • goalType (optional): Goal type filter
  • priority (optional): Priority filter
  • limit (optional): Number of goals to return
  • offset (optional): Number of goals to skip

Response:

{
  "goals": [
    {
      "id": "uuid",
      "userId": "uuid",
      "name": "Emergency Fund",
      "description": "Build emergency fund for 6 months of expenses",
      "goalType": "emergency_fund",
      "targetAmount": "25000.00",
      "currentAmount": "5000.00",
      "progressPercentage": "20.00",
      "startDate": "2024-01-01T00:00:00Z",
      "targetDate": "2024-12-31T23:59:59Z",
      "status": "active",
      "priority": "high",
      "daysRemaining": 320,
      "createdAt": "2024-01-15T10:30:00Z",
      "updatedAt": "2024-01-15T10:30:00Z"
    }
  ],
  "total": 5
}

Create Goal Contribution

Endpoint: POST /api/v1/goals/{id}/contributions

Request Payload:

{
  "amount": "500.00",
  "contributionDate": "2024-01-15T00:00:00Z",
  "transactionId": "uuid", // Optional: link to a transaction
  "description": "Monthly emergency fund contribution"
}

Response:

{
  "id": "uuid",
  "goalId": "uuid",
  "userId": "uuid",
  "amount": "500.00",
  "contributionDate": "2024-01-15T00:00:00Z",
  "transactionId": "uuid",
  "description": "Monthly emergency fund contribution",
  "createdAt": "2024-01-15T10:30:00Z",
  "updatedAt": "2024-01-15T10:30:00Z"
}

Get Goal Analysis

Endpoint: GET /api/v1/goals/{id}/analysis/progress

Response:

{
  "goalId": "uuid",
  "currentProgress": "20.00",
  "projectedCompletionDate": "2025-03-15T00:00:00Z",
  "requiredMonthlyContribution": "1750.00",
  "currentMonthlyAverage": "500.00",
  "isOnTrack": false,
  "monthsBehindSchedule": 3,
  "recommendedAdjustment": "1250.00",
  "confidenceScore": 0.85
}

Cash Flow Management

Get Cash Flow Predictions

Endpoint: GET /api/cashflow/predictions

Query Parameters:

  • periodType (optional): "weekly", "monthly", "quarterly"
  • startDate (optional): ISO date string
  • endDate (optional): ISO date string
  • limit (optional): Number of predictions to return

Response:

{
  "predictions": [
    {
      "id": "uuid",
      "periodStart": "2024-02-01T00:00:00Z",
      "periodEnd": "2024-02-29T23:59:59Z",
      "predictedIncome": "5200.00",
      "predictedExpense": "3450.00",
      "predictedNetFlow": "1750.00",
      "confidenceScore": "0.87",
      "lowerBoundIncome": "4800.00",
      "upperBoundIncome": "5600.00",
      "lowerBoundExpense": "3100.00",
      "upperBoundExpense": "3800.00",
      "createdAt": "2024-01-15T10:30:00Z"
    }
  ],
  "total": 6
}

Get Cash Flow Alerts

Endpoint: GET /api/cashflow/alerts

Query Parameters:

  • status (optional): "pending", "acknowledged", "resolved", "dismissed"
  • severity (optional): "low", "medium", "high"
  • alertType (optional): "low_balance", "negative_flow", "unusual_spending"

Response:

{
  "alerts": [
    {
      "id": "uuid",
      "alertType": "low_balance",
      "severity": "high",
      "title": "Low Balance Warning",
      "message": "Your account balance may drop below $100 in the next 7 days",
      "triggerAmount": "100.00",
      "projectedDate": "2024-01-22T00:00:00Z",
      "status": "pending",
      "createdAt": "2024-01-15T10:30:00Z",
      "actionRequired": true,
      "recommendations": [
        "Consider reducing discretionary spending",
        "Transfer funds from savings if available"
      ]
    }
  ],
  "total": 3
}

Acknowledge Alert

Endpoint: POST /api/cashflow/alerts/{id}/acknowledge

Response:

{
  "id": "uuid",
  "status": "acknowledged",
  "acknowledgedAt": "2024-01-15T10:30:00Z"
}

Get Cash Flow Snapshot

Endpoint: GET /api/cashflow/snapshot/latest

Response:

{
  "id": "uuid",
  "snapshotDate": "2024-01-15T10:30:00Z",
  "currentBalance": "2450.00",
  "projectedBalance30d": "3200.00",
  "projectedBalance60d": "4100.00",
  "projectedBalance90d": "4950.00",
  "monthlyNetCashFlow": "750.00",
  "pendingIncome": "1200.00",
  "pendingExpenses": "650.00",
  "surplusDeficitStatus": "surplus",
  "updatedAt": "2024-01-15T10:30:00Z"
}

Financial Planning

Create Planned Expense

Endpoint: POST /api/planning/expenses

Request Payload:

{
  "title": "Annual Car Insurance",
  "description": "Yearly car insurance premium payment",
  "amount": "1200.00",
  "dueDate": "2024-03-15T00:00:00Z",
  "categoryId": "uuid",
  "isRecurring": true,
  "recurrenceRule": "FREQ=YEARLY;INTERVAL=1", // RFC 5545 RRULE format
  "notifyDaysBefore": 30
}

Response:

{
  "id": "uuid",
  "title": "Annual Car Insurance",
  "description": "Yearly car insurance premium payment",
  "amount": "1200.00",
  "dueDate": "2024-03-15T00:00:00Z",
  "categoryId": "uuid",
  "isPaid": false,
  "isRecurring": true,
  "recurrenceRule": "FREQ=YEARLY;INTERVAL=1",
  "notifyDaysBefore": 30,
  "createdAt": "2024-01-15T10:30:00Z",
  "updatedAt": "2024-01-15T10:30:00Z"
}

Get Upcoming Expenses

Endpoint: GET /api/planning/expenses/upcoming

Query Parameters:

  • days (optional): Number of days to look ahead (default: 30)
  • categoryId (optional): Filter by category

Response:

{
  "expenses": [
    {
      "id": "uuid",
      "title": "Annual Car Insurance",
      "description": "Yearly car insurance premium payment",
      "amount": "1200.00",
      "dueDate": "2024-03-15T00:00:00Z",
      "categoryName": "Insurance",
      "daysUntilDue": 60,
      "isPaid": false,
      "isRecurring": true,
      "priority": "high"
    }
  ],
  "total": 5,
  "totalAmount": "3450.00"
}

Mark Expense as Paid

Endpoint: POST /api/planning/expenses/{id}/paid

Request Payload:

{
  "paidDate": "2024-01-15T00:00:00Z",
  "actualAmount": "1150.00", // Optional: if different from planned
  "transactionId": "uuid" // Optional: link to transaction
}

Validate Recurrence Rule

Endpoint: POST /api/planning/recurrence/rule/validate

Request Payload:

{
  "rule": "FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=15"
}

Response:

{
  "valid": "true",
  "rule": "FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=15",
  "userId": "uuid"
}

Generate Recurrence Instances

Endpoint: POST /api/planning/recurrence/instances

Request Payload:

{
  "rule": "FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=15",
  "startDate": "2024-01-15T00:00:00Z",
  "endDate": "2024-12-31T23:59:59Z",
  "maxCount": 12
}

Response:

{
  "instances": [
    "2024-01-15T00:00:00Z",
    "2024-02-15T00:00:00Z",
    "2024-03-15T00:00:00Z"
  ],
  "total": 12
}

Category Management

List Categories

Endpoint: GET /api/categories

Response:

{
  "categories": [
    {
      "id": "uuid",
      "name": "Groceries",
      "parentId": "uuid", // Optional: for subcategories
      "color": "#4CAF50",
      "iconName": "shopping-cart",
      "isSystem": true
    }
  ],
  "total": 15
}

Create Category

Endpoint: POST /api/categories

Request Payload:

{
  "name": "Custom Category",
  "parentId": "uuid", // Optional
  "color": "#2196F3",
  "iconName": "custom-icon"
}

Update Transaction Category

Endpoint: PATCH /api/transactions/{id}/category

Request Payload:

{
  "categoryId": "uuid",
  "learnFromCorrection": true // Optional: improve categorization
}

Scenario Planning

Create Financial Scenario

Endpoint: POST /api/planning/scenarios

Request Payload:

{
  "name": "Job Change Scenario",
  "description": "Financial projection if I change jobs",
  "baseMonth": "2024-02-01T00:00:00Z",
  "duration": 12 // Number of months to project
}

Response:

{
  "id": "uuid",
  "name": "Job Change Scenario",
  "description": "Financial projection if I change jobs",
  "baseMonth": "2024-02-01T00:00:00Z",
  "duration": 12,
  "createdAt": "2024-01-15T10:30:00Z",
  "updatedAt": "2024-01-15T10:30:00Z"
}

Add Scenario Item

Endpoint: POST /api/planning/scenarios/{id}/items

Request Payload:

{
  "name": "New Job Salary",
  "description": "Increased salary from new position",
  "amount": "6500.00",
  "type": "income", // "income" or "expense"
  "frequency": "monthly", // "monthly", "yearly", "one-time"
  "startDate": "2024-03-01T00:00:00Z",
  "endDate": "2024-12-31T23:59:59Z",
  "growthRate": "0.03" // 3% annual growth
}

Calculate Scenario Results

Endpoint: POST /api/planning/scenarios/{id}/calculate

Response:

{
  "scenarioId": "uuid",
  "monthlyProjections": [
    {
      "period": "2024-02",
      "totalIncome": "6500.00",
      "totalExpenses": "4200.00",
      "netCashFlow": "2300.00",
      "runningBalance": "2300.00"
    }
  ],
  "summary": {
    "totalAnnualIncome": "78000.00",
    "totalAnnualExpenses": "50400.00",
    "annualNetCashFlow": "27600.00",
    "averageMonthlyCashFlow": "2300.00",
    "savingsRate": "35.38",
    "expenseCategories": {
      "Housing": "18000.00",
      "Transportation": "7200.00"
    },
    "incomeCategories": {
      "Salary": "78000.00"
    }
  }
}

Compare Scenarios

Endpoint: POST /api/planning/scenarios/compare

Request Payload:

{
  "scenario1Id": "uuid",
  "scenario2Id": "uuid"
}

Response:

{
  "scenario1": {
    "name": "Current Situation",
    "annualIncome": "60000.00",
    "annualExpenses": "45000.00",
    "annualNetCashFlow": "15000.00",
    "savingsRate": "25.00"
  },
  "scenario2": {
    "name": "Job Change Scenario",
    "annualIncome": "78000.00",
    "annualExpenses": "50400.00",
    "annualNetCashFlow": "27600.00",
    "savingsRate": "35.38"
  },
  "incomeDifference": "18000.00",
  "expenseDifference": "5400.00",
  "netCashFlowDifference": "12600.00",
  "savingsRateDifference": "10.38"
}

UI Visualization Components

Get Balance Projection Chart

Endpoint: GET /api/cashflow/ui/balance-projection

Query Parameters:

  • months (optional): Number of months to project (default: 12)
  • chartType (optional): "line", "area" (default: "line")

Response:

{
  "chartData": {
    "labels": ["Jan 2024", "Feb 2024", "Mar 2024"],
    "datasets": [
      {
        "label": "Projected Balance",
        "data": [2500.00, 3250.00, 4100.00],
        "borderColor": "#4CAF50",
        "backgroundColor": "rgba(76, 175, 80, 0.1)"
      }
    ]
  },
  "metadata": {
    "currentBalance": "2500.00",
    "projectedGrowth": "64.00",
    "confidence": "0.87"
  }
}

Get Cash Flow Health Indicator

Endpoint: GET /api/cashflow/ui/health-indicator

Response:

{
  "healthScore": 85,
  "status": "healthy", // "healthy", "warning", "critical"
  "indicators": {
    "cashFlow": {
      "score": 90,
      "status": "excellent",
      "message": "Strong positive cash flow"
    },
    "liquidity": {
      "score": 75,
      "status": "good",
      "message": "Adequate emergency reserves"
    },
    "predictability": {
      "score": 80,
      "status": "good",
      "message": "Consistent income patterns"
    }
  },
  "recommendations": [
    "Consider increasing emergency fund to 6 months of expenses"
  ]
}

Get Goal Progress Visualization

Endpoint: GET /api/goals/ui/visualization/{goalId}

Response:

{
  "goalInfo": {
    "name": "Emergency Fund",
    "targetAmount": "25000.00",
    "currentAmount": "8500.00",
    "progressPercentage": "34.00"
  },
  "chartData": {
    "type": "progress",
    "data": {
      "completed": 34,
      "remaining": 66
    },
    "colors": {
      "completed": "#4CAF50",
      "remaining": "#E0E0E0"
    }
  },
  "milestones": [
    {
      "name": "First Milestone",
      "targetAmount": "5000.00",
      "achieved": true,
      "achievedDate": "2024-01-10T00:00:00Z"
    }
  ]
}

Error Handling

Standard Error Response Format

All API endpoints return errors in the following format:

{
  "error": "Error message description",
  "code": "ERROR_CODE", // Optional
  "details": { // Optional additional details
    "field": "validation error message"
  },
  "timestamp": "2024-01-15T10:30:00Z"
}

HTTP Status Codes

  • 200 OK - Request successful
  • 201 Created - Resource created successfully
  • 204 No Content - Request successful, no content to return
  • 400 Bad Request - Invalid request data
  • 401 Unauthorized - Authentication required or invalid
  • 403 Forbidden - Insufficient permissions
  • 404 Not Found - Resource not found
  • 409 Conflict - Resource conflict (e.g., duplicate)
  • 422 Unprocessable Entity - Validation errors
  • 500 Internal Server Error - Server error

Error Handling Implementation

const handleApiError = (error, response) => {
  const status = response?.status || 500;
  const errorData = response?.data || { error: 'Unknown error occurred' };
  
  switch (status) {
    case 400:
      throw new Error(`Bad Request: ${errorData.error}`);
    case 401:
      // Redirect to login or refresh token
      throw new Error('Authentication required');
    case 403:
      throw new Error('Access denied');
    case 404:
      throw new Error('Resource not found');
    case 422:
      // Handle validation errors
      const validationErrors = errorData.details || {};
      throw new Error(`Validation error: ${Object.values(validationErrors).join(', ')}`);
    case 500:
      throw new Error('Server error. Please try again later.');
    default:
      throw new Error(errorData.error || 'Unknown error occurred');
  }
};

Common Data Types

UUID Format

  • All IDs use UUID v4 format: "550e8400-e29b-41d4-a716-446655440000"

Decimal Amounts

  • All monetary amounts are strings with decimal precision: "1234.56"
  • Negative amounts are prefixed with minus sign: "-1234.56"

Date/Time Format

  • All dates use ISO 8601 format: "2024-01-15T10:30:00Z"
  • Timezone is always UTC (Z suffix)

Pagination

  • limit: Maximum number of items to return (default: 20, max: 100)
  • offset: Number of items to skip (default: 0)
  • total: Total number of items available

Status Values

Document Process Status:

  • pending - Document uploaded, waiting to be processed
  • processing - Document is being processed
  • completed - Document processed successfully
  • failed - Document processing failed

Goal Status:

  • active - Goal is currently being worked on
  • achieved - Goal has been completed
  • cancelled - Goal has been cancelled
  • on_hold - Goal is temporarily paused

Budget Period:

  • weekly - Weekly budget cycle
  • monthly - Monthly budget cycle
  • quarterly - Quarterly budget cycle
  • yearly - Annual budget cycle
  • custom - Custom date range

Priority Levels:

  • low - Low priority
  • medium - Medium priority
  • high - High priority

This guide provides a comprehensive foundation for frontend implementation. Each endpoint includes practical examples and all necessary payload structures for successful integration.