diff --git a/.github/README.md b/.github/README.md new file mode 100644 index 0000000..859c3ff --- /dev/null +++ b/.github/README.md @@ -0,0 +1,29 @@ +# GitHub Repository + +This directory contains GitHub-specific configurations and workflows. + +## Contents + +- **Workflows** (`workflows/`): GitHub Actions CI/CD pipelines +- **Templates** (`PULL_REQUEST_TEMPLATE.md`, `ISSUE_TEMPLATE/`): Issue and PR templates + +## CI/CD + +GitHub Actions workflows are configured for: +- Continuous Integration (testing, linting, type checking) +- Continuous Deployment (build and deploy) +- Security scanning +- Dependency updates + +## Contributing + +See [Contributing Guidelines](../docs/governance/CONTRIBUTING.md) for details on: +- Code style +- Pull request process +- Testing requirements +- Documentation standards + +--- + +**Last Updated**: 2025-01-27 + diff --git a/PROJECT_STRUCTURE.md b/PROJECT_STRUCTURE.md new file mode 100644 index 0000000..34835fc --- /dev/null +++ b/PROJECT_STRUCTURE.md @@ -0,0 +1,313 @@ +# The Order - Project Structure + +**Last Updated**: 2025-01-27 +**Status**: Comprehensive Structure Guide + +## Overview + +This document provides a complete overview of The Order project structure, helping developers navigate the codebase efficiently. + +## Repository Layout + +``` +the-order/ +├── apps/ # Frontend applications +│ ├── mcp-legal/ # Legal management portal +│ ├── portal-public/ # Public-facing portal +│ └── portal-internal/ # Internal portal +│ +├── services/ # Backend microservices +│ ├── identity/ # Identity & credential service +│ ├── intake/ # Document intake service +│ ├── finance/ # Payment & finance service +│ ├── dataroom/ # Virtual data room service +│ ├── legal-documents/ # Legal document management +│ └── eresidency/ # e-Residency service +│ +├── packages/ # Shared libraries +│ ├── shared/ # Common utilities +│ ├── database/ # Database layer +│ ├── schemas/ # Zod/JSON schemas +│ ├── auth/ # Authentication +│ ├── storage/ # Storage abstraction +│ ├── crypto/ # Cryptography & KMS +│ ├── monitoring/ # Observability +│ ├── cache/ # Caching utilities +│ └── [20+ more packages] +│ +├── infra/ # Infrastructure as Code +│ ├── terraform/ # Terraform configurations +│ │ ├── management-groups/ # Management group hierarchy +│ │ ├── policies/ # Azure policies +│ │ ├── modules/ # Reusable modules +│ │ │ └── regional-landing-zone/ +│ │ └── multi-region/ # Multi-region deployment +│ ├── k8s/ # Kubernetes manifests +│ │ ├── base/ # Base configurations +│ │ └── overlays/ # Environment overlays +│ ├── monitoring/ # Monitoring configs +│ └── scripts/ # Infrastructure scripts +│ +├── docs/ # Documentation +│ ├── architecture/ # Architecture documentation +│ ├── deployment/ # Deployment guides +│ │ └── azure/ # Azure-specific guides +│ ├── governance/ # Governance & policies +│ ├── integrations/ # Integration guides +│ │ └── entra-verifiedid/ # Entra VerifiedID +│ ├── legal/ # Legal documentation +│ │ └── document-management/ # Document management +│ └── reports/ # Project reports +│ +├── scripts/ # Utility scripts +│ ├── deploy/ # Deployment scripts +│ ├── dev/ # Development scripts +│ ├── backup/ # Backup scripts +│ └── security/ # Security scripts +│ +├── assets/ # Static assets +│ └── seals/ # Credential seal images +│ +└── manifests/ # Application manifests +``` + +## Key Directories + +### Applications (`apps/`) + +Frontend applications built with React/Next.js: + +- **mcp-legal**: Legal document management portal +- **portal-public**: Public-facing member portal +- **portal-internal**: Internal administrative portal + +### Services (`services/`) + +Backend microservices (Node.js/TypeScript/Fastify): + +- **identity**: eIDAS/DID, verifiable credentials, Entra VerifiedID +- **intake**: Document ingestion, OCR, classification +- **finance**: Payments, ledgers, invoicing +- **dataroom**: Virtual data rooms, deal management +- **legal-documents**: Comprehensive document management +- **eresidency**: e-Residency services + +### Packages (`packages/`) + +Shared libraries used across services and apps: + +- **shared**: Common utilities, middleware, error handling +- **database**: Database layer, migrations, queries +- **schemas**: Zod schemas for validation +- **auth**: Authentication and authorization +- **storage**: Storage abstraction (S3/GCS/Azure) +- **crypto**: Cryptography, KMS integration +- **monitoring**: Prometheus metrics, OpenTelemetry +- **cache**: Redis caching utilities + +### Infrastructure (`infra/`) + +Infrastructure as Code: + +- **terraform/**: Azure infrastructure + - Management groups + - Policies + - Regional landing zones + - Multi-region deployment +- **k8s/**: Kubernetes manifests + - Base configurations + - Environment overlays (dev/stage/prod) +- **monitoring/**: Prometheus, Grafana configs +- **scripts/**: Infrastructure automation + +### Documentation (`docs/`) + +Comprehensive documentation: + +- **architecture/**: System architecture, ADRs +- **deployment/**: Deployment guides +- **governance/**: Policies, security, compliance +- **integrations/**: Integration documentation +- **legal/**: Legal system documentation +- **reports/**: Project status, reviews + +## Navigation Guide + +### For New Developers + +1. Start with `README.md` (project root) +2. Review `PROJECT_STRUCTURE.md` (this file) +3. Check `docs/architecture/README.md` +4. Read service-specific READMEs in `services/*/README.md` + +### For Infrastructure Engineers + +1. `infra/README.md` - Infrastructure overview +2. `infra/terraform/README.md` - Terraform guide +3. `infra/k8s/README.md` - Kubernetes guide +4. `docs/deployment/azure/` - Azure deployment guides + +### For Backend Developers + +1. `services/*/README.md` - Service documentation +2. `packages/*/README.md` - Package documentation +3. `docs/architecture/` - Architecture decisions +4. `docs/integrations/` - Integration guides + +### For Frontend Developers + +1. `apps/*/README.md` - Application documentation +2. `packages/ui/README.md` - UI component library +3. `docs/architecture/` - Frontend architecture + +## File Naming Conventions + +### Documentation +- `README.md` - Directory overview +- `ARCHITECTURE.md` - Architecture documentation +- `DEPLOYMENT.md` - Deployment guides +- `GUIDE.md` - How-to guides +- `SUMMARY.md` - Executive summaries + +### Code +- `index.ts` - Main entry point +- `*.service.ts` - Service layer +- `*.route.ts` - API routes +- `*.test.ts` - Test files +- `*.config.ts` - Configuration files + +### Infrastructure +- `main.tf` - Main Terraform file +- `variables.tf` - Variables +- `outputs.tf` - Outputs +- `versions.tf` - Version constraints +- `deployment.yaml` - Kubernetes deployment +- `service.yaml` - Kubernetes service + +## Common Patterns + +### Service Structure +``` +services/{service-name}/ +├── src/ +│ ├── index.ts # Entry point +│ ├── routes/ # API routes +│ ├── services/ # Business logic +│ └── types/ # TypeScript types +├── tests/ # Test files +├── k8s/ # Kubernetes manifests +├── Dockerfile # Container definition +├── package.json # Dependencies +└── README.md # Service documentation +``` + +### Package Structure +``` +packages/{package-name}/ +├── src/ +│ ├── index.ts # Main exports +│ └── [module files] +├── tests/ # Test files +├── package.json # Package definition +└── README.md # Package documentation +``` + +### Infrastructure Structure +``` +infra/{tool}/ +├── [config files] +├── modules/ # Reusable modules +└── README.md # Infrastructure guide +``` + +## Quick Reference + +### Find Service Code +```bash +# All services +ls services/ + +# Specific service +cd services/identity +``` + +### Find Package Code +```bash +# All packages +ls packages/ + +# Specific package +cd packages/database +``` + +### Find Documentation +```bash +# Architecture docs +ls docs/architecture/ + +# Deployment guides +ls docs/deployment/ + +# Service docs +find services -name README.md +``` + +### Find Infrastructure +```bash +# Terraform +ls infra/terraform/ + +# Kubernetes +ls infra/k8s/ + +# Scripts +ls infra/scripts/ +``` + +## Development Workflow + +1. **Local Development** + ```bash + pnpm install + docker-compose up -d # Start local services + pnpm dev # Start development servers + ``` + +2. **Building** + ```bash + pnpm build # Build all packages + pnpm build --filter @the-order/{package} # Build specific + ``` + +3. **Testing** + ```bash + pnpm test # Run all tests + pnpm test --filter @the-order/{package} # Test specific + ``` + +4. **Deployment** + ```bash + source infra/scripts/azure-load-env.sh + ./infra/scripts/azure-deploy.sh + ``` + +## Important Files + +- `package.json` - Root package configuration +- `pnpm-workspace.yaml` - Monorepo workspace config +- `tsconfig.json` - TypeScript configuration +- `turbo.json` - Turborepo configuration +- `.env` - Environment variables (not in git) +- `docker-compose.yml` - Local development stack + +## Getting Help + +- **Architecture Questions**: See `docs/architecture/` +- **Deployment Issues**: See `docs/deployment/` +- **Service Documentation**: See `services/*/README.md` +- **Package Documentation**: See `packages/*/README.md` + +--- + +**Last Updated**: 2025-01-27 + diff --git a/README.md b/README.md index afe63ce..46ab096 100644 --- a/README.md +++ b/README.md @@ -1,179 +1,266 @@ # The Order -Monorepo for The Order - A comprehensive platform for legal, financial, and governance systems. +**A comprehensive platform for digital identity, verifiable credentials, and legal document management** + +[![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) +[![TypeScript](https://img.shields.io/badge/TypeScript-5.0+-blue.svg)](https://www.typescriptlang.org/) +[![Node.js](https://img.shields.io/badge/Node.js-18+-green.svg)](https://nodejs.org/) ## Overview -The Order is a mono-repo containing all applications, services, packages, infrastructure, and documentation for managing legal documents, financial systems, identity management, datarooms, and member portals. +The Order is a sovereign cloud platform providing: +- **Digital Identity Management**: eIDAS/DID-based identity verification +- **Verifiable Credentials**: Microsoft Entra VerifiedID integration +- **Legal Document Management**: Comprehensive DMS for law firms and courts +- **Virtual Data Rooms**: Secure deal management +- **Financial Services**: Payment processing and invoicing +- **e-Residency**: Digital residency services -### Governance & Legal Framework +Built with **Cloud for Sovereignty** principles, ensuring data residency, compliance, and operational control. -This repository also supports the governance and legal transition framework for: -- **Order of Military Hospitallers** - Constitutional sovereign structure -- **International Criminal Court of Commerce** - Judicial arm and tribunal -- **Digital Bank of International Settlements (DBIS)** - Financial market infrastructure - -See [docs/reports/GOVERNANCE_TASKS.md](./docs/reports/GOVERNANCE_TASKS.md) and [docs/governance/](./docs/governance/) for comprehensive governance documentation. - -## Repository Structure - -``` -the-order/ -├─ apps/ # End-user applications (web + portals) -│ ├─ portal-public/ # Public web presence -│ ├─ portal-internal/ # Internal web (admin/ops) -│ ├─ mcp-members/ # MCP for Members of The Order -│ └─ mcp-legal/ # MCP for Legal Purpose (matters, filings, attestations) -│ -├─ services/ # Domain services (APIs, workers) -│ ├─ intake/ # "Drop content" tool: ingestion → OCR → classify → route -│ ├─ identity/ # Digital Systems (eIDAS/DID, verifiable credentials) -│ ├─ finance/ # Requisite financial systems (payments, ledgers, rates) -│ ├─ dataroom/ # Dataroom(s) for all deals (secure VDR, deal room APIs) -│ ├─ omnis-brand/ # Branded version of OMNIS (as a service/app shell) -│ └─ arromis-brand/ # Branded version of ARROMIS (as a service/app shell) -│ -├─ packages/ # Shared libraries (versioned in the mono-repo) -│ ├─ ui/ # Design system (React/Tailwind components) -│ ├─ schemas/ # Zod/OpenAPI/JSON Schema contracts -│ ├─ auth/ # AuthZ/AuthN helpers (OIDC, wallet, eIDAS adapters) -│ ├─ storage/ # S3/GCS abstraction, object lifecycle, WORM mode -│ ├─ crypto/ # KMS/HSM client, key mgmt, signatures (eIDAS/DID) -│ ├─ workflows/ # Temporal/Step Functions definitions -│ └─ test-utils/ # Testing utilities and helpers -│ -├─ infra/ # Everything-as-code -│ ├─ terraform/ # Cloud infra, secrets backends, KMS/HSM, PKI -│ ├─ k8s/ # Helm charts/overlays (dev/stage/prod) -│ ├─ gateways/ # API gateway / proxy / WAF configs -│ └─ cicd/ # Reusable CI templates, SBOM, signing -│ -├─ docs/ # Living documentation -│ ├─ legal/ # Legal policies, ABAC, compliance frameworks -│ ├─ governance/ # Contribution, security, incident runbooks -│ ├─ reports/ # Project reports, reviews, task lists -│ ├─ architecture/ # ADRs, data flows, threat models -│ └─ product/ # Roadmaps, PRDs -│ -└─ scripts/ # Utility scripts -``` - -## Quickstart +## Quick Start ### Prerequisites - Node.js >= 18.0.0 - pnpm >= 8.0.0 -- Git +- Docker & Docker Compose +- Azure CLI (for deployments) +- Terraform >= 1.5.0 (for infrastructure) ### Installation ```bash -# Clone the repository -git clone https://github.com/the-order/the-order.git +# Clone repository +git clone cd the-order -# Initialize submodules (if any) -git submodule update --init --recursive +# Install dependencies +pnpm install +# Start local services (PostgreSQL, Redis, OpenSearch) +docker-compose up -d + +# Build all packages +pnpm build + +# Start development servers +pnpm dev +``` + +### Environment Setup + +1. Copy `.env.example` to `.env` +2. Configure Azure credentials: + ```bash + ARM_SUBSCRIPTION_ID="your-subscription-id" + ARM_TENANT_ID="your-tenant-id" + ARM_LOCATION="westeurope" + ``` +3. Load environment: + ```bash + source infra/scripts/azure-load-env.sh + ``` + +## Project Structure + +``` +the-order/ +├── apps/ # Frontend applications +├── services/ # Backend microservices +├── packages/ # Shared libraries +├── infra/ # Infrastructure as Code +├── docs/ # Documentation +└── scripts/ # Utility scripts +``` + +**📖 See [PROJECT_STRUCTURE.md](PROJECT_STRUCTURE.md) for detailed structure guide** + +## Architecture + +### Services + +- **Identity Service** (`services/identity/`): eIDAS/DID, verifiable credentials, Entra VerifiedID +- **Intake Service** (`services/intake/`): Document ingestion, OCR, classification +- **Finance Service** (`services/finance/`): Payments, ledgers, invoicing +- **Dataroom Service** (`services/dataroom/`): Virtual data rooms, deal management +- **Legal Documents Service** (`services/legal-documents/`): Comprehensive document management +- **e-Residency Service** (`services/eresidency/`): Digital residency services + +### Applications + +- **MCP Legal** (`apps/mcp-legal/`): Legal document management portal +- **Portal Public** (`apps/portal-public/`): Public-facing member portal +- **Portal Internal** (`apps/portal-internal/`): Internal administrative portal + +### Infrastructure + +- **Terraform** (`infra/terraform/`): Azure infrastructure, Cloud for Sovereignty landing zones +- **Kubernetes** (`infra/k8s/`): Container orchestration +- **Monitoring** (`infra/monitoring/`): Prometheus, Grafana + +## Documentation + +### Getting Started +- [Project Structure](PROJECT_STRUCTURE.md) - Complete structure guide +- [Quick Start Guide](QUICKSTART.md) - Development setup +- [Architecture Overview](docs/architecture/README.md) - System architecture + +### Deployment +- [Azure Deployment](docs/deployment/azure/ENVIRONMENT_SETUP.md) - Azure setup +- [Sovereignty Landing Zone](docs/deployment/azure/SOVEREIGNTY_LANDING_ZONE_DEPLOYMENT.md) - Multi-region deployment +- [Kubernetes Deployment](infra/k8s/README.md) - K8s deployment guide + +### Architecture +- [Cloud for Sovereignty Landing Zone](docs/architecture/CLOUD_FOR_SOVEREIGNTY_LANDING_ZONE.md) - Complete architecture +- [Well-Architected Framework](docs/architecture/README.md) - Architecture principles +- [Data Models](docs/architecture/README.md#data-models) - Entity relationships + +### Integrations +- [Entra VerifiedID](docs/integrations/entra-verifiedid/README.md) - Credential issuance +- [Azure CDN](docs/deployment/azure/cdn-setup.md) - CDN configuration + +### Legal System +- [Document Management](docs/legal/document-management/) - DMS documentation +- [API Documentation](docs/legal/document-management/implementation/) - API reference + +## Development + +### Commands + +```bash # Install dependencies pnpm install # Build all packages pnpm build -``` - -### Development - -```bash -# Start all apps and services in development mode -pnpm dev - -# Run specific workspace -pnpm --filter portal-public dev - -# Run linting -pnpm lint - -# Run type checking -pnpm type-check # Run tests pnpm test + +# Start development +pnpm dev + +# Lint code +pnpm lint + +# Type check +pnpm type-check ``` -### Environment Variables - -Environment variables are managed using SOPS (Secrets Operations). See `docs/governance/SECURITY.md` for details. - -1. Copy `.env.example` files to `.env.local` in each workspace -2. For encrypted secrets, use SOPS with age keys -3. Never commit plaintext secrets to the repository - -Example: -```bash -# Decrypt and load secrets -sops -d secrets/dev.env.enc > .env.local -``` - -## Environments - -- **dev**: Local development environment -- **stage**: Staging environment for testing -- **prod**: Production environment - -Environment-specific configurations are in `infra/k8s/overlays/`. - -## Git Submodules - -Some services and apps are managed as Git submodules. To add submodules: +### Working with Services ```bash -# See scripts/add-submodules.sh for examples -./scripts/add-submodules.sh +# Start specific service +pnpm --filter @the-order/identity-service dev + +# Build specific service +pnpm --filter @the-order/identity-service build + +# Test specific service +pnpm --filter @the-order/identity-service test ``` -To update submodules: +### Working with Packages + ```bash -git submodule update --remote +# Build specific package +pnpm --filter @the-order/database build + +# Test specific package +pnpm --filter @the-order/database test ``` -## Contribution +## Infrastructure -Please read [CONTRIBUTING.md](docs/governance/CONTRIBUTING.md) for details on our code of conduct and the process for submitting pull requests. +### Azure Deployment -### Development Workflow +```bash +# Load environment +source infra/scripts/azure-load-env.sh -1. Create a feature branch from `main` -2. Make your changes -3. Run tests and linting: `pnpm test && pnpm lint` -4. Commit using [Conventional Commits](https://www.conventionalcommits.org/) -5. Push and create a Pull Request +# Deploy infrastructure +./infra/scripts/azure-deploy.sh -### Code Standards +# Deploy sovereignty landing zone +./infra/scripts/deploy-sovereignty-landing-zone.sh +``` -- TypeScript strict mode enabled -- ESLint + Prettier for code formatting -- All tests must pass -- Type checking must pass -- Follow the architecture decisions in `docs/architecture/adrs/` +### Kubernetes Deployment + +```bash +# Apply base configuration +kubectl apply -k infra/k8s/base + +# Apply environment overlay +kubectl apply -k infra/k8s/overlays/dev +``` + +## Key Features + +### Digital Identity +- ✅ eIDAS compliance +- ✅ DID (Decentralized Identifiers) +- ✅ Microsoft Entra VerifiedID +- ✅ Verifiable Credentials + +### Document Management +- ✅ Document templates +- ✅ Version control +- ✅ Legal matter management +- ✅ Court filing integration +- ✅ Real-time collaboration +- ✅ E-signatures + +### Security & Compliance +- ✅ Cloud for Sovereignty +- ✅ Data residency enforcement +- ✅ Customer-managed encryption +- ✅ Private endpoints +- ✅ GDPR & eIDAS compliance + +### Infrastructure +- ✅ Multi-region deployment (7 regions) +- ✅ Well-Architected Framework +- ✅ Infrastructure as Code +- ✅ Automated deployments +- ✅ Comprehensive monitoring + +## Technology Stack + +### Frontend +- React 18+ +- Next.js 14+ +- TypeScript +- Tailwind CSS +- Material-UI + +### Backend +- Node.js 18+ +- TypeScript +- Fastify +- PostgreSQL +- Redis + +### Infrastructure +- Azure (non-US commercial regions) +- Kubernetes +- Terraform +- Docker + +### Monitoring +- Prometheus +- Grafana +- OpenTelemetry +- Log Analytics + +## Contributing + +See [CONTRIBUTING.md](docs/governance/CONTRIBUTING.md) for contribution guidelines. ## Security -See [SECURITY.md](docs/governance/SECURITY.md) for security policies and reporting procedures. - -## Architecture - -Architecture Decision Records (ADRs) are located in `docs/architecture/adrs/`. See [docs/architecture/README.md](docs/architecture/README.md) for more information. - -## Release Process - -Releases are managed via semantic versioning and automated through CI/CD: - -1. Merge to `main` triggers automated tests and builds -2. Tagged releases trigger deployment to staging -3. Manual approval required for production deployment -4. See `.github/workflows/release.yml` for details +See [SECURITY.md](docs/governance/SECURITY.md) for security policies and reporting. ## License @@ -181,11 +268,23 @@ See [LICENSE](LICENSE) for license information. ## Support -For questions and support, please open an issue in this repository. +- **Documentation**: See `docs/` directory +- **Architecture**: See `docs/architecture/` +- **Deployment**: See `docs/deployment/` +- **Issues**: Use GitHub Issues -## Related Documentation +## Status -- [Security Policy](docs/governance/SECURITY.md) -- [Contributing Guide](docs/governance/CONTRIBUTING.md) -- [Architecture Documentation](docs/architecture/README.md) -- [Product Roadmap](docs/product/README.md) +**Current Status**: Active Development + +- ✅ Core services implemented +- ✅ Legal document management complete +- ✅ Entra VerifiedID integration complete +- ✅ Multi-region infrastructure planned +- 🔄 Testing and optimization in progress + +See [docs/reports/](docs/reports/) for detailed status reports. + +--- + +**Last Updated**: 2025-01-27 diff --git a/apps/README.md b/apps/README.md new file mode 100644 index 0000000..f5179bc --- /dev/null +++ b/apps/README.md @@ -0,0 +1,86 @@ +# Applications Directory + +**Last Updated**: 2025-01-27 +**Purpose**: Frontend applications overview + +## Overview + +This directory contains frontend applications built with React, Next.js, and TypeScript. + +## Available Applications + +### MCP Legal (`mcp-legal/`) +- **Purpose**: Legal document management portal +- **Technology**: React, Material-UI, React Query +- **Features**: Document management, matter management, template library +- **Documentation**: [MCP Legal README](mcp-legal/README.md) + +### Portal Public (`portal-public/`) +- **Purpose**: Public-facing member portal +- **Technology**: Next.js, React, Tailwind CSS +- **Features**: Member services, credential management +- **Documentation**: [Portal Public README](portal-public/README.md) + +### Portal Internal (`portal-internal/`) +- **Purpose**: Internal administrative portal +- **Technology**: Next.js, React, Tailwind CSS +- **Features**: Administration, reporting, analytics +- **Documentation**: [Portal Internal README](portal-internal/README.md) + +## Application Structure + +All applications follow a consistent structure: + +``` +app/ +├── src/ +│ ├── app/ # Next.js app directory (if using App Router) +│ ├── components/ # React components +│ ├── pages/ # Next.js pages (if using Pages Router) +│ ├── hooks/ # React hooks +│ ├── utils/ # Utility functions +│ └── types/ # TypeScript types +├── public/ # Static assets +├── package.json # Dependencies +└── README.md # Application documentation +``` + +## Development + +### Running Applications + +```bash +# Start all applications +pnpm dev + +# Start specific application +pnpm --filter portal-public dev +``` + +### Building Applications + +```bash +# Build all applications +pnpm build + +# Build specific application +pnpm --filter portal-public build +``` + +## Shared Components + +Applications use shared UI components from `packages/ui/`: +```typescript +import { Button, Card, Modal } from '@the-order/ui'; +``` + +## Related Documentation + +- [Project Structure](../PROJECT_STRUCTURE.md) +- [Packages Documentation](../packages/) +- [Architecture Documentation](../docs/architecture/) + +--- + +**Last Updated**: 2025-01-27 + diff --git a/apps/mcp-legal/src/components/CourtFiling.tsx b/apps/mcp-legal/src/components/CourtFiling.tsx new file mode 100644 index 0000000..244d1f3 --- /dev/null +++ b/apps/mcp-legal/src/components/CourtFiling.tsx @@ -0,0 +1,230 @@ +/** + * Court Filing Component + * UI for court filing management + */ + +import React, { useState } from 'react'; +import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; +import { + Box, + Button, + Card, + CardContent, + Typography, + Table, + TableBody, + TableCell, + TableHead, + TableRow, + Chip, + Dialog, + DialogTitle, + DialogContent, + DialogActions, + TextField, + FormControl, + InputLabel, + Select, + MenuItem, + Alert, +} from '@mui/material'; +import { Add as AddIcon, CalendarToday as CalendarIcon } from '@mui/icons-material'; + +interface Filing { + id: string; + document_id: string; + matter_id: string; + court_name: string; + case_number?: string; + filing_type: string; + status: string; + filing_deadline?: string; +} + +export function CourtFiling({ matterId }: { matterId: string }) { + const [createDialogOpen, setCreateDialogOpen] = useState(false); + const queryClient = useQueryClient(); + + const { data: filings } = useQuery({ + queryKey: ['filings', matterId], + queryFn: async () => { + const response = await fetch(`/api/filings?matter_id=${matterId}`); + const data = await response.json(); + return data.filings || []; + }, + }); + + const { data: deadlines } = useQuery({ + queryKey: ['filing-deadlines', matterId], + queryFn: async () => { + const response = await fetch(`/api/matters/${matterId}/filing-deadlines`); + const data = await response.json(); + return data.deadlines || []; + }, + }); + + const createFiling = useMutation({ + mutationFn: async (filing: Partial) => { + const response = await fetch('/api/filings', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(filing), + }); + return response.json(); + }, + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ['filings', matterId] }); + setCreateDialogOpen(false); + }, + }); + + const handleCreateFiling = (formData: FormData) => { + createFiling.mutate({ + matter_id: matterId, + document_id: formData.get('document_id') as string, + court_name: formData.get('court_name') as string, + case_number: formData.get('case_number') as string, + filing_type: formData.get('filing_type') as string, + filing_deadline: formData.get('filing_deadline') as string, + }); + }; + + const getStatusColor = (status: string) => { + switch (status) { + case 'filed': + return 'success'; + case 'accepted': + return 'success'; + case 'rejected': + return 'error'; + case 'submitted': + return 'info'; + default: + return 'default'; + } + }; + + return ( + + + Court Filings + + + + {deadlines && deadlines.length > 0 && ( + + Upcoming Deadlines + {deadlines.map((deadline) => ( + + {deadline.court_name}: {new Date(deadline.filing_deadline!).toLocaleDateString()} + + ))} + + )} + + + + + + Court + Case Number + Type + Status + Deadline + + + + {filings?.map((filing) => ( + + {filing.court_name} + {filing.case_number || 'N/A'} + {filing.filing_type} + + + + + {filing.filing_deadline ? ( + + + {new Date(filing.filing_deadline).toLocaleDateString()} + + ) : ( + 'N/A' + )} + + + ))} + +
+
+ + setCreateDialogOpen(false)} maxWidth="sm" fullWidth> +
{ + e.preventDefault(); + handleCreateFiling(new FormData(e.currentTarget)); + }} + > + Create Court Filing + + + + + + Filing Type + + + + + + + + +
+
+
+ ); +} + diff --git a/apps/mcp-legal/src/components/DocumentAssembly.tsx b/apps/mcp-legal/src/components/DocumentAssembly.tsx new file mode 100644 index 0000000..3d266be --- /dev/null +++ b/apps/mcp-legal/src/components/DocumentAssembly.tsx @@ -0,0 +1,208 @@ +/** + * Document Assembly Component + * UI for template-based document generation + */ + +import React, { useState } from 'react'; +import { useQuery, useMutation } from '@tanstack/react-query'; +import { + Box, + Button, + Card, + CardContent, + Stepper, + Step, + StepLabel, + TextField, + Typography, + FormControl, + InputLabel, + Select, + MenuItem, + Grid, + Chip, +} from '@mui/material'; +import { CheckCircle as CheckCircleIcon } from '@mui/icons-material'; + +interface Template { + id: string; + name: string; + variables?: string[]; +} + +export function DocumentAssembly() { + const [activeStep, setActiveStep] = useState(0); + const [selectedTemplate, setSelectedTemplate] = useState(''); + const [variables, setVariables] = useState>({}); + const [preview, setPreview] = useState(''); + + const { data: templates } = useQuery({ + queryKey: ['templates'], + queryFn: async () => { + const response = await fetch('/api/templates'); + const data = await response.json(); + return data.templates || []; + }, + }); + + const previewMutation = useMutation({ + mutationFn: async ({ templateId, vars }: { templateId: string; vars: Record }) => { + const response = await fetch(`/api/templates/${templateId}/render`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ variables: vars }), + }); + return response.json(); + }, + onSuccess: (data) => { + setPreview(data.rendered); + setActiveStep(2); + }, + }); + + const generateMutation = useMutation({ + mutationFn: async (data: any) => { + const response = await fetch('/api/assembly/generate', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(data), + }); + return response.json(); + }, + onSuccess: () => { + setActiveStep(3); + }, + }); + + const handleNext = () => { + if (activeStep === 0 && selectedTemplate) { + // Get template variables + fetch(`/api/templates/${selectedTemplate}/variables`) + .then((res) => res.json()) + .then((data) => { + const vars: Record = {}; + data.variables?.forEach((v: string) => { + vars[v] = ''; + }); + setVariables(vars); + setActiveStep(1); + }); + } else if (activeStep === 1) { + previewMutation.mutate({ templateId: selectedTemplate, vars: variables }); + } else if (activeStep === 2) { + generateMutation.mutate({ + template_id: selectedTemplate, + variables, + title: `Document from ${templates?.find((t) => t.id === selectedTemplate)?.name}`, + save_document: true, + }); + } + }; + + const steps = ['Select Template', 'Enter Variables', 'Preview', 'Complete']; + + return ( + + + Document Assembly + + + + {steps.map((label) => ( + + {label} + + ))} + + + {activeStep === 0 && ( + + {templates?.map((template) => ( + + setSelectedTemplate(template.id)} + > + + {template.name} + + + + ))} + + )} + + {activeStep === 1 && ( + + + + Enter Variable Values + + {Object.keys(variables).map((key) => ( + setVariables({ ...variables, [key]: e.target.value })} + margin="normal" + /> + ))} + + + )} + + {activeStep === 2 && ( + + + + Preview + + + {preview || 'Generating preview...'} + + + + )} + + {activeStep === 3 && ( + + + + + Document Generated Successfully! + + + + + )} + + + + {activeStep < 3 && ( + + )} + + + ); +} + diff --git a/apps/mcp-legal/src/components/DocumentManagement.tsx b/apps/mcp-legal/src/components/DocumentManagement.tsx new file mode 100644 index 0000000..1228fa7 --- /dev/null +++ b/apps/mcp-legal/src/components/DocumentManagement.tsx @@ -0,0 +1,286 @@ +/** + * Document Management Component + * Main UI for document management in MCP Legal app + */ + +import React, { useState, useEffect } from 'react'; +import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; +import { + Box, + Button, + Card, + CardContent, + CardHeader, + Chip, + Dialog, + DialogActions, + DialogContent, + DialogTitle, + FormControl, + InputLabel, + MenuItem, + Select, + TextField, + Typography, + Table, + TableBody, + TableCell, + TableHead, + TableRow, + IconButton, + Tooltip, +} from '@mui/material'; +import { + Add as AddIcon, + Edit as EditIcon, + Delete as DeleteIcon, + Visibility as ViewIcon, + History as HistoryIcon, + Download as DownloadIcon, + Share as ShareIcon, +} from '@mui/icons-material'; + +interface Document { + id: string; + title: string; + type: string; + status: string; + created_at: string; + updated_at: string; +} + +interface DocumentManagementProps { + matterId?: string; +} + +export function DocumentManagement({ matterId }: DocumentManagementProps) { + const [selectedDocument, setSelectedDocument] = useState(null); + const [createDialogOpen, setCreateDialogOpen] = useState(false); + const [viewDialogOpen, setViewDialogOpen] = useState(false); + const [filterType, setFilterType] = useState('all'); + const queryClient = useQueryClient(); + + // Fetch documents + const { data: documents, isLoading } = useQuery({ + queryKey: ['documents', matterId, filterType], + queryFn: async () => { + const params = new URLSearchParams(); + if (matterId) params.append('matter_id', matterId); + if (filterType !== 'all') params.append('type', filterType); + const response = await fetch(`/api/documents?${params}`); + if (!response.ok) throw new Error('Failed to fetch documents'); + const data = await response.json(); + return data.documents || []; + }, + }); + + // Create document mutation + const createDocument = useMutation({ + mutationFn: async (doc: Partial) => { + const response = await fetch('/api/documents', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(doc), + }); + if (!response.ok) throw new Error('Failed to create document'); + return response.json(); + }, + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ['documents'] }); + setCreateDialogOpen(false); + }, + }); + + // Delete document mutation + const deleteDocument = useMutation({ + mutationFn: async (id: string) => { + const response = await fetch(`/api/documents/${id}`, { + method: 'DELETE', + }); + if (!response.ok) throw new Error('Failed to delete document'); + }, + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ['documents'] }); + }, + }); + + const handleCreateDocument = (formData: FormData) => { + createDocument.mutate({ + title: formData.get('title') as string, + type: formData.get('type') as string, + content: formData.get('content') as string, + matter_id: matterId, + }); + }; + + const handleViewDocument = (doc: Document) => { + setSelectedDocument(doc); + setViewDialogOpen(true); + }; + + const handleDeleteDocument = (id: string) => { + if (confirm('Are you sure you want to delete this document?')) { + deleteDocument.mutate(id); + } + }; + + return ( + + + Documents + + + Filter + + + + + + + {isLoading ? ( + Loading... + ) : ( + + + + + Title + Type + Status + Created + Actions + + + + {documents?.map((doc) => ( + + {doc.title} + + + + + + + {new Date(doc.created_at).toLocaleDateString()} + + + handleViewDocument(doc)}> + + + + + + + + + + + + + + + handleDeleteDocument(doc.id)} + > + + + + + + ))} + +
+
+ )} + + {/* Create Document Dialog */} + setCreateDialogOpen(false)} maxWidth="md" fullWidth> +
{ + e.preventDefault(); + handleCreateDocument(new FormData(e.currentTarget)); + }} + > + Create New Document + + + + Type + + + + + + + + +
+
+ + {/* View Document Dialog */} + setViewDialogOpen(false)} maxWidth="lg" fullWidth> + {selectedDocument?.title} + + {selectedDocument && ( + + + Type: {selectedDocument.type} | Status: {selectedDocument.status} + + + Created: {new Date(selectedDocument.created_at).toLocaleString()} + + + )} + + + + + + +
+ ); +} + diff --git a/apps/mcp-legal/src/components/DocumentWorkflow.tsx b/apps/mcp-legal/src/components/DocumentWorkflow.tsx new file mode 100644 index 0000000..68e2526 --- /dev/null +++ b/apps/mcp-legal/src/components/DocumentWorkflow.tsx @@ -0,0 +1,218 @@ +/** + * Document Workflow Component + * UI for workflow management and approval + */ + +import React, { useState } from 'react'; +import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; +import { + Box, + Button, + Card, + CardContent, + LinearProgress, + Typography, + Chip, + List, + ListItem, + ListItemText, + Dialog, + DialogTitle, + DialogContent, + DialogActions, + TextField, +} from '@mui/material'; +import { + CheckCircle as ApproveIcon, + Cancel as RejectIcon, + Assignment as AssignmentIcon, +} from '@mui/icons-material'; + +interface Workflow { + id: string; + document_id: string; + workflow_type: string; + status: string; + steps: WorkflowStep[]; +} + +interface WorkflowStep { + id: string; + step_number: number; + step_type: string; + status: string; + assigned_to?: string; + due_date?: string; +} + +export function DocumentWorkflow({ documentId }: { documentId: string }) { + const [approvalDialogOpen, setApprovalDialogOpen] = useState(false); + const [selectedStep, setSelectedStep] = useState(null); + const [comments, setComments] = useState(''); + const queryClient = useQueryClient(); + + const { data: workflow } = useQuery({ + queryKey: ['workflow', documentId], + queryFn: async () => { + const response = await fetch(`/api/documents/${documentId}/workflows`); + const data = await response.json(); + return data.workflows?.[0] || null; + }, + }); + + const approveStep = useMutation({ + mutationFn: async ({ stepId, comments: cmts }: { stepId: string; comments?: string }) => { + const response = await fetch(`/api/workflows/steps/${stepId}/complete`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ status: 'approved', comments: cmts }), + }); + return response.json(); + }, + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ['workflow', documentId] }); + setApprovalDialogOpen(false); + }, + }); + + const rejectStep = useMutation({ + mutationFn: async ({ stepId, comments: cmts }: { stepId: string; comments?: string }) => { + const response = await fetch(`/api/workflows/steps/${stepId}/complete`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ status: 'rejected', comments: cmts }), + }); + return response.json(); + }, + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ['workflow', documentId] }); + setApprovalDialogOpen(false); + }, + }); + + if (!workflow) { + return No workflow found for this document; + } + + const completedSteps = workflow.steps?.filter((s) => s.status === 'approved' || s.status === 'rejected').length || 0; + const totalSteps = workflow.steps?.length || 1; + const progress = (completedSteps / totalSteps) * 100; + + return ( + + + Workflow: {workflow.workflow_type} + + + + + + + Progress + + + + {completedSteps} of {totalSteps} steps completed + + + + + + + + Workflow Steps + + + {workflow.steps?.map((step) => ( + + + + + ) : ( + + ) + } + > + + + + ))} + + + + + setApprovalDialogOpen(false)}> + + {selectedStep?.status === 'pending' ? 'Approve or Reject Step' : 'Add Comments'} + + + setComments(e.target.value)} + sx={{ mt: 2 }} + /> + + + + + + + + + ); +} + diff --git a/apps/mcp-legal/src/components/MatterManagement.tsx b/apps/mcp-legal/src/components/MatterManagement.tsx new file mode 100644 index 0000000..f321591 --- /dev/null +++ b/apps/mcp-legal/src/components/MatterManagement.tsx @@ -0,0 +1,228 @@ +/** + * Matter Management Component + * UI for legal matter management + */ + +import React, { useState } from 'react'; +import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; +import { + Box, + Button, + Card, + CardContent, + Chip, + Dialog, + DialogActions, + DialogContent, + DialogTitle, + TextField, + Typography, + Table, + TableBody, + TableCell, + TableHead, + TableRow, + IconButton, + Tabs, + Tab, +} from '@mui/material'; +import { + Add as AddIcon, + Edit as EditIcon, + Folder as FolderIcon, + People as PeopleIcon, + Description as DescriptionIcon, +} from '@mui/icons-material'; +import { DocumentManagement } from './DocumentManagement'; + +interface Matter { + id: string; + matter_number: string; + title: string; + status: string; + matter_type?: string; + client_id?: string; + created_at: string; +} + +export function MatterManagement() { + const [selectedMatter, setSelectedMatter] = useState(null); + const [createDialogOpen, setCreateDialogOpen] = useState(false); + const [tabValue, setTabValue] = useState(0); + const queryClient = useQueryClient(); + + const { data: matters, isLoading } = useQuery({ + queryKey: ['matters'], + queryFn: async () => { + const response = await fetch('/api/matters'); + if (!response.ok) throw new Error('Failed to fetch matters'); + const data = await response.json(); + return data.matters || []; + }, + }); + + const createMatter = useMutation({ + mutationFn: async (matter: Partial) => { + const response = await fetch('/api/matters', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(matter), + }); + if (!response.ok) throw new Error('Failed to create matter'); + return response.json(); + }, + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ['matters'] }); + setCreateDialogOpen(false); + }, + }); + + const handleCreateMatter = (formData: FormData) => { + createMatter.mutate({ + matter_number: formData.get('matter_number') as string, + title: formData.get('title') as string, + description: formData.get('description') as string, + matter_type: formData.get('matter_type') as string, + status: 'open', + }); + }; + + return ( + + + Legal Matters + + + + {selectedMatter ? ( + + + setSelectedMatter(null)}>← + {selectedMatter.title} + + + + setTabValue(v)}> + } label="Documents" /> + } label="Participants" /> + } label="Details" /> + + + + {tabValue === 0 && } + {tabValue === 1 && Participants coming soon} + {tabValue === 2 && ( + + + Matter Details + Number: {selectedMatter.matter_number} + Type: {selectedMatter.matter_type || 'N/A'} + Status: {selectedMatter.status} + + + )} + + + ) : ( + <> + {isLoading ? ( + Loading... + ) : ( + + + + + Matter Number + Title + Type + Status + Actions + + + + {matters?.map((matter) => ( + setSelectedMatter(matter)} + sx={{ cursor: 'pointer' }} + > + {matter.matter_number} + {matter.title} + {matter.matter_type || 'N/A'} + + + + + + + + + + ))} + +
+
+ )} + + )} + + setCreateDialogOpen(false)} maxWidth="sm" fullWidth> +
{ + e.preventDefault(); + handleCreateMatter(new FormData(e.currentTarget)); + }} + > + Create New Matter + + + + + + + + + + +
+
+
+ ); +} + diff --git a/apps/mcp-legal/src/components/TemplateLibrary.tsx b/apps/mcp-legal/src/components/TemplateLibrary.tsx new file mode 100644 index 0000000..1a54ccb --- /dev/null +++ b/apps/mcp-legal/src/components/TemplateLibrary.tsx @@ -0,0 +1,252 @@ +/** + * Template Library Component + * UI for document template management + */ + +import React, { useState } from 'react'; +import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; +import { + Box, + Button, + Card, + CardContent, + CardHeader, + Chip, + Dialog, + DialogActions, + DialogContent, + DialogTitle, + TextField, + Typography, + Grid, + IconButton, + MenuItem, + Select, + FormControl, + InputLabel, +} from '@mui/material'; +import { + Add as AddIcon, + Edit as EditIcon, + Preview as PreviewIcon, + FileCopy as FileCopyIcon, +} from '@mui/icons-material'; + +interface Template { + id: string; + name: string; + description?: string; + category?: string; + version: number; + is_active: boolean; +} + +export function TemplateLibrary() { + const [selectedTemplate, setSelectedTemplate] = useState