diff --git a/.github/workflows/backend-cd.yml b/.github/workflows/backend-cd.yml index ff8fdea..c7729f7 100644 --- a/.github/workflows/backend-cd.yml +++ b/.github/workflows/backend-cd.yml @@ -105,7 +105,7 @@ jobs: fi } - echo "πŸ“€ Syncing secrets to SSM..." + echo "πŸ“€ Syncing GitHub secrets to SSM Parameter Store..." write_secret "mongodbUri" "${{ secrets.MONGO_URI }}" write_secret "jwtSecret" "${{ secrets.JWT_SECRET }}" write_secret "smtpHost" "${{ secrets.SMTP_HOST }}" @@ -113,8 +113,8 @@ jobs: write_secret "smtpUser" "${{ secrets.SMTP_USER }}" write_secret "smtpPassword" "${{ secrets.SMTP_PASSWORD }}" write_secret "smtpFrom" "${{ secrets.SMTP_FROM }}" - # Add any new secret here - just add to GitHub Secrets UI - echo "βœ… Done" + # To add new secrets: add to GitHub repo secrets, then reference here + echo "βœ… Sync complete" - name: Deploy on EC2 via SSM RunCommand (pull + restart container) shell: bash @@ -136,7 +136,7 @@ jobs: IMAGE_URI="__IMAGE_URI__" PARAM_PREFIX="/comptaleyes/dev" - echo "[1/7] Fetch ALL parameters from SSM" + echo "[1/7] Fetching SSM parameters" PARAMS_JSON=$(aws ssm get-parameters-by-path --path "$PARAM_PREFIX" --with-decryption --region "$REGION" --query 'Parameters[*].[Name,Value]' --output json) if [ "$(echo "$PARAMS_JSON" | jq 'length')" -eq 0 ]; then @@ -146,23 +146,22 @@ jobs: echo "βœ… Found $(echo "$PARAMS_JSON" | jq 'length') parameters" - echo "[2/7] Ensure docker is running" + echo "[2/7] Starting Docker service" sudo systemctl start docker || true - echo "[3/7] Login to ECR" - echo "[3/7] Login to ECR" + echo "[3/7] Authenticating with ECR" aws ecr get-login-password --region "$REGION" | sudo docker login --username AWS --password-stdin "$(echo "$IMAGE_URI" | cut -d/ -f1)" - echo "[4/7] Pull image" - echo "[4/7] Pull image" + echo "[4/7] Pulling Docker image" sudo docker pull "$IMAGE_URI" - echo "[5/7] Stop/remove old container" + echo "[5/7] Removing old container" sudo docker rm -f "$APP_NAME" || true - echo "[6/7] Run container with ALL SSM env vars" + echo "[6/7] Starting new container with environment variables" ENV_FLAGS="-e PORT=$CONTAINER_PORT -e SERVICE_NAME=comptaleyes-backend" + # Convert SSM parameters to environment variables while IFS= read -r line; do PARAM_NAME=$(echo "$line" | jq -r '.[0]' | sed 's|.*/||') PARAM_VALUE=$(echo "$line" | jq -r '.[1]') @@ -172,7 +171,7 @@ jobs: eval sudo docker run -d --name "$APP_NAME" --restart unless-stopped -p "${HOST_PORT}:${CONTAINER_PORT}" $ENV_FLAGS "$IMAGE_URI" - echo "[7/7] Container status" + echo "[7/7] Verifying container status" sudo docker ps --filter "name=$APP_NAME" --format "table {{.Names}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}" EOF ) diff --git a/.github/workflows/cdk-deploy.yml b/.github/workflows/cdk-deploy.yml index cecef87..7a6e8e6 100644 --- a/.github/workflows/cdk-deploy.yml +++ b/.github/workflows/cdk-deploy.yml @@ -23,8 +23,8 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 30 - # 1) no forks - # 2) explicitly enforce PR base branch = master + # Only run for PRs from same repo targeting master branch + # Prevents: forks from deploying, accidental deploys from feature branches if: | github.event.pull_request.head.repo.full_name == github.repository && github.event.pull_request.base.ref == 'master' @@ -51,9 +51,8 @@ jobs: - name: Verify AWS identity run: aws sts get-caller-identity - - name: Build Infra + - name: Build infrastructure TypeScript run: npm -w infra run build - # CDK deploy with real creds (localSynth MUST be false) - - name: CDK deploy (real) + - name: Deploy infrastructure to AWS run: npm -w infra run cdk -- deploy --all --require-approval never -c localSynth=false -c env=dev diff --git a/.github/workflows/frontend-cd.yml b/.github/workflows/frontend-cd.yml index ed2b8ec..4fd74f0 100644 --- a/.github/workflows/frontend-cd.yml +++ b/.github/workflows/frontend-cd.yml @@ -74,7 +74,6 @@ jobs: echo "bucket_name=$BUCKET_NAME" >> "$GITHUB_OUTPUT" echo "distribution_id=$DIST_ID" >> "$GITHUB_OUTPUT" - # This will only run once frontend/package.json exists. - name: Setup Node if: steps.fe.outputs.exists == 'true' uses: actions/setup-node@v4 @@ -86,24 +85,23 @@ jobs: if: steps.fe.outputs.exists == 'true' run: npm ci - - name: Build frontend (placeholder) - if: steps.fe.outputs.exists == 'true' - run: npm -w frontend run build - - - name: Write frontend env (Vite) + - name: Configure environment variables for build if: steps.fe.outputs.exists == 'true' run: | set -euo pipefail : "${API_BASE_URL:?Set FRONTEND_API_BASE_URL secret to your backend URL}" - echo "VITE_BACKEND_URL=${API_BASE_URL}" >> frontend/.env.production + echo "VITE_BACKEND_URL=${API_BASE_URL}" > frontend/.env.production + + - name: Build frontend application + if: steps.fe.outputs.exists == 'true' + run: npm -w frontend run build - - name: Verify build output exists (placeholder expects frontend/dist) + - name: Verify build output directory if: steps.fe.outputs.exists == 'true' run: | set -euo pipefail if [ ! -d "frontend/dist" ]; then - echo "Expected build output folder frontend/dist not found." - echo "When you create the frontend, ensure the build outputs to frontend/dist, or update this workflow." + echo "Build output folder frontend/dist not found" exit 1 fi @@ -121,9 +119,9 @@ jobs: --distribution-id "${{ steps.cf.outputs.distribution_id }}" \ --paths "/*" - - name: Skip (frontend not initialized yet) + - name: Skip deployment (frontend not found) if: steps.fe.outputs.exists != 'true' run: | - echo "frontend/package.json not found; frontend CD is intentionally a placeholder." - echo "CloudFormation lookup succeeded (infra is ready)." - echo "Once frontend exists, re-run this workflow." + echo "frontend/package.json not found" + echo "Infrastructure is ready - create frontend to enable deployment" + echo "Once frontend exists, re-run this workflow" diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..3af1c88 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +# MIT License + +Copyright (c) 2026 CisCode + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index 9e9dc3f..a5ba4a4 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,183 @@ # Comptaleyes Platform -## Structure +**Modern accounting and finance management platform built with scalable microservices architecture.** -- Backend: API Folder -- Frontend: UI folder -- Infra: IaC Factory for both stacks -- .github: Shared workflows running on paths conditions! +## πŸ“‹ Project Overview + +Comptaleyes is a full-stack web application designed for accounting and financial management. The platform features a NestJS backend API, React frontend, and automated AWS infrastructure deployment using CDK. + +## πŸ—οΈ Architecture + +This monorepo contains three main components: + +``` +comptaleyes/ +β”œβ”€β”€ backend/ # NestJS API with authentication & business logic +β”œβ”€β”€ frontend/ # React SPA with modern UI components +β”œβ”€β”€ infra/ # AWS CDK infrastructure as code +└── .github/ # CI/CD workflows (GitHub Actions) +``` + +### Backend + +- **Framework**: NestJS (Node.js 22) +- **Database**: MongoDB Atlas +- **Authentication**: JWT + OAuth2 (Microsoft, Google, Facebook) +- **Email**: SMTP-based verification & password reset +- **Deployment**: Docker β†’ AWS ECR β†’ EC2 + +### Frontend + +- **Framework**: React 19 with TypeScript +- **Build Tool**: Vite +- **UI Library**: @ciscode/ui-authentication-kit +- **Deployment**: S3 + CloudFront CDN + +### Infrastructure + +- **IaC**: AWS CDK (TypeScript) +- **Compute**: EC2 for backend containers +- **Storage**: S3 for frontend static assets +- **CDN**: CloudFront for global distribution +- **Secrets**: SSM Parameter Store + +## πŸš€ Quick Start + +### Prerequisites + +- Node.js 22+ and npm +- Docker Desktop +- AWS CLI configured (for deployment) +- MongoDB Atlas account + +### Backend Setup + +```bash +cd backend +cp .env.example .env +# Edit .env with your credentials +npm install +npm run dev +``` + +Backend will be available at `http://localhost:3000` + +**Health Check**: `curl http://localhost:3000/health` + +### Frontend Setup + +```bash +cd frontend +cp .env.example .env +# Edit .env with backend URL +npm install +npm run dev +``` + +Frontend will be available at `http://localhost:5173` + +### Full Stack with Docker + +```bash +cd backend +docker compose -f compose/docker-compose.dev.yml up --build +``` + +## πŸ“š Documentation + +- [Backend README](backend/README.md) - API architecture, domain logic, deployment +- [Frontend README](frontend/README.md) - UI components, routing, authentication +- [Infrastructure README](infra/README.md) - CDK stacks, AWS resources + +## πŸ” Environment Configuration + +All sensitive credentials are stored in `.env` files (local) or AWS SSM Parameter Store (production). + +**Required Environment Variables**: See `.env.example` files in each directory: + +- [backend/.env.example](backend/.env.example) +- [frontend/.env.example](frontend/.env.example) + +## πŸ§ͺ Testing + +```bash +# Backend tests +cd backend +npm test # All tests +npm run test:watch # Watch mode +npm run test:cov # Coverage report + +# Frontend tests +cd frontend +npm test +``` + +## 🚒 Deployment + +### CI/CD Pipelines + +GitHub Actions workflows handle automated deployments: + +- **Backend CI**: PR validation (lint, test, typecheck) +- **Backend CD**: Build Docker β†’ ECR β†’ EC2 deployment +- **Frontend CI**: PR validation (lint, test, typecheck) +- **Frontend CD**: Build Vite β†’ S3 β†’ CloudFront invalidation +- **CDK Deploy**: Infrastructure updates via CDK + +### Manual Deployment + +```bash +# Deploy infrastructure +cd infra +npm run build +npx cdk deploy --all + +# Deploy backend (via GitHub Actions) +git push origin master # Triggers backend-cd.yml + +# Deploy frontend (via GitHub Actions) +git push origin master # Triggers frontend-cd.yml +``` + +## πŸƒ Production Environments + +- **Frontend**: Deployed via CloudFront CDN for global distribution +- **Backend API**: Deployed on AWS EC2 with Docker +- **Database**: MongoDB Atlas +- **Infrastructure**: AWS (us-east-1 region) + +## πŸ› οΈ Development Workflow + +1. Create feature branch from `develop` +2. Make changes and commit +3. Push and create PR β†’ `develop` +4. CI pipeline validates (lint, test, typecheck) +5. After review, merge to `develop` +6. When ready for release, PR β†’ `master` triggers deployment + +## πŸ“¦ Tech Stack Summary + +| Component | Technologies | +| -------------- | ---------------------------------------- | +| Backend | NestJS, TypeScript, MongoDB, Docker | +| Frontend | React, Vite, TailwindCSS, React Router | +| Authentication | JWT, OAuth2, @ciscode/authentication-kit | +| Infrastructure | AWS CDK, EC2, S3, CloudFront, ECR | +| CI/CD | GitHub Actions with OIDC | +| Monitoring | CloudWatch Logs, Health endpoints | + +## 🀝 Contributing + +See [CONTRIBUTING.md](CONTRIBUTING.md) for development guidelines. + +## πŸ”’ Security + +To report security vulnerabilities: **info@ciscod.com** + +See [SECURITY](SECURITY) for our security policy. + +## πŸ“ License + +MIT License - See [LICENSE](LICENSE) file for details. + +Copyright (c) 2026 CisCode diff --git a/backend/README.md b/backend/README.md index 7813c64..932b7f4 100644 --- a/backend/README.md +++ b/backend/README.md @@ -1,204 +1,309 @@ -# Comptaleyes - Backend API +# Comptaleyes Backend API -The API side of Comptaleyes platform. +**NestJS-based REST API for the Comptaleyes accounting platform.** -## Overview +## πŸ“‹ Overview - +This is the backend service for Comptaleyes, providing authentication, business logic, and data persistence. Built with NestJS and following Domain-Driven Design principles with a modular architecture. -## Quick start +## 🎯 Domain / Business Scope -```bash -cp .env.example .env -npm i -npm run dev -``` +**What this service owns:** -β€’Health: `http://localhost:3000/health` -β€’Ready: `http://localhost:3000/ready` +- User authentication & authorization (JWT, OAuth2) +- Account management & email verification +- Business entities and accounting logic +- API endpoints for all frontend operations +- Integration with MongoDB for data persistence -## Running Locally (without Docker) +**What this service does NOT own:** -```bash -npm install -npm run dev -``` +- Frontend UI rendering (handled by frontend/) +- Infrastructure provisioning (handled by infra/) +- Static asset delivery (handled by CloudFront) -API will be available at: +## πŸ› οΈ Tech Stack -```code -http://localhost:3000 -``` +- **Runtime**: Node.js 22.x +- **Framework**: NestJS 11 +- **Language**: TypeScript +- **Database**: MongoDB Atlas with Mongoose +- **Authentication**: @ciscode/authentication-kit v1.5.0 +- **Testing**: Jest +- **Validation**: class-validator, class-transformer +- **Documentation**: Swagger/OpenAPI +- **Containerization**: Docker -## Running with Docker (recommended) +## πŸ—οΈ Architecture -```bash -docker compose -f compose/docker-compose.dev.yml up --build +``` +src/ +β”œβ”€β”€ core/ # Cross-cutting concerns +β”‚ β”œβ”€β”€ config/ # Environment & app configuration +β”‚ β”œβ”€β”€ docs/ # Swagger/OpenAPI setup +β”‚ β”œβ”€β”€ errors/ # Global error handling +β”‚ β”œβ”€β”€ health/ # Health check endpoints +β”‚ β”œβ”€β”€ http/ # HTTP middleware (request ID, context) +β”‚ └── logging/ # Centralized logging +β”‚ +β”œβ”€β”€ modules/ # Business domains +β”‚ └── example/ # Example module (DDD structure) +β”‚ β”œβ”€β”€ api/ # Controllers & DTOs +β”‚ β”œβ”€β”€ application/ # Use cases & ports +β”‚ β”œβ”€β”€ domain/ # Entities & business logic +β”‚ └── infrastructure/ # Repositories & external integrations +β”‚ +└── shared/ # Shared utilities + β”œβ”€β”€ constants/ # Application constants + β”œβ”€β”€ types/ # TypeScript types + └── utils/ # Helper functions ``` -Production-like build +**Design Principles:** + +- Domain-Driven Design (DDD) with clear boundaries +- Dependency Injection via NestJS +- Repository pattern for data access +- Clean separation: API β†’ Application β†’ Domain β†’ Infrastructure + +## πŸ“ Project Structure -```bash -docker build -f docker/Dockerfile -t app:local . -docker run --rm -p 3000:3000 --env-file .env app:local +``` +backend/ +β”œβ”€β”€ src/ +β”‚ β”œβ”€β”€ app.module.ts # Root application module +β”‚ β”œβ”€β”€ main.ts # Application entry point +β”‚ β”œβ”€β”€ core/ # Shared infrastructure +β”‚ β”œβ”€β”€ modules/ # Business feature modules +β”‚ └── shared/ # Utilities & types +β”œβ”€β”€ test/ +β”‚ β”œβ”€β”€ unit/ # Unit tests +β”‚ └── e2e/ # End-to-end tests +β”œβ”€β”€ docker/ +β”‚ └── Dockerfile # Production container image +β”œβ”€β”€ compose/ +β”‚ └── docker-compose.dev.yml # Local development setup +β”œβ”€β”€ .env.example # Environment template +└── package.json ``` -## Testing +## βš™οΈ Environment Configuration -```bash -# unit + e2e -npm test +All configuration is loaded from environment variables via `@nestjs/config`. -# watch mode -npm run test:watch +**Required variables**: See [.env.example](.env.example) for complete list. -# coverage (used by CI & Sonar) -npm run test:cov -``` +**Key configurations:** + +- `MONGO_URI`: MongoDB connection string +- `JWT_*`: Authentication secrets and expiration +- `SMTP_*`: Email service configuration +- `MICROSOFT_*`, `GOOGLE_*`, `FB_*`: OAuth provider credentials + +**Production secrets**: Stored in AWS SSM Parameter Store under `/comptaleyes/dev/*` -## Linting and Formatting +## πŸš€ Running Locally + +### Without Docker ```bash -npm run lint -npm run lint:fix +# Install dependencies +npm install -npm run format -npm run format:check +# Copy environment template +cp .env.example .env +# Edit .env with your credentials + +# Start in development mode (hot reload) +npm run dev ``` -## CI/CD Pipelines +API will be available at: `http://localhost:3000` -### CI - PR Validation +**Health endpoints:** -β€’Runs on PRs β†’ develop -β€’Typecheck -β€’Lint -β€’Tests +- Health: `http://localhost:3000/health` +- Ready: `http://localhost:3000/ready` -### CI - Release Check +### With Docker (Recommended) -β€’Runs on PRs β†’ master -β€’Full validation -β€’Docker build -β€’Optional SonarCloud analysis (manual trigger) +Development mode with hot reload: + +```bash +docker compose -f compose/docker-compose.dev.yml up --build +``` -### CD - Deploy +Production-like build: -β€’Placeholder pipeline -β€’Will handle dev / preprod / prod deployments +```bash +docker build -f docker/Dockerfile -t comptaleyes-backend:local . +docker run --rm -p 3000:3000 --env-file .env comptaleyes-backend:local +``` + +## πŸ“š API Documentation + +Swagger UI is available in development: + +``` +http://localhost:3000/api/docs +``` -## SonarCloud (Optional) +OpenAPI spec: `http://localhost:3000/api/docs-json` -SonarCloud analysis is disabled by default. +## πŸ§ͺ Testing -To run it: -1.Go to GitHub β†’ Actions -2.Open CI - Release Check -3.Click Run workflow -4.Set sonar = true -5.Run +```bash +# Run all tests (unit + e2e) +npm test -Only the SONAR_TOKEN is stored as a repo secret. +# Unit tests only +npm run test:unit -## Git Hooks +# E2E tests only +npm run test:e2e -This repo uses Husky for local quality gates: -β€’ Lint -β€’ Typecheck -β€’ Tests (as configured) +# Watch mode +npm run test:watch -Hooks do not run in Docker or CI environments. +# Coverage report (used by CI) +npm run test:cov +``` -## Contributing +Coverage reports are generated in `coverage/` directory. -See [Contributing rules](CONTRIBUTING.md) +## πŸ” Linting & Code Quality -## Security +```bash +# Run ESLint +npm run lint -To report a security vulnerability, please contact: +# Auto-fix linting issues +npm run lint:fix -πŸ“§ **info@ciscod.com** +# Format code with Prettier +npm run format -See [SECURITY.md](SECURITY)οΏΌ +# Check formatting (CI) +npm run format:check -## License +# TypeScript type checking +npm run typecheck +``` -UNLICENSED (internal use) +## 🚒 CI/CD ---- +### CI - PR Validation -## BACKEND API README (Required Sections) +**Triggers**: PRs to `develop` branch -```js +**Steps:** -# Comptalize - API +1. Checkout code +2. Install dependencies +3. Run typecheck +4. Run linting +5. Run tests -## Overview +### CI - Release Check -(What this service does, in one paragraph) +**Triggers**: PRs to `master` branch -## Domain / Business Scope +**Steps:** -(What this service owns – and what it explicitly does NOT own) +1. Full validation (typecheck, lint, test) +2. Docker build verification +3. Optional SonarCloud analysis (manual trigger) -## Tech Stack +### CD - Deployment -(Node, framework, major dependencies) +**Triggers**: Push to `master` branch -## Architecture +**Steps:** -(High-level explanation of modules, boundaries, and responsibilities) +1. Build Docker image +2. Push to AWS ECR +3. Fetch environment from SSM Parameter Store +4. Deploy to EC2 via SSM RunCommand +5. Health check verification -## Project Structure +**Deployment target**: EC2 instance -(Explain src/core, src/modules, src/shared) + -## Environment Configuration +## πŸ“Š Observability -(Required env vars and how they are loaded) +**Logging:** -## Running Locally +- Structured JSON logs via Winston +- Request ID tracking for distributed tracing +- Automatic context injection (user, tenant, correlation) -(How to start without Docker) +**Metrics:** -## Running with Docker +- Health check endpoint: `/health` +- Ready check endpoint: `/ready` -(How to run in dev and prod-like mode) +**Monitoring:** -## API Documentation +- CloudWatch Logs (production) +- Container logs via `docker logs` (local) -(OpenAPI / Swagger info if applicable) +## ⚠️ Error Handling -## Testing +**Global Exception Filter:** -(Unit, integration, e2e – how to run them) +- All errors are caught and transformed to consistent API responses +- Validation errors return structured field-level messages +- Business logic errors use custom `ApiError` class +- Unexpected errors are logged and sanitized in responses -## Linting & Code Quality +**Response format:** -(ESLint, formatting, rules) +```json +{ + "statusCode": 400, + "message": "Validation failed", + "errors": [{ "field": "email", "message": "Invalid email format" }] +} +``` -## CI / CD +## πŸ”’ Security -(What pipelines exist and when they run) +- **Authentication**: JWT tokens with refresh mechanism +- **OAuth2**: Microsoft, Google, Facebook single sign-on +- **Secrets**: Never committed; use `.env` locally, SSM in production +- **Email verification**: Required for account activation +- **Password reset**: Secure token-based flow +- **CORS**: Configured for frontend domain only -## Observability +**Secret management:** -(Logging, metrics, tracing if applicable) +- Local: `.env` file (gitignored) +- Production: AWS SSM Parameter Store +- Never log sensitive data -## Error Handling +## 🌍 Deployment Environments -(Global error strategy) +| Environment | URL | Database | Secrets | +| ----------- | ----------------------- | ------------- | ------- | +| Local | `http://localhost:3000` | `.env` | `.env` | +| Production | `#hidden` | MongoDB Atlas | AWS SSM | -## Security +## πŸ‘₯ Ownership & Contacts -(Auth, secrets, sensitive data handling – high level) +- **Team**: CisCode Development +- **Contact**: info@ciscod.com +- **Repository**: [GitHub](https://github.com/CISCDE-MA/comptaleyes) -## Deployment Environments +## πŸ”— Related Documentation -(dev / preprod / prod expectations) +- [Frontend README](../frontend/README.md) +- [Infrastructure README](../infra/README.md) +- [Root README](../README.md) +- [Contributing Guidelines](../CONTRIBUTING.md) -## Ownership & Contacts +## πŸ“ License -(Team / email / Slack / escalation path) +MIT License - See [LICENSE](../LICENSE) file for details. -``` +Copyright (c) 2026 CisCode diff --git a/backend/package.json b/backend/package.json index 52668e7..5ce21c9 100644 --- a/backend/package.json +++ b/backend/package.json @@ -4,7 +4,7 @@ "description": "", "author": "", "private": true, - "license": "UNLICENSED", + "license": "MIT", "...": "...", "scripts": { "dev": "nest start --watch", diff --git a/frontend/.env.example b/frontend/.env.example new file mode 100644 index 0000000..baa39c0 --- /dev/null +++ b/frontend/.env.example @@ -0,0 +1,19 @@ +# ============================================== +# COMPTALEYES FRONTEND - ENVIRONMENT VARIABLES +# ============================================== + +# --------------------------------------------- +# API CONFIGURATION +# --------------------------------------------- +# Backend API base URL (without trailing slash) +# Development: http://localhost:3000 +# Production: https://api.yourdomain.com or http://your-ec2-ip:3000 +VITE_BACKEND_URL=http://localhost:3000 + +# --------------------------------------------- +# NOTES +# --------------------------------------------- +# - Vite requires env vars to be prefixed with VITE_ to be exposed to the client +# - These variables are embedded at build time (not runtime) +# - For production builds, set VITE_BACKEND_URL before running `npm run build` +# - Never store secrets in frontend env vars (they're visible in the browser) diff --git a/frontend/README.md b/frontend/README.md index 952af1a..5473b12 100644 --- a/frontend/README.md +++ b/frontend/README.md @@ -1 +1,327 @@ -# Comptaleyes FrontEnd +# Comptaleyes Frontend + +**Modern React application with authentication, internationalization, and responsive design.** + +## πŸ“‹ Overview + +The frontend for Comptaleyes is a single-page application (SPA) built with React 19, Vite, and TypeScript. It provides a modern user interface for accounting and financial management with built-in authentication flows, multi-language support, and responsive design. + +## πŸ› οΈ Tech Stack + +- **Framework**: React 19 with TypeScript +- **Build Tool**: Vite (fast dev server & optimized builds) +- **Routing**: React Router v7 +- **Styling**: TailwindCSS with RTL support +- **State Management**: TanStack Query (React Query) +- **Authentication**: @ciscode/ui-authentication-kit v1.0.4 +- **Internationalization**: @ciscode/ui-translate-core +- **UI Components**: Custom components + IconifyCSS +- **File Upload**: FilePond with image preview +- **HTTP Client**: Axios via centralized httpClient + +## πŸ—οΈ Architecture + +``` +src/ +β”œβ”€β”€ app/ # Application core +β”‚ β”œβ”€β”€ App.tsx # Root component +β”‚ β”œβ”€β”€ config/ # Environment configuration +β”‚ β”œβ”€β”€ layouts/ # Page layouts (Root, App) +β”‚ β”œβ”€β”€ providers/ # Context providers wrapper +β”‚ └── router/ # Route definitions +β”‚ +β”œβ”€β”€ pages/ # Page components +β”‚ └── Loading.tsx # Loading state +β”‚ +β”œβ”€β”€ features/ # Feature modules (business logic) +β”‚ +β”œβ”€β”€ components/ # Reusable components +β”‚ +β”œβ”€β”€ services/ # External integrations +β”‚ └── api/ # Backend API client +β”‚ β”œβ”€β”€ httpClient.ts # Axios instance +β”‚ └── endpoints.ts # API endpoint definitions +β”‚ +β”œβ”€β”€ i18n/ # Internationalization +β”‚ β”œβ”€β”€ locales/ # Translation files +β”‚ β”‚ β”œβ”€β”€ en/ # English translations +β”‚ β”‚ β”œβ”€β”€ fr/ # French translations +β”‚ β”‚ └── ar/ # Arabic translations +β”‚ └── loadAll.ts # Load all translations +β”‚ +β”œβ”€β”€ shared/ # Shared utilities +β”‚ β”œβ”€β”€ lib/ # Utility functions +β”‚ β”œβ”€β”€ styles/ # Global styles +β”‚ └── ui/ # UI components library +β”‚ +└── assets/ # Static assets (images, fonts) +``` + +## βš™οΈ Environment Configuration + +Environment variables are loaded via Vite's `import.meta.env`. + +**Required variables**: See [.env.example](.env.example) + +**Key configuration:** + +- `VITE_BACKEND_URL`: Backend API base URL (e.g., `http://localhost:3000`) + +**Important**: + +- All frontend env vars must be prefixed with `VITE_` to be exposed +- Variables are embedded at **build time** (not runtime) +- Never store secrets in frontend env vars (visible in browser) + +## πŸš€ Running Locally + +### Development Server + +```bash +# Install dependencies +npm install + +# Copy environment template +cp .env.example .env +# Edit .env with backend URL + +# Start dev server (hot reload) +npm run dev +``` + +Application will be available at: `http://localhost:5173` + +### Production Build + +```bash +# Build for production +npm run build + +# Preview production build locally +npm run preview +``` + +Build output: `dist/` directory + +## 🎨 Styling + +**TailwindCSS** with custom configuration: + +- RTL (Right-to-Left) support for Arabic +- Custom color palette +- Iconify icons integration +- Dark mode ready (if enabled) + +**Global styles**: [src/shared/styles/globals.css](src/shared/styles/globals.css) + +## 🌍 Internationalization (i18n) + +Multi-language support via `@ciscode/ui-translate-core`: + +**Supported languages:** + +- English (en) +- French (fr) +- Arabic (ar) with RTL layout + +**Translation files**: [src/i18n/locales/](src/i18n/locales/) + +**Usage example:** + +```tsx +import { useTranslation } from '@ciscode/ui-translate-core'; + +function MyComponent() { + const { t } = useTranslation('common'); + return

