InfraNotes Module · v0
Welcome
Select a document from the sidebar to read it.
InfraNotes Financial Analytics Module - Developer Guide
Important
InfraNotes has fully migrated away from NATS in favor of Kafka at the platform level. This module now integrates with InfraNotes via HTTP APIs secured with shared JWT authentication. Any NATS-specific diagrams or references in this guide are historical and should not be used for new integrations; refer to the codebase (HTTP + JWT middleware) for the current behavior.
Overview
This guide is intended for developers who will be maintaining, extending, or integrating with the InfraNotes Financial Analytics Module. It provides technical details about the architecture, key components, and development workflows.
Architecture
The Financial Analytics Module is designed as a decoupled service that integrates with the core InfraNotes platform. It follows a modular structure with clearly defined boundaries between components.
High-Level Architecture
┌───────────────────────────────────────┐ ┌───────────────────────────────────────┐
│ │ │ │
│ InfraNotes Core │ │ Financial Analytics Module │
│ │ │ │
│ ┌─────────────┐ ┌──────────────┐ │ │ ┌─────────────┐ ┌──────────────┐ │
│ │ │ │ │ │ │ │ │ │ │ │
│ │ Auth & │ │ Expense │◄─┼─────┼─►│ Document │ │ Analytics │ │
│ │ Security │◄───┤ Management │ │ │ │ Processing │ │ Engine │ │
│ │ │ │ │ │ │ │ │ │ │ │
│ └─────────────┘ └──────────────┘ │ │ └─────────────┘ └──────────────┘ │
│ │ │ │
│ ┌─────────────┐ ┌──────────────┐ │ │ ┌─────────────┐ ┌──────────────┐ │
│ │ │ │ │ │ │ │ │ │ │ │
│ │ Project │ │ Budget/ │ │ │ │ Transaction │ │ Financial │ │
│ │ Management │ │ Invoice │ │ │ │ Categorizer │ │ Planner │ │
│ │ │ │ │ │ │ │ │ │ │ │
│ └─────────────┘ └──────────────┘ │ │ └─────────────┘ └──────────────┘ │
│ │ │ │
└───────────────────┬─────────────────┬─┘ └───────────────────┬─────────────────┬─┘
│ │ │ │
│ │ │ │
│ │ │ │
▼ ▼ ▼ ▼
┌─────────────────┐ ┌─────────────┐ ┌─────────────────┐ ┌─────────────┐
│ │ │ │ │ │ │ │
│ PostgreSQL │ │ NATS │◄─────────│ PostgreSQL │ │ Document │
│ (Core DB) │ │ Messaging │ │ (Analytics DB) │ │ Storage │
│ │ │ │ │ │ │ │
└─────────────────┘ └─────────────┘ └─────────────────┘ └─────────────┘
Core Design Principles
- Modularity: Each component is designed with clear boundaries and interfaces.
- Single Responsibility: Each component focuses on a specific domain concern.
- Domain-Driven Design: Models and services are organized around business capabilities.
- Clean Architecture: Separation of concerns with domain models, repositories, services, and handlers.
- Event-Driven Integration: Kafka-based messaging at the InfraNotes platform level (NATS has been deprecated).
- Performance Focus: Optimized for handling large transaction datasets.
Project Structure
The Financial Analytics Module follows a standard Go project structure with:
infranotes-module/
├── cmd/ # Application entry points
│ └── server/ # Main server application
├── internal/ # Private application code
│ ├── analytics/ # Financial analytics components
│ │ ├── analytics/ # Core analytics engine
│ │ ├── budget/ # Budget tracking
│ │ ├── cashflow/ # Cash flow management
│ │ ├── categorization/ # Transaction categorization
│ │ ├── document/ # Document processing
│ │ ├── goals/ # Financial goal tracking
│ │ └── planning/ # Financial planning
│ └── common/ # Shared utilities and infrastructure
├── migrations/ # Database migration files
├── scripts/ # Utility scripts
├── docs/ # Documentation
├── statements/ # Test data (sample financial documents)
└── ...
Core Components
Document Processing
The Document Processing component is responsible for handling uploaded financial documents, extracting transactions, and storing them for analysis.
Key Files:
internal/analytics/document/models/*.go: Domain modelsinternal/analytics/document/services/parser/*.go: Document parsing implementationsinternal/analytics/document/repositories/*.go: Repository interfacesinternal/analytics/document/repositories/postgres/*.go: PostgreSQL implementations
Extending Parser Support:
To add support for a new document format:
- Implement a new parser in
internal/analytics/document/services/parser/ - Update the parser factory in
internal/analytics/document/services/parser/factory.go - Add test cases with sample documents
Example:
// NewXYZParser creates a parser for XYZ format
func NewXYZParser() Parser {
return &xyzParser{}
}
type xyzParser struct {}
func (p *xyzParser) Parse(ctx context.Context, content []byte, options ParserOptions) ([]models.Transaction, error) {
// Implementation here
}
Transaction Categorization
The Transaction Categorization component automatically categorizes transactions based on rules and patterns.
Key Files:
internal/analytics/document/services/categorization/*.go: Categorization servicesinternal/analytics/document/repositories/postgres/category_*.go: Category repositories
Adding New Categorization Rules:
To add a new pattern matching strategy:
- Update the rule matcher in
internal/analytics/document/services/categorization/rule_matcher.go - Add tests for the new strategy
Analytics Engine
The Analytics Engine analyzes transaction data to provide insights and trends.
Key Files:
internal/analytics/analytics/services/*.go: Analytics servicesinternal/analytics/analytics/repositories/*.go: Analytics repositoriesinternal/analytics/analytics/models/*.go: Analytics models
Extending Analytics:
To add a new type of analysis:
- Create a new service in
internal/analytics/analytics/services/ - Define any necessary models in
internal/analytics/analytics/models/ - Expose endpoints in a handler
Financial Planning
The Financial Planning component manages planned expenses and financial projections.
Key Files:
internal/analytics/planning/*.go: Planning services and modelsinternal/analytics/planning/repositories/*.go: Planning repositories
Budget Tracking
The Budget Tracking component manages budgets and tracks spending against them.
Key Files:
internal/analytics/planning/budget/*.go: Budget services and models
Goal Tracking
The Goal Tracking component manages financial goals and progress tracking.
Key Files:
internal/analytics/goals/*.go: Goal services and modelsinternal/analytics/goals/ui/*.go: Goal visualization
Integration with InfraNotes Core
Authentication Integration
The Financial Analytics Module uses the same authentication system as InfraNotes core:
- Every request to the module includes a JWT token in the Authorization header
- The authentication middleware validates the token
- User ID and permissions are extracted from the token
- All repository methods include userID parameters for data isolation
Event Communication
Events are used for cross-service communication:
- Core events are published to NATS
- The module subscribes to relevant events
- The module publishes its own events
Key Events:
- From Core:
expense.created,expense.updated,expense.deleted,user.updated,category.updated - From Analytics:
insight.generated,payment.reminder,pattern.detected,document.processed
Development Workflow
Setting Up a Development Environment
- Clone the repository
- Run
make setupto install dependencies - Run
make devto start the development server and PostgreSQL database
Running Tests
make test: Run all testsmake test-unit: Run unit tests onlymake test-integration: Run integration tests only
Running Migrations
make migrate-up: Apply all pending migrationsmake migrate-down: Roll back the last migrationmake migrate-new name=<migration-name>: Create a new migration
Adding a New Feature
- Define models in the appropriate domain directory
- Create repository interfaces
- Implement PostgreSQL repositories
- Create service implementations
- Add handler endpoints
- Write unit tests
- Add integration tests
- Document the feature
Performance Optimization
Query Optimization
For handling large transaction datasets, we've implemented:
- Efficient batch processing: Using PostgreSQL's COPY command for bulk inserts
- Cursor-based pagination: More efficient than offset-based for large datasets
- Context timeouts: Prevent long-running queries
- Optimized query builder: Builds efficient SQL queries with proper conditions
- Aggregation queries: Use database-level aggregation for analytics
Caching Strategy
Redis caching is implemented for:
- Frequently accessed aggregated data
- Projection calculations
- Category rule sets
- Visualization data
Common Development Tasks
Adding a New API Endpoint
- Define the handler function in the appropriate handler
- Register the endpoint in the router
- Update OpenAPI documentation
Example:
// Handler
func (h *AnalyticsHandler) GetTransactionSummary(c echo.Context) error {
// Implementation
}
// Router registration
func registerAnalyticsRoutes(g *echo.Group, h *AnalyticsHandler) {
g.GET("/summary", h.GetTransactionSummary)
}
Adding a New Repository Method
- Define the method in the repository interface
- Implement the method in the PostgreSQL repository
- Add unit tests
Example:
// Interface
type TransactionRepository interface {
// Existing methods...
// New method
GetTransactionSummaryByMonth(ctx context.Context, userID uuid.UUID, year int) ([]models.MonthSummary, error)
}
// Implementation
func (r *TransactionRepository) GetTransactionSummaryByMonth(ctx context.Context, userID uuid.UUID, year int) ([]models.MonthSummary, error) {
// Implementation
}
Adding a New Database Table
- Create a new migration file with
make migrate-new name=add_table_name - Update the migration files with the schema
- Define the model struct
- Create repository interfaces and implementations
- Run the migration with
make migrate-up
Troubleshooting
Common Issues
-
Performance problems with large datasets:
- Check that indexes are properly defined
- Use EXPLAIN ANALYZE to identify bottlenecks
- Consider adding caching for expensive calculations
-
Document processing failures:
- Ensure document format is supported
- Check error logs for specific parsing failures
- Test with sample documents
-
Integration issues with InfraNotes Core:
- Verify NATS connection
- Check event subscription
- Validate JWT token configuration
Extending the System
Adding New Analytics Insights
To add a new type of analytical insight:
- Define the insight model in
internal/analytics/analytics/models/ - Create a service that generates the insight
- Add event publication for significant insights
- Add repository methods for persistence
- Create API endpoints to retrieve insights
Adding New Visualization Types
To add a new visualization:
- Define the chart model in the appropriate UI package
- Create generator functions for chart data
- Add new endpoints or enhance existing ones to include the visualization
Integrating with New External Systems
To add integration with an external system:
- Create a client package for the external API
- Define integration services
- Add configuration for the integration
- Implement event handlers for synchronization
Best Practices
- Domain Models: Keep models focused on domain concerns
- Transactions: Use database transactions for operations that touch multiple tables
- Context: Always pass context to repository methods for cancellation and timeout
- User ID: Always filter data by user ID for security
- Error Handling: Return meaningful errors that can be properly handled
- Logging: Use structured logging with appropriate levels
- Testing: Write unit tests for business logic and integration tests for repositories
- Documentation: Keep API documentation up to date
- Events: Use events for cross-service communication
- Performance: Consider the performance impact of changes, especially for large datasets
Contribution Guidelines
- Follow the Go style guide
- Write unit tests for all new code
- Update documentation for new features
- Run linters before submitting changes
- Submit detailed pull requests with proper descriptions
- Keep backward compatibility where possible