Development Workflow¶
This guide covers the day-to-day development workflow for Acumen ERP, including coding standards, Git practices, testing, and deployment procedures.
Daily Development Cycle¶
1. Start Your Day¶
# Navigate to project
cd /opt/acumen/project_root
# Pull latest changes
git pull origin main
# Activate virtual environment
source venv/bin/activate
# Install/update dependencies if needed
pip install -r requirements.txt
cd frontend && npm install && cd ..
2. Start Development Servers¶
Open three terminals :
Terminal 1: FastAPI
cd /opt/acumen/project_root
source venv/bin/activate
export ROUTER_MODE=core # Use 'minimal' for faster startup
python run.py
Terminal 2: Django
cd /opt/acumen/project_root/backend/django_app
source ../../venv/bin/activate
python manage.py runserver
Terminal 3: Frontend
cd /opt/acumen/project_root/frontend
npm start
3. Create Feature Branch¶
# Create and switch to feature branch
git checkout -b feature/add-invoice-management
# Or for bug fixes
git checkout -b fix/company-validation-error
4. Make Changes¶
Follow the coding standards and patterns described in this guide.
5. Test Changes¶
# Run tests
pytest
# Check code quality
black backend/
isort backend/
flake8 backend/
6. Commit Changes¶
# Stage changes
git add .
# Commit with descriptive message
git commit -m "feat: add invoice management CRUD operations
- Created Invoice model with SQLAlchemy
- Implemented CRUD operations in crud.py
- Added REST endpoints in routes.py
- Created Pydantic schemas for validation
- Added unit tests for invoice operations
"
7. Push and Create Pull Request¶
# Push to remote
git push origin feature/add-invoice-management
# Create pull request via GitHub/GitLab
# Request code review from team
Git Workflow¶
Branch Naming Conventions¶
| Type | Pattern | Example |
|---|---|---|
| Feature | feature/<description> |
feature/add-customer-portal |
| Bug Fix | fix/<description> |
fix/login-validation |
| Hotfix | hotfix/<description> |
hotfix/security-patch |
| Release | release/<version> |
release/v1.2.0 |
| Refactor | refactor/<description> |
refactor/optimize-queries |
Commit Message Format¶
Use Conventional Commits:
<type>(<scope>): <subject>
<body>
<footer>
Types: - feat - New feature - fix - Bug fix - docs - Documentation changes - style - Code style changes (formatting) - refactor - Code refactoring - test - Adding or updating tests - chore - Maintenance tasks
Examples:
# Feature
git commit -m "feat(finance): add general ledger report generation"
# Bug fix
git commit -m "fix(auth): resolve JWT token expiration issue"
# Documentation
git commit -m "docs(api): update authentication endpoint documentation"
# Refactor
git commit -m "refactor(database): optimize connection pooling"
Pull Request Process¶
- Create PR with descriptive title and description
- Link issues being addressed
- Request review from at least one team member
- Address feedback from code review
- Ensure CI passes (tests, linting)
- Squash and merge into main branch
- Delete branch after merge
Coding Standards¶
Python (Backend)¶
Code Formatting¶
Use Black for consistent formatting:
# Format all Python files
black backend/
# Check without modifying
black --check backend/
Configuration (.pyproject.toml):
[tool.black]
line-length = 88
target-version = ['py39']
include = '\.pyi?$'
Import Sorting¶
Use isort for consistent import ordering:
# Sort imports
isort backend/
# Check only
isort --check-only backend/
Import order: 1. Standard library 2. Third-party packages 3. Local application imports
# Standard library
import os
from datetime import datetime
# Third-party
from fastapi import APIRouter, HTTPException
from sqlalchemy.orm import Session
# Local
from .models import Company
from .schemas import CompanyCreate
from ....shared.database import get_db
Linting¶
Use flake8 for style checking:
# Lint code
flake8 backend/
Configuration (.flake8):
[flake8]
max-line-length = 88
extend-ignore = E203, W503
exclude = .git,__pycache__,venv,migrations
Type Hints¶
Use Python type hints for better code clarity:
from typing import List, Optional
from sqlalchemy.orm import Session
def get_company_list(
db: Session,
skip: int = 0,
limit: int = 100
) -> List[Company]:
"""
Retrieve a list of companies from the database.
Args:
db: Database session
skip: Number of records to skip
limit: Maximum number of records to return
Returns:
List of Company objects
"""
return db.query(Company).offset(skip).limit(limit).all()
Docstrings¶
Use Google-style docstrings:
def create_invoice(db: Session, invoice: InvoiceCreate) -> Invoice:
"""
Create a new invoice in the database.
Args:
db (Session): SQLAlchemy database session
invoice (InvoiceCreate): Invoice data to create
Returns:
Invoice: The created invoice object
Raises:
ValueError: If invoice number already exists
IntegrityError: If required foreign keys are invalid
Example:
>>> invoice = InvoiceCreate(
... invoice_number="INV-001",
... customer_id=123,
... amount=1500.00
... )
>>> new_invoice = create_invoice(db, invoice)
"""
# Implementation
TypeScript (Frontend)¶
Code Style¶
Use Prettier for formatting:
# Format all TypeScript/React files
npm run format
# Or manually
npx prettier --write "src/**/*.{ts,tsx}"
Linting¶
Use ESLint for code quality:
# Lint code
npm run lint
# Auto-fix issues
npm run lint:fix
Component Structure¶
Functional components with hooks:
import React, { useState, useEffect } from 'react';
import { Box, Typography, Button } from '@mui/material';
interface CompanyListProps {
companyId?: number;
onSelect?: (company: Company) => void;
}
export const CompanyList: React.FC<CompanyListProps> = ({
companyId,
onSelect
}) => {
const [companies, setCompanies] = useState<Company[]>([]);
const [loading, setLoading] = useState<boolean>(true);
useEffect(() => {
fetchCompanies();
}, []);
const fetchCompanies = async () => {
try {
setLoading(true);
const response = await api.get('/api/company/company/');
setCompanies(response.data);
} catch (error) {
console.error('Error fetching companies:', error);
} finally {
setLoading(false);
}
};
return (
<Box>
<Typography variant="h6">Companies</Typography>
{/* Component JSX */}
</Box>
);
};
Type Definitions¶
Define interfaces for data structures:
// types/company.ts
export interface Company {
CompanyID: number;
CompanyCD: string;
CompanyName: string;
BaseCuryID: string;
Active: boolean;
CreatedDate?: string;
ModifiedDate?: string;
}
export interface CompanyCreate {
CompanyCD: string;
CompanyName: string;
BaseCuryID: string;
Active?: boolean;
}
export interface CompanyUpdate extends Partial<CompanyCreate> {
CompanyID: number;
}
YAML Configuration¶
Navigation Structure¶
# Consistent indentation (2 spaces)
sidebar:
sections:
- id: "finance"
name: "Finance"
icon: "dollar-sign"
active: true
items:
- id: "general-ledger"
name: "General Ledger"
route: "/finance/general-ledger"
icon: "book"
- id: "invoices"
name: "Invoices"
route: "/finance/invoices"
icon: "file-invoice"
Page Configuration¶
# Clear structure with comments
page:
id: company-list
title: Company Management
description: View and manage companies
toolbar:
breadcrumbs:
- label: Home
route: /
- label: Companies
route: /company/companies
actions:
- label: Add Company
icon: plus
type: primary
action: navigate
route: /company/companies/new
components:
- id: companies-table
type: data-table
config:
# Table configuration
Testing Guidelines¶
Backend Testing (pytest)¶
Test structure:
backend/
└── tests/
├── __init__.py
├── conftest.py # Shared fixtures
├── test_company/
│ ├── test_models.py
│ ├── test_crud.py
│ └── test_routes.py
└── test_finance/
└── ...
Example test:
# tests/test_company/test_crud.py
import pytest
from sqlalchemy.orm import Session
from backend.api.company.Company import crud, schemas
def test_create_company(db: Session):
"""Test creating a new company."""
company_data = schemas.CompanyCreate(
CompanyCD="TEST",
CompanyName="Test Company",
BaseCuryID="USD"
)
company = crud.create_company(db, company_data)
assert company.CompanyID is not None
assert company.CompanyCD == "TEST"
assert company.CompanyName == "Test Company"
def test_get_company_list(db: Session):
"""Test retrieving company list."""
companies = crud.get_company_list(db, skip=0, limit=10)
assert isinstance(companies, list)
assert len(companies) <= 10
Run tests:
# Run all tests
pytest
# Run specific test file
pytest tests/test_company/test_crud.py
# Run with coverage
pytest --cov=backend/
# Verbose output
pytest -v
# Stop on first failure
pytest -x
Frontend Testing (Jest + React Testing Library)¶
Example test:
// components/CompanyList.test.tsx
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { CompanyList } from './CompanyList';
import * as api from '../utils/api';
jest.mock('../utils/api');
describe('CompanyList', () => {
it('renders company list', async () => {
const mockCompanies = [
{ CompanyID: 1, CompanyCD: 'MAIN', CompanyName: 'Main Company' },
{ CompanyID: 2, CompanyCD: 'BRANCH', CompanyName: 'Branch' }
];
(api.get as jest.Mock).mockResolvedValue({ data: mockCompanies });
render(<CompanyList />);
await waitFor(() => {
expect(screen.getByText('Main Company')).toBeInTheDocument();
expect(screen.getByText('Branch')).toBeInTheDocument();
});
});
it('handles company selection', async () => {
const onSelect = jest.fn();
render(<CompanyList onSelect={onSelect} />);
const firstCompany = await screen.findByText('Main Company');
userEvent.click(firstCompany);
expect(onSelect).toHaveBeenCalledWith(
expect.objectContaining({ CompanyID: 1 })
);
});
});
Run tests:
# Run all tests
npm test
# Watch mode
npm test -- --watch
# Coverage
npm test -- --coverage
Database Migrations¶
Creating Migrations (Django)¶
cd backend/django_app
# Create migration after model changes
python manage.py makemigrations
# Apply migrations
python manage.py migrate
# View migration SQL
python manage.py sqlmigrate app_name 0001
# Rollback migration
python manage.py migrate app_name 0001
SQLAlchemy Migrations (Alembic)¶
# Initialize Alembic (first time only)
alembic init alembic
# Create migration
alembic revision --autogenerate -m "add invoice table"
# Apply migrations
alembic upgrade head
# Rollback
alembic downgrade -1
Code Review Checklist¶
For Authors¶
- Code follows style guidelines (Black, isort, flake8)
- All tests pass
- New features have tests
- Documentation updated
- No commented-out code
- No debug print statements
- Environment variables documented
- Database migrations included (if schema changed)
For Reviewers¶
- Code is readable and maintainable
- Naming is clear and consistent
- No security vulnerabilities
- Error handling is appropriate
- Performance considerations addressed
- Follows existing patterns
- Tests are comprehensive
- Documentation is clear
Performance Best Practices¶
Database Queries¶
# ❌ Bad: N+1 query problem
companies = db.query(Company).all()
for company in companies:
org = company.organization # Additional query per company
# ✅ Good: Eager loading
from sqlalchemy.orm import joinedload
companies = db.query(Company).options(
joinedload(Company.organization)
).all()
API Pagination¶
# Always paginate large result sets
@router.get("/")
def read_companies(
skip: int = 0,
limit: int = 100,
db: Session = Depends(get_db)
):
# Limit maximum page size
limit = min(limit, 100)
companies = crud.get_company_list(db, skip=skip, limit=limit)
total = db.query(Company).count()
return {
"results": companies,
"count": total,
"skip": skip,
"limit": limit
}
Frontend Optimization¶
// Use React.memo for expensive components
export const CompanyList = React.memo(({ companies }) => {
// Component implementation
});
// Use useMemo for expensive computations
const sortedCompanies = useMemo(() => {
return companies.sort((a, b) => a.CompanyName.localeCompare(b.CompanyName));
}, [companies]);
// Use useCallback for event handlers
const handleSelect = useCallback((company: Company) => {
onSelect?.(company);
}, [onSelect]);
Debugging¶
Backend Debugging¶
Using pdb:
# Add breakpoint in code
import pdb; pdb.set_trace()
# Or in Python 3.7+
breakpoint()
Logging:
import logging
logger = logging.getLogger(__name__)
def process_invoice(invoice: Invoice):
logger.info(f"Processing invoice {invoice.invoice_number}")
try:
# Process
logger.debug(f"Invoice data: {invoice}")
except Exception as e:
logger.error(f"Error processing invoice: {e}", exc_info=True)
Frontend Debugging¶
React DevTools: - Install browser extension - Inspect component props and state - Profile component renders
Console logging:
console.log('Companies:', companies);
console.error('API Error:', error);
console.warn('Deprecated prop used');
console.table(companies); // Display as table
Next Steps¶
- API Documentation - Explore available APIs
- Adding Entities Guide - Create new features
- YAML Configuration Guide - Configure UI
- Testing Guide - Write comprehensive tests