InfraForge Docs

InfraNotes Core · v2

Welcome

Select a document from the sidebar to read it.

Project Finance Management API Documentation

Next.js Frontend Implementation Guide

Overview

This document provides comprehensive documentation for the Project Finance Management API endpoints. All endpoints require authentication via JWT Bearer token and follow RESTful conventions with standardized response formats.

Base URL: /api/project-finance
Authentication: Bearer Token (JWT) in Authorization header
Content-Type: application/json


🔑 Authentication & Headers

Required Headers

  • Authorization: Bearer <jwt_token>
  • Content-Type: application/json

Standard Response Format

All API responses follow this structure:

  • success (boolean): Indicates if the request was successful
  • data (object/array): The response payload
  • message (string): Human-readable success message
  • error (string): Error message if success is false
  • request_id (string): Unique identifier for request tracing
  • details (string): Additional error details if applicable

📊 Project Finance CRUD Operations

1. Create Project Finance

Endpoint: POST /api/project-finance/
Purpose: Initialize financial management for a project

Request Payload:

  • project_id (number, required): ID of the project
  • billing_model (string, required): One of "fixed_price", "time_and_material", "milestone", "retainer", "hourly"
  • estimated_revenue (number, required): Expected project revenue (≥0)
  • estimated_costs (number, required): Expected project costs (≥0)
  • estimated_profit_margin (number, required): Expected profit margin (-100 to 100)
  • currency (string, optional): 3-letter currency code (defaults to "USD")
  • client_id (number, optional): Associated client ID
  • billing_frequency (string, optional): Billing frequency (defaults to "monthly")
  • phases (array, optional): Array of project phases to create
  • cost_centers (array, optional): Array of cost centers to create

Success Response (201):

  • Returns complete ProjectFinance object with computed fields
  • Includes id, timestamps, status ("planning"), and calculated billing dates

Error Responses:

  • 400: Validation error (invalid billing model, negative values, etc.)
  • 401: Authentication required
  • 409: Project finance already exists for this project

2. Get Project Finance by ID

Endpoint: GET /api/project-finance/{projectFinanceID}
Purpose: Retrieve specific project finance details

URL Parameters:

  • projectFinanceID (number): The project finance ID

Success Response (200):

  • Returns complete ProjectFinance object
  • Includes computed fields: actual_profit_margin, budget_utilization, revenue_recognized
  • Contains related data if available

Error Responses:

  • 400: Invalid project finance ID
  • 401: Authentication required
  • 404: Project finance not found or access denied

3. Refresh Project Financials

Endpoint: PUT /api/project-finance/{projectFinanceID}/refresh
Purpose: Recalculate financial metrics and update computed fields

URL Parameters:

  • projectFinanceID (number): The project finance ID

Success Response (200):

  • Returns updated ProjectFinance object with refreshed calculations
  • Updates actual costs from expenses, revenue from invoices
  • Recalculates profit margins and health scores

Error Responses:

  • 400: Invalid project finance ID
  • 401: Authentication required
  • 404: Project finance not found

🏗️ Project-Specific Financial Operations

4. Get Project Finance by Project

Endpoint: GET /api/project-finance/project/{projectID}
Purpose: Get financial data for a specific project

URL Parameters:

  • projectID (number): The project ID

Success Response (200):

  • Returns ProjectFinance object associated with the project
  • Null if no financial setup exists for the project

5. Get Project Financial Dashboard

Endpoint: GET /api/project-finance/project/{projectID}/dashboard
Purpose: Get comprehensive financial dashboard data for a project

URL Parameters:

  • projectID (number): The project ID

Success Response (200):
Returns ProjectFinancialDashboard object containing:

  • project: Basic project information
  • finance: Project finance details
  • health: Financial health metrics and scoring
  • phases: Array of project phases with financial data
  • cost_centers: Array of cost centers with budget allocations
  • milestones: Array of milestones with billing information
  • summary: Dashboard summary with key metrics
  • alerts: Array of financial alerts requiring attention
  • last_updated: Timestamp of last data refresh

