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

559
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**
- JWT-based authentication
- Supabase integration for OTP
- Role-based access control (RBAC)
- Telegram ID compatibility
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.
- 👥 **User Management**
- System Admin, Business Owner, Staff, Auditor roles
- Hierarchical user creation
- Redis-cached role lookups
## Core Features
- 🧾 **Receipt Processing** (Coming Soon)
- OCR with Tesseract.js
- Asynchronous processing with BullMQ
- Duplicate detection
- Fraud flagging
### Authentication & Security
- **JWT-based Authentication** with configurable expiration
- **Multi-factor Authentication** via OTP integration
- **Role-based Access Control (RBAC)** with hierarchical permissions
- **Password Security** with bcrypt hashing
- **API Documentation** with Swagger/OpenAPI 3.0
- 📊 **Reporting & Analytics** (Coming Soon)
- Daily sales summaries
- Transaction reports
- Performance metrics
- CSV/PDF exports
### User Management
- **Hierarchical Role System**: System Admin → Business Owner → Staff → Auditor
- **Granular Permissions** with role-based endpoint access
- **User Lifecycle Management** with soft deletion
- **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)
- **Database**: PostgreSQL with Prisma ORM
- **Cache**: Redis
- **Queue**: BullMQ
- **Auth**: JWT + Supabase
- **Storage**: Supabase Storage
- **OCR**: Tesseract.js
## Technology Stack
## 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
- Node.js 18+
- PostgreSQL
- Redis
- Supabase account
Ensure your development environment meets these requirements:
- **Node.js** 18.0 or higher
- **PostgreSQL** 13.0 or higher
- **Redis** 6.0 or higher
- **npm** or **yarn** package manager
### Installation
1. Clone the repository
```bash
git clone <repository-url>
cd receipt-verification-api
1. **Clone the repository**
```bash
git clone https://gitea.yaltopia.com/DebelaH/Yaltopia-Tickets-Backend.git
cd Yaltopia-Tickets-Backend
```
2. **Install dependencies**
```bash
npm install
```
3. **Environment configuration**
```bash
cp .env.example .env
```
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. **Database setup**
```bash
npx prisma generate
npx prisma db push
```
5. **Start the application**
```bash
# Development
npm run start:dev
# Production
npm run build
npm run start:prod
```
The API will be available at `http://localhost:3000` with documentation at `http://localhost:3000/api`
## API Documentation
### Authentication Endpoints
| Method | Endpoint | Description | Access |
|--------|----------|-------------|---------|
| `POST` | `/api/v1/auth/login` | User authentication | Public |
| `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 |
### User Management Endpoints
| Method | Endpoint | Description | Access |
|--------|----------|-------------|---------|
| `GET` | `/api/v1/users` | List users (role-filtered) | Authenticated |
| `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+ |
## Role-Based Access Control
### 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
```
2. Install dependencies
```bash
npm install
### Permission Matrix
| Action | System Admin | Business Owner | Staff | Auditor |
|--------|:------------:|:--------------:|:-----:|:-------:|
| Create Users | ✅ | ✅ (Staff only) | ❌ | ❌ |
| View All Users | ✅ | ✅ (Own staff) | ❌ | ❌ |
| Modify Users | ✅ | ✅ (Own staff) | ❌ | ❌ |
| View Reports | ✅ | ✅ (Own business) | ❌ | ✅ (Read-only) |
| System Config | ✅ | ❌ | ❌ | ❌ |
## Architecture
### Universal Database Adapter
The system implements a unique universal adapter pattern that provides database-agnostic operations:
```typescript
// Switch providers with environment variables only
DATABASE_PROVIDER=prisma # PostgreSQL with Prisma
DATABASE_PROVIDER=supabase # Supabase (PostgreSQL + Auth)
DATABASE_PROVIDER=mongodb # MongoDB (Future)
```
3. Set up environment variables
```bash
cp .env.example .env
# Edit .env with your configuration
```
4. Set up the database
```bash
npx prisma generate
npx prisma db push
```
5. Start the development server
```bash
npm run start:dev
```
The API will be available at `http://localhost:3000/api/v1`
## Environment Variables
```env
# Database
DATABASE_URL="postgresql://username:password@localhost:5432/receipt_verification?schema=public"
# Supabase
SUPABASE_URL="https://your-project.supabase.co"
SUPABASE_ANON_KEY="your-anon-key"
SUPABASE_SERVICE_ROLE_KEY="your-service-role-key"
# JWT
JWT_SECRET="your-jwt-secret-key"
JWT_EXPIRES_IN="7d"
# Redis
REDIS_HOST="localhost"
REDIS_PORT=6379
REDIS_PASSWORD=""
# App
PORT=3000
NODE_ENV="development"
```
## API Endpoints
### Authentication
- `POST /api/v1/auth/login` - Login with credentials
- `POST /api/v1/auth/register` - Register new user (admin/owner only)
- `POST /api/v1/auth/request-otp` - Request OTP via Supabase
- `POST /api/v1/auth/verify-otp` - Verify OTP and login
- `GET /api/v1/auth/profile` - Get current user profile
- `GET /api/v1/auth/validate` - Validate JWT token
### Users
- `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
### System Admin
- Full system access
- Manage all users
- View all reports
- System configuration
### Business Owner
- Create/manage staff and auditors
- View business reports
- Manage receipts
- Verify transactions
### 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
```
src/
├── features/ # Feature modules
│ ├── auth/ # Authentication & authorization
│ ├── users/ # User management
│ ├── receipts/ # Receipt processing (coming soon)
│ ├── ocr/ # OCR processing (coming soon)
│ └── reports/ # Reporting (coming soon)
├── shared/ # Shared utilities
│ ├── config/ # Configuration
│ ├── constants/ # Constants and enums
│ ├── decorators/ # Custom decorators
│ ├── guards/ # Auth guards
│ ├── services/ # Shared services
│ └── utils/ # Utility functions
└── prisma/ # Database schema
├── features/ # Feature-based modules
│ ├── auth/ # Authentication & authorization
│ │ ├── guards/ # JWT and role guards
│ │ ├── strategies/ # Passport strategies
│ │ └── dto/ # Data transfer objects
│ └── users/ # User management
│ ├── dto/ # User DTOs
│ └── services/ # Business logic
├── 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
│ └── config/ # Configuration modules
└── prisma/ # Database schema and migrations
```
## 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
- JWT token authentication
- Role-based access control
- Password hashing with bcrypt
- Request validation with class-validator
- CORS protection
- Rate limiting (recommended for production)
### Authentication Security
- **JWT Tokens** with configurable expiration
- **Password Hashing** using bcrypt with salt rounds
- **OTP Verification** for enhanced security
- **Role-based Route Protection** with guards
## 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)
- User profiles cached (5 minutes TTL)
- Automatic cache invalidation on updates
### Data Security
- **Environment Variable Protection** - no secrets in code
- **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
2. Add receipt upload and processing
3. Create verification workflows
4. Build reporting system
5. Add performance monitoring
6. Implement notification system
### Docker Deployment
```dockerfile
# Production Dockerfile
FROM node:18-alpine
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
1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests
5. Submit a pull request
### Development Workflow
## 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.**