docs(README): Expand and restructure documentation for enterprise API

This commit is contained in:
debudebuye 2025-12-21 22:15:20 +03:00
parent 104bbdb59f
commit 968fd26252

495
README.md
View File

@ -1,224 +1,409 @@
# Receipt & Ticket Verification API # Yaltopia Tickets Backend API
A production-ready backend API for receipt & ticket verification system with OCR processing, role-based access, reporting, and performance monitoring. Enterprise-grade backend service for ticket and receipt verification system with advanced authentication, role-based access control, and universal database adapter architecture.
## Features ## Overview
- 🔐 **Authentication & Authorization** This API provides a robust foundation for ticket verification systems with enterprise-level security, scalability, and maintainability. Built with modern TypeScript and NestJS framework, it features a unique universal adapter pattern that allows seamless switching between different database providers without code changes.
- JWT-based authentication
- Supabase integration for OTP
- Role-based access control (RBAC)
- Telegram ID compatibility
- 👥 **User Management** ## Core Features
- System Admin, Business Owner, Staff, Auditor roles
- Hierarchical user creation
- Redis-cached role lookups
- 🧾 **Receipt Processing** (Coming Soon) ### Authentication & Security
- OCR with Tesseract.js - **JWT-based Authentication** with configurable expiration
- Asynchronous processing with BullMQ - **Multi-factor Authentication** via OTP integration
- Duplicate detection - **Role-based Access Control (RBAC)** with hierarchical permissions
- Fraud flagging - **Password Security** with bcrypt hashing
- **API Documentation** with Swagger/OpenAPI 3.0
- 📊 **Reporting & Analytics** (Coming Soon) ### User Management
- Daily sales summaries - **Hierarchical Role System**: System Admin → Business Owner → Staff → Auditor
- Transaction reports - **Granular Permissions** with role-based endpoint access
- Performance metrics - **User Lifecycle Management** with soft deletion
- CSV/PDF exports - **Team Management** capabilities for business owners
## Tech Stack ### Architecture Highlights
- **Universal Database Adapter** - Switch between PostgreSQL, MongoDB, or other providers
- **Provider-Agnostic Design** - No vendor lock-in
- **Microservice-Ready** architecture with modular design
- **Production-Grade** error handling and logging
- **Type-Safe** implementation with comprehensive TypeScript coverage
- **Framework**: NestJS (TypeScript) ## Technology Stack
- **Database**: PostgreSQL with Prisma ORM
- **Cache**: Redis
- **Queue**: BullMQ
- **Auth**: JWT + Supabase
- **Storage**: Supabase Storage
- **OCR**: Tesseract.js
## Quick Start | Component | Technology | Version |
|-----------|------------|---------|
| **Runtime** | Node.js | 18+ |
| **Framework** | NestJS | 10.x |
| **Language** | TypeScript | 5.1+ |
| **Database** | PostgreSQL | 13+ |
| **ORM** | Prisma | 5.7+ |
| **Cache** | Redis | 6+ |
| **Queue** | BullMQ | 4.x |
| **Authentication** | JWT + Supabase | Latest |
| **Documentation** | Swagger/OpenAPI | 3.0 |
| **Testing** | Jest | 29+ |
## Getting Started
### Prerequisites ### Prerequisites
- Node.js 18+ Ensure your development environment meets these requirements:
- PostgreSQL
- Redis - **Node.js** 18.0 or higher
- Supabase account - **PostgreSQL** 13.0 or higher
- **Redis** 6.0 or higher
- **npm** or **yarn** package manager
### Installation ### Installation
1. Clone the repository 1. **Clone the repository**
```bash ```bash
git clone <repository-url> git clone https://gitea.yaltopia.com/DebelaH/Yaltopia-Tickets-Backend.git
cd receipt-verification-api cd Yaltopia-Tickets-Backend
``` ```
2. Install dependencies 2. **Install dependencies**
```bash ```bash
npm install npm install
``` ```
3. Set up environment variables 3. **Environment configuration**
```bash ```bash
cp .env.example .env cp .env.example .env
# Edit .env with your configuration ```
Configure the following required environment variables:
```env
DATABASE_URL="postgresql://username:password@localhost:5432/database_name"
JWT_SECRET="your-secure-jwt-secret-key"
SUPABASE_URL="https://your-project.supabase.co"
SUPABASE_ANON_KEY="your-supabase-anon-key"
REDIS_URL="redis://localhost:6379"
``` ```
4. Set up the database 4. **Database setup**
```bash ```bash
npx prisma generate npx prisma generate
npx prisma db push npx prisma db push
``` ```
5. Start the development server 5. **Start the application**
```bash ```bash
# Development
npm run start:dev npm run start:dev
# Production
npm run build
npm run start:prod
``` ```
The API will be available at `http://localhost:3000/api/v1` The API will be available at `http://localhost:3000` with documentation at `http://localhost:3000/api`
## Environment Variables ## API Documentation
```env ### Authentication Endpoints
# Database
DATABASE_URL="postgresql://username:password@localhost:5432/receipt_verification?schema=public"
# Supabase | Method | Endpoint | Description | Access |
SUPABASE_URL="https://your-project.supabase.co" |--------|----------|-------------|---------|
SUPABASE_ANON_KEY="your-anon-key" | `POST` | `/api/v1/auth/login` | User authentication | Public |
SUPABASE_SERVICE_ROLE_KEY="your-service-role-key" | `POST` | `/api/v1/auth/register` | User registration | Admin Only |
| `POST` | `/api/v1/auth/request-otp` | Request OTP verification | Public |
| `POST` | `/api/v1/auth/verify-otp` | Verify OTP and authenticate | Public |
| `GET` | `/api/v1/auth/profile` | Get current user profile | Authenticated |
| `GET` | `/api/v1/auth/validate` | Validate JWT token | Authenticated |
# JWT ### User Management Endpoints
JWT_SECRET="your-jwt-secret-key"
JWT_EXPIRES_IN="7d"
# Redis | Method | Endpoint | Description | Access |
REDIS_HOST="localhost" |--------|----------|-------------|---------|
REDIS_PORT=6379 | `GET` | `/api/v1/users` | List users (role-filtered) | Authenticated |
REDIS_PASSWORD="" | `GET` | `/api/v1/users/:id` | Get user by ID | Authenticated |
| `POST` | `/api/v1/users/staff` | Create staff/auditor | Owner+ |
| `PATCH` | `/api/v1/users/:id` | Update user | Owner+ |
| `DELETE` | `/api/v1/users/:id` | Deactivate user | Owner+ |
| `GET` | `/api/v1/users/my-staff` | Get owner's staff | Owner+ |
# App ## Role-Based Access Control
PORT=3000
NODE_ENV="development" ### Role Hierarchy
```
System Admin (Level 4)
├── Full system access
├── Manage all users and data
└── System configuration
Business Owner (Level 3)
├── Create and manage staff
├── View business reports
├── Manage business data
└── Verify transactions
Staff (Level 2)
├── Upload and process tickets
├── View assigned data
└── Basic verification tasks
Auditor (Level 1)
├── Read-only access to reports
├── View tickets for auditing
└── No modification permissions
``` ```
## API Endpoints ### Permission Matrix
### Authentication | Action | System Admin | Business Owner | Staff | Auditor |
- `POST /api/v1/auth/login` - Login with credentials |--------|:------------:|:--------------:|:-----:|:-------:|
- `POST /api/v1/auth/register` - Register new user (admin/owner only) | Create Users | ✅ | ✅ (Staff only) | ❌ | ❌ |
- `POST /api/v1/auth/request-otp` - Request OTP via Supabase | View All Users | ✅ | ✅ (Own staff) | ❌ | ❌ |
- `POST /api/v1/auth/verify-otp` - Verify OTP and login | Modify Users | ✅ | ✅ (Own staff) | ❌ | ❌ |
- `GET /api/v1/auth/profile` - Get current user profile | View Reports | ✅ | ✅ (Own business) | ❌ | ✅ (Read-only) |
- `GET /api/v1/auth/validate` - Validate JWT token | System Config | ✅ | ❌ | ❌ | ❌ |
### Users ## Architecture
- `GET /api/v1/users` - List users (filtered by role)
- `GET /api/v1/users/:id` - Get user by ID
- `POST /api/v1/users/staff` - Create staff/auditor
- `PATCH /api/v1/users/:id` - Update user
- `DELETE /api/v1/users/:id` - Deactivate user
- `GET /api/v1/users/my-staff` - Get owner's staff
## User Roles & Permissions ### Universal Database Adapter
### System Admin The system implements a unique universal adapter pattern that provides database-agnostic operations:
- Full system access
- Manage all users
- View all reports
- System configuration
### Business Owner ```typescript
- Create/manage staff and auditors // Switch providers with environment variables only
- View business reports DATABASE_PROVIDER=prisma # PostgreSQL with Prisma
- Manage receipts DATABASE_PROVIDER=supabase # Supabase (PostgreSQL + Auth)
- Verify transactions DATABASE_PROVIDER=mongodb # MongoDB (Future)
### Staff (Cashier)
- Upload receipts
- View own receipts
- Basic verification tasks
### Auditor
- Read-only access to reports
- View receipts for auditing
- No modification permissions
## Database Schema
The system uses Prisma with PostgreSQL. Key entities:
- **User**: Authentication and role management
- **Receipt**: Receipt data and OCR results
- **Verification**: Receipt verification records
- **PerformanceMetric**: System performance tracking
## Development
### Scripts
```bash
npm run start:dev # Development server with hot reload
npm run build # Build for production
npm run start:prod # Start production server
npm run lint # Run ESLint
npm run test # Run tests
npm run prisma:studio # Open Prisma Studio
``` ```
**Benefits:**
- **Zero Code Changes** when switching providers
- **No Vendor Lock-in** - migrate between services seamlessly
- **Future-Proof** architecture for evolving requirements
- **Cost Optimization** - switch to most cost-effective provider
### Project Structure ### Project Structure
``` ```
src/ src/
├── features/ # Feature modules ├── features/ # Feature-based modules
│ ├── auth/ # Authentication & authorization │ ├── auth/ # Authentication & authorization
│ ├── users/ # User management │ │ ├── guards/ # JWT and role guards
│ ├── receipts/ # Receipt processing (coming soon) │ │ ├── strategies/ # Passport strategies
│ ├── ocr/ # OCR processing (coming soon) │ │ └── dto/ # Data transfer objects
│ └── reports/ # Reporting (coming soon) │ └── users/ # User management
├── shared/ # Shared utilities │ ├── dto/ # User DTOs
│ ├── config/ # Configuration │ └── services/ # Business logic
│ ├── constants/ # Constants and enums ├── shared/ # Shared utilities and services
│ ├── adapters/ # Universal database adapter
│ ├── repositories/ # Data access layer
│ ├── factories/ # Provider factories
│ ├── interfaces/ # Type definitions
│ ├── services/ # Shared services (Redis, Prisma)
│ ├── guards/ # Authentication guards
│ ├── decorators/ # Custom decorators │ ├── decorators/ # Custom decorators
│ ├── guards/ # Auth guards │ └── config/ # Configuration modules
│ ├── services/ # Shared services └── prisma/ # Database schema and migrations
│ └── utils/ # Utility functions ```
└── prisma/ # Database schema
## Database Schema
### Core Entities
```sql
-- Users table with role-based access
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
email VARCHAR UNIQUE NOT NULL,
password_hash VARCHAR NOT NULL,
role user_role NOT NULL,
full_name VARCHAR NOT NULL,
is_active BOOLEAN DEFAULT true,
created_by UUID REFERENCES users(id),
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
-- Enum for user roles
CREATE TYPE user_role AS ENUM (
'SYSTEM_ADMIN',
'BUSINESS_OWNER',
'STAFF',
'AUDITOR'
);
```
## Development
### Available Scripts
```bash
# Development
npm run start:dev # Start with hot reload
npm run start:debug # Start with debugging
# Production
npm run build # Build for production
npm run start:prod # Start production server
# Database
npm run prisma:generate # Generate Prisma client
npm run prisma:push # Push schema to database
npm run prisma:migrate # Run database migrations
npm run prisma:studio # Open Prisma Studio
# Code Quality
npm run lint # Run ESLint
npm run format # Format code with Prettier
npm run test # Run unit tests
npm run test:e2e # Run end-to-end tests
npm run test:cov # Run tests with coverage
# Provider Management
npm run migrate:provider # Migrate between database providers
npm run health:check # Check system health
```
### Environment Configuration
#### Development Environment
```env
NODE_ENV=development
PORT=3000
DATABASE_PROVIDER=prisma
DATABASE_URL="postgresql://user:pass@localhost:5432/yaltopia_dev"
JWT_SECRET="dev-secret-key"
REDIS_URL="redis://localhost:6379"
```
#### Production Environment
```env
NODE_ENV=production
PORT=3000
DATABASE_PROVIDER=prisma
DATABASE_URL="postgresql://user:pass@prod-db:5432/yaltopia_prod"
JWT_SECRET="secure-production-secret"
REDIS_URL="redis://prod-redis:6379"
``` ```
## Security Features ## Security Features
- JWT token authentication ### Authentication Security
- Role-based access control - **JWT Tokens** with configurable expiration
- Password hashing with bcrypt - **Password Hashing** using bcrypt with salt rounds
- Request validation with class-validator - **OTP Verification** for enhanced security
- CORS protection - **Role-based Route Protection** with guards
- Rate limiting (recommended for production)
## Caching Strategy ### API Security
- **CORS Protection** with configurable origins
- **Request Validation** using class-validator
- **Rate Limiting** (recommended for production)
- **Helmet.js** for security headers
- **Input Sanitization** to prevent injection attacks
- User roles cached in Redis (1 hour TTL) ### Data Security
- User profiles cached (5 minutes TTL) - **Environment Variable Protection** - no secrets in code
- Automatic cache invalidation on updates - **Database Connection Encryption** with SSL
- **Audit Logging** for sensitive operations
- **Soft Deletion** to maintain data integrity
## Next Steps ## Deployment
1. Implement OCR module with BullMQ ### Docker Deployment
2. Add receipt upload and processing
3. Create verification workflows ```dockerfile
4. Build reporting system # Production Dockerfile
5. Add performance monitoring FROM node:18-alpine
6. Implement notification system WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY dist ./dist
EXPOSE 3000
CMD ["node", "dist/main"]
```
### Environment Setup
1. **Database Setup**
```bash
# PostgreSQL with Docker
docker run -d \
--name yaltopia-postgres \
-e POSTGRES_DB=yaltopia \
-e POSTGRES_USER=admin \
-e POSTGRES_PASSWORD=secure_password \
-p 5432:5432 \
postgres:13
```
2. **Redis Setup**
```bash
# Redis with Docker
docker run -d \
--name yaltopia-redis \
-p 6379:6379 \
redis:6-alpine
```
3. **Application Deployment**
```bash
# Build and deploy
npm run build
npm run start:prod
```
## Monitoring & Observability
### Health Checks
- **Database Connectivity** monitoring
- **Redis Connection** status
- **Service Dependencies** health verification
- **API Response Time** tracking
### Logging
- **Structured Logging** with Winston
- **Request/Response Logging** for debugging
- **Error Tracking** with stack traces
- **Performance Metrics** collection
## Contributing ## Contributing
1. Fork the repository ### Development Workflow
2. Create a feature branch
3. Make your changes
4. Add tests
5. Submit a pull request
## License 1. **Fork the repository**
2. **Create a feature branch**
```bash
git checkout -b feature/your-feature-name
```
3. **Make your changes**
4. **Run tests and linting**
```bash
npm run test
npm run lint
```
5. **Commit your changes**
```bash
git commit -m "feat: add your feature description"
```
6. **Push to your fork**
7. **Create a Pull Request**
This project is licensed under the MIT License. ### Code Standards
- **TypeScript** strict mode enabled
- **ESLint** configuration enforced
- **Prettier** for code formatting
- **Conventional Commits** for commit messages
- **Unit Tests** required for new features
## Support & Maintenance
### Version Support
- **Current Version**: 1.0.0
- **Node.js**: 18.x LTS (recommended)
- **Database**: PostgreSQL 13+ (primary), MongoDB (future)
- **Security Updates**: Applied within 48 hours
### Contact Information
- **Development Team**: Yaltopia Backend Team
- **Repository**: https://gitea.yaltopia.com/DebelaH/Yaltopia-Tickets-Backend
- **Issues**: Use GitHub Issues for bug reports and feature requests
---
**© 2025 Yaltopia. All rights reserved.**