Dashboard Summary includes:

  • total_budget: Total allocated budget
  • spent_to_date: Amount spent so far
  • budget_remaining: Remaining budget
  • completed_phases: Number of completed phases
  • total_phases: Total number of phases
  • completed_milestones: Number of completed milestones
  • total_milestones: Total number of milestones
  • project_progress: Overall completion percentage

📈 Phase Management

6. Create Project Phase

Endpoint: POST /api/project-finance/phases/
Purpose: Create a new project phase

Request Payload:

  • project_finance_id (number, required): Associated project finance ID
  • name (string, required): Phase name
  • description (string, optional): Phase description
  • phase_order (number, required): Phase sequence number (≥1)
  • budget_allocation (number, required): Budget allocated to this phase (≥0)
  • estimated_costs (number, required): Estimated costs for this phase (≥0)
  • billable_amount (number, required): Amount that can be billed (≥0)
  • planned_start_date (string, required): ISO date string
  • planned_end_date (string, required): ISO date string

Success Response (201):

  • Returns created ProjectPhase object with computed fields
  • Includes status ("planned"), timestamps, and financial allocations

7. Get Project Phases

Endpoint: GET /api/project-finance/phases/project/{projectID}
Purpose: Retrieve all phases for a project

URL Parameters:

  • projectID (number): The project ID

Success Response (200):

  • Returns array of ProjectPhase objects
  • Ordered by phase_order
  • Includes budget allocation and completion status

8. Complete Project Phase

Endpoint: PUT /api/project-finance/phases/{phaseID}/complete
Purpose: Mark a phase as completed with actual financial data

URL Parameters:

  • phaseID (number): The phase ID

Request Payload:

  • actual_spent (number, required): Actual amount spent (≥0)
  • billed_amount (number, required): Amount billed for this phase (≥0)
  • notes (string, optional): Completion notes

Success Response (200):

  • Returns updated ProjectPhase object with completion data
  • Status changed to "completed"
  • Includes actual vs. estimated variance calculations

🎯 Milestone Management

9. Create Project Milestone

Endpoint: POST /api/project-finance/milestones/
Purpose: Create a project milestone with billing information

Request Payload:

  • project_finance_id (number, required): Associated project finance ID
  • project_phase_id (number, optional): Associated phase ID
  • name (string, required): Milestone name
  • description (string, optional): Milestone description
  • planned_date (string, required): ISO date string for target completion
  • billable_amount (number, required): Amount to bill upon completion (≥0)
  • completion_criteria (string, optional): Criteria for completion

Success Response (201):

  • Returns created ProjectMilestone object
  • Status set to "planned"
  • Ready for completion tracking

10. Complete Milestone

Endpoint: PUT /api/project-finance/milestones/{milestoneID}/complete
Purpose: Mark milestone as completed and optionally generate invoice

URL Parameters:

  • milestoneID (number): The milestone ID

Request Payload:

  • create_invoice (boolean, optional): Whether to automatically create invoice (defaults to false)

Success Response (200):

  • Returns updated ProjectMilestone object
  • Status changed to "completed"
  • completed_date populated
  • If invoice creation requested, includes invoice information

🔍 Analytics and Health Monitoring

11. Get Project Financial Health

Endpoint: GET /api/project-finance/analytics/{projectFinanceID}/health
Purpose: Retrieve current financial health metrics

URL Parameters:

  • projectFinanceID (number): The project finance ID

Success Response (200):
Returns ProjectFinancialHealth object containing:

  • health_score: Overall health score (0-100)
  • risk_level: Risk assessment ("low", "medium", "high", "critical")
  • budget_utilization: Percentage of budget used
  • profit_margin: Current profit margin
  • cash_flow: Current cash flow status
  • cash_flow_projection: Projected cash flow
  • budget_variance: Variance from planned budget
  • budget_burn_rate: Rate of budget consumption
  • projected_budget_overrun: Estimated budget overrun
  • roi: Return on investment calculation
  • outstanding_receivables: Unpaid invoice amounts

12. Recalculate Project Health

Endpoint: POST /api/project-finance/analytics/{projectFinanceID}/health/recalculate
Purpose: Force recalculation of financial health metrics

URL Parameters:

  • projectFinanceID (number): The project finance ID

