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 successfuldata(object/array): The response payloadmessage(string): Human-readable success messageerror(string): Error message if success is falserequest_id(string): Unique identifier for request tracingdetails(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 projectbilling_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 IDbilling_frequency(string, optional): Billing frequency (defaults to "monthly")phases(array, optional): Array of project phases to createcost_centers(array, optional): Array of cost centers to create
Success Response (201):
- Returns complete
ProjectFinanceobject 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
ProjectFinanceobject - 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
ProjectFinanceobject 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
ProjectFinanceobject 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 informationfinance: Project finance detailshealth: Financial health metrics and scoringphases: Array of project phases with financial datacost_centers: Array of cost centers with budget allocationsmilestones: Array of milestones with billing informationsummary: Dashboard summary with key metricsalerts: Array of financial alerts requiring attentionlast_updated: Timestamp of last data refresh
Dashboard Summary includes:
total_budget: Total allocated budgetspent_to_date: Amount spent so farbudget_remaining: Remaining budgetcompleted_phases: Number of completed phasestotal_phases: Total number of phasescompleted_milestones: Number of completed milestonestotal_milestones: Total number of milestonesproject_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 IDname(string, required): Phase namedescription(string, optional): Phase descriptionphase_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 stringplanned_end_date(string, required): ISO date string
Success Response (201):
- Returns created
ProjectPhaseobject 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
ProjectPhaseobjects - 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
ProjectPhaseobject 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 IDproject_phase_id(number, optional): Associated phase IDname(string, required): Milestone namedescription(string, optional): Milestone descriptionplanned_date(string, required): ISO date string for target completionbillable_amount(number, required): Amount to bill upon completion (≥0)completion_criteria(string, optional): Criteria for completion
Success Response (201):
- Returns created
ProjectMilestoneobject - 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
ProjectMilestoneobject - Status changed to "completed"
completed_datepopulated- 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 usedprofit_margin: Current profit margincash_flow: Current cash flow statuscash_flow_projection: Projected cash flowbudget_variance: Variance from planned budgetbudget_burn_rate: Rate of budget consumptionprojected_budget_overrun: Estimated budget overrunroi: Return on investment calculationoutstanding_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
ProjectFinancialHealthobject - All metrics recalculated based on current data
- Updates
calculated_attimestamp
🏢 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 teamstatus(string): Filter by project statusbilling_model(string): Filter by billing modelclient_id(number): Filter by clientmanager_id(number): Filter by project managerstart_date(string): ISO date for date rangeend_date(string): ISO date for date rangecurrency(string): Filter by currencymin_budget(number): Minimum budget filtermax_budget(number): Maximum budget filter
Success Response (200):
Returns PortfolioFinancialSummary object containing:
total_projects: Total number of projectsactive_projects: Number of active projectscompleted_projects: Number of completed projectstotal_estimated_budget: Sum of all estimated budgetstotal_actual_costs: Sum of all actual coststotal_revenue: Sum of all revenueoverall_profit_margin: Portfolio-wide profit marginaverage_health_score: Average health across projectshigh_risk_projects: Count of high-risk projectsprojects_by_status: Breakdown by project statusprojects_by_risk: Breakdown by risk levelrevenue_by_month: Monthly revenue distributiontop_performing_projects: Best performing projectsunderperforming_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 IDbudget_id(number, required): Source budget IDallocated_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 IDproject_id: Target projectbudget_id: Source budgetallocated_amount: Allocated amountused_amount: Amount used (initially 0)remaining_amount: Available amountallocation_type: Type of allocationallocated_by: User who created allocationcreated_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
ProjectBudgetAllocationobjects - 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 identifierproject_name: Project nametotal_allocated_budget: Total budget allocated to projecttotal_used_budget: Total budget usedtotal_remaining_budget: Total budget remainingbudget_utilization_rate: Percentage of budget usedbudget_allocations: Array of all allocationsis_over_budget: Whether project is over budgetbudget_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 amountnotes(string, optional): Updated notesallocation_type(string, optional): Updated allocation type
Success Response (200):
- Returns updated
ProjectBudgetAllocationobject - Recalculates remaining amounts
- Updates
updated_attimestamp
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 identifierproject_name: Project nameproject_finance_id: Associated project finance IDbudget_id: Primary budget IDbudget_name: Primary budget nameallocated_amount: Total allocated amountused_amount: Total used amountremaining_amount: Total remaining amountcurrency: Currency codeusage_percentage: Percentage of budget usedallocation_date: When allocation was createdallocated_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 identifierbudget_name: Budget namebudget_total: Total budget amountbudget_used_total: Total amount used across all projectstotal_allocated_to_projects: Total allocated to projectstotal_used_by_projects: Total used by projectsprojects_count: Number of projects using this budgetproject_usage_percentage: Percentage of budget used by projects
📊 Financial Analytics & Forecasting
21. Get Expense Trends
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 periodtotal_expenses: Total expenses in periodaverage_daily_expense: Average daily spendingtrend_direction: Overall trend ("increasing", "decreasing", "stable")growth_rate: Percentage change over periodcategory_trends: Breakdown by expense categorymonthly_breakdown: Month-by-month analysissignificant_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 categoryamount: Expense amountdate: Date of expenseseverity: Anomaly severity score (0-1)description: Human-readable explanationz_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 periodtotal_expense: Total forecasted expensestotal_income: Total forecasted incomenet_amount: Net forecasted amountmonthly_forecasts: Month-by-month expense forecastscategory_forecasts: Forecasts by expense categoryconfidence_level: Forecast confidence (0-1)recommendations: Array of budget recommendations
Budget Recommendation includes:
category: Expense categorycurrent_avg: Current average spendingrecommended: Recommended spending levelsavings: Potential savings amountreason: 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 predictionstimeframe: Prediction granularitystart_date: Forecast start dateend_date: Forecast end datetotal_expected_in: Total expected inflowtotal_expected_out: Total expected outflownet_forecast: Net cash flow forecastaverage_confidence: Average prediction confidencesignificant_events: Notable events affecting cash flowlast_model_updated: When prediction model was last updatedrecommended_actions: Suggested actions based on forecast
Cash Flow Prediction includes:
date: Prediction dateexpected_inflow: Expected money coming inexpected_outflow: Expected money going outnet_cash_flow: Net cash flow for the dateconfidence: Prediction confidence (0-1)is_based_on_data: Whether prediction uses actual datafactors: 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 existslast_trained: When model was last traineddata_points: Number of data points used in trainingaccuracy: Model accuracy percentagenext_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 datacash_flow_stability_score: Stability score (0-1)seasonal_patterns_detected: Whether seasonal patterns existseasonal_peak_months: Months with highest cash flowseasonal_low_months: Months with lowest cash flowyear_over_year_growth_rate: Growth rate percentageprobability_negative_cashflow: Risk of negative cash flow (0-1)recommended_safety_buffer: Recommended cash reserverisk_factors: Array of identified risksopportunities: 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 IDstart_date(string): Start date in YYYY-MM-DD formatend_date(string): End date in YYYY-MM-DD formatperiod(string): Preset period ("month", "quarter", "year", "ytd")
Success Response (200):
Returns PaymentAnalytics object containing:
time_range: Analysis periodtotal_invoices: Total number of invoicestotal_amount: Total invoice amountpaid_amount: Total amount paidoutstanding_amount: Total outstanding amountaverage_days_to_payment: Average payment timecollection_rate: Payment collection rate percentagecash_flow_forecast: Future cash flow projections
Error Responses:
- 400: Invalid date format or parameters
- 401: Authentication required
29. Get Payment Trends
Endpoint: GET /api/analytics/payments/trends
Purpose: Analyze trends in payment behavior over time
Query Parameters (all optional):
team_id(number): Filter by team IDstart_date(string): Start date in YYYY-MM-DD formatend_date(string): End date in YYYY-MM-DD format
Success Response (200):
Returns PaymentTrend object containing:
time_range: Analysis periodmonthly_trends: Payment amounts by monthquarterly_trends: Payment amounts by quarterpayment_method_trends: Trends by payment methodtrend_direction: Overall trend directiongrowth_rate: Payment growth rateseasonal_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 amountaging_buckets: Breakdown by age rangesoverdue_invoices: List of overdue invoicesaverage_age: Average age of unpaid invoicescollection_recommendations: Suggested collection actions
Aging Buckets include:
0-30 days: Current invoices31-60 days: Slightly overdue61-90 days: Overdue90+ 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 typepriority: Priority level ("high", "medium", "low")description: Recommendation descriptionexpected_impact: Expected financial impactimplementation_effort: Required effort levelaction_items: Specific steps to implement
Error Responses:
- 401: Authentication required
🚨 Error Handling
Common Error Codes
VALIDATION_ERROR: Request validation failedNOT_FOUND: Resource not found or access deniedUNAUTHORIZED: Authentication required or invalidCONFLICT: Resource already existsINTERNAL_ERROR: Server errorTIMEOUT: Request timeoutCONTEXT_CANCELED: Request was canceled
HTTP Status Codes
200: Success201: Created successfully400: Bad request (validation error)401: Unauthorized403: Forbidden404: Not found409: Conflict500: Internal server error504: 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 costtime_and_material: Hourly/daily ratesmilestone: Payment based on milestonesretainer: Ongoing monthly paymentshourly: Pure hourly billing
Project Finance Status
planning: Initial setup phaseactive: Project is activeon_hold: Temporarily pausedcompleted: Project finishedcancelled: Project canceled
Phase Status
planned: Not started yetactive: Currently in progresscompleted: Phase finishedcancelled: Phase canceled
Risk Levels
low: Minimal riskmedium: Moderate risk requiring monitoringhigh: High risk requiring attentioncritical: Critical risk requiring immediate action
Allocation Types
project: Budget allocated to entire projectphase: Budget allocated to specific phasecost_center: Budget allocated to cost centermilestone: Budget allocated to milestone
This documentation provides everything needed for Next.js frontend implementation of the Project Finance Management system.