Add scope-aware subscriptions using existing registrations

This commit is contained in:
A R R R Associates
2026-08-05 19:36:55 +05:30
parent 9b307ebcdd
commit 28277590cc
13 changed files with 1135 additions and 643 deletions
+47
View File
@@ -203,3 +203,50 @@ class ClientEngagementLetter(CommonBase):
created_at_utc: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), nullable=False)
updated_at_utc: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc), nullable=False)
class ClientBusinessUnit(CommonBase):
__tablename__ = "client_business_units"
__table_args__ = (
UniqueConstraint("tenant_id", "client_id", "business_code", name="uq_cbu_tenant_client_code"),
)
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
tenant_id: Mapped[int] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False, index=True)
client_id: Mapped[int] = mapped_column(ForeignKey("clients.id", ondelete="CASCADE"), nullable=False, index=True)
business_code: Mapped[str] = mapped_column(String(50), nullable=False, index=True)
business_name: Mapped[str] = mapped_column(String(200), nullable=False, index=True)
trade_name: Mapped[str | None] = mapped_column(String(200), nullable=True)
nature_of_business: Mapped[str | None] = mapped_column(String(200), nullable=True)
is_primary: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, index=True)
is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True, index=True)
created_by_user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), nullable=True)
updated_by_user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), nullable=True)
created_at_utc: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), nullable=False)
updated_at_utc: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc), nullable=False)
class ClientBranch(CommonBase):
__tablename__ = "client_branches"
__table_args__ = (
UniqueConstraint("tenant_id", "business_unit_id", "branch_code", name="uq_cbranch_tenant_business_code"),
)
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
tenant_id: Mapped[int] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False, index=True)
client_id: Mapped[int] = mapped_column(ForeignKey("clients.id", ondelete="CASCADE"), nullable=False, index=True)
business_unit_id: Mapped[int] = mapped_column(ForeignKey("client_business_units.id", ondelete="CASCADE"), nullable=False, index=True)
branch_code: Mapped[str] = mapped_column(String(50), nullable=False, index=True)
branch_name: Mapped[str] = mapped_column(String(200), nullable=False, index=True)
branch_type: Mapped[str] = mapped_column(String(40), nullable=False, default="branch", index=True)
address_line_1: Mapped[str | None] = mapped_column(String(255), nullable=True)
address_line_2: Mapped[str | None] = mapped_column(String(255), nullable=True)
city: Mapped[str | None] = mapped_column(String(100), nullable=True)
state: Mapped[str | None] = mapped_column(String(100), nullable=True)
pincode: Mapped[str | None] = mapped_column(String(20), nullable=True)
is_primary: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, index=True)
is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True, index=True)
created_by_user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), nullable=True)
updated_by_user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), nullable=True)
created_at_utc: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), nullable=False)
updated_at_utc: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc), nullable=False)
+202
View File
@@ -0,0 +1,202 @@
from __future__ import annotations
from fastapi import APIRouter, Form, Request
from fastapi.responses import RedirectResponse
from sqlalchemy import select
from app.core.db.common import CommonSessionLocal
from app.core.security.csrf import get_or_create_csrf_token, validate_csrf
from app.core.security.session_auth import get_current_user
from app.core.templating import templates
from app.modules.clients.models import Client, ClientBusinessUnit, ClientBranch
from app.modules.registrations.models import ClientRegistration, RegistrationType
from app.modules.core.rbac.deps import get_user_permissions, get_user_roles
from app.modules.core.rbac.permission_guard import require_permission
router = APIRouter(prefix="/clients", tags=["client-business-structure"])
def _tenant_id(request, user):
return int(request.session.get("active_tenant_id") or request.session.get("tenant_id") or user.tenant_id)
def _load_client(db, tenant_id: int, client_id: int):
return db.execute(select(Client).where(Client.id == client_id, Client.tenant_id == tenant_id)).scalar_one_or_none()
def _context(request, db, user, **extra):
data = {
"request": request, "current_user": user,
"current_user_roles": get_user_roles(db, user.id),
"current_user_permissions": get_user_permissions(db, user.id),
"csrf_token": get_or_create_csrf_token(request),
}
data.update(extra)
return data
@router.get("/{client_id}/business-structure")
def business_structure_page(request: Request, client_id: int):
db = CommonSessionLocal()
try:
user = get_current_user(request, db=db)
if not user:
return RedirectResponse("/login", 303)
require_permission(db, user, "clients.view")
client = _load_client(db, _tenant_id(request, user), client_id)
if not client:
return RedirectResponse("/clients", 303)
businesses = db.execute(select(ClientBusinessUnit).where(
ClientBusinessUnit.client_id == client.id
).order_by(ClientBusinessUnit.is_active.desc(), ClientBusinessUnit.is_primary.desc(), ClientBusinessUnit.business_name)).scalars().all()
branches = db.execute(select(ClientBranch).where(
ClientBranch.client_id == client.id
).order_by(ClientBranch.is_active.desc(), ClientBranch.is_primary.desc(), ClientBranch.branch_name)).scalars().all()
registration_rows = db.execute(
select(ClientRegistration, RegistrationType).join(
RegistrationType, RegistrationType.id == ClientRegistration.registration_type_id
).where(ClientRegistration.client_id == client.id).order_by(
ClientRegistration.status, RegistrationType.code, ClientRegistration.registration_number
)
).all()
registrations = [row[0] for row in registration_rows]
registration_type_codes = {row[0].id: row[1].code for row in registration_rows}
registration_types = db.execute(
select(RegistrationType).where(RegistrationType.is_active.is_(True)).order_by(
RegistrationType.sort_order, RegistrationType.name
)
).scalars().all()
return templates.TemplateResponse(
"modules/clients/templates/clients/business_structure.html",
_context(request, db, user, title="Client Business Structure", client=client,
businesses=businesses, branches=branches, registrations=registrations,
registration_type_codes=registration_type_codes, registration_types=registration_types,
can_edit="clients.edit" in set(get_user_permissions(db, user.id))),
)
finally:
db.close()
@router.post("/{client_id}/business-units")
def add_business_unit(request: Request, client_id: int, business_code: str = Form(...),
business_name: str = Form(...), trade_name: str = Form(""),
nature_of_business: str = Form(""), is_primary: str | None = Form(None),
csrf_token: str = Form(...)):
validate_csrf(request, csrf_token)
db = CommonSessionLocal()
try:
user = get_current_user(request, db=db); require_permission(db, user, "clients.edit")
tenant_id = _tenant_id(request, user); client = _load_client(db, tenant_id, client_id)
if not client: return RedirectResponse("/clients", 303)
if is_primary:
db.query(ClientBusinessUnit).filter_by(client_id=client.id).update({"is_primary": False})
db.add(ClientBusinessUnit(
tenant_id=tenant_id, client_id=client.id, business_code=business_code.strip().upper(),
business_name=business_name.strip(), trade_name=trade_name.strip() or None,
nature_of_business=nature_of_business.strip() or None, is_primary=bool(is_primary),
is_active=True, created_by_user_id=user.id, updated_by_user_id=user.id,
))
db.commit()
return RedirectResponse(f"/clients/{client_id}/business-structure", 303)
finally:
db.close()
@router.post("/{client_id}/branches")
def add_client_branch(request: Request, client_id: int, business_unit_id: int = Form(...),
branch_code: str = Form(...), branch_name: str = Form(...),
branch_type: str = Form("branch"), city: str = Form(""),
state: str = Form(""), pincode: str = Form(""),
is_primary: str | None = Form(None), csrf_token: str = Form(...)):
validate_csrf(request, csrf_token)
db = CommonSessionLocal()
try:
user = get_current_user(request, db=db); require_permission(db, user, "clients.edit")
tenant_id = _tenant_id(request, user); client = _load_client(db, tenant_id, client_id)
business = db.get(ClientBusinessUnit, business_unit_id)
if not client or not business or business.client_id != client.id or business.tenant_id != tenant_id:
return RedirectResponse("/clients", 303)
if is_primary:
db.query(ClientBranch).filter_by(business_unit_id=business.id).update({"is_primary": False})
db.add(ClientBranch(
tenant_id=tenant_id, client_id=client.id, business_unit_id=business.id,
branch_code=branch_code.strip().upper(), branch_name=branch_name.strip(),
branch_type=branch_type.strip() or "branch", city=city.strip() or None,
state=state.strip() or None, pincode=pincode.strip() or None,
is_primary=bool(is_primary), is_active=True,
created_by_user_id=user.id, updated_by_user_id=user.id,
))
db.commit()
return RedirectResponse(f"/clients/{client_id}/business-structure", 303)
finally:
db.close()
@router.post("/{client_id}/registrations")
def add_registration(request: Request, client_id: int, business_unit_id: str = Form(""),
client_branch_id: str = Form(""), registration_type_id: int = Form(...),
registration_number: str = Form(...), legal_name: str = Form(""),
trade_name: str = Form(""), state: str = Form(""),
csrf_token: str = Form(...)):
validate_csrf(request, csrf_token)
db = CommonSessionLocal()
try:
user = get_current_user(request, db=db); require_permission(db, user, "clients.edit")
tenant_id = _tenant_id(request, user); client = _load_client(db, tenant_id, client_id)
if not client: return RedirectResponse("/clients", 303)
bu_id = int(business_unit_id) if business_unit_id else None
br_id = int(client_branch_id) if client_branch_id else None
if bu_id:
business = db.get(ClientBusinessUnit, bu_id)
if not business or business.client_id != client.id: return RedirectResponse(f"/clients/{client_id}/business-structure", 303)
if br_id:
branch = db.get(ClientBranch, br_id)
if not branch or branch.client_id != client.id: return RedirectResponse(f"/clients/{client_id}/business-structure", 303)
bu_id = branch.business_unit_id
registration_type = db.get(RegistrationType, registration_type_id)
if not registration_type or not registration_type.is_active:
return RedirectResponse(f"/clients/{client_id}/business-structure", 303)
db.add(ClientRegistration(
tenant_id=tenant_id,
branch_id=getattr(client, "branch_id", None),
client_id=client.id,
business_unit_id=bu_id,
client_branch_id=br_id,
registration_type_id=registration_type.id,
registration_number=registration_number.strip().upper(),
legal_name=legal_name.strip() or client.client_name,
trade_name=trade_name.strip() or None,
state=state.strip() or None,
jurisdiction=state.strip() or None,
status="active",
primary_registration=False,
responsible_party="firm",
auto_create_task=True,
created_by_user_id=user.id,
))
db.commit()
return RedirectResponse(f"/clients/{client_id}/business-structure", 303)
finally:
db.close()
@router.post("/{client_id}/business-structure/{entity}/{entity_id}/toggle")
def toggle_scope_record(request: Request, client_id: int, entity: str, entity_id: int, csrf_token: str = Form(...)):
validate_csrf(request, csrf_token)
db = CommonSessionLocal()
try:
user = get_current_user(request, db=db); require_permission(db, user, "clients.edit")
tenant_id = _tenant_id(request, user); client = _load_client(db, tenant_id, client_id)
model = {"business": ClientBusinessUnit, "branch": ClientBranch, "registration": ClientRegistration}.get(entity)
row = db.get(model, entity_id) if model else None
if not client or not row or row.client_id != client.id or row.tenant_id != tenant_id:
return RedirectResponse("/clients", 303)
if entity == "registration":
row.status = "inactive" if row.status in {"active", "valid", "registered"} else "active"
else:
row.is_active = not bool(row.is_active)
row.updated_by_user_id = user.id
db.commit()
return RedirectResponse(f"/clients/{client_id}/business-structure", 303)
finally:
db.close()
@@ -0,0 +1,77 @@
{% extends "ui/templates/base/layout.html" %}
{% block content %}
<div class="space-y-6">
<div class="flex flex-wrap items-center justify-between gap-3">
<div><h2 class="text-xl font-semibold text-slate-900">{{ client.client_name }} — Business Structure</h2>
<p class="text-sm text-slate-500">Maintain Business Units, Client Branches and statutory registrations under one PAN/legal client.</p></div>
<a href="/clients/{{ client.id }}" class="rounded-xl border border-slate-300 px-4 py-2 text-sm">Back to Client</a>
</div>
{% if can_edit %}
<div class="grid gap-5 xl:grid-cols-3">
<form method="post" action="/clients/{{ client.id }}/business-units" class="rounded-2xl bg-white p-5 shadow-soft space-y-3">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<h3 class="font-semibold text-slate-900">Add Business Unit</h3>
<input name="business_code" required placeholder="Business code" class="w-full rounded-xl border px-3 py-2 text-sm">
<input name="business_name" required placeholder="Business unit name" class="w-full rounded-xl border px-3 py-2 text-sm">
<input name="trade_name" placeholder="Trade name" class="w-full rounded-xl border px-3 py-2 text-sm">
<input name="nature_of_business" placeholder="Nature of business" class="w-full rounded-xl border px-3 py-2 text-sm">
<label class="flex gap-2 text-sm"><input type="checkbox" name="is_primary"> Primary Business Unit</label>
<button class="rounded-xl bg-brand-600 px-4 py-2 text-sm text-white">Add Business Unit</button>
</form>
<form method="post" action="/clients/{{ client.id }}/branches" class="rounded-2xl bg-white p-5 shadow-soft space-y-3">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<h3 class="font-semibold text-slate-900">Add Client Branch</h3>
<select name="business_unit_id" required class="w-full rounded-xl border px-3 py-2 text-sm">
<option value="">Select Business Unit</option>
{% for row in businesses if row.is_active %}<option value="{{ row.id }}">{{ row.business_name }}</option>{% endfor %}
</select>
<input name="branch_code" required placeholder="Branch code" class="w-full rounded-xl border px-3 py-2 text-sm">
<input name="branch_name" required placeholder="Client Branch name" class="w-full rounded-xl border px-3 py-2 text-sm">
<select name="branch_type" class="w-full rounded-xl border px-3 py-2 text-sm">
<option value="head_office">Head Office</option><option value="branch">Branch</option>
<option value="warehouse">Warehouse</option><option value="unit">Unit</option>
</select>
<div class="grid grid-cols-3 gap-2"><input name="city" placeholder="City" class="rounded-xl border px-3 py-2 text-sm"><input name="state" placeholder="State" class="rounded-xl border px-3 py-2 text-sm"><input name="pincode" placeholder="Pincode" class="rounded-xl border px-3 py-2 text-sm"></div>
<label class="flex gap-2 text-sm"><input type="checkbox" name="is_primary"> Primary Branch</label>
<button class="rounded-xl bg-brand-600 px-4 py-2 text-sm text-white">Add Client Branch</button>
</form>
<form method="post" action="/clients/{{ client.id }}/registrations" class="rounded-2xl bg-white p-5 shadow-soft space-y-3">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<h3 class="font-semibold text-slate-900">Add Registration</h3>
<select name="business_unit_id" class="w-full rounded-xl border px-3 py-2 text-sm"><option value="">Client level / derive from Branch</option>{% for row in businesses if row.is_active %}<option value="{{ row.id }}">{{ row.business_name }}</option>{% endfor %}</select>
<select name="client_branch_id" class="w-full rounded-xl border px-3 py-2 text-sm"><option value="">No Client Branch</option>{% for row in branches if row.is_active %}<option value="{{ row.id }}">{{ row.branch_name }}</option>{% endfor %}</select>
<select name="registration_type_id" required class="w-full rounded-xl border px-3 py-2 text-sm">
<option value="">Select Registration Type</option>
{% for row in registration_types %}<option value="{{ row.id }}">{{ row.name }} ({{ row.code }})</option>{% endfor %}
</select>
<input name="registration_number" required placeholder="Registration number" class="w-full rounded-xl border px-3 py-2 text-sm">
<input name="legal_name" placeholder="Legal name" class="w-full rounded-xl border px-3 py-2 text-sm">
<input name="trade_name" placeholder="Trade / deductor unit name" class="w-full rounded-xl border px-3 py-2 text-sm">
<input name="state" placeholder="State" class="w-full rounded-xl border px-3 py-2 text-sm">
<button class="rounded-xl bg-brand-600 px-4 py-2 text-sm text-white">Add Registration</button>
</form>
</div>
{% endif %}
<section class="rounded-2xl bg-white shadow-soft overflow-hidden">
<div class="border-b p-4 font-semibold">Business Units</div>
<table class="min-w-full text-sm"><thead class="bg-slate-50"><tr><th class="p-3 text-left">Code</th><th class="p-3 text-left">Business Unit</th><th class="p-3 text-left">Trade Name</th><th class="p-3 text-left">Nature</th><th class="p-3">Status</th><th></th></tr></thead>
<tbody>{% for row in businesses %}<tr class="border-t"><td class="p-3">{{ row.business_code }}</td><td class="p-3 font-medium">{{ row.business_name }}{% if row.is_primary %} <span class="text-xs text-brand-700">Primary</span>{% endif %}</td><td class="p-3">{{ row.trade_name or '-' }}</td><td class="p-3">{{ row.nature_of_business or '-' }}</td><td class="p-3 text-center">{{ 'Active' if row.is_active else 'Inactive' }}</td><td class="p-3">{% if can_edit %}<form method="post" action="/clients/{{ client.id }}/business-structure/business/{{ row.id }}/toggle"><input type="hidden" name="csrf_token" value="{{ csrf_token }}"><button class="text-xs text-brand-700">{{ 'Deactivate' if row.is_active else 'Activate' }}</button></form>{% endif %}</td></tr>{% else %}<tr><td colspan="6" class="p-6 text-center text-slate-500">No Business Units added.</td></tr>{% endfor %}</tbody></table>
</section>
<section class="rounded-2xl bg-white shadow-soft overflow-hidden">
<div class="border-b p-4 font-semibold">Client Branches</div>
<table class="min-w-full text-sm"><thead class="bg-slate-50"><tr><th class="p-3 text-left">Code</th><th class="p-3 text-left">Client Branch</th><th class="p-3 text-left">Type</th><th class="p-3 text-left">Location</th><th class="p-3">Status</th><th></th></tr></thead>
<tbody>{% for row in branches %}<tr class="border-t"><td class="p-3">{{ row.branch_code }}</td><td class="p-3 font-medium">{{ row.branch_name }}{% if row.is_primary %} <span class="text-xs text-brand-700">Primary</span>{% endif %}</td><td class="p-3">{{ row.branch_type|replace('_',' ')|title }}</td><td class="p-3">{{ row.city or '' }}{% if row.city and row.state %}, {% endif %}{{ row.state or '-' }}</td><td class="p-3 text-center">{{ 'Active' if row.is_active else 'Inactive' }}</td><td class="p-3">{% if can_edit %}<form method="post" action="/clients/{{ client.id }}/business-structure/branch/{{ row.id }}/toggle"><input type="hidden" name="csrf_token" value="{{ csrf_token }}"><button class="text-xs text-brand-700">{{ 'Deactivate' if row.is_active else 'Activate' }}</button></form>{% endif %}</td></tr>{% else %}<tr><td colspan="6" class="p-6 text-center text-slate-500">No Client Branches added.</td></tr>{% endfor %}</tbody></table>
</section>
<section class="rounded-2xl bg-white shadow-soft overflow-hidden">
<div class="border-b p-4 font-semibold">Registrations</div>
<table class="min-w-full text-sm"><thead class="bg-slate-50"><tr><th class="p-3 text-left">Type</th><th class="p-3 text-left">Number</th><th class="p-3 text-left">Trade / Unit Name</th><th class="p-3 text-left">State</th><th class="p-3">Status</th><th></th></tr></thead>
<tbody>{% for row in registrations %}<tr class="border-t"><td class="p-3">{{ registration_type_codes.get(row.id, "-") }}</td><td class="p-3 font-medium">{{ row.registration_number }}</td><td class="p-3">{{ row.trade_name or row.legal_name or '-' }}</td><td class="p-3">{{ row.state or '-' }}</td><td class="p-3 text-center">{{ row.status|replace('_',' ')|title }}</td><td class="p-3">{% if can_edit %}<form method="post" action="/clients/{{ client.id }}/business-structure/registration/{{ row.id }}/toggle"><input type="hidden" name="csrf_token" value="{{ csrf_token }}"><button class="text-xs text-brand-700">{{ 'Deactivate' if row.status in ['active','valid','registered'] else 'Activate' }}</button></form>{% endif %}</td></tr>{% else %}<tr><td colspan="6" class="p-6 text-center text-slate-500">No registrations added.</td></tr>{% endfor %}</tbody></table>
</section>
</div>
{% endblock %}
@@ -9,6 +9,7 @@
<div class="flex flex-wrap gap-3">
{% if can_edit %}
<a href="/clients/{{ row.id }}/business-structure" class="rounded-xl border border-emerald-300 px-4 py-2 text-sm font-medium text-emerald-700 hover:bg-emerald-50">Business Structure</a>
<a href="/client-identity/clients/{{ row.id }}" class="rounded-xl border border-indigo-300 px-4 py-2 text-sm font-medium text-indigo-700 hover:bg-indigo-50">Portal Identity</a>
<a href="/clients/{{ row.id }}/edit"
class="rounded-xl border border-slate-300 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50">