Success Response (200):

  • Returns updated ProjectFinancialHealth object
  • All metrics recalculated based on current data
  • Updates calculated_at timestamp

🏢 Portfolio Management

13. Get Portfolio Dashboard

Endpoint: GET /api/project-finance/portfolio/dashboard
Purpose: Retrieve portfolio-level financial overview

Query Parameters (all optional):

  • team_id (number): Filter by team
  • status (string): Filter by project status
  • billing_model (string): Filter by billing model
  • client_id (number): Filter by client
  • manager_id (number): Filter by project manager
  • start_date (string): ISO date for date range
  • end_date (string): ISO date for date range
  • currency (string): Filter by currency
  • min_budget (number): Minimum budget filter
  • max_budget (number): Maximum budget filter

Success Response (200):
Returns PortfolioFinancialSummary object containing:

  • total_projects: Total number of projects
  • active_projects: Number of active projects
  • completed_projects: Number of completed projects
  • total_estimated_budget: Sum of all estimated budgets
  • total_actual_costs: Sum of all actual costs
  • total_revenue: Sum of all revenue
  • overall_profit_margin: Portfolio-wide profit margin
  • average_health_score: Average health across projects
  • high_risk_projects: Count of high-risk projects
  • projects_by_status: Breakdown by project status
  • projects_by_risk: Breakdown by risk level
  • revenue_by_month: Monthly revenue distribution
  • top_performing_projects: Best performing projects
  • underperforming_projects: Projects needing attention

💰 Budget Integration Endpoints

14. Create Project Budget Allocation

Endpoint: POST /api/project-finance/budget/allocation
Purpose: Allocate budget from an existing budget to a project

Request Payload:

  • project_id (number, required): Target project ID
  • budget_id (number, required): Source budget ID
  • allocated_amount (number, required): Amount to allocate (>0)
  • currency (string, optional): Currency code (defaults to budget currency)
  • allocation_type (string, required): One of "project", "phase", "cost_center", "milestone"
  • notes (string, optional): Allocation notes

Success Response (201):
Returns ProjectBudgetAllocation object containing:

  • id: Allocation ID
  • project_id: Target project
  • budget_id: Source budget
  • allocated_amount: Allocated amount
  • used_amount: Amount used (initially 0)
  • remaining_amount: Available amount
  • allocation_type: Type of allocation
  • allocated_by: User who created allocation
  • created_at: Creation timestamp
  • Related objects: budget, allocated_by_user

15. Get Project Budget Allocations

Endpoint: GET /api/project-finance/budget/allocations/{projectID}
Purpose: Retrieve all budget allocations for a project

URL Parameters:

  • projectID (number): The project ID

Success Response (200):

  • Returns array of ProjectBudgetAllocation objects
  • Includes related budget and user information
  • Shows current usage and remaining amounts

16. Get Project Budget Analytics

Endpoint: GET /api/project-finance/budget/analytics/{projectID}
Purpose: Get comprehensive budget analytics with recommendations

URL Parameters:

  • projectID (number): The project ID

Success Response (200):
Returns ProjectBudgetAnalytics object containing:

  • project_id: Project identifier
  • project_name: Project name
  • total_allocated_budget: Total budget allocated to project
  • total_used_budget: Total budget used
  • total_remaining_budget: Total budget remaining
  • budget_utilization_rate: Percentage of budget used
  • budget_allocations: Array of all allocations
  • is_over_budget: Whether project is over budget
  • budget_health_score: Health score (0-100)
  • recommendations: Array of actionable recommendations

Recommendations include:

  • Budget utilization advice
  • Reallocation suggestions
  • Risk warnings
  • Optimization opportunities

17. Update Project Budget Allocation

Endpoint: PUT /api/project-finance/budget/allocation/{allocationID}
Purpose: Update an existing budget allocation

URL Parameters:

  • allocationID (number): The allocation ID

Request Payload:

  • allocated_amount (number, optional): New allocated amount
  • notes (string, optional): Updated notes
  • allocation_type (string, optional): Updated allocation type

Success Response (200):

  • Returns updated ProjectBudgetAllocation object
  • Recalculates remaining amounts
  • Updates updated_at timestamp

18. Delete Project Budget Allocation