{t('welcome')}

; +} +``` + +## πŸ” Authentication + +Authentication is handled by `@ciscode/ui-authentication-kit`: + +**Features:** + +- Login / Signup forms +- Email verification flow +- Password reset flow +- OAuth2 integration (Microsoft, Google, Facebook) +- JWT token management +- Protected routes + +**Auth pages:** + +- `/login` - User login +- `/signup` - User registration +- `/verify-email` - Email verification +- `/reset-password` - Password reset request +- `/reset-password/:token` - Password reset confirmation + +## πŸ›£οΈ Routing + +React Router v7 with protected routes: + +```tsx +// Example route structure +const router = createBrowserRouter([ + { + path: '/', + element: , + children: [ + { path: 'login', element: }, + { path: 'signup', element: }, + { + path: 'app', + element: ( + + + + ), + children: [ + { path: 'dashboard', element: }, + // ... other protected routes + ], + }, + ], + }, +]); +``` + +## πŸ“‘ API Integration + +**HTTP Client**: [src/services/api/httpClient.ts](src/services/api/httpClient.ts) + +- Axios instance with interceptors +- Automatic authentication header injection +- Request/response logging +- Error handling + +**Endpoints**: [src/services/api/endpoints.ts](src/services/api/endpoints.ts) + +```tsx +// Example API call +import { httpClient } from '@/services/api/httpClient'; + +const fetchUser = async () => { + const response = await httpClient.get('/api/users/me'); + return response.data; +}; +``` + +## πŸ§ͺ Testing + +```bash +# Run tests (placeholder - no tests yet) +npm test +``` + +**Testing stack** (to be implemented): + +- Vitest for unit tests +- React Testing Library for component tests +- MSW for API mocking + +## πŸ” Linting & Code Quality + +```bash +# Run ESLint +npm run lint + +# Auto-fix linting issues +npm run lint:fix + +# Format code with Prettier +npm run format + +# Check formatting (CI) +npm run format + +# TypeScript type checking +npm run typecheck +``` + +## 🚒 CI/CD + +### CI - PR Validation + +**Triggers**: PRs to `develop` branch + +**Steps:** + +1. Checkout code +2. Install dependencies +3. Run typecheck +4. Run linting +5. Run tests (when implemented) + +### CI - Release Check + +**Triggers**: PRs to `master` branch + +**Steps:** + +1. Full validation (typecheck, lint, test) +2. Production build verification + +### CD - Deployment + +**Triggers**: Push to `master` branch + +**Steps:** + +1. Configure environment variables +2. Build frontend application (`npm run build`) +3. Upload to S3 bucket +4. Invalidate CloudFront cache +5. Deployment complete + +**Deployment target**: AWS CloudFront distribution (configured via infrastructure code) + +## 🌍 Deployment Environments + +| Environment | URL | Backend API | Build | +| ----------- | --------------------------------------- | ----------------------- | --------------- | +| Local | `http://localhost:5173` | `http://localhost:3000` | Dev server | +| Production | `https://d2wphahz78yg97.cloudfront.net` | `#hidden` | S3 + CloudFront | + +## πŸ“¦ Build Output + +```bash +npm run build +``` + +Output structure: + +``` +dist/ +β”œβ”€β”€ assets/ # Bundled JS, CSS, fonts +β”œβ”€β”€ index.html # Entry HTML +└── ... # Static assets +``` + +**Optimization:** + +- Code splitting +- Tree shaking +- Minification +- Asset hashing for cache busting + +## πŸ‘₯ Ownership & Contacts + +- **Team**: CisCode Development +- **Contact**: info@ciscod.com +- **Repository**: [GitHub](https://github.com/CISCODE-MA/comptaleyes) + +## πŸ”— Related Documentation + +- [Backend README](../backend/README.md) +- [Infrastructure README](../infra/README.md) +- [Root README](../README.md) +- [Contributing Guidelines](../CONTRIBUTING.md) + +## πŸ“ License + +MIT License - See [LICENSE](../LICENSE) file for details. + +Copyright (c) 2026 CisCode diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx index 27d5f6f..c96a5f6 100644 --- a/frontend/src/main.tsx +++ b/frontend/src/main.tsx @@ -37,15 +37,5 @@ createRoot(document.getElementById('root')!).render( - - - - - - - - - - , ); diff --git a/infra/README.md b/infra/README.md index 80c3df3..a096a45 100644 --- a/infra/README.md +++ b/infra/README.md @@ -1,14 +1,261 @@ -# Welcome to your CDK TypeScript project +# Comptaleyes Infrastructure -This is a blank project for CDK development with TypeScript. +**AWS CDK infrastructure as code for Comptaleyes platform.** -The `cdk.json` file tells the CDK Toolkit how to execute your app. +## πŸ“‹ Overview -## Useful commands +This directory contains AWS Cloud Development Kit (CDK) code that defines and deploys the entire Comptaleyes infrastructure. The infrastructure is written in TypeScript and automatically provisions AWS resources for backend (EC2, ECR), frontend (S3, CloudFront), and shared resources (IAM, budgets). -- `npm run build` compile typescript to js -- `npm run watch` watch for changes and compile -- `npm run test` perform the jest unit tests -- `npx cdk deploy` deploy this stack to your default AWS account/region -- `npx cdk diff` compare deployed stack with current state -- `npx cdk synth` emits the synthesized CloudFormation template +## πŸ—οΈ Architecture + +The infrastructure is organized into three main stacks: + +``` +lib/ +β”œβ”€β”€ config/ +β”‚ └── env.ts # Environment configuration +└── stacks/ + β”œβ”€β”€ backend.stack.ts # Backend infrastructure (EC2, ECR) + β”œβ”€β”€ frontend.stack.ts # Frontend infrastructure (S3, CloudFront) + └── budgets.stack.ts # AWS cost monitoring & alerts +``` + +### Backend Stack + +**Resources:** + +- **ECR Repository**: Docker image storage for backend containers +- **EC2 Instance**: t3.small instance running Docker +- **Security Group**: Allows HTTP (3000) and SSH (22) traffic +- **IAM Role**: EC2 instance profile with SSM permissions +- **SSM Agent**: Pre-installed for remote management + +**Key Features:** + +- Automated Docker deployment via SSM RunCommand +- Parameter Store integration for secrets +- CloudWatch logging +- Security group with configurable access + +### Frontend Stack + +**Resources:** + +- **S3 Bucket**: Static website hosting for React build +- **CloudFront Distribution**: Global CDN with HTTPS +- **Origin Access Identity**: Secure S3 access +- **Bucket Policy**: CloudFront-only access to S3 + +**Key Features:** + +- Static website hosting with index.html fallback +- Global edge caching via CloudFront +- Automatic cache invalidation on deployment +- Public HTTPS access via CloudFront URL + +### Budgets Stack + +**Resources:** + +- **Cost Budgets**: Monthly spending alerts +- **Email Notifications**: Budget threshold alerts + +**Key Features:** + +- Track AWS spending across all services +- Alert when exceeding budget thresholds + +## βš™οΈ Configuration + +Configuration is managed via environment variables in [lib/config/env.ts](lib/config/env.ts): + +```typescript +export const config = { + env: process.env.CDK_ENV || 'dev', + region: 'us-east-1', + account: process.env.CDK_DEFAULT_ACCOUNT, + // ... other config +}; +``` + +**Customization:** + +- Change `CDK_ENV` to deploy different environments +- Modify instance types, security rules, budget limits in stack files + +## πŸš€ Deployment + +### Prerequisites + +- AWS CLI configured with credentials +- Node.js 18+ and npm +- CDK CLI installed: `npm install -g aws-cdk` + +### Setup + +```bash +cd infra +npm install +``` + +### CDK Commands + +```bash +# Synthesize CloudFormation templates +npm run build +npx cdk synth + +# View changes before deployment +npx cdk diff + +# Deploy all stacks +npx cdk deploy --all + +# Deploy specific stack +npx cdk deploy ComptaleysBackendStack-dev +npx cdk deploy ComptaleyseFrontendStack-dev + +# Destroy all infrastructure (careful!) +npx cdk destroy --all +``` + +## πŸ” Security + +**IAM Roles:** + +- EC2 instance has SSM managed instance core policy +- CloudFront has read-only access to S3 bucket +- GitHub Actions uses OIDC role for deployments + +**Secrets Management:** + +- All secrets stored in AWS SSM Parameter Store +- Prefix: `/comptaleyes/dev/*` +- Never hardcoded in CDK code + +**Network Security:** + +- Backend security group restricts access to necessary ports +- S3 bucket is private (CloudFront-only access) +- CloudFront provides HTTPS encryption + +## 🚒 CI/CD Integration + +Infrastructure changes are deployed via GitHub Actions: + +**Workflow**: [.github/workflows/cdk-deploy.yml](../.github/workflows/cdk-deploy.yml) + +**Triggers**: PRs to `master` from same repo + +**Process:** + +1. Checkout code +2. Assume AWS OIDC role +3. Install CDK dependencies +4. Run `cdk synth` +5. Run `cdk deploy --all --require-approval never` + +## πŸ“Š Stack Outputs + +After deployment, CDK outputs important values: + +**Backend Stack:** + +- `BackendECRRepository`: ECR repository URI +- `BackendEC2InstanceId`: EC2 instance ID +- `BackendPublicIP`: Public IP address + +**Frontend Stack:** + +- `FrontendBucketName`: S3 bucket name +- `FrontendDistributionURL`: CloudFront URL +- `FrontendDistributionId`: CloudFront distribution ID + +**View outputs:** + +```bash +aws cloudformation describe-stacks \ + --stack-name ComptaleysBackendStack-dev \ + --query 'Stacks[0].Outputs' +``` + +## πŸ§ͺ Testing + +```bash +# Run CDK unit tests (if implemented) +npm test + +# Validate CDK synthesis +npx cdk synth --all +``` + +## πŸ’° Cost Estimation + +Approximate monthly costs (us-east-1): + +| Service | Instance | Monthly Cost | +| ---------- | ------------- | ----------------- | +| EC2 | t3.small | ~$15 | +| CloudFront | Data transfer | ~$1-10 | +| S3 | Storage | <$1 | +| ECR | Image storage | <$1 | +| **Total** | | **~$17-27/month** | + +_Actual costs vary based on traffic and usage_ + +## 🌍 Environments + +| Environment | Prefix | Region | +| ----------- | ------ | --------- | +| Development | `dev` | us-east-1 | + +**To add environments:** + +1. Modify `lib/config/env.ts` +2. Update SSM parameter prefixes +3. Deploy with `CDK_ENV=staging cdk deploy --all` + +## πŸ”§ Troubleshooting + +**CDK Synthesis Fails:** + +- Check Node.js version (18+ required) +- Run `npm install` in infra directory +- Verify AWS credentials: `aws sts get-caller-identity` + +**Deployment Fails:** + +- Check IAM permissions for CDK deployment +- Verify account and region in `cdk.json` +- Review CloudFormation events in AWS Console + +**Stack Update Blocked:** + +- Some resources require replacement (may cause downtime) +- Use `cdk diff` to review changes first +- Consider blue-green deployment for critical changes + +## πŸ“š CDK Documentation + +- [AWS CDK Developer Guide](https://docs.aws.amazon.com/cdk/v2/guide/home.html) +- [CDK TypeScript API Reference](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html) +- [CDK Best Practices](https://docs.aws.amazon.com/cdk/v2/guide/best-practices.html) + +## πŸ‘₯ Ownership & Contacts + +- **Team**: CisCode Development +- **Contact**: info@ciscod.com +- **Repository**: [GitHub](https://github.com/your-org/comptaleyes) + +## πŸ”— Related Documentation + +- [Backend README](../backend/README.md) +- [Frontend README](../frontend/README.md) +- [Root README](../README.md) +- [Contributing Guidelines](../CONTRIBUTING.md) + +## πŸ“ License + +MIT License - See [LICENSE](../LICENSE) file for details. + +Copyright (c) 2026 CisCode