Implement adjudicated DO items across backend, frontend, deploy
From the ROADMAP adjudication (12 of 13 DO items; D2 is a commit action). Backend: - B3: pytest suite (auth, entity CRUD, rollup) + dev deps + pytest config - B4: cap document uploads at TEN31_MAX_UPLOAD_SIZE (default 50MB), stream- checked with partial-file cleanup, 413 on overflow - B7: type AuditLog.detail as dict|list|str|None to match the JSON column - B10: index foreign-key columns (migration a7b8c9d0e1f2 + index=True) - B11: cli delete-user logs file-removal errors instead of swallowing them Frontend: - F2: distinguish "server unreachable" from "logged out"; retry prompt - F4: confirm before destructive holdings-replace on import; step progress - F6: expandable audit-log detail with full JSON - F7: empty-state on the Investments page - F8: shared role helpers (WRITER_ROLES/canEditRound/isApprover), used by EntitiesList, AuditLog, Import, ValuationWorkflow Deploy: - D5: run tsc --noEmit before packaging (build script) - D6: TEN31_LOG_LEVEL env var (defaults to info) Verified: 8/8 backend tests pass; alembic upgrades to head with 13 FK indexes; upload limit rejects oversized + cleans up; frontend tsc + vite build clean; dev server serves and proxies to the API.
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
"""add indexes on foreign-key columns
|
||||
|
||||
Indexes the FK columns that are commonly filtered/joined and are not already the left-most
|
||||
column of an existing unique constraint (those are covered by the constraint's index). Names
|
||||
match SQLModel's index=True default (ix_<table>_<column>) so the ORM and DB stay in sync.
|
||||
|
||||
Revision ID: a7b8c9d0e1f2
|
||||
Revises: f6a7b8c9d0e1
|
||||
Create Date: 2026-07-01 09:30:00.000000
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision: str = 'a7b8c9d0e1f2'
|
||||
down_revision: Union[str, None] = 'f6a7b8c9d0e1'
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
# (index_name, table, column)
|
||||
_INDEXES = [
|
||||
('ix_users_primary_account_id', 'users', 'primary_account_id'),
|
||||
('ix_holdings_entity_id', 'holdings', 'entity_id'),
|
||||
('ix_positions_holding_id', 'positions', 'holding_id'),
|
||||
('ix_valuation_rounds_submitted_by', 'valuation_rounds', 'submitted_by'),
|
||||
('ix_valuation_rounds_approved_by', 'valuation_rounds', 'approved_by'),
|
||||
('ix_valuations_position_id', 'valuations', 'position_id'),
|
||||
('ix_audit_log_actor_user_id', 'audit_log', 'actor_user_id'),
|
||||
('ix_entity_access_entity_id', 'entity_access', 'entity_id'),
|
||||
('ix_documents_entity_id', 'documents', 'entity_id'),
|
||||
('ix_documents_investor_user_id', 'documents', 'investor_user_id'),
|
||||
('ix_documents_uploaded_by', 'documents', 'uploaded_by'),
|
||||
('ix_capital_account_statements_investor_user_id',
|
||||
'capital_account_statements', 'investor_user_id'),
|
||||
('ix_capital_account_statements_document_id',
|
||||
'capital_account_statements', 'document_id'),
|
||||
]
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
for name, table, column in _INDEXES:
|
||||
op.create_index(name, table, [column])
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
for name, table, _column in reversed(_INDEXES):
|
||||
op.drop_index(name, table_name=table)
|
||||
@@ -14,6 +14,13 @@ dependencies = [
|
||||
"aiosqlite==0.21.0",
|
||||
"starlette-session==0.4.3",
|
||||
"openpyxl==3.1.5",
|
||||
"msoffcrypto-tool==6.0.0",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
dev = [
|
||||
"pytest==8.3.4",
|
||||
"httpx==0.28.1", # required by starlette's TestClient
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
@@ -23,3 +30,6 @@ ten31portal-cli = "ten31portal.cli:main"
|
||||
[build-system]
|
||||
requires = ["hatchling"]
|
||||
build-backend = "hatchling.build"
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
|
||||
@@ -16,7 +16,12 @@ def record_audit(
|
||||
object_id: int | None = None,
|
||||
detail: Any = None,
|
||||
) -> AuditLog:
|
||||
"""Write one audit log entry and flush it."""
|
||||
"""Write one audit log entry and flush it.
|
||||
|
||||
``detail`` is a small JSON-serializable payload describing the change (typically a dict of
|
||||
changed fields, sometimes an identifying value on delete, or None). It is persisted to a
|
||||
JSON column on AuditLog.
|
||||
"""
|
||||
entry = AuditLog(
|
||||
actor_user_id=actor_user_id,
|
||||
action=action,
|
||||
|
||||
+225
-7
@@ -1,4 +1,4 @@
|
||||
"""CLI commands for Ten31Portal."""
|
||||
"""CLI commands for Ten31Portal (also driven by the StartOS service Actions)."""
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
@@ -8,7 +8,21 @@ from sqlmodel import Session, select
|
||||
from ten31portal.auth import hash_password
|
||||
from ten31portal.database import engine
|
||||
from ten31portal.db_init import run_migrations
|
||||
from ten31portal.models import User, UserRole
|
||||
from ten31portal.models import (
|
||||
AuditLog, CapitalAccountStatement, Document, EntityAccess, User, UserRole,
|
||||
ValuationRound,
|
||||
)
|
||||
|
||||
|
||||
def _find_user(session: Session, username: str | None, email: str | None) -> User | None:
|
||||
"""Look a user up by username (preferred) or email."""
|
||||
if username:
|
||||
u = session.exec(select(User).where(User.username == username)).first()
|
||||
if u:
|
||||
return u
|
||||
if email:
|
||||
return session.exec(select(User).where(User.email == email)).first()
|
||||
return None
|
||||
|
||||
|
||||
def create_user(args: argparse.Namespace) -> None:
|
||||
@@ -16,8 +30,10 @@ def create_user(args: argparse.Namespace) -> None:
|
||||
run_migrations()
|
||||
|
||||
with Session(engine) as session:
|
||||
existing = session.exec(select(User).where(User.email == args.email)).first()
|
||||
if existing:
|
||||
if session.exec(select(User).where(User.username == args.username)).first():
|
||||
print(f"Error: user with username {args.username} already exists.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
if args.email and session.exec(select(User).where(User.email == args.email)).first():
|
||||
print(f"Error: user with email {args.email} already exists.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
@@ -29,13 +45,179 @@ def create_user(args: argparse.Namespace) -> None:
|
||||
|
||||
user = User(
|
||||
name=args.name,
|
||||
email=args.email,
|
||||
username=args.username,
|
||||
email=args.email or None,
|
||||
password_hash=hash_password(args.password),
|
||||
role=role,
|
||||
is_service_admin=bool(getattr(args, "service_admin", False)),
|
||||
)
|
||||
session.add(user)
|
||||
session.commit()
|
||||
print(f"Created user: {user.name} ({user.email}) with role {user.role.value}")
|
||||
print(f"Created user: {user.name} ({user.username}) with role {user.role.value}")
|
||||
|
||||
|
||||
def reset_password(args: argparse.Namespace) -> None:
|
||||
"""Reset a user's password (and re-enable their login)."""
|
||||
run_migrations()
|
||||
|
||||
with Session(engine) as session:
|
||||
user = _find_user(session, args.username, args.email)
|
||||
if user is None:
|
||||
who = args.username or args.email
|
||||
print(f"Error: no user found for '{who}'.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
user.password_hash = hash_password(args.password)
|
||||
user.login_enabled = True
|
||||
session.add(user)
|
||||
session.commit()
|
||||
print(f"Password reset for {user.name} ({user.username}).")
|
||||
|
||||
|
||||
def list_users(args: argparse.Namespace) -> None:
|
||||
"""Print all user accounts."""
|
||||
run_migrations()
|
||||
|
||||
with Session(engine) as session:
|
||||
users = session.exec(select(User).order_by(User.role, User.name)).all() # type: ignore[arg-type]
|
||||
if not users:
|
||||
print("No users.")
|
||||
return
|
||||
print(f"{'USERNAME':<20} {'NAME':<24} {'ROLE':<14} {'STATUS':<10} EMAIL")
|
||||
print("-" * 84)
|
||||
for u in users:
|
||||
status = "active" if u.is_active else "disabled"
|
||||
tag = " [SERVICE ADMIN]" if u.is_service_admin else ""
|
||||
print(f"{u.username:<20} {u.name:<24} {u.role.value:<14} {status:<10} {u.email or '-'}{tag}")
|
||||
print(f"\n{len(users)} user(s). The Service Admin cannot be deleted.")
|
||||
|
||||
|
||||
def delete_user(args: argparse.Namespace) -> None:
|
||||
"""Delete a user account and its dependent rows. The Service Admin is protected."""
|
||||
run_migrations()
|
||||
|
||||
from ten31portal import storage
|
||||
|
||||
with Session(engine) as session:
|
||||
user = _find_user(session, args.username, args.email)
|
||||
if user is None:
|
||||
who = args.username or args.email
|
||||
print(f"Error: no user found for '{who}'.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
if user.is_service_admin:
|
||||
print(f"Error: '{user.username}' is the Service Admin and cannot be deleted.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
uid = user.id
|
||||
|
||||
# Entity-access grants and capital-account statements are this user's own data.
|
||||
for acc in session.exec(select(EntityAccess).where(EntityAccess.user_id == uid)).all():
|
||||
session.delete(acc)
|
||||
for stmt in session.exec(
|
||||
select(CapitalAccountStatement).where(CapitalAccountStatement.investor_user_id == uid)
|
||||
).all():
|
||||
session.delete(stmt)
|
||||
|
||||
# Documents addressed privately to this investor are removed (file + row); documents
|
||||
# they uploaded stay, with the uploader cleared.
|
||||
for doc in session.exec(select(Document).where(Document.investor_user_id == uid)).all():
|
||||
try:
|
||||
storage.delete_file(doc.storage_path)
|
||||
except OSError as exc:
|
||||
# Don't abort the whole deletion, but surface it — a swallowed disk/permission
|
||||
# error would silently orphan the file on the data volume.
|
||||
print(f"Warning: could not delete file {doc.storage_path}: {exc}", file=sys.stderr)
|
||||
session.delete(doc)
|
||||
for doc in session.exec(select(Document).where(Document.uploaded_by == uid)).all():
|
||||
doc.uploaded_by = None
|
||||
session.add(doc)
|
||||
|
||||
# Preserve history/rounds by clearing the references to this user.
|
||||
for rnd in session.exec(
|
||||
select(ValuationRound).where(
|
||||
(ValuationRound.submitted_by == uid) | (ValuationRound.approved_by == uid)
|
||||
)
|
||||
).all():
|
||||
if rnd.submitted_by == uid:
|
||||
rnd.submitted_by = None
|
||||
if rnd.approved_by == uid:
|
||||
rnd.approved_by = None
|
||||
session.add(rnd)
|
||||
for log in session.exec(select(AuditLog).where(AuditLog.actor_user_id == uid)).all():
|
||||
log.actor_user_id = None
|
||||
session.add(log)
|
||||
|
||||
# Detach any linked sub-accounts so they log in on their own again.
|
||||
for sub in session.exec(select(User).where(User.primary_account_id == uid)).all():
|
||||
sub.primary_account_id = None
|
||||
session.add(sub)
|
||||
|
||||
name, username = user.name, user.username
|
||||
session.delete(user)
|
||||
session.commit()
|
||||
print(f"Deleted user {name} ({username}).")
|
||||
|
||||
|
||||
def dedupe_holdings(args: argparse.Namespace) -> None:
|
||||
"""Remove duplicate holdings/positions left by old double-imports (fixes inflated Invested)."""
|
||||
run_migrations()
|
||||
from ten31portal.models import Entity
|
||||
from ten31portal.routers.import_router import dedupe_entity
|
||||
|
||||
with Session(engine) as session:
|
||||
if args.entity_id:
|
||||
entities = [e for e in [session.get(Entity, args.entity_id)] if e]
|
||||
else:
|
||||
entities = session.exec(select(Entity).order_by(Entity.name)).all() # type: ignore[arg-type]
|
||||
total_h = total_p = 0
|
||||
for ent in entities:
|
||||
res = dedupe_entity(ent.id, session)
|
||||
if res["removed_holdings"] or res["removed_positions"]:
|
||||
print(f"{ent.name}: removed {res['removed_holdings']} holding(s), "
|
||||
f"{res['removed_positions']} position(s)")
|
||||
total_h += res["removed_holdings"]
|
||||
total_p += res["removed_positions"]
|
||||
session.commit()
|
||||
if total_h or total_p:
|
||||
print(f"\nDone. Removed {total_h} duplicate holding(s) and {total_p} position(s).")
|
||||
else:
|
||||
print("No duplicates found — nothing to clean up.")
|
||||
|
||||
|
||||
def reset_holdings(args: argparse.Namespace) -> None:
|
||||
"""Clear a fund's holdings/positions/rounds so it can be re-imported from scratch."""
|
||||
run_migrations()
|
||||
from ten31portal.models import Entity
|
||||
from ten31portal.routers.import_router import reset_entity_holdings
|
||||
|
||||
with Session(engine) as session:
|
||||
entity = None
|
||||
if args.entity_id:
|
||||
entity = session.get(Entity, args.entity_id)
|
||||
elif args.name:
|
||||
entity = session.exec(select(Entity).where(Entity.name == args.name)).first()
|
||||
if entity is None:
|
||||
print(f"Error: no fund found for '{args.name or args.entity_id}'. "
|
||||
f"Check the exact name with list-funds.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
res = reset_entity_holdings(entity.id, session)
|
||||
session.commit()
|
||||
print(f"Cleared {entity.name}: removed {res['holdings']} holding(s), "
|
||||
f"{res['positions']} position(s), {res['rounds']} round(s). "
|
||||
f"Re-import the fund's NAV to repopulate it.")
|
||||
|
||||
|
||||
def list_funds(args: argparse.Namespace) -> None:
|
||||
"""Print every entity's id and name (so the exact name is known for reset-holdings)."""
|
||||
run_migrations()
|
||||
from ten31portal.models import Entity
|
||||
|
||||
with Session(engine) as session:
|
||||
entities = session.exec(select(Entity).order_by(Entity.name)).all() # type: ignore[arg-type]
|
||||
if not entities:
|
||||
print("No funds yet.")
|
||||
return
|
||||
for e in entities:
|
||||
print(f"[{e.id}] {e.name} ({e.type.value})")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
@@ -44,13 +226,49 @@ def main() -> None:
|
||||
|
||||
create = sub.add_parser("create-user", help="Provision a new user")
|
||||
create.add_argument("--name", required=True)
|
||||
create.add_argument("--email", required=True)
|
||||
create.add_argument("--username", required=True)
|
||||
create.add_argument("--email", required=False, default=None)
|
||||
create.add_argument("--role", required=True, choices=[r.value for r in UserRole])
|
||||
create.add_argument("--password", required=True)
|
||||
create.add_argument("--service-admin", action="store_true",
|
||||
help="Mark as the protected built-in Service Admin")
|
||||
|
||||
reset = sub.add_parser("reset-password", help="Reset a user's password")
|
||||
reset.add_argument("--username", required=False, default=None)
|
||||
reset.add_argument("--email", required=False, default=None)
|
||||
reset.add_argument("--password", required=True)
|
||||
|
||||
sub.add_parser("list-users", help="List all user accounts")
|
||||
|
||||
delete = sub.add_parser("delete-user", help="Delete a user (not the Service Admin)")
|
||||
delete.add_argument("--username", required=False, default=None)
|
||||
delete.add_argument("--email", required=False, default=None)
|
||||
|
||||
dedupe = sub.add_parser("dedupe-holdings", help="Remove duplicate holdings/positions")
|
||||
dedupe.add_argument("--entity-id", type=int, required=False, default=None,
|
||||
help="Limit to one entity; omit to clean all")
|
||||
|
||||
sub.add_parser("list-funds", help="List entities (funds/SPVs) with their ids")
|
||||
|
||||
reset = sub.add_parser("reset-holdings", help="Clear a fund's holdings to re-import fresh")
|
||||
reset.add_argument("--name", required=False, default=None, help="Exact fund name")
|
||||
reset.add_argument("--entity-id", type=int, required=False, default=None)
|
||||
|
||||
args = parser.parse_args()
|
||||
if args.command == "create-user":
|
||||
create_user(args)
|
||||
elif args.command == "reset-password":
|
||||
reset_password(args)
|
||||
elif args.command == "list-users":
|
||||
list_users(args)
|
||||
elif args.command == "delete-user":
|
||||
delete_user(args)
|
||||
elif args.command == "dedupe-holdings":
|
||||
dedupe_holdings(args)
|
||||
elif args.command == "list-funds":
|
||||
list_funds(args)
|
||||
elif args.command == "reset-holdings":
|
||||
reset_holdings(args)
|
||||
else:
|
||||
parser.print_help()
|
||||
|
||||
|
||||
@@ -5,3 +5,7 @@ import os
|
||||
|
||||
DB_PATH: str = os.getenv("TEN31_DB_PATH", "/data/ten31portal/portal.db")
|
||||
SESSION_SECRET: str = os.getenv("TEN31_SESSION_SECRET", "change-me-in-production")
|
||||
DOCS_DIR: str = os.getenv("TEN31_DOCS_DIR", "/data/ten31portal/documents")
|
||||
# Cap on a single uploaded document. The docs dir shares the data volume with the DB, so an
|
||||
# unbounded upload could fill the disk and take the portal down. Default 50 MB.
|
||||
MAX_UPLOAD_SIZE: int = int(os.getenv("TEN31_MAX_UPLOAD_SIZE", str(50 * 1024 * 1024)))
|
||||
|
||||
@@ -11,10 +11,27 @@ from sqlmodel import Field, SQLModel, Column, String, JSON, UniqueConstraint
|
||||
# --- Enums ---
|
||||
|
||||
class UserRole(str, enum.Enum):
|
||||
approver = "approver"
|
||||
# Internal staff
|
||||
approver = "approver" # "Managing Partner" — full access incl. valuation sign-off
|
||||
operations = "operations" # full access except final sign-off
|
||||
cfo = "cfo"
|
||||
fund_admin = "fund_admin"
|
||||
viewer = "viewer"
|
||||
# External accounts (entity-scoped via EntityAccess)
|
||||
investor = "investor"
|
||||
fund_administrator = "fund_administrator"
|
||||
|
||||
|
||||
# External roles see only the entities granted to them.
|
||||
EXTERNAL_ROLES = (UserRole.investor, UserRole.fund_administrator)
|
||||
|
||||
|
||||
class DocumentCategory(str, enum.Enum):
|
||||
capital_account = "capital_account"
|
||||
k1 = "k1"
|
||||
statement = "statement"
|
||||
tax = "tax"
|
||||
other = "other"
|
||||
|
||||
|
||||
class EntityType(str, enum.Enum):
|
||||
@@ -43,10 +60,21 @@ class User(SQLModel, table=True):
|
||||
|
||||
id: int | None = Field(default=None, primary_key=True)
|
||||
name: str
|
||||
email: str = Field(sa_column=Column(String, unique=True, nullable=False))
|
||||
username: str = Field(sa_column=Column(String, unique=True, nullable=False))
|
||||
email: str | None = Field(default=None, sa_column=Column(String, unique=True, nullable=True))
|
||||
password_hash: str
|
||||
role: UserRole
|
||||
is_active: bool = Field(default=True)
|
||||
# The built-in Service Admin (bootstrap account). Can be reset but never deleted.
|
||||
is_service_admin: bool = Field(default=False)
|
||||
# False for members imported without a password; set True when an admin sets one.
|
||||
login_enabled: bool = Field(default=True)
|
||||
# When an investor invests under several legal names (one per Partner/vehicle), each name
|
||||
# is its own account. Linking the secondary accounts to one "primary" lets that person sign
|
||||
# in once and see every name's investments. Null = this account logs in on its own.
|
||||
primary_account_id: int | None = Field(default=None, foreign_key="users.id", index=True)
|
||||
# Fund-administrator investor ID (from the eNAV ALLOC SI tab) for idempotent re-import.
|
||||
external_investor_id: str | None = Field(default=None, sa_column=Column(String, nullable=True))
|
||||
created_at: datetime = Field(default_factory=datetime.utcnow)
|
||||
|
||||
|
||||
@@ -66,7 +94,7 @@ class Holding(SQLModel, table=True):
|
||||
__tablename__ = "holdings"
|
||||
|
||||
id: int | None = Field(default=None, primary_key=True)
|
||||
entity_id: int = Field(foreign_key="entities.id")
|
||||
entity_id: int = Field(foreign_key="entities.id", index=True)
|
||||
company_name: str
|
||||
created_at: datetime = Field(default_factory=datetime.utcnow)
|
||||
|
||||
@@ -75,7 +103,7 @@ class Position(SQLModel, table=True):
|
||||
__tablename__ = "positions"
|
||||
|
||||
id: int | None = Field(default=None, primary_key=True)
|
||||
holding_id: int = Field(foreign_key="holdings.id")
|
||||
holding_id: int = Field(foreign_key="holdings.id", index=True)
|
||||
security_name: str
|
||||
investment_date: date
|
||||
shares: str | None = None # Decimal stored as string
|
||||
@@ -93,9 +121,9 @@ class ValuationRound(SQLModel, table=True):
|
||||
entity_id: int = Field(foreign_key="entities.id")
|
||||
quarter_end: date
|
||||
status: RoundStatus = Field(default=RoundStatus.draft)
|
||||
submitted_by: int | None = Field(default=None, foreign_key="users.id")
|
||||
submitted_by: int | None = Field(default=None, foreign_key="users.id", index=True)
|
||||
submitted_at: datetime | None = None
|
||||
approved_by: int | None = Field(default=None, foreign_key="users.id")
|
||||
approved_by: int | None = Field(default=None, foreign_key="users.id", index=True)
|
||||
approved_at: datetime | None = None
|
||||
return_note: str | None = None
|
||||
is_seed: bool = Field(default=False)
|
||||
@@ -110,7 +138,7 @@ class Valuation(SQLModel, table=True):
|
||||
|
||||
id: int | None = Field(default=None, primary_key=True)
|
||||
round_id: int = Field(foreign_key="valuation_rounds.id")
|
||||
position_id: int = Field(foreign_key="positions.id")
|
||||
position_id: int = Field(foreign_key="positions.id", index=True)
|
||||
value_cents: int
|
||||
created_at: datetime = Field(default_factory=datetime.utcnow)
|
||||
|
||||
@@ -119,9 +147,63 @@ class AuditLog(SQLModel, table=True):
|
||||
__tablename__ = "audit_log"
|
||||
|
||||
id: int | None = Field(default=None, primary_key=True)
|
||||
actor_user_id: int | None = Field(default=None, foreign_key="users.id")
|
||||
actor_user_id: int | None = Field(default=None, foreign_key="users.id", index=True)
|
||||
action: str
|
||||
object_type: str
|
||||
object_id: int | None = None
|
||||
detail: str | None = Field(default=None, sa_column=Column(JSON, nullable=True))
|
||||
# An action-specific JSON payload describing the change (stored in a JSON column). Most
|
||||
# callers pass a dict of changed fields (e.g. an entity update); some pass an identifying
|
||||
# field on delete, and some pass None. Matches AuditLogResponse.detail in schemas.py.
|
||||
detail: dict | list | str | None = Field(default=None, sa_column=Column(JSON, nullable=True))
|
||||
created_at: datetime = Field(default_factory=datetime.utcnow)
|
||||
|
||||
|
||||
class EntityAccess(SQLModel, table=True):
|
||||
"""Which entities an external account may view."""
|
||||
__tablename__ = "entity_access"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("user_id", "entity_id", name="uq_access_user_entity"),
|
||||
)
|
||||
|
||||
id: int | None = Field(default=None, primary_key=True)
|
||||
user_id: int = Field(foreign_key="users.id")
|
||||
entity_id: int = Field(foreign_key="entities.id", index=True)
|
||||
created_at: datetime = Field(default_factory=datetime.utcnow)
|
||||
|
||||
|
||||
class Document(SQLModel, table=True):
|
||||
"""An uploaded file. Shared to a fund (investor_user_id null) or private to one investor."""
|
||||
__tablename__ = "documents"
|
||||
|
||||
id: int | None = Field(default=None, primary_key=True)
|
||||
entity_id: int = Field(foreign_key="entities.id", index=True)
|
||||
investor_user_id: int | None = Field(default=None, foreign_key="users.id", index=True)
|
||||
category: DocumentCategory = Field(default=DocumentCategory.other)
|
||||
title: str
|
||||
original_filename: str
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
storage_path: str # opaque filename on the data volume, relative to DOCS_DIR
|
||||
uploaded_by: int | None = Field(default=None, foreign_key="users.id", index=True)
|
||||
created_at: datetime = Field(default_factory=datetime.utcnow)
|
||||
|
||||
|
||||
class CapitalAccountStatement(SQLModel, table=True):
|
||||
"""An investor's capital-account figures for one fund as of a date."""
|
||||
__tablename__ = "capital_account_statements"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("entity_id", "investor_user_id", "as_of_date",
|
||||
name="uq_capacct_entity_investor_date"),
|
||||
)
|
||||
|
||||
id: int | None = Field(default=None, primary_key=True)
|
||||
entity_id: int = Field(foreign_key="entities.id")
|
||||
investor_user_id: int = Field(foreign_key="users.id", index=True)
|
||||
as_of_date: date
|
||||
commitment_cents: int = 0 # initial capital commitment
|
||||
beginning_balance_cents: int = 0
|
||||
contributions_cents: int = 0 # paid-in capital
|
||||
distributions_cents: int = 0 # capital returned (for DPI)
|
||||
ending_balance_cents: int = 0 # current capital value
|
||||
document_id: int | None = Field(default=None, foreign_key="documents.id", index=True)
|
||||
created_at: datetime = Field(default_factory=datetime.utcnow)
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
"""Document upload, listing, download, and deletion with per-account access control."""
|
||||
|
||||
from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile
|
||||
from fastapi.responses import FileResponse
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from ten31portal.audit import record_audit
|
||||
from ten31portal.auth import (
|
||||
accessible_entity_ids, can_access_entity, get_current_user,
|
||||
household_user_ids, require_internal_admin,
|
||||
)
|
||||
from ten31portal.database import get_session
|
||||
from ten31portal.models import (
|
||||
Document, DocumentCategory, Entity, User, UserRole,
|
||||
)
|
||||
from ten31portal.schemas import DocumentResponse
|
||||
from ten31portal import storage
|
||||
|
||||
router = APIRouter(prefix="/api/documents", tags=["documents"])
|
||||
|
||||
|
||||
def _can_upload(user: User, entity_id: int, session: Session) -> bool:
|
||||
"""Internal admins upload anywhere; external fund admins upload for their entities."""
|
||||
if user.role in (UserRole.approver, UserRole.cfo, UserRole.operations):
|
||||
return True
|
||||
if user.role == UserRole.fund_administrator:
|
||||
return can_access_entity(user, entity_id, session)
|
||||
return False
|
||||
|
||||
|
||||
def _can_view(user: User, doc: Document, session: Session) -> bool:
|
||||
allowed = accessible_entity_ids(user, session)
|
||||
if allowed is None: # internal staff
|
||||
return True
|
||||
if doc.entity_id not in allowed:
|
||||
return False
|
||||
# Investors only see shared docs or those addressed to any of their linked names;
|
||||
# fund admins see all docs for the entity.
|
||||
if user.role == UserRole.investor:
|
||||
return (
|
||||
doc.investor_user_id is None
|
||||
or doc.investor_user_id in household_user_ids(user, session)
|
||||
)
|
||||
return True
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_documents(
|
||||
entity_id: int | None = None,
|
||||
investor_user_id: int | None = None,
|
||||
user: User = Depends(get_current_user),
|
||||
session: Session = Depends(get_session),
|
||||
) -> list[DocumentResponse]:
|
||||
query = select(Document)
|
||||
if entity_id is not None:
|
||||
query = query.where(Document.entity_id == entity_id)
|
||||
if investor_user_id is not None:
|
||||
query = query.where(Document.investor_user_id == investor_user_id)
|
||||
rows = session.exec(query.order_by(Document.created_at.desc())).all() # type: ignore[union-attr]
|
||||
visible = [d for d in rows if _can_view(user, d, session)]
|
||||
return [DocumentResponse.model_validate(d, from_attributes=True) for d in visible]
|
||||
|
||||
|
||||
@router.post("", status_code=201)
|
||||
def upload_document(
|
||||
entity_id: int = Form(...),
|
||||
category: DocumentCategory = Form(DocumentCategory.other),
|
||||
title: str | None = Form(None),
|
||||
investor_user_id: int | None = Form(None),
|
||||
file: UploadFile = File(...),
|
||||
user: User = Depends(get_current_user),
|
||||
session: Session = Depends(get_session),
|
||||
) -> DocumentResponse:
|
||||
entity = session.get(Entity, entity_id)
|
||||
if entity is None:
|
||||
raise HTTPException(status_code=404, detail="Entity not found")
|
||||
if not _can_upload(user, entity_id, session):
|
||||
raise HTTPException(status_code=403, detail="Insufficient permissions")
|
||||
|
||||
# If targeting a specific investor, they must have access to this entity.
|
||||
if investor_user_id is not None:
|
||||
target = session.get(User, investor_user_id)
|
||||
if target is None:
|
||||
raise HTTPException(status_code=404, detail="Investor not found")
|
||||
if not can_access_entity(target, entity_id, session):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="That investor does not have access to this entity.",
|
||||
)
|
||||
|
||||
try:
|
||||
storage_name, size = storage.save_upload(file)
|
||||
except storage.UploadTooLarge as exc:
|
||||
raise HTTPException(status_code=413, detail=str(exc))
|
||||
doc = Document(
|
||||
entity_id=entity_id,
|
||||
investor_user_id=investor_user_id,
|
||||
category=category,
|
||||
title=title or (file.filename or "Untitled"),
|
||||
original_filename=file.filename or storage_name,
|
||||
content_type=file.content_type or "application/octet-stream",
|
||||
size_bytes=size,
|
||||
storage_path=storage_name,
|
||||
uploaded_by=user.id,
|
||||
)
|
||||
session.add(doc)
|
||||
session.flush()
|
||||
record_audit(session, user.id, "upload", "document", doc.id, {
|
||||
"entity_id": entity_id,
|
||||
"investor_user_id": investor_user_id,
|
||||
"category": category.value,
|
||||
"filename": doc.original_filename,
|
||||
})
|
||||
session.commit()
|
||||
session.refresh(doc)
|
||||
return DocumentResponse.model_validate(doc, from_attributes=True)
|
||||
|
||||
|
||||
@router.get("/{document_id}/download")
|
||||
def download_document(
|
||||
document_id: int,
|
||||
user: User = Depends(get_current_user),
|
||||
session: Session = Depends(get_session),
|
||||
) -> FileResponse:
|
||||
doc = session.get(Document, document_id)
|
||||
if doc is None or not _can_view(user, doc, session):
|
||||
raise HTTPException(status_code=404, detail="Document not found")
|
||||
try:
|
||||
path = storage.full_path(doc.storage_path)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=404, detail="Document not found")
|
||||
if not path.is_file():
|
||||
raise HTTPException(status_code=404, detail="File missing on disk")
|
||||
return FileResponse(
|
||||
path,
|
||||
media_type=doc.content_type,
|
||||
filename=doc.original_filename,
|
||||
)
|
||||
|
||||
|
||||
@router.delete("/{document_id}")
|
||||
def delete_document(
|
||||
document_id: int,
|
||||
admin: User = Depends(require_internal_admin),
|
||||
session: Session = Depends(get_session),
|
||||
) -> dict[str, str]:
|
||||
doc = session.get(Document, document_id)
|
||||
if doc is None:
|
||||
raise HTTPException(status_code=404, detail="Document not found")
|
||||
storage.delete_file(doc.storage_path)
|
||||
record_audit(session, admin.id, "delete", "document", document_id, {
|
||||
"filename": doc.original_filename,
|
||||
})
|
||||
session.delete(doc)
|
||||
session.commit()
|
||||
return {"status": "deleted"}
|
||||
@@ -0,0 +1,62 @@
|
||||
"""File storage on the data volume for uploaded documents."""
|
||||
|
||||
import os
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi import UploadFile
|
||||
|
||||
from ten31portal.config import DOCS_DIR, MAX_UPLOAD_SIZE
|
||||
|
||||
|
||||
class UploadTooLarge(Exception):
|
||||
"""Raised when an upload exceeds MAX_UPLOAD_SIZE. The partial file is removed first."""
|
||||
|
||||
|
||||
def ensure_docs_dir() -> Path:
|
||||
path = Path(DOCS_DIR)
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
def save_upload(file: UploadFile) -> tuple[str, int]:
|
||||
"""Stream an upload to disk under an opaque name. Returns (storage_path, size_bytes).
|
||||
|
||||
Enforces MAX_UPLOAD_SIZE as it streams so a runaway upload can't fill the data volume;
|
||||
the partial file is deleted before UploadTooLarge propagates.
|
||||
"""
|
||||
docs = ensure_docs_dir()
|
||||
suffix = Path(file.filename or "").suffix
|
||||
storage_name = f"{uuid4().hex}{suffix}"
|
||||
dest = docs / storage_name
|
||||
size = 0
|
||||
try:
|
||||
with dest.open("wb") as out:
|
||||
while chunk := file.file.read(1024 * 1024):
|
||||
size += len(chunk)
|
||||
if size > MAX_UPLOAD_SIZE:
|
||||
raise UploadTooLarge(
|
||||
f"Upload exceeds the {MAX_UPLOAD_SIZE}-byte limit."
|
||||
)
|
||||
out.write(chunk)
|
||||
except UploadTooLarge:
|
||||
dest.unlink(missing_ok=True)
|
||||
raise
|
||||
return storage_name, size
|
||||
|
||||
|
||||
def full_path(storage_path: str) -> Path:
|
||||
"""Resolve a stored file, guarding against path traversal."""
|
||||
docs = ensure_docs_dir().resolve()
|
||||
candidate = (docs / storage_path).resolve()
|
||||
if not str(candidate).startswith(str(docs) + os.sep):
|
||||
raise ValueError("Invalid storage path")
|
||||
return candidate
|
||||
|
||||
|
||||
def delete_file(storage_path: str) -> None:
|
||||
try:
|
||||
full_path(storage_path).unlink(missing_ok=True)
|
||||
except ValueError:
|
||||
pass
|
||||
@@ -0,0 +1,77 @@
|
||||
"""Shared pytest fixtures: an in-memory DB and a FastAPI TestClient.
|
||||
|
||||
The client is created WITHOUT the context-manager form on purpose, so the app lifespan (which
|
||||
runs real Alembic migrations against the configured DB_PATH) never fires. Tables come from
|
||||
SQLModel.metadata.create_all against a throwaway in-memory database instead.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy.pool import StaticPool
|
||||
from sqlmodel import Session, SQLModel, create_engine
|
||||
|
||||
import ten31portal.models # noqa: F401 — importing registers every table on SQLModel.metadata
|
||||
from ten31portal.auth import hash_password
|
||||
from ten31portal.database import get_session
|
||||
from ten31portal.main import app
|
||||
from ten31portal.models import User, UserRole
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def engine():
|
||||
eng = create_engine(
|
||||
"sqlite://",
|
||||
connect_args={"check_same_thread": False},
|
||||
poolclass=StaticPool, # one shared in-memory connection across sessions
|
||||
)
|
||||
SQLModel.metadata.create_all(eng)
|
||||
yield eng
|
||||
SQLModel.metadata.drop_all(eng)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def session(engine):
|
||||
with Session(engine) as s:
|
||||
yield s
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(engine):
|
||||
def override_get_session():
|
||||
with Session(engine) as s:
|
||||
yield s
|
||||
|
||||
app.dependency_overrides[get_session] = override_get_session
|
||||
yield TestClient(app)
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
def make_user(session, *, username="admin", password="password123",
|
||||
role=UserRole.approver, name="Test User", email=None, **kwargs):
|
||||
user = User(
|
||||
name=name,
|
||||
username=username,
|
||||
email=email,
|
||||
password_hash=hash_password(password),
|
||||
role=role,
|
||||
**kwargs,
|
||||
)
|
||||
session.add(user)
|
||||
session.commit()
|
||||
session.refresh(user)
|
||||
return user
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def approver(session):
|
||||
return make_user(session, username="approver", role=UserRole.approver)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def auth_client(client, approver):
|
||||
"""A TestClient already logged in as an approver (a writer)."""
|
||||
resp = client.post(
|
||||
"/api/auth/login", json={"login": "approver", "password": "password123"}
|
||||
)
|
||||
assert resp.status_code == 200, resp.text
|
||||
return client
|
||||
@@ -0,0 +1,40 @@
|
||||
"""Auth: login works, and protected/writer endpoints reject the wrong caller."""
|
||||
|
||||
from tests.conftest import make_user
|
||||
from ten31portal.models import UserRole
|
||||
|
||||
|
||||
def test_login_success(client, approver):
|
||||
resp = client.post(
|
||||
"/api/auth/login", json={"login": "approver", "password": "password123"}
|
||||
)
|
||||
assert resp.status_code == 200, resp.text
|
||||
assert resp.json()["username"] == "approver"
|
||||
|
||||
|
||||
def test_login_wrong_password(client, approver):
|
||||
resp = client.post(
|
||||
"/api/auth/login", json={"login": "approver", "password": "nope"}
|
||||
)
|
||||
assert resp.status_code == 401
|
||||
|
||||
|
||||
def test_me_requires_authentication(client):
|
||||
assert client.get("/api/auth/me").status_code == 401
|
||||
|
||||
|
||||
def test_me_returns_current_user(auth_client):
|
||||
resp = auth_client.get("/api/auth/me")
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["role"] == "approver"
|
||||
|
||||
|
||||
def test_writer_endpoint_rejects_viewer(client, session):
|
||||
"""A viewer is authenticated but not a writer — create-entity must 403, not 401."""
|
||||
make_user(session, username="viewer", role=UserRole.viewer)
|
||||
login = client.post(
|
||||
"/api/auth/login", json={"login": "viewer", "password": "password123"}
|
||||
)
|
||||
assert login.status_code == 200
|
||||
resp = client.post("/api/entities", json={"name": "X", "type": "fund"})
|
||||
assert resp.status_code == 403
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Entity CRUD round-trips through the API as a writer."""
|
||||
|
||||
|
||||
def test_entity_crud_roundtrip(auth_client):
|
||||
# Create
|
||||
created = auth_client.post(
|
||||
"/api/entities",
|
||||
json={"name": "Ten31 Fund I", "type": "fund", "vintage_year": 2025},
|
||||
)
|
||||
assert created.status_code == 201, created.text
|
||||
entity_id = created.json()["id"]
|
||||
|
||||
# Read (single)
|
||||
got = auth_client.get(f"/api/entities/{entity_id}")
|
||||
assert got.status_code == 200
|
||||
assert got.json()["name"] == "Ten31 Fund I"
|
||||
|
||||
# List
|
||||
listed = auth_client.get("/api/entities")
|
||||
assert listed.status_code == 200
|
||||
assert any(e["id"] == entity_id for e in listed.json())
|
||||
|
||||
# Update
|
||||
patched = auth_client.patch(
|
||||
f"/api/entities/{entity_id}", json={"name": "Ten31 Fund I, LP"}
|
||||
)
|
||||
assert patched.status_code == 200
|
||||
assert patched.json()["name"] == "Ten31 Fund I, LP"
|
||||
|
||||
|
||||
def test_get_missing_entity_404(auth_client):
|
||||
assert auth_client.get("/api/entities/99999").status_code == 404
|
||||
@@ -0,0 +1,48 @@
|
||||
"""The entity rollup aggregates invested cost and the latest signed valuation correctly."""
|
||||
|
||||
from datetime import date
|
||||
|
||||
from ten31portal.models import (
|
||||
Entity, EntityType, Holding, Position, RoundStatus, Valuation, ValuationRound,
|
||||
)
|
||||
|
||||
|
||||
def test_rollup_sums_cost_and_latest_signed_value(auth_client, session):
|
||||
entity = Entity(name="Rollup Fund", type=EntityType.fund)
|
||||
session.add(entity)
|
||||
session.commit()
|
||||
session.refresh(entity)
|
||||
|
||||
holding = Holding(entity_id=entity.id, company_name="Acme")
|
||||
session.add(holding)
|
||||
session.commit()
|
||||
session.refresh(holding)
|
||||
|
||||
position = Position(
|
||||
holding_id=holding.id,
|
||||
security_name="Acme Series A",
|
||||
investment_date=date(2025, 1, 15),
|
||||
cost_cents=100_000,
|
||||
)
|
||||
session.add(position)
|
||||
session.commit()
|
||||
session.refresh(position)
|
||||
|
||||
rnd = ValuationRound(
|
||||
entity_id=entity.id,
|
||||
quarter_end=date(2026, 3, 31),
|
||||
status=RoundStatus.approved,
|
||||
)
|
||||
session.add(rnd)
|
||||
session.commit()
|
||||
session.refresh(rnd)
|
||||
|
||||
session.add(Valuation(round_id=rnd.id, position_id=position.id, value_cents=150_000))
|
||||
session.commit()
|
||||
|
||||
resp = auth_client.get("/api/entities/rollup")
|
||||
assert resp.status_code == 200, resp.text
|
||||
row = next(r for r in resp.json() if r["id"] == entity.id)
|
||||
assert row["invested_cents"] == 100_000
|
||||
assert row["last_signed_value_cents"] == 150_000
|
||||
assert row["committed_cents"] == 0 # no capital-account statements added
|
||||
+2
-2
@@ -1,9 +1,9 @@
|
||||
{
|
||||
"name": "ten31portal-startos",
|
||||
"version": "0.1.0",
|
||||
"version": "0.2.20",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"build": "rm -rf ./javascript && ncc build startos/index.ts -o ./javascript",
|
||||
"build": "npm run check && rm -rf ./javascript && ncc build startos/index.ts -o ./javascript",
|
||||
"check": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
+9
-3
@@ -18,21 +18,27 @@ if [ ! -f /data/.initialized ]; then
|
||||
|
||||
# Set default credentials (user can change via CLI later)
|
||||
ADMIN_NAME="${TEN31_ADMIN_NAME:-Jonathan}"
|
||||
ADMIN_USERNAME="${TEN31_ADMIN_USERNAME:-admin}"
|
||||
ADMIN_EMAIL="${TEN31_ADMIN_EMAIL:-jonathan@ten31.xyz}"
|
||||
ADMIN_PASSWORD="${TEN31_ADMIN_PASSWORD:-Ten31}"
|
||||
|
||||
python3 -m ten31portal.cli create-user \
|
||||
--name "$ADMIN_NAME" \
|
||||
--username "$ADMIN_USERNAME" \
|
||||
--email "$ADMIN_EMAIL" \
|
||||
--role approver \
|
||||
--password "$ADMIN_PASSWORD" || true
|
||||
--password "$ADMIN_PASSWORD" \
|
||||
--service-admin || true
|
||||
|
||||
touch /data/.initialized
|
||||
echo "Default approver created: $ADMIN_EMAIL"
|
||||
echo "Default approver created: username=$ADMIN_USERNAME"
|
||||
fi
|
||||
|
||||
# Log level is overridable at runtime for debugging; defaults to info.
|
||||
LOG_LEVEL="${TEN31_LOG_LEVEL:-info}"
|
||||
|
||||
# Serve frontend static files from the backend
|
||||
exec uvicorn ten31portal.main:app \
|
||||
--host 0.0.0.0 \
|
||||
--port 8000 \
|
||||
--log-level info
|
||||
--log-level "$LOG_LEVEL"
|
||||
|
||||
+62
-15
@@ -1,16 +1,73 @@
|
||||
import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom";
|
||||
import { AuthProvider, useAuth } from "./context/AuthContext";
|
||||
import { isInternal } from "./api";
|
||||
import Layout from "./components/Layout";
|
||||
import Login from "./pages/Login";
|
||||
import EntitiesList from "./pages/EntitiesList";
|
||||
import EntityOverview from "./pages/EntityOverview";
|
||||
import EntityPartners from "./pages/EntityPartners";
|
||||
import EntityDocuments from "./pages/EntityDocuments";
|
||||
import Investments from "./pages/Investments";
|
||||
import ValuationWorkflow from "./pages/ValuationWorkflow";
|
||||
import Import from "./pages/Import";
|
||||
import AuditLog from "./pages/AuditLog";
|
||||
import Users from "./pages/Users";
|
||||
import Documents from "./pages/Documents";
|
||||
import CapitalAccounts from "./pages/CapitalAccounts";
|
||||
import AccessGrid from "./pages/AccessGrid";
|
||||
import PortalLayout from "./portal/PortalLayout";
|
||||
import InvestorHome from "./portal/InvestorHome";
|
||||
import FundAdminHome from "./portal/FundAdminHome";
|
||||
|
||||
function InternalApp() {
|
||||
return (
|
||||
<Layout>
|
||||
<Routes>
|
||||
<Route path="/" element={<EntitiesList />} />
|
||||
<Route path="/entities/:id" element={<EntityOverview />} />
|
||||
<Route path="/entities/:id/partners" element={<EntityPartners />} />
|
||||
<Route path="/entities/:id/documents" element={<EntityDocuments />} />
|
||||
<Route path="/entities/:id/investments" element={<Investments />} />
|
||||
<Route path="/entities/:id/valuation" element={<ValuationWorkflow />} />
|
||||
<Route path="/import" element={<Import />} />
|
||||
<Route path="/audit" element={<AuditLog />} />
|
||||
<Route path="/users" element={<Users />} />
|
||||
<Route path="/access" element={<AccessGrid />} />
|
||||
<Route path="/documents" element={<Documents />} />
|
||||
<Route path="/capital-accounts" element={<CapitalAccounts />} />
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
</Layout>
|
||||
);
|
||||
}
|
||||
|
||||
function ExternalApp() {
|
||||
const { user } = useAuth();
|
||||
return (
|
||||
<PortalLayout>
|
||||
{user?.role === "fund_administrator" ? <FundAdminHome /> : <InvestorHome />}
|
||||
</PortalLayout>
|
||||
);
|
||||
}
|
||||
|
||||
function OfflineNotice({ onRetry }: { onRetry: () => void }) {
|
||||
return (
|
||||
<div className="min-h-screen flex flex-col items-center justify-center gap-4 text-center px-4">
|
||||
<p className="text-gray-700 text-sm">
|
||||
Couldn't reach the server. Check your connection and try again.
|
||||
</p>
|
||||
<button
|
||||
onClick={onRetry}
|
||||
className="px-4 py-2 bg-gray-900 text-white text-sm rounded hover:bg-gray-800"
|
||||
>
|
||||
Retry
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ProtectedRoutes() {
|
||||
const { user, loading } = useAuth();
|
||||
const { user, loading, offline, retry } = useAuth();
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
@@ -21,22 +78,12 @@ function ProtectedRoutes() {
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
return <Login />;
|
||||
// Only show the login screen for a real auth failure; a server we can't reach gets a
|
||||
// retry prompt so a momentary blip doesn't read as "you've been logged out."
|
||||
return offline ? <OfflineNotice onRetry={retry} /> : <Login />;
|
||||
}
|
||||
|
||||
return (
|
||||
<Layout>
|
||||
<Routes>
|
||||
<Route path="/" element={<EntitiesList />} />
|
||||
<Route path="/entities/:id" element={<EntityOverview />} />
|
||||
<Route path="/entities/:id/investments" element={<Investments />} />
|
||||
<Route path="/entities/:id/valuation" element={<ValuationWorkflow />} />
|
||||
<Route path="/import" element={<Import />} />
|
||||
<Route path="/audit" element={<AuditLog />} />
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
</Layout>
|
||||
);
|
||||
return isInternal(user.role) ? <InternalApp /> : <ExternalApp />;
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
|
||||
+294
-5
@@ -4,17 +4,144 @@
|
||||
|
||||
// --- Types ---
|
||||
|
||||
export type UserRole = "approver" | "cfo" | "fund_admin" | "viewer";
|
||||
export type UserRole =
|
||||
| "approver"
|
||||
| "operations"
|
||||
| "cfo"
|
||||
| "fund_admin"
|
||||
| "viewer"
|
||||
| "investor"
|
||||
| "fund_administrator";
|
||||
export type EntityType = "fund" | "spv" | "gp" | "mgmt_co";
|
||||
export type EntityStatus = "active" | "closed";
|
||||
export type RoundStatus = "draft" | "submitted" | "approved" | "returned";
|
||||
export type DocumentCategory =
|
||||
| "capital_account"
|
||||
| "k1"
|
||||
| "statement"
|
||||
| "tax"
|
||||
| "other";
|
||||
|
||||
export const INTERNAL_ROLES: UserRole[] = ["approver", "operations", "cfo", "fund_admin", "viewer"];
|
||||
export const EXTERNAL_ROLES: UserRole[] = ["investor", "fund_administrator"];
|
||||
// Roles that can administer users, documents, and capital accounts (everything except sign-off).
|
||||
export const ADMIN_ROLES: UserRole[] = ["approver", "operations", "cfo"];
|
||||
|
||||
// Roles that can create/edit entities and valuation rounds (staff, excluding read-only viewer).
|
||||
export const WRITER_ROLES: UserRole[] = ["fund_admin", "operations", "cfo", "approver"];
|
||||
|
||||
export const isInternal = (role: UserRole) => INTERNAL_ROLES.includes(role);
|
||||
export const isAdmin = (role: UserRole) => ADMIN_ROLES.includes(role);
|
||||
export const canEditRound = (role: UserRole) => WRITER_ROLES.includes(role);
|
||||
export const isApprover = (role: UserRole) => role === "approver";
|
||||
|
||||
export interface User {
|
||||
id: number;
|
||||
name: string;
|
||||
email: string;
|
||||
username: string;
|
||||
email: string | null;
|
||||
role: UserRole;
|
||||
is_active: boolean;
|
||||
is_service_admin: boolean;
|
||||
primary_account_id: number | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface LinkedAccount {
|
||||
id: number;
|
||||
name: string;
|
||||
username: string;
|
||||
}
|
||||
|
||||
export interface UserDetail extends User {
|
||||
primary_account_name: string | null;
|
||||
linked_accounts: LinkedAccount[];
|
||||
entity_ids: number[];
|
||||
}
|
||||
|
||||
export interface PortalDocument {
|
||||
id: number;
|
||||
entity_id: number;
|
||||
investor_user_id: number | null;
|
||||
category: DocumentCategory;
|
||||
title: string;
|
||||
original_filename: string;
|
||||
content_type: string;
|
||||
size_bytes: number;
|
||||
uploaded_by: number | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface Partner {
|
||||
user_id: number;
|
||||
name: string;
|
||||
username: string;
|
||||
external_investor_id: string | null;
|
||||
is_active: boolean;
|
||||
login_enabled: boolean;
|
||||
latest_commitment_cents: number | null;
|
||||
latest_contributions_cents: number | null;
|
||||
latest_distributions_cents: number | null;
|
||||
latest_value_cents: number | null;
|
||||
latest_as_of: string | null;
|
||||
statements_count: number;
|
||||
}
|
||||
|
||||
export interface AccessGrant {
|
||||
user_id: number;
|
||||
entity_id: number;
|
||||
}
|
||||
|
||||
export interface AccessMatrix {
|
||||
users: User[];
|
||||
entities: Entity[];
|
||||
grants: AccessGrant[];
|
||||
}
|
||||
|
||||
export interface ImportValueRow {
|
||||
row_index: number;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export interface ImportInvestorPreview {
|
||||
source_name: string;
|
||||
column_index: number;
|
||||
value_dollars: number;
|
||||
commitment_dollars: number;
|
||||
contributions_dollars: number;
|
||||
distributions_dollars: number;
|
||||
external_id: string | null;
|
||||
matched_user_id: number | null;
|
||||
matched_username: string | null;
|
||||
suggested_username: string | null;
|
||||
}
|
||||
|
||||
export interface CapitalImportPreview {
|
||||
as_of_date: string | null;
|
||||
value_rows: ImportValueRow[];
|
||||
chosen_row_index: number;
|
||||
investors: ImportInvestorPreview[];
|
||||
}
|
||||
|
||||
export interface CapitalImportResult {
|
||||
status: string;
|
||||
created_accounts: number;
|
||||
matched_accounts_updated: number;
|
||||
statements_written: number;
|
||||
}
|
||||
|
||||
export interface CapitalAccount {
|
||||
id: number;
|
||||
entity_id: number;
|
||||
investor_user_id: number;
|
||||
investor_name: string | null;
|
||||
as_of_date: string;
|
||||
commitment_cents: number;
|
||||
beginning_balance_cents: number;
|
||||
contributions_cents: number;
|
||||
distributions_cents: number;
|
||||
ending_balance_cents: number;
|
||||
document_id: number | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
@@ -80,7 +207,7 @@ export interface AuditEntry {
|
||||
|
||||
// --- API helpers ---
|
||||
|
||||
class ApiError extends Error {
|
||||
export class ApiError extends Error {
|
||||
status: number;
|
||||
constructor(status: number, message: string) {
|
||||
super(message);
|
||||
@@ -106,16 +233,22 @@ async function request<T>(path: string, options?: RequestInit): Promise<T> {
|
||||
// --- Auth ---
|
||||
|
||||
export const api = {
|
||||
login: (email: string, password: string) =>
|
||||
login: (login: string, password: string) =>
|
||||
request<User>("/api/auth/login", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ email, password }),
|
||||
body: JSON.stringify({ login, password }),
|
||||
}),
|
||||
|
||||
logout: () => request<{ status: string }>("/api/auth/logout", { method: "POST" }),
|
||||
|
||||
me: () => request<User>("/api/auth/me"),
|
||||
|
||||
changePassword: (current_password: string, new_password: string) =>
|
||||
request<{ status: string }>("/api/auth/change-password", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ current_password, new_password }),
|
||||
}),
|
||||
|
||||
// Entities
|
||||
listEntities: () => request<Entity[]>("/api/entities"),
|
||||
listEntityRollup: () =>
|
||||
@@ -126,10 +259,12 @@ export const api = {
|
||||
vintage_year: number | null;
|
||||
fund_size_cents: number | null;
|
||||
status: EntityStatus;
|
||||
committed_cents: number;
|
||||
invested_cents: number;
|
||||
last_signed_value_cents: number;
|
||||
}[]>("/api/entities/rollup"),
|
||||
getEntity: (id: number) => request<Entity>(`/api/entities/${id}`),
|
||||
listPartners: (entityId: number) => request<Partner[]>(`/api/entities/${entityId}/partners`),
|
||||
createEntity: (data: Partial<Entity>) =>
|
||||
request<Entity>("/api/entities", { method: "POST", body: JSON.stringify(data) }),
|
||||
updateEntity: (id: number, data: Partial<Entity>) =>
|
||||
@@ -180,4 +315,158 @@ export const api = {
|
||||
if (params?.page) q.set("page", String(params.page));
|
||||
return request<AuditEntry[]>(`/api/audit?${q}`);
|
||||
},
|
||||
|
||||
// Users (admin)
|
||||
listUsers: () => request<User[]>("/api/users"),
|
||||
investorsForEntity: (entityId: number) =>
|
||||
request<User[]>(`/api/users/investors-for-entity/${entityId}`),
|
||||
accessMatrix: () => request<AccessMatrix>("/api/users/access-matrix"),
|
||||
grantAccess: (userId: number, entityId: number) =>
|
||||
request<{ status: string }>(`/api/users/${userId}/access/${entityId}`, { method: "PUT" }),
|
||||
revokeAccess: (userId: number, entityId: number) =>
|
||||
request<{ status: string }>(`/api/users/${userId}/access/${entityId}`, { method: "DELETE" }),
|
||||
|
||||
// Holdings / NAV import (eNAV HLD tab)
|
||||
scheduleImport: async (
|
||||
file: File,
|
||||
opts: {
|
||||
commit: boolean;
|
||||
entityId?: number | null;
|
||||
password?: string;
|
||||
asOf?: string;
|
||||
createType?: EntityType;
|
||||
vintageYear?: string;
|
||||
replaceExisting?: boolean;
|
||||
},
|
||||
): Promise<any> => {
|
||||
const form = new FormData();
|
||||
form.set("file", file);
|
||||
if (opts.password) form.set("password", opts.password);
|
||||
const p = new URLSearchParams();
|
||||
p.set("commit", String(opts.commit));
|
||||
if (opts.replaceExisting) p.set("replace_existing", "true");
|
||||
if (opts.asOf) p.set("as_of", opts.asOf);
|
||||
if (opts.entityId != null) {
|
||||
p.set("entity_id", String(opts.entityId));
|
||||
} else {
|
||||
p.set("create_entity_type", opts.createType || "fund");
|
||||
if (opts.vintageYear) p.set("create_vintage_year", opts.vintageYear);
|
||||
}
|
||||
const res = await fetch(`/api/import/schedule?${p}`, { method: "POST", body: form });
|
||||
const data = await res.json().catch(() => ({ detail: res.statusText }));
|
||||
if (!res.ok) throw new ApiError(res.status, data.detail || "Import failed");
|
||||
return data;
|
||||
},
|
||||
|
||||
// Capital-account import (fund-admin spreadsheet)
|
||||
capitalImportPreview: async (
|
||||
file: File,
|
||||
entityId: number,
|
||||
rowIndex?: number,
|
||||
password?: string,
|
||||
): Promise<CapitalImportPreview> => {
|
||||
const form = new FormData();
|
||||
form.set("file", file);
|
||||
form.set("entity_id", String(entityId));
|
||||
if (rowIndex != null) form.set("row_index", String(rowIndex));
|
||||
if (password) form.set("password", password);
|
||||
const res = await fetch("/api/import/capital-accounts/preview", { method: "POST", body: form });
|
||||
if (!res.ok) {
|
||||
const body = await res.json().catch(() => ({ detail: res.statusText }));
|
||||
throw new ApiError(res.status, body.detail || res.statusText);
|
||||
}
|
||||
return res.json();
|
||||
},
|
||||
capitalImportCommit: (data: {
|
||||
entity_id: number;
|
||||
as_of_date: string;
|
||||
investors: {
|
||||
action: "match" | "create" | "skip";
|
||||
value_dollars: number;
|
||||
commitment_dollars?: number;
|
||||
contributions_dollars?: number;
|
||||
distributions_dollars?: number;
|
||||
user_id?: number | null;
|
||||
name?: string | null;
|
||||
username?: string | null;
|
||||
email?: string | null;
|
||||
password?: string | null;
|
||||
external_id?: string | null;
|
||||
}[];
|
||||
}) =>
|
||||
request<CapitalImportResult>("/api/import/capital-accounts/commit", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(data),
|
||||
}),
|
||||
getUser: (id: number) => request<UserDetail>(`/api/users/${id}`),
|
||||
createUser: (data: {
|
||||
name: string;
|
||||
username: string;
|
||||
password: string;
|
||||
role: UserRole;
|
||||
email?: string | null;
|
||||
entity_ids?: number[];
|
||||
}) => request<UserDetail>("/api/users", { method: "POST", body: JSON.stringify(data) }),
|
||||
updateUser: (
|
||||
id: number,
|
||||
data: Partial<{
|
||||
name: string;
|
||||
username: string;
|
||||
email: string | null;
|
||||
role: UserRole;
|
||||
is_active: boolean;
|
||||
entity_ids: number[];
|
||||
}>,
|
||||
) => request<UserDetail>(`/api/users/${id}`, { method: "PATCH", body: JSON.stringify(data) }),
|
||||
resetPassword: (id: number, password: string) =>
|
||||
request<{ status: string }>(`/api/users/${id}/reset-password`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ password }),
|
||||
}),
|
||||
linkAccount: (id: number, primary_account_id: number | null) =>
|
||||
request<UserDetail>(`/api/users/${id}/primary-account`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({ primary_account_id }),
|
||||
}),
|
||||
|
||||
// Documents
|
||||
listDocuments: (params?: { entity_id?: number; investor_user_id?: number }) => {
|
||||
const q = new URLSearchParams();
|
||||
if (params?.entity_id != null) q.set("entity_id", String(params.entity_id));
|
||||
if (params?.investor_user_id != null) q.set("investor_user_id", String(params.investor_user_id));
|
||||
const qs = q.toString();
|
||||
return request<PortalDocument[]>(`/api/documents${qs ? `?${qs}` : ""}`);
|
||||
},
|
||||
uploadDocument: async (form: FormData): Promise<PortalDocument> => {
|
||||
const res = await fetch("/api/documents", { method: "POST", body: form });
|
||||
if (!res.ok) {
|
||||
const body = await res.json().catch(() => ({ detail: res.statusText }));
|
||||
throw new ApiError(res.status, body.detail || res.statusText);
|
||||
}
|
||||
return res.json();
|
||||
},
|
||||
downloadUrl: (id: number) => `/api/documents/${id}/download`,
|
||||
deleteDocument: (id: number) =>
|
||||
request<{ status: string }>(`/api/documents/${id}`, { method: "DELETE" }),
|
||||
|
||||
// Capital accounts
|
||||
listCapitalAccounts: (params?: { entity_id?: number; investor_user_id?: number }) => {
|
||||
const q = new URLSearchParams();
|
||||
if (params?.entity_id != null) q.set("entity_id", String(params.entity_id));
|
||||
if (params?.investor_user_id != null) q.set("investor_user_id", String(params.investor_user_id));
|
||||
const qs = q.toString();
|
||||
return request<CapitalAccount[]>(`/api/capital-accounts${qs ? `?${qs}` : ""}`);
|
||||
},
|
||||
createCapitalAccount: (data: {
|
||||
entity_id: number;
|
||||
investor_user_id: number;
|
||||
as_of_date: string;
|
||||
beginning_balance_dollars: number;
|
||||
contributions_dollars: number;
|
||||
distributions_dollars: number;
|
||||
ending_balance_dollars: number;
|
||||
document_id?: number | null;
|
||||
}) => request<CapitalAccount>("/api/capital-accounts", { method: "POST", body: JSON.stringify(data) }),
|
||||
deleteCapitalAccount: (id: number) =>
|
||||
request<{ status: string }>(`/api/capital-accounts/${id}`, { method: "DELETE" }),
|
||||
};
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { createContext, useContext, useEffect, useState, type ReactNode } from "react";
|
||||
import { api, type User } from "../api";
|
||||
import { createContext, useCallback, useContext, useEffect, useState, type ReactNode } from "react";
|
||||
import { api, ApiError, type User } from "../api";
|
||||
|
||||
interface AuthState {
|
||||
user: User | null;
|
||||
loading: boolean;
|
||||
login: (email: string, password: string) => Promise<void>;
|
||||
offline: boolean; // couldn't reach the server (vs. genuinely logged out)
|
||||
retry: () => void;
|
||||
login: (handle: string, password: string) => Promise<void>;
|
||||
logout: () => Promise<void>;
|
||||
}
|
||||
|
||||
@@ -13,14 +15,29 @@ const AuthContext = createContext<AuthState | null>(null);
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [offline, setOffline] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
api.me().then(setUser).catch(() => setUser(null)).finally(() => setLoading(false));
|
||||
const bootstrap = useCallback(() => {
|
||||
setLoading(true);
|
||||
api
|
||||
.me()
|
||||
.then((u) => { setUser(u); setOffline(false); })
|
||||
.catch((err) => {
|
||||
setUser(null);
|
||||
// A 401/403 means genuinely logged out. A network error or 5xx means we couldn't
|
||||
// reach the server — don't present that as "you're logged out."
|
||||
const authFailure = err instanceof ApiError && (err.status === 401 || err.status === 403);
|
||||
setOffline(!authFailure);
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
const login = async (email: string, password: string) => {
|
||||
const u = await api.login(email, password);
|
||||
useEffect(() => { bootstrap(); }, [bootstrap]);
|
||||
|
||||
const login = async (handle: string, password: string) => {
|
||||
const u = await api.login(handle, password);
|
||||
setUser(u);
|
||||
setOffline(false);
|
||||
};
|
||||
|
||||
const logout = async () => {
|
||||
@@ -29,7 +46,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
};
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ user, loading, login, logout }}>
|
||||
<AuthContext.Provider value={{ user, loading, offline, retry: bootstrap, login, logout }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { api, type AuditEntry } from "../api";
|
||||
import { Fragment, useEffect, useState } from "react";
|
||||
import { api, isAdmin, type AuditEntry } from "../api";
|
||||
import { useAuth } from "../context/AuthContext";
|
||||
import { formatDate } from "../format";
|
||||
|
||||
@@ -9,8 +9,9 @@ export default function AuditLog() {
|
||||
const [page, setPage] = useState(1);
|
||||
const [filterType, setFilterType] = useState("");
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [expandedId, setExpandedId] = useState<number | null>(null);
|
||||
|
||||
const canView = user && ["approver", "cfo"].includes(user.role);
|
||||
const canView = user && isAdmin(user.role);
|
||||
|
||||
useEffect(() => {
|
||||
if (!canView) return;
|
||||
@@ -32,7 +33,7 @@ export default function AuditLog() {
|
||||
if (!canView) {
|
||||
return (
|
||||
<div className="text-gray-500 text-sm">
|
||||
Audit log requires approver or CFO role.
|
||||
Audit log requires Managing Partner, Operations, or CFO role.
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -73,7 +74,7 @@ export default function AuditLog() {
|
||||
<div className="text-gray-500 text-sm">Loading...</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="bg-white border border-gray-200 rounded-lg overflow-hidden">
|
||||
<div className="bg-white border border-gray-200 rounded-lg overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="bg-gray-50 border-b border-gray-200">
|
||||
@@ -86,8 +87,13 @@ export default function AuditLog() {
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{entries.map((e) => (
|
||||
<tr key={e.id} className="border-b border-gray-100">
|
||||
{entries.map((e) => {
|
||||
const hasDetail = e.detail != null;
|
||||
const detailText = hasDetail ? JSON.stringify(e.detail) : "—";
|
||||
const expanded = expandedId === e.id;
|
||||
return (
|
||||
<Fragment key={e.id}>
|
||||
<tr className="border-b border-gray-100">
|
||||
<td className="px-4 py-2 text-gray-600 whitespace-nowrap">
|
||||
{formatDate(e.created_at)}
|
||||
</td>
|
||||
@@ -99,11 +105,32 @@ export default function AuditLog() {
|
||||
<td className="px-4 py-2 text-gray-700">{e.object_type}</td>
|
||||
<td className="px-4 py-2 text-gray-500">{e.object_id ?? "—"}</td>
|
||||
<td className="px-4 py-2 text-gray-600">#{e.actor_user_id ?? "system"}</td>
|
||||
<td className="px-4 py-2 text-gray-500 text-xs max-w-xs truncate">
|
||||
{e.detail ? JSON.stringify(e.detail) : "—"}
|
||||
<td className="px-4 py-2 text-gray-500 text-xs">
|
||||
{hasDetail ? (
|
||||
<button
|
||||
onClick={() => setExpandedId(expanded ? null : e.id)}
|
||||
title={detailText}
|
||||
className="block max-w-xs truncate text-left hover:text-gray-700 underline decoration-dotted"
|
||||
>
|
||||
{detailText}
|
||||
</button>
|
||||
) : (
|
||||
"—"
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{expanded && hasDetail && (
|
||||
<tr className="border-b border-gray-100 bg-gray-50">
|
||||
<td colSpan={6} className="px-4 py-2">
|
||||
<pre className="text-xs text-gray-700 whitespace-pre-wrap break-all">
|
||||
{JSON.stringify(e.detail, null, 2)}
|
||||
</pre>
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
{entries.length === 0 && (
|
||||
<tr>
|
||||
<td className="px-4 py-6 text-center text-gray-400" colSpan={6}>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { api, type EntityType } from "../api";
|
||||
import { api, WRITER_ROLES, type EntityType } from "../api";
|
||||
import { useAuth } from "../context/AuthContext";
|
||||
import { formatMoney, formatGainLoss } from "../format";
|
||||
|
||||
@@ -11,6 +11,7 @@ interface EntityRow {
|
||||
vintage_year: number | null;
|
||||
fund_size_cents: number | null;
|
||||
status: string;
|
||||
committedCents: number;
|
||||
investedCents: number;
|
||||
lastValueCents: number;
|
||||
}
|
||||
@@ -22,8 +23,6 @@ const TYPE_LABELS: Record<string, string> = {
|
||||
mgmt_co: "Mgmt Co",
|
||||
};
|
||||
|
||||
const WRITER_ROLES = ["fund_admin", "cfo", "approver"];
|
||||
|
||||
export default function EntitiesList() {
|
||||
const { user } = useAuth();
|
||||
const [entities, setEntities] = useState<EntityRow[]>([]);
|
||||
@@ -48,6 +47,7 @@ export default function EntitiesList() {
|
||||
vintage_year: r.vintage_year,
|
||||
fund_size_cents: r.fund_size_cents,
|
||||
status: r.status,
|
||||
committedCents: r.committed_cents,
|
||||
investedCents: r.invested_cents,
|
||||
lastValueCents: r.last_signed_value_cents,
|
||||
})),
|
||||
@@ -219,28 +219,126 @@ function AddEntityForm({
|
||||
);
|
||||
}
|
||||
|
||||
type SortKey = "name" | "type" | "vintage" | "committed" | "invested" | "value" | "gain";
|
||||
|
||||
function EntityTable({ title, rows }: { title: string; rows: EntityRow[] }) {
|
||||
const [sortKey, setSortKey] = useState<SortKey>("name");
|
||||
const [dir, setDir] = useState<1 | -1>(1);
|
||||
|
||||
const totalCommitted = rows.reduce((s, r) => s + r.committedCents, 0);
|
||||
const totalInvested = rows.reduce((s, r) => s + r.investedCents, 0);
|
||||
const totalValue = rows.reduce((s, r) => s + r.lastValueCents, 0);
|
||||
const totalGain = totalValue - totalInvested;
|
||||
|
||||
const sorted = useMemo(() => {
|
||||
const val = (r: EntityRow): string | number => {
|
||||
switch (sortKey) {
|
||||
case "name": return r.name.toLowerCase();
|
||||
case "type": return r.type;
|
||||
case "vintage": return r.vintage_year ?? -Infinity;
|
||||
case "committed": return r.committedCents;
|
||||
case "invested": return r.investedCents;
|
||||
case "value": return r.lastValueCents;
|
||||
case "gain": return r.lastValueCents - r.investedCents;
|
||||
}
|
||||
};
|
||||
return [...rows].sort((a, b) => {
|
||||
const av = val(a), bv = val(b);
|
||||
if (av < bv) return -1 * dir;
|
||||
if (av > bv) return 1 * dir;
|
||||
return 0;
|
||||
});
|
||||
}, [rows, sortKey, dir]);
|
||||
|
||||
const sortBy = (key: SortKey) => {
|
||||
if (key === sortKey) setDir((d) => (d === 1 ? -1 : 1));
|
||||
else { setSortKey(key); setDir(1); }
|
||||
};
|
||||
|
||||
const arrow = (key: SortKey) => (sortKey === key ? (dir === 1 ? " ↑" : " ↓") : "");
|
||||
const Th = ({ k, label, align = "left" }: { k: SortKey; label: string; align?: "left" | "right" }) => {
|
||||
const a = align === "right" ? "text-right" : "text-left";
|
||||
return (
|
||||
<th className={`px-4 py-3 font-medium text-gray-600 select-none ${a}`}>
|
||||
<button onClick={() => sortBy(k)} className={`w-full hover:text-gray-900 ${a}`}>
|
||||
{label}<span className="text-orange-500">{arrow(k)}</span>
|
||||
</button>
|
||||
</th>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold text-gray-900 mb-3">{title}</h2>
|
||||
<div className="bg-white border border-gray-200 rounded-lg overflow-hidden">
|
||||
<table className="w-full text-sm">
|
||||
|
||||
{/* Mobile: stacked cards (a wide financial table doesn't fit a phone) */}
|
||||
<div className="md:hidden space-y-3">
|
||||
{sorted.map((row) => {
|
||||
const gl = formatGainLoss(row.lastValueCents, row.investedCents);
|
||||
return (
|
||||
<Link
|
||||
key={row.id}
|
||||
to={`/entities/${row.id}`}
|
||||
className="block bg-white border border-gray-200 rounded-lg p-4 active:bg-gray-50"
|
||||
>
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<span className="font-medium text-gray-900">{row.name}</span>
|
||||
<span className="shrink-0 inline-block px-2 py-0.5 bg-gray-100 text-gray-600 text-xs rounded">
|
||||
{TYPE_LABELS[row.type] || row.type}
|
||||
</span>
|
||||
</div>
|
||||
{row.vintage_year && (
|
||||
<div className="mt-0.5 text-xs text-gray-400">Vintage {row.vintage_year}</div>
|
||||
)}
|
||||
<div className="grid grid-cols-2 gap-x-4 gap-y-2 mt-3">
|
||||
<CardMetric label="Committed" value={formatMoney(row.committedCents)} />
|
||||
<CardMetric label="Invested" value={formatMoney(row.investedCents)} />
|
||||
<CardMetric label="Last value" value={formatMoney(row.lastValueCents)} />
|
||||
<CardMetric
|
||||
label="Gain/Loss"
|
||||
value={`${gl.positive ? "+" : "-"}${gl.text}`}
|
||||
valueClass={gl.positive ? "text-green-600" : "text-red-600"}
|
||||
/>
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
{rows.length > 0 && (
|
||||
<div className="bg-gray-50 border border-gray-200 rounded-lg p-4">
|
||||
<div className="text-xs font-medium text-gray-500 uppercase mb-2">Total</div>
|
||||
<div className="grid grid-cols-2 gap-x-4 gap-y-2">
|
||||
<CardMetric label="Committed" value={formatMoney(totalCommitted)} />
|
||||
<CardMetric label="Invested" value={formatMoney(totalInvested)} />
|
||||
<CardMetric label="Last value" value={formatMoney(totalValue)} />
|
||||
<CardMetric
|
||||
label="Gain/Loss"
|
||||
value={`${totalGain >= 0 ? "+" : "-"}${formatMoney(Math.abs(totalGain))}`}
|
||||
valueClass={totalGain >= 0 ? "text-green-600" : "text-red-600"}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{rows.length === 0 && (
|
||||
<p className="text-sm text-gray-400 px-1">No entities yet.</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Desktop: full sortable table */}
|
||||
<div className="hidden md:block bg-white border border-gray-200 rounded-lg overflow-x-auto">
|
||||
<table className="w-full min-w-[46rem] text-sm">
|
||||
<thead>
|
||||
<tr className="bg-gray-50 border-b border-gray-200">
|
||||
<th className="text-left px-4 py-3 font-medium text-gray-600">Name</th>
|
||||
<th className="text-left px-4 py-3 font-medium text-gray-600">Type</th>
|
||||
<th className="text-left px-4 py-3 font-medium text-gray-600">Vintage</th>
|
||||
<th className="text-right px-4 py-3 font-medium text-gray-600">Invested</th>
|
||||
<th className="text-right px-4 py-3 font-medium text-gray-600">Last Signed Value</th>
|
||||
<th className="text-right px-4 py-3 font-medium text-gray-600">Gain/Loss</th>
|
||||
<Th k="name" label="Name" />
|
||||
<Th k="type" label="Type" />
|
||||
<Th k="vintage" label="Vintage" />
|
||||
<Th k="committed" label="Committed" align="right" />
|
||||
<Th k="invested" label="Invested" align="right" />
|
||||
<Th k="value" label="Last Signed Value" align="right" />
|
||||
<Th k="gain" label="Gain/Loss" align="right" />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((row) => {
|
||||
{sorted.map((row) => {
|
||||
const gl = formatGainLoss(row.lastValueCents, row.investedCents);
|
||||
return (
|
||||
<tr key={row.id} className="border-b border-gray-100 hover:bg-gray-50">
|
||||
@@ -258,6 +356,7 @@ function EntityTable({ title, rows }: { title: string; rows: EntityRow[] }) {
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-gray-600">{row.vintage_year || "—"}</td>
|
||||
<td className="px-4 py-3 text-right text-gray-900">{formatMoney(row.committedCents)}</td>
|
||||
<td className="px-4 py-3 text-right text-gray-900">{formatMoney(row.investedCents)}</td>
|
||||
<td className="px-4 py-3 text-right text-gray-900">{formatMoney(row.lastValueCents)}</td>
|
||||
<td className={`px-4 py-3 text-right font-medium ${gl.positive ? "text-green-600" : "text-red-600"}`}>
|
||||
@@ -271,6 +370,7 @@ function EntityTable({ title, rows }: { title: string; rows: EntityRow[] }) {
|
||||
<td className="px-4 py-3 text-gray-900" colSpan={3}>
|
||||
Total
|
||||
</td>
|
||||
<td className="px-4 py-3 text-right text-gray-900">{formatMoney(totalCommitted)}</td>
|
||||
<td className="px-4 py-3 text-right text-gray-900">{formatMoney(totalInvested)}</td>
|
||||
<td className="px-4 py-3 text-right text-gray-900">{formatMoney(totalValue)}</td>
|
||||
<td className={`px-4 py-3 text-right ${totalGain >= 0 ? "text-green-600" : "text-red-600"}`}>
|
||||
@@ -280,7 +380,7 @@ function EntityTable({ title, rows }: { title: string; rows: EntityRow[] }) {
|
||||
)}
|
||||
{rows.length === 0 && (
|
||||
<tr>
|
||||
<td className="px-4 py-6 text-center text-gray-400" colSpan={6}>
|
||||
<td className="px-4 py-6 text-center text-gray-400" colSpan={7}>
|
||||
No entities yet.
|
||||
</td>
|
||||
</tr>
|
||||
@@ -291,3 +391,20 @@ function EntityTable({ title, rows }: { title: string; rows: EntityRow[] }) {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CardMetric({
|
||||
label,
|
||||
value,
|
||||
valueClass = "text-gray-900",
|
||||
}: {
|
||||
label: string;
|
||||
value: string;
|
||||
valueClass?: string;
|
||||
}) {
|
||||
return (
|
||||
<div>
|
||||
<div className="text-xs text-gray-400 uppercase">{label}</div>
|
||||
<div className={`text-sm font-medium ${valueClass}`}>{value}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
+317
-293
@@ -1,382 +1,406 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { api, type Entity, type EntityType } from "../api";
|
||||
import { useEffect, useState } from "react";
|
||||
import { api, isAdmin, type Entity, type EntityType, type CapitalImportPreview } from "../api";
|
||||
import { useAuth } from "../context/AuthContext";
|
||||
import { formatMoneyExact } from "../format";
|
||||
|
||||
type EntityMode = "existing" | "from_file";
|
||||
|
||||
type Decision = {
|
||||
action: "match" | "create" | "skip";
|
||||
source_name: string;
|
||||
external_id: string | null;
|
||||
matched_username: string | null;
|
||||
user_id: number | null;
|
||||
value_dollars: number;
|
||||
commitment_dollars: number;
|
||||
contributions_dollars: number;
|
||||
distributions_dollars: number;
|
||||
// create fields
|
||||
name: string;
|
||||
username: string;
|
||||
email: string;
|
||||
};
|
||||
|
||||
export default function Import() {
|
||||
const { user } = useAuth();
|
||||
const [entities, setEntities] = useState<Entity[]>([]);
|
||||
const [entityMode, setEntityMode] = useState<EntityMode>("from_file");
|
||||
const [entityMode, setEntityMode] = useState<EntityMode>("existing");
|
||||
const [entityId, setEntityId] = useState("");
|
||||
const [createType, setCreateType] = useState<EntityType>("fund");
|
||||
const [vintageYear, setVintageYear] = useState("");
|
||||
const [asOf, setAsOf] = useState("");
|
||||
const [mode, setMode] = useState<"entities" | "schedule">("schedule");
|
||||
const [commit, setCommit] = useState(false);
|
||||
const [password, setPassword] = useState("");
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const [replaceExisting, setReplaceExisting] = useState(false);
|
||||
|
||||
const [holdings, setHoldings] = useState<{ count: number; nav: number; sourceName: string | null } | null>(null);
|
||||
const [memberPv, setMemberPv] = useState<CapitalImportPreview | null>(null);
|
||||
const [decisions, setDecisions] = useState<Decision[]>([]);
|
||||
const [asOf, setAsOf] = useState("");
|
||||
|
||||
const [result, setResult] = useState<any>(null);
|
||||
const [error, setError] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const fileRef = useRef<HTMLInputElement>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [step, setStep] = useState("");
|
||||
const [confirmReplace, setConfirmReplace] = useState(false);
|
||||
|
||||
const canImport = user && ["approver", "cfo"].includes(user.role);
|
||||
const canImport = user && isAdmin(user.role);
|
||||
const inputCls = "w-full px-3 py-2 border border-gray-300 rounded text-sm";
|
||||
|
||||
useEffect(() => {
|
||||
api.listEntities().then(setEntities);
|
||||
}, []);
|
||||
|
||||
async function handleImport() {
|
||||
if (!file) return;
|
||||
setError("");
|
||||
function reset() {
|
||||
setHoldings(null);
|
||||
setMemberPv(null);
|
||||
setDecisions([]);
|
||||
setResult(null);
|
||||
setLoading(true);
|
||||
setReplaceExisting(false);
|
||||
}
|
||||
|
||||
try {
|
||||
const form = new FormData();
|
||||
form.append("file", file);
|
||||
|
||||
const params = new URLSearchParams();
|
||||
params.set("commit", String(commit));
|
||||
|
||||
let url: string;
|
||||
if (mode === "entities") {
|
||||
url = `/api/import/entities?${params}`;
|
||||
} else {
|
||||
if (!asOf) {
|
||||
setError("Quarter-end date is required.");
|
||||
setLoading(false);
|
||||
async function readEnav() {
|
||||
if (!file) return;
|
||||
if (entityMode === "existing" && !entityId) {
|
||||
setError("Select the fund, or choose 'Create from file'.");
|
||||
return;
|
||||
}
|
||||
params.set("as_of", asOf);
|
||||
setError("");
|
||||
setBusy(true);
|
||||
setResult(null);
|
||||
try {
|
||||
const eid = entityMode === "existing" ? Number(entityId) : undefined;
|
||||
// Holdings (dry run) + members preview from the same file.
|
||||
const [sched, members] = await Promise.all([
|
||||
api.scheduleImport(file, {
|
||||
commit: false,
|
||||
entityId: eid,
|
||||
password: password || undefined,
|
||||
createType,
|
||||
vintageYear,
|
||||
}),
|
||||
api.capitalImportPreview(file, eid as number, undefined, password || undefined),
|
||||
]);
|
||||
|
||||
const nav = (sched.positions || []).reduce((s: number, p: any) => s + (p.value_cents || 0), 0);
|
||||
setHoldings({
|
||||
count: sched.positions?.length ?? 0,
|
||||
nav,
|
||||
sourceName: sched.source_entity_name ?? null,
|
||||
});
|
||||
setAsOf(members.as_of_date ?? sched.seed_round?.quarter_end ?? "");
|
||||
setMemberPv(members);
|
||||
setDecisions(
|
||||
members.investors.map((i) => ({
|
||||
action: i.matched_user_id ? "match" : "create",
|
||||
source_name: i.source_name,
|
||||
external_id: i.external_id,
|
||||
matched_username: i.matched_username,
|
||||
user_id: i.matched_user_id,
|
||||
value_dollars: i.value_dollars,
|
||||
commitment_dollars: i.commitment_dollars,
|
||||
contributions_dollars: i.contributions_dollars,
|
||||
distributions_dollars: i.distributions_dollars,
|
||||
name: i.source_name,
|
||||
username: i.suggested_username ?? "",
|
||||
email: "",
|
||||
})),
|
||||
);
|
||||
} catch (e: any) {
|
||||
setError(e.message || "Could not read the workbook");
|
||||
reset();
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
const update = (idx: number, patch: Partial<Decision>) =>
|
||||
setDecisions((d) => d.map((row, i) => (i === idx ? { ...row, ...patch } : row)));
|
||||
|
||||
// The "Confirm import" button routes through here so a destructive holdings-replace gets a
|
||||
// final confirmation before anything is cleared.
|
||||
function handleConfirmClick() {
|
||||
if (entityMode === "existing" && replaceExisting) {
|
||||
setConfirmReplace(true);
|
||||
return;
|
||||
}
|
||||
confirmImport();
|
||||
}
|
||||
|
||||
async function confirmImport() {
|
||||
if (!file || !asOf) return;
|
||||
setConfirmReplace(false);
|
||||
setError("");
|
||||
setBusy(true);
|
||||
try {
|
||||
const memberPayload = {
|
||||
as_of_date: asOf,
|
||||
investors: decisions.map((d) => ({
|
||||
action: d.action,
|
||||
value_dollars: d.value_dollars,
|
||||
commitment_dollars: d.commitment_dollars,
|
||||
contributions_dollars: d.contributions_dollars,
|
||||
distributions_dollars: d.distributions_dollars,
|
||||
user_id: d.action === "match" ? d.user_id : undefined,
|
||||
name: d.action === "create" ? d.name : undefined,
|
||||
username: d.action === "create" ? d.username : undefined,
|
||||
email: d.action === "create" ? d.email || undefined : undefined,
|
||||
external_id: d.external_id || undefined,
|
||||
})),
|
||||
};
|
||||
|
||||
let resolvedEntityId: number;
|
||||
let holdingsNote = "";
|
||||
|
||||
if (entityMode === "existing") {
|
||||
if (!entityId) {
|
||||
setError("Select an entity.");
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
params.set("entity_id", entityId);
|
||||
resolvedEntityId = Number(entityId);
|
||||
// Members first (idempotent), then holdings.
|
||||
setStep("Saving members…");
|
||||
await api.capitalImportCommit({ entity_id: resolvedEntityId, ...memberPayload });
|
||||
setStep(replaceExisting ? "Replacing holdings…" : "Loading holdings…");
|
||||
try {
|
||||
await api.scheduleImport(file, {
|
||||
commit: true,
|
||||
entityId: resolvedEntityId,
|
||||
password: password || undefined,
|
||||
asOf,
|
||||
replaceExisting,
|
||||
});
|
||||
} catch (e: any) {
|
||||
if (String(e.message).toLowerCase().includes("already exists")) {
|
||||
holdingsNote = "A signed valuation round exists for this quarter — holdings left unchanged.";
|
||||
} else {
|
||||
// from_file mode: let backend resolve from row 1
|
||||
params.set("create_entity_type", createType);
|
||||
if (vintageYear) params.set("create_vintage_year", vintageYear);
|
||||
throw e;
|
||||
}
|
||||
url = `/api/import/schedule?${params}`;
|
||||
}
|
||||
} else {
|
||||
// Create-from-file: holdings commit creates the fund, then members.
|
||||
setStep("Creating fund and loading holdings…");
|
||||
const sres = await api.scheduleImport(file, {
|
||||
commit: true,
|
||||
password: password || undefined,
|
||||
asOf,
|
||||
createType,
|
||||
vintageYear,
|
||||
});
|
||||
resolvedEntityId = sres.entity.entity_id;
|
||||
setStep("Saving members…");
|
||||
await api.capitalImportCommit({ entity_id: resolvedEntityId, ...memberPayload });
|
||||
}
|
||||
|
||||
const res = await fetch(url, { method: "POST", body: form });
|
||||
let data: any;
|
||||
try {
|
||||
data = await res.json();
|
||||
} catch {
|
||||
setError(`Server error (${res.status}). Check file format and try again.`);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
if (!res.ok) {
|
||||
setError(data.detail || "Import failed");
|
||||
} else {
|
||||
setResult(data);
|
||||
// Refresh entity list after commit
|
||||
if (data.committed) {
|
||||
setResult({
|
||||
holdings: holdings?.count ?? 0,
|
||||
nav: holdings?.nav ?? 0,
|
||||
members: decisions.filter((d) => d.action !== "skip").length,
|
||||
created: decisions.filter((d) => d.action === "create").length,
|
||||
note: holdingsNote,
|
||||
});
|
||||
reset();
|
||||
api.listEntities().then(setEntities);
|
||||
}
|
||||
}
|
||||
} catch (err: any) {
|
||||
setError(err.message);
|
||||
} catch (e: any) {
|
||||
setError(e.message || "Import failed");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setBusy(false);
|
||||
setStep("");
|
||||
}
|
||||
}
|
||||
|
||||
if (!canImport) {
|
||||
return (
|
||||
<div className="text-gray-500 text-sm">
|
||||
Import requires approver or CFO role.
|
||||
</div>
|
||||
);
|
||||
return <div className="text-gray-500 text-sm">Import requires Managing Partner, Operations, or CFO role.</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="max-w-2xl">
|
||||
<h1 className="text-2xl font-semibold text-gray-900 mb-6">Import</h1>
|
||||
<div className="max-w-4xl">
|
||||
<h1 className="text-2xl font-semibold text-gray-900 mb-1">Import eNAV</h1>
|
||||
<p className="text-sm text-gray-500 mb-6">
|
||||
Upload the fund administrator's eNAV workbook once. Portal loads the fund's holdings and NAV
|
||||
(HLD tab) and the members with their capital — commitment, paid-in, distributions, and
|
||||
current value (ALLOC SI tab). You confirm new members before anything is saved.
|
||||
</p>
|
||||
|
||||
{/* Mode selector */}
|
||||
<div className="flex gap-4 mb-6">
|
||||
<button
|
||||
onClick={() => setMode("schedule")}
|
||||
className={`px-4 py-2 text-sm rounded ${
|
||||
mode === "schedule"
|
||||
? "bg-gray-900 text-white"
|
||||
: "bg-gray-100 text-gray-700 hover:bg-gray-200"
|
||||
}`}
|
||||
>
|
||||
Schedule of Investments
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setMode("entities")}
|
||||
className={`px-4 py-2 text-sm rounded ${
|
||||
mode === "entities"
|
||||
? "bg-gray-900 text-white"
|
||||
: "bg-gray-100 text-gray-700 hover:bg-gray-200"
|
||||
}`}
|
||||
>
|
||||
Entities
|
||||
{error && <div className="p-3 bg-red-50 border border-red-200 rounded text-sm text-red-700 mb-4">{error}</div>}
|
||||
|
||||
{result ? (
|
||||
<div className="bg-green-50 border border-green-200 rounded-lg p-4 text-sm">
|
||||
<p className="font-medium text-green-800">Import complete.</p>
|
||||
<ul className="mt-2 text-green-700 list-disc list-inside">
|
||||
<li>{result.holdings} holdings loaded · NAV {formatMoneyExact(result.nav)}</li>
|
||||
<li>{result.members} members ({result.created} newly created)</li>
|
||||
{result.note && <li className="text-amber-700">{result.note}</li>}
|
||||
</ul>
|
||||
<button onClick={() => setResult(null)} className="mt-3 px-3 py-1.5 bg-gray-900 text-white rounded hover:bg-gray-800">
|
||||
Import another
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="bg-white border border-gray-200 rounded-lg p-6 space-y-4">
|
||||
{mode === "schedule" && (
|
||||
<>
|
||||
{/* Entity resolution mode */}
|
||||
) : (
|
||||
<div className="bg-white border border-gray-200 rounded-lg p-4 space-y-3">
|
||||
<div>
|
||||
<label className="block text-sm text-gray-700 mb-2">Entity</label>
|
||||
<div className="flex gap-4 mb-3">
|
||||
<label className="block text-sm text-gray-700 mb-2">Fund</label>
|
||||
<div className="flex gap-4 mb-2">
|
||||
<label className="flex items-center gap-2 text-sm text-gray-700 cursor-pointer">
|
||||
<input
|
||||
type="radio"
|
||||
name="entityMode"
|
||||
checked={entityMode === "from_file"}
|
||||
onChange={() => setEntityMode("from_file")}
|
||||
className="text-orange-500"
|
||||
/>
|
||||
<input type="radio" checked={entityMode === "existing"} onChange={() => { setEntityMode("existing"); reset(); }} className="text-orange-500" />
|
||||
Use existing fund
|
||||
</label>
|
||||
<label className="flex items-center gap-2 text-sm text-gray-700 cursor-pointer">
|
||||
<input type="radio" checked={entityMode === "from_file"} onChange={() => { setEntityMode("from_file"); reset(); }} className="text-orange-500" />
|
||||
Create from file
|
||||
</label>
|
||||
<label className="flex items-center gap-2 text-sm text-gray-700 cursor-pointer">
|
||||
<input
|
||||
type="radio"
|
||||
name="entityMode"
|
||||
checked={entityMode === "existing"}
|
||||
onChange={() => setEntityMode("existing")}
|
||||
className="text-orange-500"
|
||||
/>
|
||||
Use existing entity
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{entityMode === "existing" ? (
|
||||
<select
|
||||
value={entityId}
|
||||
onChange={(e) => setEntityId(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded text-sm"
|
||||
>
|
||||
<option value="">Select entity...</option>
|
||||
{entities.map((e) => (
|
||||
<option key={e.id} value={e.id}>
|
||||
{e.name}
|
||||
</option>
|
||||
))}
|
||||
<select value={entityId} onChange={(e) => { setEntityId(e.target.value); reset(); }} className={inputCls}>
|
||||
<option value="">Select fund…</option>
|
||||
{entities.map((e) => <option key={e.id} value={e.id}>{e.name}</option>)}
|
||||
</select>
|
||||
) : (
|
||||
<div className="flex gap-3">
|
||||
<div className="flex-1">
|
||||
<label className="block text-xs text-gray-500 mb-1">Type</label>
|
||||
<select
|
||||
value={createType}
|
||||
onChange={(e) => setCreateType(e.target.value as EntityType)}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded text-sm"
|
||||
>
|
||||
<select value={createType} onChange={(e) => setCreateType(e.target.value as EntityType)} className={inputCls}>
|
||||
<option value="fund">Fund</option>
|
||||
<option value="spv">SPV</option>
|
||||
<option value="gp">GP</option>
|
||||
<option value="mgmt_co">Mgmt Co</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="w-32">
|
||||
<label className="block text-xs text-gray-500 mb-1">Vintage Year</label>
|
||||
<input
|
||||
type="text"
|
||||
value={vintageYear}
|
||||
onChange={(e) => setVintageYear(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded text-sm"
|
||||
placeholder="2021"
|
||||
/>
|
||||
</div>
|
||||
<input className={inputCls} placeholder="Vintage year" value={vintageYear} onChange={(e) => setVintageYear(e.target.value)} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className="block text-sm text-gray-700 mb-1">
|
||||
Quarter-end date (seed round)
|
||||
</label>
|
||||
<input
|
||||
type="date"
|
||||
value={asOf}
|
||||
onChange={(e) => setAsOf(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded text-sm"
|
||||
/>
|
||||
<label className="block text-xs text-gray-500 mb-1">eNAV workbook (.xlsx)</label>
|
||||
<input type="file" accept=".xlsx" onChange={(e) => { setFile(e.target.files?.[0] ?? null); reset(); }} className="text-sm" />
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<label className="block text-sm text-gray-700 mb-1">
|
||||
{mode === "schedule" ? "Carta XLSX or CSV file" : "Entities CSV file"}
|
||||
</label>
|
||||
<input
|
||||
ref={fileRef}
|
||||
type="file"
|
||||
accept={mode === "schedule" ? ".xlsx,.xls,.csv" : ".csv"}
|
||||
onChange={(e) => setFile(e.target.files?.[0] || null)}
|
||||
className="w-full text-sm text-gray-600"
|
||||
/>
|
||||
<label className="block text-xs text-gray-500 mb-1">Spreadsheet password</label>
|
||||
<input type="text" className={inputCls} value={password} placeholder="If the file is protected" autoComplete="off" onChange={(e) => { setPassword(e.target.value); reset(); }} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="commit"
|
||||
checked={commit}
|
||||
onChange={(e) => setCommit(e.target.checked)}
|
||||
className="rounded border-gray-300"
|
||||
/>
|
||||
<label htmlFor="commit" className="text-sm text-gray-700">
|
||||
Commit (uncheck for dry-run preview)
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="p-3 bg-red-50 border border-red-200 rounded text-sm text-red-700">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
onClick={handleImport}
|
||||
disabled={loading || !file}
|
||||
className="px-4 py-2 bg-gray-900 text-white text-sm rounded hover:bg-gray-800 disabled:opacity-50"
|
||||
>
|
||||
{loading ? "Importing..." : commit ? "Import" : "Preview (dry run)"}
|
||||
<div className="flex justify-end">
|
||||
<button onClick={readEnav} disabled={busy || !file} className="px-3 py-1.5 bg-gray-900 text-white text-sm rounded hover:bg-gray-800 disabled:opacity-50">
|
||||
{busy ? "Reading…" : "Read eNAV"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Results */}
|
||||
{result && (
|
||||
<div className="mt-6 bg-white border border-gray-200 rounded-lg p-6">
|
||||
<h3 className="text-sm font-medium text-gray-900 mb-3">
|
||||
{result.committed ? "Import Complete" : "Dry Run Preview"}
|
||||
</h3>
|
||||
{memberPv && !result && (
|
||||
<div className="mt-6 space-y-4">
|
||||
{/* Holdings summary */}
|
||||
<div className="bg-white border border-gray-200 rounded-lg p-4 text-sm flex items-center gap-6">
|
||||
<div>
|
||||
<span className="text-gray-500">Holdings: </span>
|
||||
<span className="text-gray-900 font-medium">{holdings?.count ?? 0}</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-gray-500">Fund NAV: </span>
|
||||
<span className="text-gray-900 font-medium">{formatMoneyExact(holdings?.nav ?? 0)}</span>
|
||||
</div>
|
||||
<div className="ml-auto">
|
||||
<label className="text-xs text-gray-500 mr-2">As-of</label>
|
||||
<input type="date" className="px-2 py-1 border border-gray-300 rounded text-sm" value={asOf} onChange={(e) => setAsOf(e.target.value)} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Entity resolution info */}
|
||||
{result.entity && (
|
||||
<div className="mb-3 p-3 bg-gray-50 border border-gray-200 rounded text-sm">
|
||||
{result.entity.resolution === "will_create" ? (
|
||||
<span className="text-purple-700">
|
||||
Will create entity: <strong>{result.entity.entity_name}</strong> ({result.entity.entity_type})
|
||||
{result.entity.vintage_year && `, vintage ${result.entity.vintage_year}`}
|
||||
{entityMode === "existing" && (
|
||||
<label className="flex items-start gap-2 text-sm text-gray-700 bg-amber-50 border border-amber-200 rounded-lg p-3">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="mt-0.5"
|
||||
checked={replaceExisting}
|
||||
onChange={(e) => setReplaceExisting(e.target.checked)}
|
||||
/>
|
||||
<span>
|
||||
<span className="font-medium">Replace existing holdings</span> — clear this fund's
|
||||
current holdings, positions, and valuation history first, then rebuild from this file.
|
||||
Use after switching source workbooks (e.g. Carta → eNAV) renamed the positions.
|
||||
Investor capital accounts are not affected.
|
||||
</span>
|
||||
) : result.entity.resolution === "matched" ? (
|
||||
<span className="text-blue-700">
|
||||
Matched existing entity: <strong>{result.entity.entity_name}</strong> (#{result.entity.entity_id})
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-gray-700">
|
||||
Entity: <strong>{result.entity.entity_name}</strong> (#{result.entity.entity_id})
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</label>
|
||||
)}
|
||||
|
||||
{result.source_entity_name && !result.entity && (
|
||||
<p className="text-sm text-gray-600 mb-2">
|
||||
Source: {result.source_entity_name}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{result.summary && (
|
||||
<div className="text-sm text-gray-700 mb-3">
|
||||
Created: {result.summary.created} | Updated: {result.summary.updated} | Errors: {result.summary.error_rows}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{result.holdings_count != null && (
|
||||
<div className="text-sm text-gray-700 mb-3">
|
||||
Holdings: {result.holdings_count} | Positions: {result.positions_count}
|
||||
{result.seed_round_id && ` | Seed round #${result.seed_round_id}`}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{result.holdings && result.holdings.length > 0 && (
|
||||
<div className="mb-3">
|
||||
<h4 className="text-xs font-medium text-gray-500 uppercase mb-1">Holdings</h4>
|
||||
<ul className="text-sm text-gray-700 space-y-0.5">
|
||||
{result.holdings.map((h: any, i: number) => (
|
||||
<li key={i}>{h.company_name}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{result.positions && result.positions.length > 0 && (
|
||||
<div className="mb-3">
|
||||
<h4 className="text-xs font-medium text-gray-500 uppercase mb-1">
|
||||
Positions ({result.positions.length})
|
||||
</h4>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="text-xs w-full">
|
||||
<thead>
|
||||
<tr className="text-left text-gray-500">
|
||||
<th className="pr-3 py-1">Company</th>
|
||||
<th className="pr-3 py-1">Security</th>
|
||||
<th className="pr-3 py-1">Date</th>
|
||||
<th className="pr-3 py-1 text-right">Cost</th>
|
||||
<th className="pr-3 py-1 text-right">Value</th>
|
||||
{/* Members review */}
|
||||
<div className="bg-white border border-gray-200 rounded-lg overflow-hidden">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-gray-50 text-gray-500 text-left">
|
||||
<tr>
|
||||
<th className="px-3 py-2 font-medium">Member</th>
|
||||
<th className="px-3 py-2 font-medium text-right">Commitment</th>
|
||||
<th className="px-3 py-2 font-medium text-right">Paid-in</th>
|
||||
<th className="px-3 py-2 font-medium text-right">Distrib.</th>
|
||||
<th className="px-3 py-2 font-medium text-right">Value</th>
|
||||
<th className="px-3 py-2 font-medium">Action</th>
|
||||
<th className="px-3 py-2 font-medium">New account</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{result.positions.map((p: any, i: number) => (
|
||||
<tr key={i} className="text-gray-700">
|
||||
<td className="pr-3 py-0.5">{p.company_name}</td>
|
||||
<td className="pr-3 py-0.5">{p.security_name}</td>
|
||||
<td className="pr-3 py-0.5">{p.investment_date || "—"}</td>
|
||||
<td className="pr-3 py-0.5 text-right">
|
||||
{p.cost_cents != null ? `$${(p.cost_cents / 100).toLocaleString()}` : "—"}
|
||||
{decisions.map((d, i) => (
|
||||
<tr key={i} className="border-t border-gray-100 align-top">
|
||||
<td className="px-3 py-2 text-gray-900">{d.source_name}</td>
|
||||
<td className="px-3 py-2 text-right text-gray-600">{formatMoneyExact(Math.round(d.commitment_dollars * 100))}</td>
|
||||
<td className="px-3 py-2 text-right text-gray-600">{formatMoneyExact(Math.round(d.contributions_dollars * 100))}</td>
|
||||
<td className="px-3 py-2 text-right text-gray-600">{formatMoneyExact(Math.round(d.distributions_dollars * 100))}</td>
|
||||
<td className="px-3 py-2 text-right text-gray-900">{formatMoneyExact(Math.round(d.value_dollars * 100))}</td>
|
||||
<td className="px-3 py-2">
|
||||
<select className="px-2 py-1 border border-gray-300 rounded text-sm" value={d.action} onChange={(e) => update(i, { action: e.target.value as Decision["action"] })}>
|
||||
{d.user_id != null && <option value="match">Match {d.matched_username}</option>}
|
||||
<option value="create">Create new</option>
|
||||
<option value="skip">Skip</option>
|
||||
</select>
|
||||
</td>
|
||||
<td className="pr-3 py-0.5 text-right">
|
||||
{p.value_cents != null ? `$${(p.value_cents / 100).toLocaleString()}` : "—"}
|
||||
<td className="px-3 py-2">
|
||||
{d.action === "create" ? (
|
||||
<div className="flex gap-2">
|
||||
<input className="px-2 py-1 border border-gray-300 rounded text-sm w-28" placeholder="Username" value={d.username} onChange={(e) => update(i, { username: e.target.value })} />
|
||||
<span className="text-xs text-gray-400 self-center">no login until set</span>
|
||||
</div>
|
||||
) : d.action === "match" ? (
|
||||
<span className="text-xs text-gray-500">updates {d.matched_username}</span>
|
||||
) : (
|
||||
<span className="text-xs text-gray-400">ignored</span>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-end gap-3">
|
||||
<span className="text-xs text-gray-400">
|
||||
{decisions.filter((d) => d.action === "create").length} new ·{" "}
|
||||
{decisions.filter((d) => d.action === "match").length} matched ·{" "}
|
||||
{decisions.filter((d) => d.action === "skip").length} skipped
|
||||
</span>
|
||||
<button onClick={handleConfirmClick} disabled={busy || !asOf} className="px-4 py-1.5 bg-gray-900 text-white text-sm rounded hover:bg-gray-800 disabled:opacity-50">
|
||||
{busy ? (step || "Importing…") : "Confirm import"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{result.errors && result.errors.length > 0 && (
|
||||
<div>
|
||||
<h4 className="text-xs font-medium text-red-500 uppercase mb-1">
|
||||
Errors ({result.errors.length})
|
||||
</h4>
|
||||
<ul className="text-xs text-red-600 space-y-1">
|
||||
{result.errors.map((e: any, i: number) => (
|
||||
<li key={i}>
|
||||
Row {e.row}: {e.errors?.join(", ")}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{confirmReplace && (
|
||||
<div className="fixed inset-0 bg-black/40 flex items-center justify-center p-4 z-50">
|
||||
<div className="bg-white rounded-lg p-6 max-w-md w-full">
|
||||
<h3 className="text-sm font-semibold text-gray-900 mb-2">Replace existing holdings?</h3>
|
||||
<p className="text-sm text-gray-600">
|
||||
This will permanently clear this fund's current holdings, positions, and valuation
|
||||
history, then rebuild them from this file. Investor capital accounts are not
|
||||
affected. This can't be undone.
|
||||
</p>
|
||||
<div className="flex justify-end gap-2 mt-5">
|
||||
<button
|
||||
onClick={() => setConfirmReplace(false)}
|
||||
className="px-4 py-1.5 border border-gray-300 text-sm rounded hover:bg-gray-50"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
onClick={confirmImport}
|
||||
className="px-4 py-1.5 bg-red-600 text-white text-sm rounded hover:bg-red-700"
|
||||
>
|
||||
Replace and import
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{result.preview && result.preview.length > 0 && (
|
||||
<div>
|
||||
<h4 className="text-xs font-medium text-gray-500 uppercase mb-1">
|
||||
Entities ({result.preview.length})
|
||||
</h4>
|
||||
<ul className="text-sm text-gray-700 space-y-0.5">
|
||||
{result.preview.map((p: any, i: number) => (
|
||||
<li key={i}>
|
||||
<span className={`text-xs px-1 rounded ${p.action === "create" ? "bg-green-100 text-green-700" : "bg-yellow-100 text-yellow-700"}`}>
|
||||
{p.action}
|
||||
</span>{" "}
|
||||
{p.name}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -1,14 +1,8 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Link, useParams } from "react-router-dom";
|
||||
import { api, type Entity, type Holding, type Position, type ValuationRound, type Valuation } from "../api";
|
||||
import { formatMoney, formatMoneyExact, formatDate, formatQuarter, formatPerShare } from "../format";
|
||||
|
||||
const TYPE_LABELS: Record<string, string> = {
|
||||
fund: "Fund",
|
||||
spv: "SPV",
|
||||
gp: "GP",
|
||||
mgmt_co: "Mgmt Co",
|
||||
};
|
||||
import { useParams } from "react-router-dom";
|
||||
import { api, type Entity, type Holding, type Position } from "../api";
|
||||
import { formatMoney, formatDate, formatQuarter, formatPerShare } from "../format";
|
||||
import EntityHeader from "../components/EntityHeader";
|
||||
|
||||
interface PositionWithValuation extends Position {
|
||||
lastValueCents: number | null;
|
||||
@@ -95,28 +89,7 @@ export default function Investments() {
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* Header */}
|
||||
<div className="mb-6">
|
||||
<div className="flex items-center gap-3 mb-1">
|
||||
<h1 className="text-2xl font-semibold text-gray-900">{entity.name}</h1>
|
||||
<span className="inline-block px-2 py-0.5 bg-gray-100 text-gray-600 text-xs rounded">
|
||||
{TYPE_LABELS[entity.type] || entity.type}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex gap-6 mt-4 border-b border-gray-200">
|
||||
<Link
|
||||
to={`/entities/${entity.id}`}
|
||||
className="pb-2 text-sm text-gray-500 hover:text-gray-800"
|
||||
>
|
||||
Overview
|
||||
</Link>
|
||||
<span className="pb-2 border-b-2 border-orange-500 text-sm font-medium text-orange-600">
|
||||
Investments
|
||||
</span>
|
||||
<span className="pb-2 text-sm text-gray-400 cursor-not-allowed">Partners</span>
|
||||
<span className="pb-2 text-sm text-gray-400 cursor-not-allowed">Documents</span>
|
||||
</div>
|
||||
</div>
|
||||
<EntityHeader entity={entity} active="investments" />
|
||||
|
||||
{/* Header band */}
|
||||
<div className="flex gap-6 mb-6 text-sm">
|
||||
@@ -141,7 +114,15 @@ export default function Investments() {
|
||||
</div>
|
||||
|
||||
{/* Grouped table */}
|
||||
<div className="bg-white border border-gray-200 rounded-lg overflow-hidden">
|
||||
{groups.length === 0 ? (
|
||||
<div className="bg-white border border-gray-200 rounded-lg p-8 text-center">
|
||||
<p className="text-sm text-gray-500">No investments recorded for this entity yet.</p>
|
||||
<p className="text-xs text-gray-400 mt-1">
|
||||
Holdings and positions are added by importing the fund's eNAV workbook.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="bg-white border border-gray-200 rounded-lg overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="bg-gray-50 border-b border-gray-200">
|
||||
@@ -166,6 +147,7 @@ export default function Investments() {
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,14 +2,14 @@ import { useEffect, useState } from "react";
|
||||
import { useParams, Link } from "react-router-dom";
|
||||
import {
|
||||
api,
|
||||
canEditRound,
|
||||
isApprover as roleIsApprover,
|
||||
type Entity,
|
||||
type Holding,
|
||||
type Position,
|
||||
type ValuationRound,
|
||||
type Valuation,
|
||||
} from "../api";
|
||||
import { useAuth } from "../context/AuthContext";
|
||||
import { formatMoney, formatMoneyExact, formatQuarter, formatDate } from "../format";
|
||||
import { formatMoney, formatQuarter, formatDate } from "../format";
|
||||
|
||||
const STATUS_COLORS: Record<string, string> = {
|
||||
draft: "bg-gray-100 text-gray-600",
|
||||
@@ -39,13 +39,12 @@ export default function ValuationWorkflow() {
|
||||
const [error, setError] = useState("");
|
||||
|
||||
const entityId = id ? parseInt(id) : 0;
|
||||
const isApprover = user?.role === "approver";
|
||||
const isApprover = !!user && roleIsApprover(user.role);
|
||||
const canEdit =
|
||||
selectedRound &&
|
||||
(selectedRound.status === "draft" || selectedRound.status === "returned") &&
|
||||
user &&
|
||||
["fund_admin", "cfo", "approver"].includes(user.role);
|
||||
const canSubmit = canEdit;
|
||||
!!user &&
|
||||
canEditRound(user.role);
|
||||
const canApprove =
|
||||
selectedRound?.status === "submitted" && isApprover;
|
||||
const canReturn =
|
||||
@@ -302,7 +301,7 @@ export default function ValuationWorkflow() {
|
||||
)}
|
||||
|
||||
{/* Valuations table */}
|
||||
<div className="bg-white border border-gray-200 rounded-lg overflow-hidden">
|
||||
<div className="bg-white border border-gray-200 rounded-lg overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="bg-gray-50 border-b border-gray-200">
|
||||
|
||||
Reference in New Issue
Block a user