Endpoint: DELETE /api/project-finance/budget/allocation/{allocationID}
Purpose: Remove a budget allocation

URL Parameters:

  • allocationID (number): The allocation ID

Success Response (200):

  • Returns confirmation message
  • Allocation is permanently removed
  • Budget becomes available for reallocation

19. Get Project Budget Summary

Endpoint: GET /api/project-finance/budget/summary/{projectID}
Purpose: Get high-level budget summary for a project

URL Parameters:

  • projectID (number): The project ID

Success Response (200):
Returns ProjectBudgetSummary object containing:

  • project_id: Project identifier
  • project_name: Project name
  • project_finance_id: Associated project finance ID
  • budget_id: Primary budget ID
  • budget_name: Primary budget name
  • allocated_amount: Total allocated amount
  • used_amount: Total used amount
  • remaining_amount: Total remaining amount
  • currency: Currency code
  • usage_percentage: Percentage of budget used
  • allocation_date: When allocation was created
  • allocated_by: User who created allocation

20. Get Budget Project Utilization

Endpoint: GET /api/project-finance/budget/utilization/{budgetID}
Purpose: See how a budget is utilized across multiple projects

URL Parameters:

  • budgetID (number): The budget ID

Success Response (200):
Returns BudgetProjectUtilization object containing:

  • budget_id: Budget identifier
  • budget_name: Budget name
  • budget_total: Total budget amount
  • budget_used_total: Total amount used across all projects
  • total_allocated_to_projects: Total allocated to projects
  • total_used_by_projects: Total used by projects
  • projects_count: Number of projects using this budget
  • project_usage_percentage: Percentage of budget used by projects

📊 Financial Analytics & Forecasting

Endpoint: GET /api/analytics/trends
Purpose: Analyze expense trends over time

Query Parameters (all optional):

  • start_date (string): Start date in YYYY-MM-DD format (default: 30 days ago)
  • end_date (string): End date in YYYY-MM-DD format (default: today)

Success Response (200):
Returns TrendReport object containing:

  • time_range: Analysis time period
  • total_expenses: Total expenses in period
  • average_daily_expense: Average daily spending
  • trend_direction: Overall trend ("increasing", "decreasing", "stable")
  • growth_rate: Percentage change over period
  • category_trends: Breakdown by expense category
  • monthly_breakdown: Month-by-month analysis
  • significant_changes: Notable trend changes

Error Responses:

  • 400: Invalid date format
  • 401: Authentication required

22. Detect Expense Anomalies

Endpoint: GET /api/analytics/anomalies
Purpose: Identify unusual spending patterns and outliers

Query Parameters (all optional):

  • sensitivity (number): Detection sensitivity (0.1-1.0, default: 0.7)

Success Response (200):
Returns array of Anomaly objects containing:

  • expense_id: ID of anomalous expense (if applicable)
  • category: Expense category
  • amount: Expense amount
  • date: Date of expense
  • severity: Anomaly severity score (0-1)
  • description: Human-readable explanation
  • z_score: Statistical measure of unusualness

Error Responses:

  • 400: Invalid sensitivity value
  • 401: Authentication required

23. Get Expense Forecast

Endpoint: GET /api/analytics/forecast
Purpose: Generate expense forecasts for future periods

Query Parameters (all optional):

  • months (number): Number of months to forecast (1-24, default: 3)

Success Response (200):
Returns Forecast object containing:

  • time_range: Forecast period
  • total_expense: Total forecasted expenses
  • total_income: Total forecasted income
  • net_amount: Net forecasted amount
  • monthly_forecasts: Month-by-month expense forecasts
  • category_forecasts: Forecasts by expense category
  • confidence_level: Forecast confidence (0-1)
  • recommendations: Array of budget recommendations

Budget Recommendation includes:

  • category: Expense category
  • current_avg: Current average spending
  • recommended: Recommended spending level
  • savings: Potential savings amount
  • reason: Explanation for recommendation

Error Responses:

  • 400: Invalid months parameter
  • 401: Authentication required

24. Get Cash Flow Prediction

Endpoint: GET /api/cash-flow/prediction
Purpose: Predict future cash flow based on historical data and invoices

