From 8f668d85f3c573e36bca8204dc5f79c9a5e5963a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 7 Apr 2026 16:00:20 +0000 Subject: [PATCH] Add comprehensive backend capabilities analysis and frontend build prompt Two documents for enabling client teams to build frontends against OpenCap: - OPENCAP_BACKEND_CAPABILITIES.md: Full analysis of all 150+ API endpoints, 27 route modules, 30+ controllers, 7 services, data models, auth/RBAC, real-time features, and infrastructure - OPENCAP_FRONTEND_BUILD_PROMPT.md: Copy-pasteable LLM prompt with complete API spec, TypeScript interfaces, page layouts, and UI requirements for building a Next.js frontend https://claude.ai/code/session_01782XQaeFXFR5zxpYg8Gqvz --- docs/OPENCAP_BACKEND_CAPABILITIES.md | 445 ++++++++++++++ docs/OPENCAP_FRONTEND_BUILD_PROMPT.md | 848 ++++++++++++++++++++++++++ 2 files changed, 1293 insertions(+) create mode 100644 docs/OPENCAP_BACKEND_CAPABILITIES.md create mode 100644 docs/OPENCAP_FRONTEND_BUILD_PROMPT.md diff --git a/docs/OPENCAP_BACKEND_CAPABILITIES.md b/docs/OPENCAP_BACKEND_CAPABILITIES.md new file mode 100644 index 0000000..42d9f79 --- /dev/null +++ b/docs/OPENCAP_BACKEND_CAPABILITIES.md @@ -0,0 +1,445 @@ +# OpenCap Stack - Complete Backend Capabilities Analysis + +## Platform Overview + +OpenCap is a **cap table management and financial operations platform** built for startups, venture-backed companies, and SPV (Special Purpose Vehicle) management. The backend is a Node.js/Express API backed by MongoDB (primary), Neo4j (graph relationships), PostgreSQL (relational), Redis (caching/sessions), and MinIO (file storage). + +**Base URL:** `http://localhost:5000` +**API Prefix:** `/api/v1` +**Documentation:** Swagger UI at `/api-docs` + +--- + +## 1. Authentication & Identity + +### Endpoints (`/api/v1/auth`) +| Method | Path | Auth | Description | +|--------|------|------|-------------| +| POST | `/register` | None | Register user (email, password, firstName, lastName, role) | +| POST | `/login` | None | Login, returns JWT access + refresh tokens | +| POST | `/oauth-login` | None | Google OAuth login | +| POST | `/token/refresh` | None | Refresh expired access token | +| POST | `/logout` | JWT | Logout, blacklists token | +| POST | `/password/reset-request` | None | Send password reset email | +| POST | `/password/verify-token` | None | Verify reset token validity | +| POST | `/password/reset` | None | Complete password reset | +| GET | `/profile` | JWT | Get current user profile | +| PUT | `/profile` | JWT | Update current user profile | +| POST | `/verify/send` | JWT | Send email verification | +| GET | `/verify/:token` | None | Verify email address | + +### Security Details +- **JWT tokens** with configurable expiration +- **Refresh token** flow for session continuity +- **Password requirements:** 8+ chars, uppercase, lowercase, number, special character +- **Token blacklisting** via Redis (falls back to in-memory) +- **bcrypt** hashing (10 rounds) +- **Google OAuth2** integration +- **Email verification** workflow via Nodemailer + +### RBAC System +Four roles with hierarchical permissions: +- **admin** - Full access (`admin:all`, `read:*`, `write:*`, `delete:*`) +- **manager** - Read/write access (`read:companies`, `write:companies`, `read:reports`, `write:reports`) +- **user** - Read access + own profile (`read:companies`, `read:reports`, `read:own_profile`, `write:own_profile`) +- **client** - Limited read access (`read:own_data`, `read:own_profile`) + +--- + +## 2. Company Management + +### Endpoints (`/api/v1/companies`) +| Method | Path | Auth | Permission | Description | +|--------|------|------|------------|-------------| +| POST | `/` | JWT | `write:companies` | Create company | +| GET | `/` | JWT | `read:companies` | List all companies | +| GET | `/:id` | JWT | `read:companies` | Get company by ID | +| PUT | `/:id` | JWT | `write:companies` | Update company | +| DELETE | `/:id` | JWT | `delete:companies` or `admin:all` | Delete company | + +### Company Model Fields +- `companyId` (String, required, unique) +- `CompanyName` (String, required) +- `CompanyType` (String, required) +- `RegisteredAddress` (String, required) +- `TaxID` (String, required) +- `corporationDate` (Date, required) +- `incorporationCountry`, `incorporationState` (String) +- `industry`, `website`, `description` (String) +- `status` (Enum: Active, Inactive, Dissolved, Suspended) +- `founders` (Array of ObjectId refs to User) +- `totalAuthorizedShares`, `parValue` (Number) +- `fiscalYearEnd` (String) + +--- + +## 3. Cap Table / Equity Management + +### Share Classes (`/api/v1/share-classes`) +| Method | Path | Auth | Description | +|--------|------|------|-------------| +| GET | `/api/shareClasses` | None | List all share classes | +| POST | `/api/shareClasses` | None | Create share class | + +**ShareClass Model:** `classId`, `ClassName`, `ClassType`, `PricePerShare`, `TotalShares`, `VotingRights`, `DividendRights`, `ConversionRights`, `AntiDilutionProtection`, `LiquidationPreference`, `RedemptionRights`, `CompanyID` + +### Equity Plans (`/api/v1/equity-plans`) +Full CRUD. Fields: `planId`, `PlanName`, `PlanType`, `TotalSharesReserved`, `VestingSchedule`, `CompanyId` + +### Stakeholders (`/api/v1/stakeholders`) +Full CRUD. Fields: `stakeholderId`, `name`, `role`, `email`, `ContactNumber`, `Address`, `Type` (Individual/Entity/Trust/Other), `documents[]`, `projectId` + +### Investors (`/api/v1/investors`) +Full CRUD. Fields: `investorId`, `name`, `email`, `phone`, `investmentAmount`, `equityPercentage`, `investorType`, `relatedFundraisingRound` + +--- + +## 4. Fundraising + +### Endpoints (`/api/v1/fundraising-rounds`) +Full CRUD (POST, GET all, GET by ID, PUT, DELETE) + +**FundraisingRound Model:** `roundId`, `RoundName`, `RoundType`, `TargetAmount`, `AmountRaised`, `StartDate`, `EndDate`, `Status`, `LeadInvestor`, `Valuation`, `Terms`, `CompanyId`, `Investors[]` + +--- + +## 5. SPV (Special Purpose Vehicle) Management + +### SPV Endpoints (`/api/v1/spvs`) +| Method | Path | Auth | Description | +|--------|------|------|-------------| +| POST | `/` | None | Create SPV | +| GET | `/` | None | List all SPVs | +| GET | `/status/:status` | None | Filter by status (Active/Pending/Closed) | +| GET | `/compliance/:status` | None | Filter by compliance (Compliant/NonCompliant/PendingReview) | +| GET | `/parent/:id` | None | Get SPVs by parent company | +| GET | `/:id` | None | Get SPV by ID | +| PUT | `/:id` | None | Update SPV | +| DELETE | `/:id` | None | Delete SPV | + +**SPV Model:** `SPVID`, `Name`, `Purpose`, `CreationDate`, `Status`, `ParentCompanyID`, `ComplianceStatus`, `NAV`, `TotalCommitments`, `FundedAmount`, `InvestmentStrategy`, `TargetReturn`, `ManagementFee`, `PerformanceFee` + +### SPV Asset Endpoints (`/api/v1/spv-assets`) +| Method | Path | Auth | Description | +|--------|------|------|-------------| +| POST | `/` | JWT + Admin | Create asset | +| GET | `/` | JWT | List all assets | +| GET | `/spv/:spvId` | JWT | Get assets for specific SPV | +| GET | `/valuation/spv/:spvId` | JWT | Calculate total SPV valuation | +| GET | `/valuation/type/:type` | JWT | Valuation breakdown by asset type | +| GET | `/:id` | JWT | Get asset by ID | +| PUT | `/:id` | JWT + Admin | Update asset | +| DELETE | `/:id` | JWT + Admin | Delete asset | + +**SPVAsset Model:** `AssetID`, `SPVID`, `AssetType`, `Value`, `Description`, `AcquisitionDate`, `MaturityDate`, `Status` (Active/Sold/Written Off/Pending), `ReturnRate` + +**Calculations:** +- Total SPV valuation = SUM(asset.Value) +- Asset type aggregation with breakdown percentages + +--- + +## 6. Financial Management + +### Financial Reports (`/api/v1/financial-reports`) +| Method | Path | Auth | Description | +|--------|------|------|-------------| +| POST | `/` | JWT | Create report | +| GET | `/` | JWT | List reports (paginated) | +| GET | `/search` | JWT | Search reports | +| GET | `/analytics` | JWT | Analytics aggregation | +| POST | `/bulk` | JWT | Bulk create reports | +| GET | `/:id` | JWT | Get report by ID | +| PUT | `/:id` | JWT | Update report | +| DELETE | `/:id` | JWT | Delete report | + +**FinancialReport Model:** `reportId`, `ReportName`, `ReportType`, `DateGenerated`, `ReportingPeriod` (Annual/Quarterly), `Data` (object: revenue, expenses, netIncome, assets, liabilities, equity, cashFlow), `CompanyID`, `Status`, `GeneratedBy` + +**Validations:** Net income must equal revenue - expenses. No negative financial values. + +### Financial Metrics (`/api/v1/metrics`) +| Method | Path | Auth | Description | +|--------|------|------|-------------| +| GET | `/companies/:companyId/metrics/profitability?period=YYYY-QX` | JWT + Permission | Gross, operating, net margins | +| GET | `/companies/:companyId/metrics/liquidity?period=YYYY-QX` | JWT + Permission | Current, quick, cash ratios | +| GET | `/companies/:companyId/metrics/solvency?period=YYYY-QX` | JWT + Permission | Debt-to-equity, debt-to-asset, interest coverage | +| GET | `/companies/:companyId/metrics/efficiency?period=YYYY-QX` | JWT + Permission | Asset/inventory/receivables turnover | +| GET | `/companies/:companyId/metrics/dashboard` | JWT + Permission | All metrics combined | + +**Period format:** `YYYY-QX` (e.g., `2024-Q1`) or `YYYY-full` + +### Financial Data Import/Export (`/api/v1/financial-data`) +| Method | Path | Auth | Description | +|--------|------|------|-------------| +| POST | `/import` | JWT + admin/financial_manager | Import data (CSV/JSON/XLSX, 50MB max) | +| GET | `/export` | JWT + admin/financial_manager/analyst | Export data (CSV/JSON/XLSX/PDF) | +| GET | `/templates/:importType` | JWT | Download import template | +| GET | `/import-status/:importId` | JWT | Check import job status | +| POST | `/validate` | JWT | Validate data without importing | + +**Import types:** transactions, financial_reports, spv_data, chart_of_accounts +**Export types:** transactions, financial_reports, spv_performance, compliance_report + +### Tax Calculator (`/api/v1/tax-calculations`) +Full CRUD + auto-calculation. Fields: `calculationId`, `SaleAmount`, `TaxRate` (0-1), `CalculatedTax` (auto: SaleAmount * TaxRate), `EquityType`, `TaxYear`, `Jurisdiction` + +### Balance Sheet Model +`companyId`, `fiscalYear`, `quarter`, `totalAssets`, `currentAssets`, `nonCurrentAssets`, `totalLiabilities`, `currentLiabilities`, `nonCurrentLiabilities`, `shareholdersEquity`, `retainedEarnings` + +### Cash Flow Statement Model +`companyId`, `fiscalYear`, `quarter`, `operatingCashFlow`, `investingCashFlow`, `financingCashFlow`, `netCashFlow` (auto-calculated), `beginningCash`, `endingCash` + +--- + +## 7. Document Management + +### Document Endpoints (`/api/v1/documents`) +| Method | Path | Auth | Description | +|--------|------|------|-------------| +| GET | `/` | None | List documents (with search, filter, paginate) | +| POST | `/` | None | Create document | + +**Document Model (comprehensive):** +- Core: `documentId`, `name`, `title`, `content`, `path`, `metadata` +- File: `fileType`, `fileSize`, `mimeType`, `checksum` +- Access: `accessLevel` (public/private/shared), `sharedWith[]`, `accessLog[]` +- Versioning: `version`, `versionHistory[]`, `previousVersions[]` +- Organization: `category`, `tags[]`, `company` (ref) +- AI: `embeddings[]`, `embeddingModel`, `embeddingDimension`, `lastEmbeddedAt` +- Status: `status` (draft/active/archived/deleted), `retentionDate`, `isArchived` + +**Search capabilities:** +- Vector-based semantic search (via ZeroDB) +- Text search fallback +- Filter by category, tags, access level, company +- Pagination and sorting + +### Document Access Control (`/api/v1/document-accesses`) +Full CRUD for managing per-document access grants. + +### Document AI Processing (`/api/v1/document-embeddings`) +Full CRUD for embeddings, plus: +- Text extraction from PDF, Word, plain text, images +- OCR processing via Tesseract.js +- AI-powered document classification (OpenAI) +- Automated summarization (extractive + AI-generated) +- Batch processing with parallel execution + +--- + +## 8. Compliance & Audit + +### Compliance Checks (`/api/v1/compliance-checks`) +| Method | Path | Auth | Description | +|--------|------|------|-------------| +| POST | `/` | None | Create compliance check | +| GET | `/` | None | List all checks | +| GET | `/non-compliant` | None | Get non-compliant items | +| GET | `/:id` | None | Get check by ID | +| PUT | `/:id` | None | Update check | +| DELETE | `/:id` | None | Delete check | + +**ComplianceCheck Model:** `CheckID`, `SPVID`, `RegulationType` (GDPR/HIPAA/SOX/CCPA/SEC/FinCEN), `Status` (Compliant/NonCompliant/PendingReview), `Details`, `Timestamp`, `LastCheckedBy` + +### Security Audit Logs (`/api/v1/security-audits`) +All endpoints require JWT + admin/security_analyst role. + +| Method | Path | Description | +|--------|------|-------------| +| GET | `/` | Query audit logs (filter by eventType, level, userId, days) | +| GET | `/summary` | Audit summary statistics | +| GET | `/suspicious` | Suspicious activity detection | +| GET | `/user/:userId` | User-specific audit trail | +| GET | `/export` | Export as CSV | +| PATCH | `/:id/review` | Mark log as reviewed | + +**SecurityAudit Model:** `eventType`, `level` (info/warning/error/critical), `userId`, `action`, `resource`, `resourceId`, `ipAddress`, `userAgent`, `details`, `riskScore`, `reviewed`, `reviewedBy`, `reviewNotes` + +--- + +## 9. Analytics & AI + +### Analytics Controller (internal, exposed via services) +- **Predictive financial modeling** - Linear regression trend analysis with confidence intervals +- **Risk assessment** - Multi-domain scoring (financial, operational, compliance, market) +- **Performance benchmarking** - Industry standard comparisons +- **Automated report generation** - Financial, risk, performance, compliance reports +- **Anomaly detection** - Statistical anomaly identification with severity levels (critical/high/medium/low) + +### Graph Database (Neo4j) +Models for relationship analysis: +- Company-User employment relationships +- Ownership structures +- Document access patterns +- Compliance trails +- Financial transaction flows +- SPV-Stakeholder relationships +- Network centrality calculations +- Shortest path analysis +- Compliance violation tracking + +--- + +## 10. Real-Time Features + +### WebSocket Service +- JWT-authenticated WebSocket connections +- Room/channel management +- Document collaboration (real-time updates, cursor positions, typing indicators) +- User presence (online/offline status) +- Heartbeat health checks (30s interval) +- Event broadcasting (document events, SPV events, activity updates) + +### Streaming Service +Event topics: +- `FINANCIAL_TRANSACTION` - Real-time financial events +- `USER_ACTIVITY` - User action tracking +- `DOCUMENT_ACTIVITY` - Document operations +- `COMPLIANCE_EVENT` - Compliance status changes +- `WORKFLOW_STATE` - Workflow transitions +- `SPV_ACTIVITY` - SPV operations +- `SYSTEM_ALERT` - System notifications +- `NOTIFICATION` - User notifications + +Batch processing with buffering (1000 max, 10 per flush, 5s interval). + +--- + +## 11. Communication & Notifications + +### Communications (`/api/v1/communications`) +| Method | Path | Description | +|--------|------|-------------| +| POST | `/` | Send message | +| POST | `/thread` | Reply in thread | +| GET | `/` | List all communications | +| GET | `/thread/:threadId` | Get thread messages | +| GET | `/user/:userId` | Get user's messages | +| GET | `/:id` | Get message by ID | +| PUT | `/:id` | Update message | +| DELETE | `/:id` | Delete message | + +### Notifications (`/api/v1/notifications`) +Create, list all, get by ID, delete. Fields: `notificationId`, `notificationType`, `title`, `message`, `recipient`, `Timestamp`, `RelatedObjects`, `UserInvolved` + +### Invite Management (`/api/v1/invites`) +Full CRUD for stakeholder/investor invitations. + +--- + +## 12. Employee Management + +### Endpoints (`/api/v1/employees`) +Full CRUD with pagination. + +**Employee Model:** `EmployeeID`, `FirstName`, `LastName`, `Email`, `Phone`, `Department`, `Role`, `StartDate`, `EndDate`, `EquityOverview` (object: TotalEquity, VestedEquity, UnvestedEquity, ExercisableOptions, StrikePrice, LastVestingDate), `SSN`, `CompanyID` + +--- + +## 13. Administration + +### Admin Endpoints (`/api/v1/admins`) +| Method | Path | Description | +|--------|------|-------------| +| POST | `/admins` | Create admin | +| GET | `/admins` | List all admins | +| GET | `/admins/:id` | Get admin by ID | +| PUT | `/admins/:id` | Update admin | +| DELETE | `/admins/:id` | Delete admin | +| POST | `/admins/login` | Admin login | +| POST | `/admins/logout` | Admin logout | +| PUT | `/admins/:id/change-password` | Change password | + +--- + +## 14. Infrastructure & Middleware + +### Rate Limiting +- **Default:** 100 requests / 15 min per IP +- **Auth routes:** 10 requests / hour (brute-force protection) +- **Tiered plans:** Basic (100), Standard (500), Premium (1000), Enterprise (5000) per 15 min + +### Security Headers +CSP directives, HSTS (1 year), X-Frame-Options DENY, XSS protection, no-sniff, referrer-policy + +### API Versioning +All routes prefixed with `/api/v1`. Version header validation middleware. + +### Databases +| Database | Purpose | +|----------|---------| +| MongoDB | Primary data store (all models) | +| Neo4j | Graph relationships, compliance trails, network analysis | +| PostgreSQL | Relational data | +| Redis | Token blacklisting, session cache | +| MinIO | S3-compatible file/object storage | +| ZeroDB | Vector embeddings, semantic search, event streaming | + +### Required Environment Variables +``` +# Core +NODE_ENV, PORT, JWT_SECRET, JWT_EXPIRATION + +# MongoDB +MONGODB_URI + +# Neo4j +NEO4J_URI, NEO4J_USER, NEO4J_PASSWORD + +# PostgreSQL +DATABASE_URL + +# Redis (optional) +REDIS_URL + +# Email +EMAIL_HOST, EMAIL_PORT, EMAIL_USER, EMAIL_PASSWORD + +# OAuth +GOOGLE_CLIENT_ID + +# File Storage +MINIO_ENDPOINT, MINIO_PORT, MINIO_ACCESS_KEY, MINIO_SECRET_KEY, MINIO_BUCKET + +# AI +OPENAI_API_KEY + +# ZeroDB +ZERODB_API_KEY, ZERODB_PROJECT_ID +``` + +### Docker Deployment +Two Docker Compose configurations: +- `docker-compose.yml` - Full stack (all databases + services) +- `docker-compose.simple.yml` - Minimal (MongoDB only) + +Requirements: Node.js >= 18.0.0, npm >= 9.0.0 + +--- + +## 15. Activity Logging + +### Endpoints (`/api/v1/activities`) +Full CRUD. Fields: `activityId`, `ActivityType`, `Description`, `UserInvolved`, `Timestamp`, `RelatedObjects`, `IPAddress`, `Device` + +--- + +## 16. Investment Tracking + +### Endpoints (`/api/v1/investments`) +| Method | Path | Auth | Description | +|--------|------|------|-------------| +| POST | `/` | JWT | Track new investment | + +**Fields:** `TrackID`, `Company`, `EquityPercentage`, `CurrentValue` + +--- + +## 17. Integration Modules + +### Endpoints (`/api/v1/integration-modules`) +| Method | Path | Description | +|--------|------|-------------| +| POST | `/integration-modules` | Register external integration | + +**Fields:** `IntegrationID`, `ToolName`, `Description`, `Link` diff --git a/docs/OPENCAP_FRONTEND_BUILD_PROMPT.md b/docs/OPENCAP_FRONTEND_BUILD_PROMPT.md new file mode 100644 index 0000000..8c83eb7 --- /dev/null +++ b/docs/OPENCAP_FRONTEND_BUILD_PROMPT.md @@ -0,0 +1,848 @@ +# OpenCap Stack - Frontend Build Prompt for LLM/Coding Agent + +> **Instructions:** Copy everything below the line into your LLM or coding agent as the system/task prompt. It contains the complete backend specification needed to build a fully integrated Next.js frontend. + +--- + +## PROMPT START + +You are building a **Next.js (App Router)** frontend for **OpenCap**, a cap table management and financial operations platform. The backend API already exists and is fully operational. Your job is to build a production-ready frontend that consumes every capability of this backend. + +### Tech Stack Requirements +- **Framework:** Next.js 14+ with App Router +- **Language:** TypeScript +- **Styling:** Tailwind CSS +- **State Management:** React Context + TanStack Query (React Query) for server state +- **Forms:** React Hook Form + Zod validation +- **Charts:** Recharts or Chart.js for financial visualizations +- **Real-time:** Native WebSocket client +- **Auth:** JWT stored in httpOnly cookies (use Next.js middleware for route protection) +- **API Client:** Axios or fetch wrapper with interceptors for token refresh + +### Backend Connection +- **API Base URL:** Configurable via `NEXT_PUBLIC_API_URL` env var (default: `http://localhost:5000/api/v1`) +- **WebSocket URL:** Configurable via `NEXT_PUBLIC_WS_URL` env var (default: `ws://localhost:5000`) +- **Auth:** JWT Bearer token in Authorization header. Refresh token flow supported. +- **API Docs:** Swagger UI available at `{API_URL}/api-docs` + +--- + +## COMPLETE API SPECIFICATION + +### 1. AUTHENTICATION (`/auth`) + +**Public endpoints (no auth required):** +``` +POST /auth/register + Body: { email, password, confirmPassword, firstName, lastName, role? } + Password rules: 8+ chars, uppercase, lowercase, number, special char + Returns: { user, token } + +POST /auth/login + Body: { email, password } + Returns: { user, token, refreshToken } + +POST /auth/oauth-login + Body: { provider: "google", token: "" } + Returns: { user, token, refreshToken } + +POST /auth/token/refresh + Body: { refreshToken } + Returns: { token, refreshToken } + +POST /auth/password/reset-request + Body: { email } + +POST /auth/password/verify-token + Body: { token } + +POST /auth/password/reset + Body: { token, newPassword, confirmPassword } + +GET /auth/verify/:token (email verification callback) +``` + +**Protected endpoints (JWT required):** +``` +POST /auth/logout +GET /auth/profile +PUT /auth/profile Body: { firstName, lastName, email, ... } +POST /auth/verify/send (resend verification email) +``` + +**RBAC Roles & Permissions:** +| Role | Permissions | +|------|-------------| +| admin | Full access to everything | +| manager | Read/write companies, reports, SPVs | +| user | Read companies, reports; manage own profile | +| client | Read own data only | + +Build the frontend to show/hide UI elements based on the user's role and permissions. + +--- + +### 2. COMPANIES (`/companies`) - All routes require JWT + permissions + +``` +POST /companies Permission: write:companies +GET /companies Permission: read:companies +GET /companies/:id Permission: read:companies +PUT /companies/:id Permission: write:companies +DELETE /companies/:id Permission: delete:companies or admin:all +``` + +**Company object:** +```typescript +interface Company { + _id: string; + companyId: string; + CompanyName: string; + CompanyType: string; + RegisteredAddress: string; + TaxID: string; + corporationDate: string; // ISO date + incorporationCountry?: string; + incorporationState?: string; + industry?: string; + website?: string; + description?: string; + status: 'Active' | 'Inactive' | 'Dissolved' | 'Suspended'; + founders?: string[]; // User IDs + totalAuthorizedShares?: number; + parValue?: number; + fiscalYearEnd?: string; +} +``` + +--- + +### 3. SHARE CLASSES (`/share-classes`) + +``` +GET /api/shareClasses +POST /api/shareClasses +``` + +**ShareClass object:** +```typescript +interface ShareClass { + classId: string; + ClassName: string; + ClassType: string; + PricePerShare: number; + TotalShares: number; + VotingRights: boolean; + DividendRights: boolean; + ConversionRights?: object; + AntiDilutionProtection?: string; + LiquidationPreference?: number; + RedemptionRights?: object; + CompanyID: string; +} +``` + +--- + +### 4. STAKEHOLDERS (`/stakeholders`) + +``` +GET /api/stakeholders +POST /api/stakeholders +``` + +**Stakeholder object:** +```typescript +interface Stakeholder { + stakeholderId: string; + name: string; + role: string; + email: string; + ContactNumber?: string; + Address?: string; + Type: 'Individual' | 'Entity' | 'Trust' | 'Other'; + documents?: string[]; + projectId?: string; +} +``` + +--- + +### 5. INVESTORS (`/investors`) + +``` +POST /investors +GET /investors +GET /investors/:id +PUT /investors/:id +DELETE /investors/:id +``` + +**Investor object:** +```typescript +interface Investor { + investorId: string; + name: string; + email: string; + phone?: string; + investmentAmount: number; + equityPercentage: number; + investorType: string; + relatedFundraisingRound?: string; +} +``` + +--- + +### 6. FUNDRAISING ROUNDS (`/fundraising-rounds`) + +``` +POST /fundraising-rounds +GET /fundraising-rounds +GET /fundraising-rounds/:id +PUT /fundraising-rounds/:id +DELETE /fundraising-rounds/:id +``` + +**FundraisingRound object:** +```typescript +interface FundraisingRound { + roundId: string; + RoundName: string; + RoundType: string; + TargetAmount: number; + AmountRaised: number; + StartDate: string; + EndDate: string; + Status: string; + LeadInvestor?: string; + Valuation?: number; + Terms?: string; + CompanyId: string; + Investors?: string[]; +} +``` + +--- + +### 7. EQUITY PLANS (`/equity-plans`) + +``` +POST /equity-plans +GET /equity-plans +GET /equity-plans/:id +PUT /equity-plans/:id +DELETE /equity-plans/:id +``` + +**EquityPlan object:** +```typescript +interface EquityPlan { + planId: string; + PlanName: string; + PlanType: string; + TotalSharesReserved: number; + VestingSchedule: object; + CompanyId: string; +} +``` + +--- + +### 8. EMPLOYEES (`/employees`) + +``` +POST /employees +GET /employees (supports pagination) +GET /employees/:id +PUT /employees/:id +DELETE /employees/:id +``` + +**Employee object:** +```typescript +interface Employee { + EmployeeID: string; + FirstName: string; + LastName: string; + Email: string; + Phone?: string; + Department?: string; + Role?: string; + StartDate: string; + EndDate?: string; + EquityOverview?: { + TotalEquity: number; + VestedEquity: number; + UnvestedEquity: number; + ExercisableOptions: number; + StrikePrice: number; + LastVestingDate: string; + }; + SSN?: string; + CompanyID: string; +} +``` + +--- + +### 9. SPV MANAGEMENT (`/spvs`) + +``` +POST /spvs +GET /spvs +GET /spvs/status/:status (Active | Pending | Closed) +GET /spvs/compliance/:status (Compliant | NonCompliant | PendingReview) +GET /spvs/parent/:companyId +GET /spvs/:id +PUT /spvs/:id +DELETE /spvs/:id +``` + +**SPV object:** +```typescript +interface SPV { + SPVID: string; + Name: string; + Purpose: string; + CreationDate: string; + Status: 'Active' | 'Pending' | 'Closed'; + ParentCompanyID: string; + ComplianceStatus: 'Compliant' | 'NonCompliant' | 'PendingReview'; + NAV?: number; + TotalCommitments?: number; + FundedAmount?: number; + InvestmentStrategy?: string; + TargetReturn?: number; + ManagementFee?: number; + PerformanceFee?: number; +} +``` + +### SPV ASSETS (`/spv-assets`) - JWT required, admin for write ops + +``` +POST /spv-assets (Admin only) +GET /spv-assets +GET /spv-assets/spv/:spvId +GET /spv-assets/valuation/spv/:spvId (returns total valuation) +GET /spv-assets/valuation/type/:type (returns valuation by asset type) +GET /spv-assets/:id +PUT /spv-assets/:id (Admin only) +DELETE /spv-assets/:id (Admin only) +``` + +**SPVAsset object:** +```typescript +interface SPVAsset { + AssetID: string; + SPVID: string; + AssetType: string; + Value: number; + Description?: string; + AcquisitionDate?: string; + MaturityDate?: string; + Status: 'Active' | 'Sold' | 'Written Off' | 'Pending'; + ReturnRate?: number; +} +``` + +--- + +### 10. FINANCIAL REPORTS (`/financial-reports`) - JWT required + +``` +POST /financial-reports +GET /financial-reports (paginated) +GET /financial-reports/search +GET /financial-reports/analytics +POST /financial-reports/bulk +GET /financial-reports/:id +PUT /financial-reports/:id +DELETE /financial-reports/:id +``` + +**FinancialReport object:** +```typescript +interface FinancialReport { + reportId: string; + ReportName: string; + ReportType: string; + DateGenerated: string; + ReportingPeriod: 'Annual' | 'Quarterly'; + Data: { + revenue: number; + expenses: number; + netIncome: number; // Must equal revenue - expenses + assets: number; + liabilities: number; + equity: number; + cashFlow: object; + }; + CompanyID: string; + Status?: string; + GeneratedBy?: string; +} +``` + +--- + +### 11. FINANCIAL METRICS (`/metrics`) - JWT + financialReports.view permission + +``` +GET /companies/:companyId/metrics/profitability?period=2024-Q1 + Returns: { grossProfitMargin, operatingProfitMargin, netProfitMargin } + +GET /companies/:companyId/metrics/liquidity?period=2024-Q1 + Returns: { currentRatio, quickRatio, cashRatio } + +GET /companies/:companyId/metrics/solvency?period=2024-Q1 + Returns: { debtToEquity, debtToAsset, interestCoverage } + +GET /companies/:companyId/metrics/efficiency?period=2024-Q1 + Returns: { assetTurnover, inventoryTurnover, receivablesTournover } + +GET /companies/:companyId/metrics/dashboard + Returns: all metrics combined +``` + +**Period format:** `YYYY-QX` (e.g., `2024-Q1`) or `YYYY-full` + +--- + +### 12. FINANCIAL DATA IMPORT/EXPORT (`/financial-data`) - JWT required + +``` +POST /financial-data/import + Content-Type: multipart/form-data + Fields: file (max 50MB), importType, companyId?, format? + importType: transactions | financial_reports | spv_data | chart_of_accounts + Formats: csv, json, xlsx, xls + +GET /financial-data/export?exportType=X&format=Y&companyId=Z&startDate=A&endDate=B + exportType: transactions | financial_reports | spv_performance | compliance_report + format: csv, json, xlsx, pdf + +GET /financial-data/templates/:importType +GET /financial-data/import-status/:importId +POST /financial-data/validate (dry-run validation) +``` + +--- + +### 13. TAX CALCULATOR (`/tax-calculations`) + +``` +POST /tax-calculations/calculate +GET /tax-calculations +GET /tax-calculations/:id +PUT /tax-calculations/:id +DELETE /tax-calculations/:id +``` + +**TaxCalculation object:** +```typescript +interface TaxCalculation { + calculationId: string; + SaleAmount: number; + TaxRate: number; // 0 to 1 + CalculatedTax: number; // Auto: SaleAmount * TaxRate + EquityType?: string; + TaxYear?: number; + Jurisdiction?: string; +} +``` + +--- + +### 14. DOCUMENTS (`/documents`) + +``` +GET /documents (supports search, filter by category/tags/accessLevel, pagination) +POST /documents +``` + +**Document object:** +```typescript +interface Document { + documentId: string; + name: string; + title?: string; + content?: string; + path?: string; + fileType?: string; + fileSize?: number; + mimeType?: string; + accessLevel: 'public' | 'private' | 'shared'; + sharedWith?: string[]; + category?: string; + tags?: string[]; + status: 'draft' | 'active' | 'archived' | 'deleted'; + version?: number; + company?: string; + uploadedBy?: string; + metadata?: object; +} +``` + +### Document Access Control (`/document-accesses`) +Full CRUD for managing per-document access grants. + +### Document Embeddings/AI (`/document-embeddings`) +Full CRUD. Backend supports: +- Text extraction (PDF, Word, plain text, images via OCR) +- AI-powered classification with confidence scores +- Automated summarization +- Semantic vector search + +--- + +### 15. COMPLIANCE (`/compliance-checks`) + +``` +POST /compliance-checks +GET /compliance-checks +GET /compliance-checks/non-compliant +GET /compliance-checks/:id +PUT /compliance-checks/:id +DELETE /compliance-checks/:id +``` + +**ComplianceCheck object:** +```typescript +interface ComplianceCheck { + CheckID: string; + SPVID: string; + RegulationType: 'GDPR' | 'HIPAA' | 'SOX' | 'CCPA' | 'SEC' | 'FinCEN'; + Status: 'Compliant' | 'NonCompliant' | 'PendingReview'; + Details?: string; + Timestamp: string; + LastCheckedBy?: string; +} +``` + +--- + +### 16. SECURITY AUDIT LOGS (`/security-audits`) - JWT + admin/security_analyst role + +``` +GET /security-audits?eventType=X&level=Y&userId=Z&days=7&page=1&limit=50&reviewed=false +GET /security-audits/summary?days=7 +GET /security-audits/suspicious?days=1 +GET /security-audits/user/:userId?days=30 +GET /security-audits/export?days=30&level=X (CSV download) +PATCH /security-audits/:id/review Body: { notes: "..." } +``` + +--- + +### 17. COMMUNICATIONS (`/communications`) + +``` +POST /communications (send message) +POST /communications/thread (reply in thread) +GET /communications +GET /communications/thread/:threadId +GET /communications/user/:userId +GET /communications/:id +PUT /communications/:id +DELETE /communications/:id +``` + +**Communication object:** +```typescript +interface Communication { + communicationId: string; + MessageType: string; + Sender: string; + Recipient: string; + Timestamp?: string; + Content: string; + ThreadId?: string; +} +``` + +--- + +### 18. NOTIFICATIONS (`/notifications`) + +``` +POST /notifications +GET /notifications +GET /notifications/:id +DELETE /notifications/:id +``` + +--- + +### 19. INVITES (`/invites`) +Full CRUD for stakeholder/investor invitations. + +--- + +### 20. ACTIVITIES (`/activities`) +Full CRUD for activity/audit logging. Fields: `activityId`, `ActivityType`, `Description`, `UserInvolved`, `Timestamp`, `RelatedObjects`, `IPAddress`, `Device` + +--- + +### 21. INVESTMENTS (`/investments`) - JWT required + +``` +POST /investments Body: { TrackID, Company, EquityPercentage, CurrentValue } +``` + +--- + +### 22. ADMINS (`/admins`) + +``` +POST /admins +GET /admins +GET /admins/:id +PUT /admins/:id +DELETE /admins/:id +POST /admins/login +POST /admins/logout +PUT /admins/:id/change-password +``` + +--- + +### 23. INTEGRATION MODULES (`/integration-modules`) + +``` +POST /integration-modules Body: { IntegrationID, ToolName, Description, Link } +``` + +--- + +### 24. WEBSOCKET EVENTS + +Connect to `ws://localhost:5000` with JWT token for auth. + +**Client-to-server messages:** +```typescript +{ type: 'ping' } +{ type: 'join_room', roomId: string } +{ type: 'leave_room', roomId: string } +{ type: 'document_update', roomId: string, data: object } +{ type: 'cursor_position', roomId: string, position: object } +{ type: 'user_typing', roomId: string, isTyping: boolean } +``` + +**Server-to-client events:** +- User presence (online/offline) +- Document updates (real-time collaboration) +- Notifications +- SPV events +- Activity updates + +--- + +## FRONTEND PAGES TO BUILD + +Based on the backend capabilities, build these pages/routes: + +### Public Pages +- `/login` - Login form with email/password + Google OAuth button +- `/register` - Registration form with password strength indicator +- `/forgot-password` - Password reset request +- `/reset-password/:token` - Password reset form +- `/verify-email/:token` - Email verification callback + +### Protected Pages (require auth) + +**Dashboard (`/dashboard`)** +- Overview cards: total companies, active SPVs, pending compliance, recent activity +- Financial metrics summary charts +- Recent notifications +- Quick action buttons + +**Company Management (`/companies`)** +- Company list with search/filter +- `/companies/new` - Create company form +- `/companies/:id` - Company detail view with tabs: + - Overview (company info) + - Cap Table (share classes, stakeholders, investors) + - Fundraising (rounds, investors) + - Equity Plans + - Employees (with equity overview) + - Documents + - Financial Reports + - Compliance + - Settings + +**Cap Table (`/companies/:id/cap-table`)** +- Visual cap table showing ownership breakdown (pie chart) +- Share class list with details +- Stakeholder table with equity percentages +- Investor table +- Waterfall analysis visualization + +**SPV Management (`/spvs`)** +- SPV list with status/compliance filters +- `/spvs/new` - Create SPV form +- `/spvs/:id` - SPV detail view with: + - Asset portfolio table + - Total valuation display + - Asset type breakdown chart + - Compliance status + - Performance metrics (NAV, returns, fees) + +**Financial Reports (`/reports`)** +- Report list with search +- Create/edit report forms +- Report detail view with: + - Revenue vs expenses chart + - Balance sheet visualization + - Cash flow statement + - Key financial ratios +- Bulk import interface +- Export options (CSV, JSON, XLSX, PDF) + +**Financial Metrics Dashboard (`/companies/:id/metrics`)** +- Profitability metrics (margin charts) +- Liquidity ratios (gauge charts) +- Solvency metrics +- Efficiency metrics +- Period selector (quarterly/annual) +- Trend analysis over time + +**Document Management (`/documents`)** +- Document list with search, category filter, tag filter +- Upload interface (drag & drop) +- Document viewer +- Access control management (share with users) +- Version history +- AI features: classification results, summaries + +**Compliance (`/compliance`)** +- Compliance dashboard with status overview +- Check list filtered by regulation type +- Non-compliant items highlighted +- Compliance check creation form +- SPV compliance drill-down + +**Security & Audit (`/admin/security`)** - Admin only +- Audit log table with filters (event type, level, date range) +- Suspicious activity alerts +- Per-user audit trail +- Audit summary statistics +- CSV export button +- Review/acknowledge workflow + +**Communications (`/messages`)** +- Inbox/outbox view +- Thread view +- Compose message +- Real-time updates via WebSocket + +**Notifications (`/notifications`)** +- Notification list +- Mark as read +- Real-time notification bell in header via WebSocket + +**Employee Management (`/employees`)** +- Employee directory with search/pagination +- Employee detail view with equity overview +- Vesting schedule visualization + +**Data Import/Export (`/admin/data`)** +- Import wizard (select type, upload file, validate, confirm) +- Import status tracking +- Export interface with format/type selection +- Template downloads + +**Tax Calculator (`/tools/tax-calculator`)** +- Input form (sale amount, tax rate, equity type, jurisdiction) +- Auto-calculated results +- History of calculations + +**Invite Management (`/invites`)** +- Invite list +- Send invite form +- Invite status tracking + +**Admin Panel (`/admin`)** +- User management (list, create, edit, delete users) +- Admin management +- System activity log +- Integration module management +- Rate limiting status + +**Settings (`/settings`)** +- User profile edit +- Password change +- Notification preferences +- API key management + +--- + +## UI/UX REQUIREMENTS + +1. **Responsive design** - Mobile-first, works on desktop, tablet, mobile +2. **Dark/light mode** toggle +3. **Sidebar navigation** with collapsible sections grouped by domain: + - Dashboard + - Companies > Cap Table, Fundraising, Equity Plans + - SPV Management > Assets, Compliance + - Financial > Reports, Metrics, Data Import/Export, Tax Calculator + - Documents + - People > Employees, Stakeholders, Investors + - Communications > Messages, Notifications + - Admin > Users, Security Audit, Settings (role-gated) +4. **Global search** bar in header +5. **Notification bell** with real-time count via WebSocket +6. **User avatar menu** with profile, settings, logout +7. **Breadcrumb navigation** +8. **Loading skeletons** for all data-fetching states +9. **Error boundaries** with retry options +10. **Toast notifications** for CRUD operations +11. **Confirmation dialogs** for destructive actions (delete) +12. **Data tables** with sorting, filtering, pagination +13. **Charts and visualizations** for all financial data +14. **Form validation** matching backend requirements (e.g., password strength) +15. **Empty states** with call-to-action for all list views + +--- + +## AUTHENTICATION FLOW + +1. User logs in -> receives JWT + refreshToken +2. Store JWT in httpOnly cookie (set via Next.js API route proxy) +3. Next.js middleware checks cookie on every protected route +4. Axios interceptor catches 401 -> attempts token refresh -> retries request +5. If refresh fails -> redirect to login +6. On logout -> call `/auth/logout` + clear cookies + +--- + +## API ERROR HANDLING + +All endpoints return errors in this format: +```json +{ + "error": "Error message string" +} +``` + +HTTP status codes: 200 (OK), 201 (Created), 400 (Bad Request), 403 (Forbidden), 404 (Not Found), 500 (Server Error) + +Handle all error states in the UI with user-friendly messages. + +--- + +## RATE LIMITING + +The API has rate limits. Handle 429 (Too Many Requests) responses with: +- Retry-After header respect +- User-facing "please wait" message +- Exponential backoff on API client + +Tiers: Basic (100/15min), Standard (500), Premium (1000), Enterprise (5000) + +--- + +## END OF PROMPT + +The above specification covers 100% of the OpenCap backend's capabilities. Build every page, every form, every data visualization to fully utilize this API.