13 KiB
🎉 NestJS Retail POS Backend - Setup Complete!
Your complete NestJS backend API for the Retail POS Flutter application has been successfully created!
📦 What's Been Created
✅ Core Infrastructure
- NestJS Application: Latest version with TypeScript
- PostgreSQL Database: Complete schema with migrations
- Redis Caching: Ready for performance optimization
- JWT Authentication: Secure token-based auth
- Role-Based Access Control (RBAC): Admin, Manager, Cashier, User roles
- Swagger Documentation: Auto-generated API docs
✅ Database Layer
- 5 Entities: User, Category, Product, Transaction, TransactionItem
- Initial Migration: Complete schema with 11 indexes
- Seed Data: Sample categories, products, and users
- TypeORM Configuration: Production-ready setup
✅ API Modules
1. Auth Module (/api/auth)
POST /auth/register- Register new userPOST /auth/login- Login with JWTGET /auth/profile- Get current userPOST /auth/refresh- Refresh token
2. Users Module (/api/users)
- Complete CRUD for user management
- Admin-only access
- Password hashing with bcrypt
3. Categories Module (/api/categories)
GET /categories- List all categories (Public)GET /categories/:id- Get single category (Public)GET /categories/:id/products- Products by category (Public)POST /categories- Create category (Admin/Manager)PUT /categories/:id- Update category (Admin/Manager)DELETE /categories/:id- Delete category (Admin only)
4. Products Module (/api/products)
GET /products- List with pagination, filters, search (Public)GET /products/:id- Get single product (Public)GET /products/category/:categoryId- By category (Public)GET /products/search- Search products (Public)POST /products- Create product (Admin/Manager)PUT /products/:id- Update product (Admin/Manager)DELETE /products/:id- Delete product (Admin only)
5. Transactions Module (/api/transactions)
GET /transactions- List transactions (Cashier+)GET /transactions/:id- Get transaction (Cashier+)POST /transactions- Create transaction (Cashier+)GET /transactions/stats- Statistics (Manager+)GET /transactions/stats/daily- Daily sales (Manager+)
Features:
- ✅ Atomic transaction processing
- ✅ Stock validation and updates
- ✅ Automatic tax calculation (10%)
- ✅ Price snapshots at transaction time
- ✅ Pessimistic locking for concurrency
6. Sync Module (/api/sync)
POST /sync- Sync all data (Cashier+)POST /sync/products- Sync products only (Cashier+)POST /sync/categories- Sync categories only (Cashier+)GET /sync/status- Get sync status (Cashier+)
Features:
- ✅ Incremental sync based on timestamps
- ✅ Offline-first mobile support
- ✅ Efficient bandwidth usage
✅ Common Utilities
- DTOs: Pagination, API Response wrappers
- Filters: HTTP exception handler, catch-all filter
- Interceptors: Logging, response transformation, caching
- Pipes: Global validation pipe
- Guards: JWT auth guard, roles guard
- Decorators: @CurrentUser(), @Public(), @Roles()
✅ Configuration
- Environment Variables:
.envfile with dummy data - TypeScript Config: Strict mode enabled
- ESLint & Prettier: Code formatting
- Jest: Testing framework setup
✅ Docker Setup
- Dockerfile: Multi-stage build for production
- docker-compose.yml: Complete stack (API, PostgreSQL, Redis, pgAdmin)
- .dockerignore: Optimized build context
🚀 Quick Start
Option 1: Local Development
1. Create Database
# Using psql
createdb retail_pos
# Or using Docker
docker-compose up -d postgres redis
2. Configure Environment
The .env file is already created with dummy data. Update these values:
DB_HOST=localhost
DB_PORT=5432
DB_USERNAME=postgres
DB_PASSWORD=postgres # Change this!
DB_DATABASE=retail_pos
JWT_SECRET=retail-pos-super-secret-key-change-in-production-2025 # Change this!
3. Run Migrations
npm run migration:run
4. Seed Database (Optional)
npm run seed:run
This creates:
- Categories: 6 retail categories (Electronics, Clothing, Food, etc.)
- Products: 14 sample products
- Users:
- Admin:
admin@retailpos.com/Admin123! - Manager:
manager@retailpos.com/Manager123! - Cashier:
cashier@retailpos.com/Cashier123!
- Admin:
5. Start Server
# Development mode with hot-reload
npm run start:dev
# Production mode
npm run build
npm run start:prod
6. Access Application
- API: http://localhost:3000/api
- Swagger Docs: http://localhost:3000/api/docs
- Health Check: http://localhost:3000/health
Option 2: Docker Deployment
Start All Services
# Start API, PostgreSQL, Redis
docker-compose up -d
# View logs
docker-compose logs -f api
# Include pgAdmin for database management
docker-compose --profile tools up -d
Run Migrations in Docker
docker-compose exec api npm run migration:run
docker-compose exec api npm run seed:run
Access Services
- API: http://localhost:3000/api
- Swagger: http://localhost:3000/api/docs
- pgAdmin: http://localhost:5050 (admin@retailpos.com / admin123)
- PostgreSQL: localhost:5432
- Redis: localhost:6379
🔐 Test the API
1. Login to Get Token
curl -X POST http://localhost:3000/api/auth/login \
-H "Content-Type: application/json" \
-d '{"email": "admin@retailpos.com", "password": "Admin123!"}'
Response:
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"user": {
"id": "uuid",
"email": "admin@retailpos.com",
"name": "Admin User",
"roles": ["admin"]
}
}
2. List Products (Public)
curl http://localhost:3000/api/products
3. Create Product (Auth Required)
curl -X POST http://localhost:3000/api/products \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "Gaming Mouse",
"price": 49.99,
"categoryId": "CATEGORY_UUID",
"stockQuantity": 100
}'
4. Create Transaction
curl -X POST http://localhost:3000/api/transactions \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"items": [
{"productId": "PRODUCT_UUID", "quantity": 2}
],
"paymentMethod": "cash",
"discount": 5.00
}'
📚 Project Structure
retail-nest/
├── src/
│ ├── common/ # Global utilities
│ │ ├── decorators/ # @CurrentUser, @Public, @Roles
│ │ ├── dto/ # PaginationDto, ApiResponseDto
│ │ ├── filters/ # Exception handlers
│ │ ├── guards/ # JWT, Roles guards
│ │ ├── interceptors/ # Logging, Transform, Cache
│ │ └── pipes/ # Validation pipe
│ ├── config/ # Configuration modules
│ │ ├── app.config.ts
│ │ ├── database.config.ts
│ │ ├── jwt.config.ts
│ │ └── redis.config.ts
│ ├── database/
│ │ ├── migrations/ # TypeORM migrations
│ │ └── seeds/ # Database seeds
│ ├── modules/
│ │ ├── auth/ # Authentication
│ │ ├── users/ # User management
│ │ ├── categories/ # Category API
│ │ ├── products/ # Product API
│ │ ├── transactions/ # Transaction API
│ │ └── sync/ # Mobile sync API
│ ├── app.module.ts
│ └── main.ts
├── test/ # Unit & E2E tests
├── .env # Environment variables
├── .env.example # Environment template
├── Dockerfile # Production Docker image
├── docker-compose.yml # Full stack setup
└── package.json
🎯 Key Features
Security
✅ JWT authentication with refresh tokens ✅ Password hashing with bcrypt (10 rounds) ✅ Role-based access control (RBAC) ✅ Rate limiting (100 req/min) ✅ CORS protection ✅ Helmet security headers
Performance
✅ Redis caching layer ✅ Database query optimization with indexes ✅ Pessimistic locking for transactions ✅ Pagination for large datasets ✅ Response compression (gzip)
Data Integrity
✅ Database transactions for critical operations ✅ Foreign key constraints ✅ Unique constraints ✅ Stock validation before transactions ✅ Price snapshots in transactions
Developer Experience
✅ Swagger/OpenAPI documentation ✅ TypeScript with strict mode ✅ Hot-reload in development ✅ Docker support for easy deployment ✅ Comprehensive error handling
🧪 Available Scripts
# Development
npm run start:dev # Start with hot-reload
npm run start:debug # Start with debugger
# Production
npm run build # Build for production
npm run start:prod # Run production build
# Database
npm run migration:generate # Generate migration
npm run migration:create # Create empty migration
npm run migration:run # Run migrations
npm run migration:revert # Revert last migration
npm run seed:run # Seed database
# Testing
npm run test # Run unit tests
npm run test:watch # Watch mode
npm run test:cov # With coverage
npm run test:e2e # E2E tests
# Code Quality
npm run lint # Lint code
npm run format # Format with Prettier
🔧 Environment Variables
All required environment variables are in .env (already created):
# Application
NODE_ENV=development
PORT=3000
API_PREFIX=api
# Database
DB_HOST=localhost
DB_PORT=5432
DB_USERNAME=postgres
DB_PASSWORD=postgres
DB_DATABASE=retail_pos
# JWT
JWT_SECRET=your-secret-key-here
JWT_EXPIRES_IN=1d
# Redis
REDIS_HOST=localhost
REDIS_PORT=6379
CACHE_TTL=300
# CORS
CORS_ORIGIN=http://localhost:3000,capacitor://localhost
# Rate Limiting
THROTTLE_TTL=60
THROTTLE_LIMIT=100
# Security
BCRYPT_ROUNDS=10
📖 API Documentation
Access Swagger UI
Once the server is running, visit:
- Swagger UI: http://localhost:3000/api/docs
- OpenAPI JSON: http://localhost:3000/api/docs-json
Default Users
| Role | Password | |
|---|---|---|
| Admin | admin@retailpos.com | Admin123! |
| Manager | manager@retailpos.com | Manager123! |
| Cashier | cashier@retailpos.com | Cashier123! |
🎨 Response Format
All API responses follow a consistent format:
Success Response
{
"success": true,
"data": { /* your data */ },
"message": "Operation successful"
}
Paginated Response
{
"success": true,
"data": [ /* items */ ],
"meta": {
"page": 1,
"limit": 20,
"total": 100,
"totalPages": 5
}
}
Error Response
{
"success": false,
"error": {
"statusCode": 400,
"message": "Validation failed",
"details": ["error details"]
},
"timestamp": "2025-10-10T12:00:00.000Z",
"path": "/api/products"
}
🚀 Next Steps
1. Update Environment Variables
Edit .env file with your actual database credentials and JWT secret.
2. Run Migrations
npm run migration:run
3. Seed Database
npm run seed:run
4. Start Development Server
npm run start:dev
5. Test API
Visit http://localhost:3000/api/docs to test endpoints.
6. Integrate with Flutter App
- Update Flutter app API base URL to
http://localhost:3000/api - Use JWT token from login response for authenticated requests
- Implement offline sync using
/api/syncendpoints
📝 Additional Documentation
Created documentation files:
DATABASE_SETUP.md- Complete database guideDATABASE_SUMMARY.md- Quick database referenceAUTH_SYSTEM.md- Authentication system detailsIMPLEMENTATION_SUMMARY.md- Implementation guide
✨ What Makes This Production-Ready
✅ Security First: JWT auth, bcrypt hashing, RBAC, rate limiting ✅ Scalable Architecture: Modular design, dependency injection ✅ Performance Optimized: Redis caching, database indexes, query optimization ✅ Data Integrity: Transactions, constraints, stock validation ✅ Developer Friendly: Swagger docs, TypeScript, hot-reload ✅ Docker Ready: Multi-stage builds, docker-compose stack ✅ Testing Ready: Jest setup, unit & E2E test structure ✅ Mobile Ready: Sync API for offline-first Flutter app
🎉 You're All Set!
Your NestJS Retail POS Backend is production-ready and waiting for you to:
- Update
.envwith your credentials - Run migrations:
npm run migration:run - Seed data:
npm run seed:run - Start server:
npm run start:dev - Open Swagger: http://localhost:3000/api/docs
Happy coding! 🚀