Query Parameters (all optional):

  • start_date (string): Prediction start date in YYYY-MM-DD format (default: today)
  • end_date (string): Prediction end date in YYYY-MM-DD format (default: 1 month from start)
  • timeframe (string): Prediction granularity ("daily", "weekly", "monthly", "yearly", default: "daily")

Success Response (200):
Returns CashFlowForecast object containing:

  • predictions: Array of cash flow predictions
  • timeframe: Prediction granularity
  • start_date: Forecast start date
  • end_date: Forecast end date
  • total_expected_in: Total expected inflow
  • total_expected_out: Total expected outflow
  • net_forecast: Net cash flow forecast
  • average_confidence: Average prediction confidence
  • significant_events: Notable events affecting cash flow
  • last_model_updated: When prediction model was last updated
  • recommended_actions: Suggested actions based on forecast

Cash Flow Prediction includes:

  • date: Prediction date
  • expected_inflow: Expected money coming in
  • expected_outflow: Expected money going out
  • net_cash_flow: Net cash flow for the date
  • confidence: Prediction confidence (0-1)
  • is_based_on_data: Whether prediction uses actual data
  • factors: Factors influencing the prediction

Error Responses:

  • 400: Invalid date format or timeframe
  • 401: Authentication required

25. Get Cash Flow Model Status

Endpoint: GET /api/cash-flow/model/status
Purpose: Get the status of the cash flow prediction model

Success Response (200):
Returns model status object containing:

  • model_exists: Whether a trained model exists
  • last_trained: When model was last trained
  • data_points: Number of data points used in training
  • accuracy: Model accuracy percentage
  • next_training_due: When next training is recommended

Error Responses:

  • 401: Authentication required

26. Train Cash Flow Model

Endpoint: POST /api/cash-flow/model/train
Purpose: Train or retrain the cash flow prediction model

Success Response (202):
Returns training status:

  • status: "Model training started"
  • estimated_completion: Estimated completion time

Error Responses:

  • 401: Authentication required
  • 500: Training failed to start

27. Get Cash Flow Analytics

Endpoint: GET /api/cash-flow/analytics
Purpose: Get comprehensive cash flow analytics and insights

Query Parameters (all optional):

  • period (number): Analysis period in months (1-60, default: 12)

Success Response (200):
Returns comprehensive analytics object containing:

  • forecast: Cash flow forecast data
  • cash_flow_stability_score: Stability score (0-1)
  • seasonal_patterns_detected: Whether seasonal patterns exist
  • seasonal_peak_months: Months with highest cash flow
  • seasonal_low_months: Months with lowest cash flow
  • year_over_year_growth_rate: Growth rate percentage
  • probability_negative_cashflow: Risk of negative cash flow (0-1)
  • recommended_safety_buffer: Recommended cash reserve
  • risk_factors: Array of identified risks
  • opportunities: Array of optimization opportunities

Error Responses:

  • 400: Invalid period parameter
  • 401: Authentication required

28. Get Payment Analytics

Endpoint: GET /api/analytics/payments
Purpose: Analyze payment patterns and performance

Query Parameters (all optional):

  • team_id (number): Filter by team ID
  • start_date (string): Start date in YYYY-MM-DD format
  • end_date (string): End date in YYYY-MM-DD format
  • period (string): Preset period ("month", "quarter", "year", "ytd")

Success Response (200):
Returns PaymentAnalytics object containing:

  • time_range: Analysis period
  • total_invoices: Total number of invoices
  • total_amount: Total invoice amount
  • paid_amount: Total amount paid
  • outstanding_amount: Total outstanding amount
  • average_days_to_payment: Average payment time
  • collection_rate: Payment collection rate percentage
  • cash_flow_forecast: Future cash flow projections

Error Responses:

  • 400: Invalid date format or parameters
  • 401: Authentication required

Endpoint: GET /api/analytics/payments/trends
Purpose: Analyze trends in payment behavior over time

Query Parameters (all optional):

  • team_id (number): Filter by team ID
  • start_date (string): Start date in YYYY-MM-DD format
  • end_date (string): End date in YYYY-MM-DD format

