Adding New Entities¶
This guide walks you through adding a complete new entity to Acumen ERP, from database to user interface.
Overview¶
Adding a new entity involves four main steps:
- Backend : Create API endpoints with FastAPI
- Database : Define models and CRUD operations
- Frontend : Create YAML page configuration
- Integration : Connect frontend to backend
Example: We'll create a Customer entity for the CRM domain.
Prerequisites¶
- Development environment set up
- Database access
- Basic understanding of FastAPI, SQLAlchemy, and YAML
Step 1: Database Table¶
First, ensure your database table exists.
Option A: Existing Table¶
If migrating from legacy system, table already exists in PostgreSQL.
Option B: Create New Table¶
Create migration (Django) or SQL script:
CREATE TABLE "Customer" (
"CustomerID" SERIAL PRIMARY KEY,
"CustomerCD" VARCHAR(30) NOT NULL UNIQUE,
"CustomerName" VARCHAR(255) NOT NULL,
"Email" VARCHAR(255),
"Phone" VARCHAR(50),
"Active" BOOLEAN DEFAULT TRUE,
"CreatedDate" TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
"ModifiedDate" TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_customer_cd ON "Customer"("CustomerCD");
CREATE INDEX idx_customer_name ON "Customer"("CustomerName");
Step 2: Generate API Code¶
Acumen provides an API builder to auto-generate code from database tables.
Manual Code Generation¶
Create the entity directory structure:
cd /opt/acumen/project_root/backend/api/crm
mkdir -p Customer
cd Customer
touch __init__.py models.py schemas.py crud.py routes.py
Create Models (models.py)¶
Define the SQLAlchemy ORM model:
from sqlalchemy import Column, Integer, String, Boolean, DateTime, UniqueConstraint
from sqlalchemy.sql import func
from ....shared.database.base_models import Base
class Customer(Base):
"""Customer entity for CRM"""
__tablename__ = "Customer"
__table_args__ = (
UniqueConstraint('CustomerID', name='Customer_PK'),
{"schema": "public", "extend_existing": True}
)
# Primary Key
CustomerID = Column(Integer, primary_key=True, index=True)
# Business Fields
CustomerCD = Column(String(30), nullable=False, unique=True, index=True)
CustomerName = Column(String(255), nullable=False, index=True)
Email = Column(String(255))
Phone = Column(String(50))
# Status
Active = Column(Boolean, default=True)
# Audit Fields
CreatedDate = Column(DateTime(timezone=True), server_default=func.now())
ModifiedDate = Column(DateTime(timezone=True), onupdate=func.now())
def __repr__(self):
return f"<Customer(CustomerID={self.CustomerID}, CustomerCD='{self.CustomerCD}')>"
Create Schemas (schemas.py)¶
Define Pydantic models for validation:
from pydantic import BaseModel, EmailStr, Field
from typing import Optional
from datetime import datetime
# Base schema with common fields
class CustomerBase(BaseModel):
CustomerCD: str = Field(..., min_length=1, max_length=30, description="Customer Code")
CustomerName: str = Field(..., min_length=1, max_length=255, description="Customer Name")
Email: Optional[EmailStr] = Field(None, description="Email Address")
Phone: Optional[str] = Field(None, max_length=50, description="Phone Number")
Active: bool = Field(True, description="Active Status")
# Schema for creating new customer
class CustomerCreate(CustomerBase):
pass
# Schema for updating customer
class CustomerUpdate(CustomerBase):
CustomerCD: Optional[str] = None
CustomerName: Optional[str] = None
Active: Optional[bool] = None
# Schema for database model (includes ID and dates)
class CustomerInDB(CustomerBase):
CustomerID: int
CreatedDate: Optional[datetime] = None
ModifiedDate: Optional[datetime] = None
class Config:
from_attributes = True # Pydantic v2 (was orm_mode in v1)
# Schema for API responses
class Customer(CustomerInDB):
pass
Create CRUD Operations (crud.py)¶
Implement database operations:
from sqlalchemy.orm import Session
from typing import List, Optional
from . import models, schemas
def get_customer(db: Session, customer_id: int) -> Optional[models.Customer]:
"""Get a single customer by ID"""
return db.query(models.Customer).filter(
models.Customer.CustomerID == customer_id
).first()
def get_customer_by_code(db: Session, customer_cd: str) -> Optional[models.Customer]:
"""Get a customer by code"""
return db.query(models.Customer).filter(
models.Customer.CustomerCD == customer_cd
).first()
def get_customer_list(
db: Session,
skip: int = 0,
limit: int = 100,
active_only: bool = False
) -> List[models.Customer]:
"""Get list of customers with pagination"""
query = db.query(models.Customer)
if active_only:
query = query.filter(models.Customer.Active == True)
return query.offset(skip).limit(limit).all()
def create_customer(db: Session, customer: schemas.CustomerCreate) -> models.Customer:
"""Create a new customer"""
# Check if customer code already exists
existing = get_customer_by_code(db, customer.CustomerCD)
if existing:
raise ValueError(f"Customer with code '{customer.CustomerCD}' already exists")
# Create new customer
db_customer = models.Customer(**customer.model_dump())
db.add(db_customer)
db.commit()
db.refresh(db_customer)
return db_customer
def update_customer(
db: Session,
customer_id: int,
customer: schemas.CustomerUpdate
) -> Optional[models.Customer]:
"""Update an existing customer"""
db_customer = get_customer(db, customer_id)
if db_customer is None:
return None
# Update only fields that were provided
update_data = customer.model_dump(exclude_unset=True)
for key, value in update_data.items():
setattr(db_customer, key, value)
db.commit()
db.refresh(db_customer)
return db_customer
def delete_customer(db: Session, customer_id: int) -> bool:
"""Delete a customer"""
db_customer = get_customer(db, customer_id)
if db_customer is None:
return False
db.delete(db_customer)
db.commit()
return True
def search_customers(
db: Session,
query: str,
skip: int = 0,
limit: int = 100
) -> List[models.Customer]:
"""Search customers by code or name"""
search_pattern = f"%{query}%"
return db.query(models.Customer).filter(
(models.Customer.CustomerCD.ilike(search_pattern)) |
(models.Customer.CustomerName.ilike(search_pattern))
).offset(skip).limit(limit).all()
Create Routes (routes.py)¶
Define FastAPI endpoints:
from fastapi import APIRouter, HTTPException, Depends, Query
from sqlalchemy.orm import Session
from typing import List
from ....shared.database.connection import get_db
from . import crud, schemas
router = APIRouter(prefix="/customer", tags=["Customer"])
@router.get("/", response_model=List[schemas.Customer])
def read_customer_list(
skip: int = Query(0, ge=0, description="Records to skip"),
limit: int = Query(100, ge=1, le=100, description="Max records to return"),
active_only: bool = Query(False, description="Only active customers"),
db: Session = Depends(get_db)
):
"""
Retrieve list of customers.
- **skip**: Number of records to skip (for pagination)
- **limit**: Maximum number of records to return (max 100)
- **active_only**: Filter to only active customers
"""
return crud.get_customer_list(db, skip=skip, limit=limit, active_only=active_only)
@router.get("/search", response_model=List[schemas.Customer])
def search_customers(
q: str = Query(..., min_length=1, description="Search query"),
skip: int = Query(0, ge=0),
limit: int = Query(100, ge=1, le=100),
db: Session = Depends(get_db)
):
"""
Search customers by code or name.
- **q**: Search query (matches code or name)
"""
return crud.search_customers(db, query=q, skip=skip, limit=limit)
@router.get("/{customer_id}", response_model=schemas.Customer)
def read_customer(
customer_id: int,
db: Session = Depends(get_db)
):
"""
Get a specific customer by ID.
- **customer_id**: Customer ID to retrieve
"""
db_customer = crud.get_customer(db, customer_id)
if db_customer is None:
raise HTTPException(status_code=404, detail="Customer not found")
return db_customer
@router.post("/", response_model=schemas.Customer, status_code=201)
def create_customer(
customer: schemas.CustomerCreate,
db: Session = Depends(get_db)
):
"""
Create a new customer.
- **CustomerCD**: Unique customer code
- **CustomerName**: Customer name
- **Email**: Email address (optional)
- **Phone**: Phone number (optional)
- **Active**: Active status (default: true)
"""
try:
return crud.create_customer(db=db, customer=customer)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
@router.put("/{customer_id}", response_model=schemas.Customer)
def update_customer(
customer_id: int,
customer: schemas.CustomerUpdate,
db: Session = Depends(get_db)
):
"""
Update an existing customer.
- **customer_id**: Customer ID to update
"""
db_customer = crud.update_customer(db, customer_id, customer)
if db_customer is None:
raise HTTPException(status_code=404, detail="Customer not found")
return db_customer
@router.delete("/{customer_id}", status_code=200)
def delete_customer(
customer_id: int,
db: Session = Depends(get_db)
):
"""
Delete a customer.
- **customer_id**: Customer ID to delete
"""
success = crud.delete_customer(db, customer_id)
if not success:
raise HTTPException(status_code=404, detail="Customer not found")
return {"status": "success", "message": f"Customer {customer_id} deleted"}
Step 3: Register Routes¶
Add your new router to the domain router:
Edit CRM Domain Router¶
File : backend/api/crm/routes.py
from fastapi import APIRouter
from .Customer.routes import router as Customer_router
# ... other imports
router = APIRouter(prefix="/crm", tags=["CRM"])
# Include Customer router
router.include_router(Customer_router)
# ... include other routers
Include in Main Router¶
Ensure CRM router is included in main API router:
File : backend/api/router_registry.py (or router_registry_core.py)
from .crm.routes import router as crm_router
api_router = APIRouter(prefix="/api")
api_router.include_router(crm_router)
Step 4: Test API Endpoints¶
Restart FastAPI and test your endpoints:
# Restart FastAPI
cd /opt/acumen/project_root
python run.py
Visit Swagger UI: http://localhost:8001/docs
Test endpoints: - GET /api/crm/customer/ - List customers - POST /api/crm/customer/ - Create customer - GET /api/crm/customer/{id} - Get customer - PUT /api/crm/customer/{id} - Update customer - DELETE /api/crm/customer/{id} - Delete customer
Step 5: Create YAML Page Configuration¶
Create page configuration for the UI:
File : frontend/public/navigation/pages/customers.yaml
page:
id: "customer-list"
title: "Customer Management"
description: "View and manage customers"
toolbar:
breadcrumbs:
- label: "Home"
route: "/"
- label: "CRM"
route: "/crm"
- label: "Customers"
route: "/crm/customers"
actions:
- label: "Add Customer"
icon: "plus"
type: "primary"
action: "navigate"
route: "/crm/customers/new"
- label: "Export"
icon: "download"
type: "secondary"
action: "export"
format: "csv"
navigation:
back_button: true
back_route: "/crm"
components:
- id: "customers-table"
type: "data-table"
config:
# Data source
data_source:
endpoint: "/api/crm/customer/"
method: "GET"
params:
skip: 0
limit: 100
# Column definitions
columns:
- key: "CustomerID"
label: "ID"
type: "number"
sortable: true
width: 80
- key: "CustomerCD"
label: "Code"
type: "text"
sortable: true
searchable: true
width: 120
- key: "CustomerName"
label: "Name"
type: "text"
sortable: true
searchable: true
width: 250
- key: "Email"
label: "Email"
type: "custom"
renderer: "email"
width: 200
- key: "Phone"
label: "Phone"
type: "custom"
renderer: "phone"
width: 150
- key: "Active"
label: "Status"
type: "custom"
renderer: "badge"
width: 100
render_config:
true_label: "Active"
true_color: "success"
false_label: "Inactive"
false_color: "error"
# Table features
features:
pagination: true
page_size: 25
page_size_options: [10, 25, 50, 100]
sorting: true
filtering: true
selection: true
export: true
refresh: true
# Row actions
actions:
- label: "Edit"
icon: "edit"
type: "primary"
action: "navigate"
route: "/crm/customers/{{CustomerID}}"
- label: "Delete"
icon: "trash"
type: "danger"
action: "delete"
endpoint: "/api/crm/customer/{{CustomerID}}"
confirm:
title: "Delete Customer?"
message: "Are you sure you want to delete {{CustomerName}}?"
confirm_text: "Delete"
cancel_text: "Cancel"
success_message: "Customer deleted successfully"
refresh_on_success: true
- label: "Deactivate"
icon: "times"
type: "warning"
action: "api_call"
endpoint: "/api/crm/customer/{{CustomerID}}"
method: "PUT"
payload:
Active: false
condition:
field: "Active"
operator: "equals"
value: true
success_message: "Customer deactivated"
refresh_on_success: true
# Filters
filters:
- id: "search"
label: "Search"
type: "search"
placeholder: "Search customers..."
fields: ["CustomerCD", "CustomerName"]
- id: "active"
label: "Status"
type: "select"
options:
- value: true
label: "Active"
- value: false
label: "Inactive"
Create Form Page¶
File : frontend/public/navigation/pages/customer-form.yaml
page:
id: "customer-form"
title: "{{mode}} Customer"
description: "{{mode}} customer information"
toolbar:
breadcrumbs:
- label: "Home"
route: "/"
- label: "CRM"
route: "/crm"
- label: "Customers"
route: "/crm/customers"
- label: "{{mode}}"
components:
- id: "customer-form"
type: "form"
config:
# Form submission
submit:
endpoint: "/api/crm/customer/"
method: "{{isEdit ? 'PUT' : 'POST'}}"
success_message: "Customer {{isEdit ? 'updated' : 'created'}} successfully"
success_route: "/crm/customers"
error_message: "Failed to {{isEdit ? 'update' : 'create'}} customer"
# Form layout
layout: "grid"
columns: 2
# Form fields
fields:
- id: "CustomerCD"
label: "Customer Code"
type: "text"
required: true
placeholder: "e.g., CUST001"
help_text: "Unique identifier for the customer"
validation:
pattern: "^[A-Z0-9-]+$"
message: "Only uppercase letters, numbers, and hyphens allowed"
- id: "CustomerName"
label: "Customer Name"
type: "text"
required: true
max_length: 255
placeholder: "e.g., Acme Corporation"
- id: "Email"
label: "Email Address"
type: "email"
placeholder: "customer@example.com"
- id: "Phone"
label: "Phone Number"
type: "tel"
placeholder: "+1 (555) 123-4567"
- id: "Active"
label: "Active"
type: "checkbox"
default_value: true
grid_span: 2
# Form actions
actions:
- label: "Save"
type: "submit"
variant: "primary"
- label: "Cancel"
type: "button"
variant: "secondary"
action: "navigate"
route: "/crm/customers"
Step 6: Add to Navigation¶
Update the main navigation to include your new entity:
File : frontend/public/navigation/erp-navigation.yaml
sidebar:
sections:
# ... existing sections
- id: "crm"
name: "CRM"
icon: "users"
items:
- id: "customers"
name: "Customers"
route: "/crm/customers"
icon: "user"
page_config: "/navigation/pages/customers.yaml"
- id: "customer-new"
name: "New Customer"
route: "/crm/customers/new"
hidden: true # Don't show in menu
page_config: "/navigation/pages/customer-form.yaml"
- id: "customer-edit"
name: "Edit Customer"
route: "/crm/customers/:id"
hidden: true
page_config: "/navigation/pages/customer-form.yaml"
Step 7: Test the UI¶
-
Restart the frontend:
cd frontend npm start -
Navigate to http://localhost:3000
-
Login and access "CRM" → "Customers"
-
Test:
-
View customer list
- Create new customer
- Edit customer
- Delete customer
Next Steps¶
Add More Features¶
1. Add Relationships¶
# In models.py
from sqlalchemy.orm import relationship
class Customer(Base):
# ... existing fields
# Relationships
addresses = relationship("Address", back_populates="customer")
invoices = relationship("Invoice", back_populates="customer")
2. Add Custom Endpoints¶
# In routes.py
@router.get("/{customer_id}/invoices")
def get_customer_invoices(customer_id: int, db: Session = Depends(get_db)):
"""Get all invoices for a customer"""
customer = crud.get_customer(db, customer_id)
if not customer:
raise HTTPException(status_code=404, detail="Customer not found")
return customer.invoices
3. Add Business Logic¶
# In crud.py
def activate_customer(db: Session, customer_id: int):
"""Activate a customer and send welcome email"""
customer = get_customer(db, customer_id)
if not customer:
return None
customer.Active = True
db.commit()
# Send welcome email
send_welcome_email(customer.Email)
return customer
Troubleshooting¶
API Not Appearing in Swagger¶
Problem: New endpoints don't show in http://localhost:8001/docs
Solution: 1. Check router is included in domain router 2. Check domain router is included in main router 3. Restart FastAPI server 4. Clear browser cache
Database Connection Errors¶
Problem: sqlalchemy.exc.OperationalError
Solution: 1. Verify table exists in database 2. Check DATABASE_URL in .env 3. Verify table name matches model __tablename__
YAML Page Not Loading¶
Problem: 404 or blank page in frontend
Solution: 1. Check YAML file exists in frontend/public/navigation/pages/ 2. Verify YAML syntax is valid 3. Check page_config path in navigation 4. Restart frontend server
Summary¶
You've successfully: - ✅ Created database models with SQLAlchemy - ✅ Implemented CRUD operations - ✅ Built REST API endpoints with FastAPI - ✅ Created YAML page configurations - ✅ Added navigation entries - ✅ Connected frontend to backend
Related Guides¶
- YAML Configuration Guide - Master YAML syntax
- API Reference - Explore all endpoints
- Testing Guide - Write tests for your entity
- Development Workflow - Daily practices