Success Response (200):
Returns PaymentTrend object containing:

  • time_range: Analysis period
  • monthly_trends: Payment amounts by month
  • quarterly_trends: Payment amounts by quarter
  • payment_method_trends: Trends by payment method
  • trend_direction: Overall trend direction
  • growth_rate: Payment growth rate
  • seasonal_patterns: Detected seasonal patterns

Error Responses:

  • 400: Invalid parameters
  • 401: Authentication required

30. Get Payment Aging Report

Endpoint: GET /api/analytics/payments/aging
Purpose: Generate aging report for unpaid invoices

Query Parameters (all optional):

  • team_id (number): Filter by team ID

Success Response (200):
Returns PaymentAgingReport object containing:

  • total_outstanding: Total unpaid amount
  • aging_buckets: Breakdown by age ranges
  • overdue_invoices: List of overdue invoices
  • average_age: Average age of unpaid invoices
  • collection_recommendations: Suggested collection actions

Aging Buckets include:

  • 0-30 days: Current invoices
  • 31-60 days: Slightly overdue
  • 61-90 days: Overdue
  • 90+ days: Significantly overdue

Error Responses:

  • 401: Authentication required

31. Get Payment Recommendations

Endpoint: GET /api/analytics/payments/recommendations
Purpose: Get AI-powered recommendations to improve payment collection

Query Parameters (all optional):

  • team_id (number): Filter by team ID

Success Response (200):
Returns array of recommendation objects containing:

  • type: Recommendation type
  • priority: Priority level ("high", "medium", "low")
  • description: Recommendation description
  • expected_impact: Expected financial impact
  • implementation_effort: Required effort level
  • action_items: Specific steps to implement

Error Responses:

  • 401: Authentication required

🚨 Error Handling

Common Error Codes

  • VALIDATION_ERROR: Request validation failed
  • NOT_FOUND: Resource not found or access denied
  • UNAUTHORIZED: Authentication required or invalid
  • CONFLICT: Resource already exists
  • INTERNAL_ERROR: Server error
  • TIMEOUT: Request timeout
  • CONTEXT_CANCELED: Request was canceled

HTTP Status Codes

  • 200: Success
  • 201: Created successfully
  • 400: Bad request (validation error)
  • 401: Unauthorized
  • 403: Forbidden
  • 404: Not found
  • 409: Conflict
  • 500: Internal server error
  • 504: Gateway timeout

💡 Implementation Tips for Next.js

1. API Client Setup

Create a centralized API client with authentication handling and base URL configuration.

2. Error Handling

Implement consistent error handling that parses the standardized error responses and shows appropriate user feedback.

3. Loading States

All endpoints may take time to process. Implement loading states for better user experience.

4. Real-time Updates

Consider implementing WebSocket connections or polling for real-time financial data updates.

5. Data Validation

Validate request payloads on the frontend before sending to match the backend validation rules.

6. Currency Formatting

Implement proper currency formatting based on the currency codes returned by the API.

7. Date Handling

All dates are returned in ISO format. Use proper date libraries for parsing and formatting.

8. Pagination

For large datasets, implement pagination using limit/offset parameters where supported.

9. Caching Strategy

Implement appropriate caching for dashboard data that doesn't change frequently.

10. Permissions

Check user roles and permissions before showing UI elements for financial operations.


📝 Data Types Reference

Billing Models

  • fixed_price: Fixed project cost
  • time_and_material: Hourly/daily rates
  • milestone: Payment based on milestones
  • retainer: Ongoing monthly payments
  • hourly: Pure hourly billing

Project Finance Status

  • planning: Initial setup phase
  • active: Project is active
  • on_hold: Temporarily paused
  • completed: Project finished
  • cancelled: Project canceled

Phase Status

  • planned: Not started yet
  • active: Currently in progress
  • completed: Phase finished
  • cancelled: Phase canceled

Risk Levels

  • low: Minimal risk
  • medium: Moderate risk requiring monitoring
  • high: High risk requiring attention
  • critical: Critical risk requiring immediate action

Allocation Types

  • project: Budget allocated to entire project
  • phase: Budget allocated to specific phase
  • cost_center: Budget allocated to cost center
  • milestone: Budget allocated to milestone

This documentation provides everything needed for Next.js frontend implementation of the Project Finance Management system.