464 lines
15 KiB
Markdown
464 lines
15 KiB
Markdown
# Instructions for AI Assistant (Cursor/Windsurf/Cline/etc.)
|
|
|
|
## 🎯 Objective
|
|
|
|
Complete the Royal Enfield Dealership Onboarding System backend by creating all remaining files based on the comprehensive documentation and examples provided.
|
|
|
|
## 📚 Documentation Files to Read First
|
|
|
|
1. **`back.md`** - MOST IMPORTANT - Complete architecture, API endpoints, database schema
|
|
2. **`README.md`** - Quick start guide and file structure overview
|
|
3. **`config/constants.js`** - All system constants, roles, statuses
|
|
4. **`server.js`** - Main entry point and setup
|
|
5. **Example files:**
|
|
- `models/User.js` and `models/Outlet.js` - Model pattern
|
|
- `models/Resignation.js` - Complete resignation model
|
|
- `controllers/resignationController.js` - Complete controller with business logic
|
|
- `routes/resignations.js` - Route pattern
|
|
- `middleware/auth.js` - Authentication middleware
|
|
- `middleware/roleCheck.js` - Authorization middleware
|
|
|
|
## 📋 Files Already Created ✅
|
|
|
|
### Core Files
|
|
|
|
- ✅ package.json
|
|
- ✅ .env.example
|
|
- ✅ server.js
|
|
- ✅ .gitignore
|
|
- ✅ README.md
|
|
- ✅ back.md
|
|
- ✅ AI-ASSISTANT-INSTRUCTIONS.md (this file)
|
|
|
|
### Config
|
|
|
|
- ✅ config/database.js
|
|
- ✅ config/email.js
|
|
- ✅ config/constants.js
|
|
|
|
### Models
|
|
|
|
- ✅ models/index.js
|
|
- ✅ models/User.js
|
|
- ✅ models/Outlet.js
|
|
- ✅ models/Resignation.js
|
|
|
|
### Controllers
|
|
|
|
- ✅ controllers/resignationController.js
|
|
|
|
### Routes
|
|
|
|
- ✅ routes/resignations.js
|
|
|
|
### Middleware
|
|
|
|
- ✅ middleware/auth.js
|
|
- ✅ middleware/roleCheck.js
|
|
- ✅ middleware/errorHandler.js
|
|
|
|
### Utils
|
|
|
|
- ✅ utils/logger.js
|
|
|
|
## 🚧 Files YOU Need to Create
|
|
|
|
### Models (Follow pattern in models/Resignation.js)
|
|
|
|
**models/Application.js**
|
|
|
|
- See schema in back.md under "applications" table
|
|
- Fields: id, applicationId, applicantName, email, phone, businessType, proposedLocation, city, state, pincode, currentStage, status, ranking, submittedBy, submittedAt, progressPercentage, documents, timeline
|
|
- Associations: belongsTo User (submittedBy), hasMany FinancePayment, hasMany Worknote
|
|
|
|
**models/ConstitutionalChange.js**
|
|
|
|
- See schema in back.md under "constitutional_changes" table
|
|
- Fields: id, requestId, outletId, dealerId, changeType, currentStructure, proposedStructure, reason, effectiveDate, currentStage, status, progressPercentage, submittedOn, documents, timeline
|
|
- Associations: belongsTo Outlet, belongsTo User (dealer), hasMany Worknote
|
|
|
|
**models/RelocationRequest.js**
|
|
|
|
- See schema in back.md under "relocation_requests" table
|
|
- Fields: id, requestId, outletId, dealerId, relocationType, currentAddress, currentLatitude, currentLongitude, proposedAddress, proposedLatitude, proposedLongitude, proposedCity, proposedState, proposedPincode, distance, reason, effectiveDate, currentStage, status, progressPercentage, submittedOn, documents, timeline
|
|
- Associations: belongsTo Outlet, belongsTo User (dealer), hasMany Worknote
|
|
|
|
**models/Worknote.js**
|
|
|
|
- See schema in back.md under "worknotes" table
|
|
- Fields: id, requestId, requestType (ENUM: application, resignation, constitutional, relocation), userId, userName, userRole, message, attachments, timestamp
|
|
- Associations: belongsTo User
|
|
|
|
**models/Document.js**
|
|
|
|
- See schema in back.md under "documents" table
|
|
- Fields: id, filename, originalName, mimeType, size, path, uploadedBy, relatedTo, relatedId, documentType, uploadedAt
|
|
- Associations: belongsTo User (uploadedBy)
|
|
|
|
**models/AuditLog.js**
|
|
|
|
- See schema in back.md under "audit_logs" table
|
|
- Fields: id, userId, userName, userRole, action (ENUM from AUDIT_ACTIONS), entityType, entityId, changes (JSON), ipAddress, timestamp
|
|
- Associations: belongsTo User
|
|
|
|
**models/FinancePayment.js**
|
|
|
|
- See schema in back.md under "finance_payments" table
|
|
- Fields: id, applicationId, outletId, dealerId, paymentType, amount, dueDate, paidDate, status, transactionId, paymentMode, remarks
|
|
- Associations: belongsTo Application, belongsTo Outlet, belongsTo User (dealer)
|
|
|
|
**models/FnF.js**
|
|
|
|
- See schema in back.md under "fnf_settlements" table
|
|
- Fields: id, fnfId, resignationId, outletId, dealerId, totalDues, securityDepositRefund, otherCharges, netSettlement, status, settledDate, progressPercentage
|
|
- Associations: belongsTo Resignation, belongsTo Outlet, belongsTo User (dealer)
|
|
|
|
**models/Region.js**
|
|
|
|
- See schema in back.md under "regions" table
|
|
- Fields: id, name (ENUM: East, West, North, South, Central), code, headName, headEmail, isActive
|
|
- Associations: hasMany Zone
|
|
|
|
**models/Zone.js**
|
|
|
|
- See schema in back.md under "zones" table
|
|
- Fields: id, name, code, regionId, managerName, managerEmail, states (JSON array), isActive
|
|
- Associations: belongsTo Region
|
|
|
|
### Controllers (Follow pattern in controllers/resignationController.js)
|
|
|
|
**controllers/authController.js**
|
|
|
|
- login(req, res, next) - Validate credentials, generate JWT token, return user info
|
|
- logout(req, res, next) - Invalidate token (if using token blacklist)
|
|
- getMe(req, res, next) - Get current user info from token
|
|
- refreshToken(req, res, next) - Refresh expired token
|
|
|
|
**controllers/userController.js**
|
|
|
|
- getAllUsers(req, res, next) - Get all users (Super Admin only)
|
|
- getUserById(req, res, next) - Get specific user
|
|
- createUser(req, res, next) - Create new user
|
|
- updateUser(req, res, next) - Update user info
|
|
- deleteUser(req, res, next) - Deactivate user
|
|
- changePassword(req, res, next) - Change password
|
|
|
|
**controllers/applicationController.js**
|
|
|
|
- createApplication(req, res, next) - Public endpoint for dealer application
|
|
- getApplications(req, res, next) - Get applications (role-based filtering)
|
|
- getApplicationById(req, res, next) - Get application details
|
|
- assignRanking(req, res, next) - DD assigns ranking
|
|
- approveApplication(req, res, next) - Move to next stage
|
|
- rejectApplication(req, res, next) - Reject application
|
|
|
|
**controllers/constitutionalController.js**
|
|
|
|
- createConstitutionalChange(req, res, next) - Dealer creates request
|
|
- getConstitutionalChanges(req, res, next) - List requests
|
|
- getConstitutionalChangeById(req, res, next) - Get details
|
|
- approveConstitutionalChange(req, res, next) - Approve and move stage
|
|
- rejectConstitutionalChange(req, res, next) - Reject request
|
|
|
|
**controllers/relocationController.js**
|
|
|
|
- createRelocation(req, res, next) - Dealer creates request
|
|
- getRelocations(req, res, next) - List requests
|
|
- getRelocationById(req, res, next) - Get details
|
|
- calculateDistance(req, res, next) - Calculate distance between locations
|
|
- approveRelocation(req, res, next) - Approve and move stage
|
|
- rejectRelocation(req, res, next) - Reject request
|
|
|
|
**controllers/outletController.js**
|
|
|
|
- getMyOutlets(req, res, next) - Dealer gets their outlets
|
|
- getAllOutlets(req, res, next) - Get all outlets (Admin)
|
|
- getOutletById(req, res, next) - Get outlet details
|
|
- createOutlet(req, res, next) - Create new outlet (Admin)
|
|
- updateOutlet(req, res, next) - Update outlet info
|
|
|
|
**controllers/worknoteController.js**
|
|
|
|
- createWorknote(req, res, next) - Add worknote to any request
|
|
- getWorknotes(req, res, next) - Get worknotes for a request
|
|
- deleteWorknote(req, res, next) - Delete own worknote (if needed)
|
|
|
|
**controllers/financeController.js**
|
|
|
|
- getOnboardingPayments(req, res, next) - Get pending payments for onboarding
|
|
- getPaymentById(req, res, next) - Get payment details
|
|
- markPaymentPaid(req, res, next) - Mark payment as received
|
|
- getFnFList(req, res, next) - Get F&F settlement requests
|
|
- getFnFById(req, res, next) - Get F&F details
|
|
- processFnF(req, res, next) - Process F&F settlement
|
|
|
|
**controllers/masterController.js**
|
|
|
|
- getRegions(req, res, next) - Get all regions
|
|
- createRegion(req, res, next) - Create region (Super Admin)
|
|
- updateRegion(req, res, next) - Update region
|
|
- getZones(req, res, next) - Get zones (optionally by region)
|
|
- createZone(req, res, next) - Create zone
|
|
- updateZone(req, res, next) - Update zone
|
|
|
|
**controllers/dashboardController.js**
|
|
|
|
- getStats(req, res, next) - Get dashboard stats (role-based)
|
|
- getRecentActivity(req, res, next) - Get recent activities
|
|
|
|
### Routes (Follow pattern in routes/resignations.js)
|
|
|
|
Create route files for all controllers:
|
|
|
|
- routes/auth.js
|
|
- routes/users.js
|
|
- routes/applications.js
|
|
- routes/constitutional.js
|
|
- routes/relocations.js
|
|
- routes/outlets.js
|
|
- routes/worknotes.js
|
|
- routes/finance.js
|
|
- routes/master.js
|
|
- routes/dashboard.js
|
|
|
|
Each route file should:
|
|
|
|
1. Import required controller
|
|
2. Import auth and roleCheck middleware
|
|
3. Define routes with appropriate HTTP methods
|
|
4. Apply auth middleware to protected routes
|
|
5. Apply roleCheck middleware with correct roles (see back.md permission matrix)
|
|
|
|
### Middleware
|
|
|
|
**middleware/upload.js**
|
|
|
|
- Configure multer for file uploads
|
|
- File type validation (PDF, images only)
|
|
- File size limit (10MB)
|
|
- Storage configuration (disk or cloud)
|
|
|
|
**middleware/validation.js**
|
|
|
|
- Validation functions using express-validator
|
|
- Examples: validateRegistration, validateLogin, validateResignation, etc.
|
|
|
|
### Utilities
|
|
|
|
**utils/emailService.js**
|
|
|
|
- sendEmail(to, subject, html) - Send email using nodemailer
|
|
- sendApplicationConfirmation(application)
|
|
- sendApprovalNotification(application, stage)
|
|
- sendRejectionNotification(application, reason)
|
|
- sendDeadlineReminder(application)
|
|
- Use config/email.js for SMTP configuration
|
|
|
|
**utils/emailTemplates.js**
|
|
|
|
- HTML templates for all email types
|
|
- applicationConfirmationTemplate(data)
|
|
- approvalNotificationTemplate(data)
|
|
- rejectionNotificationTemplate(data)
|
|
- stageProgressionTemplate(data)
|
|
- deadlineReminderTemplate(data)
|
|
|
|
**utils/helpers.js**
|
|
|
|
- calculateDistance(lat1, lon1, lat2, lon2) - Haversine formula for distance
|
|
- generateUniqueId(prefix, count) - Generate unique IDs
|
|
- formatDate(date) - Date formatting helper
|
|
- validatePincode(pincode) - Indian pincode validation
|
|
|
|
### Migrations
|
|
|
|
**migrations/initial-setup.js**
|
|
|
|
- Create all tables using Sequelize sync
|
|
- Seed initial data:
|
|
- Super Admin user (email: admin@royalenfield.com, password: Admin@123)
|
|
- 5 Regions (East, West, North, South, Central)
|
|
- Sample zones for each region
|
|
- Sample users for each role (for testing)
|
|
- Sample outlets for dealer users
|
|
|
|
## 🎨 Code Patterns to Follow
|
|
|
|
### Model Pattern
|
|
|
|
```javascript
|
|
const { CONSTANT } = require('../config/constants');
|
|
|
|
module.exports = (sequelize, DataTypes) => {
|
|
const ModelName = sequelize.define('ModelName', {
|
|
id: {
|
|
type: DataTypes.UUID,
|
|
defaultValue: DataTypes.UUIDV4,
|
|
primaryKey: true
|
|
},
|
|
// ... other fields from schema in back.md
|
|
}, {
|
|
tableName: 'table_name',
|
|
timestamps: true,
|
|
indexes: [/* ... */]
|
|
});
|
|
|
|
ModelName.associate = (models) => {
|
|
// Define relationships
|
|
};
|
|
|
|
return ModelName;
|
|
};
|
|
```
|
|
|
|
### Controller Pattern
|
|
|
|
```javascript
|
|
const db = require('../models');
|
|
const logger = require('../utils/logger');
|
|
const { CONSTANT } = require('../config/constants');
|
|
|
|
exports.functionName = async (req, res, next) => {
|
|
try {
|
|
// Business logic here
|
|
|
|
// Log action
|
|
logger.info('Action performed', { user: req.user.email });
|
|
|
|
// Return response
|
|
res.json({
|
|
success: true,
|
|
data: result
|
|
});
|
|
} catch (error) {
|
|
logger.error('Error:', error);
|
|
next(error);
|
|
}
|
|
};
|
|
```
|
|
|
|
### Route Pattern
|
|
|
|
```javascript
|
|
const express = require('express');
|
|
const router = express.Router();
|
|
const controller = require('../controllers/controllerName');
|
|
const auth = require('../middleware/auth');
|
|
const roleCheck = require('../middleware/roleCheck');
|
|
const { ROLES } = require('../config/constants');
|
|
|
|
router.post('/create', auth, roleCheck([ROLES.ROLE_NAME]), controller.create);
|
|
router.get('/list', auth, controller.getList);
|
|
router.get('/:id', auth, controller.getById);
|
|
|
|
module.exports = router;
|
|
```
|
|
|
|
## 🔒 Security Checklist
|
|
|
|
For each controller function:
|
|
|
|
- [ ] Use try-catch blocks
|
|
- [ ] Validate input data
|
|
- [ ] Check user permissions
|
|
- [ ] Use database transactions for multi-step operations
|
|
- [ ] Log actions to AuditLog
|
|
- [ ] Sanitize user input
|
|
- [ ] Return appropriate HTTP status codes
|
|
|
|
## 🧪 Testing Approach
|
|
|
|
After creating files:
|
|
|
|
1. Run `npm install` to install dependencies
|
|
2. Set up PostgreSQL database
|
|
3. Configure .env file
|
|
4. Run migrations: `npm run migrate`
|
|
5. Start server: `npm run dev`
|
|
6. Test endpoints using Postman/Thunder Client
|
|
7. Test each role's permissions
|
|
8. Verify database constraints
|
|
|
|
## 📊 Database Relationships Summary
|
|
|
|
- **User** → hasMany → Application, Outlet, Resignation, ConstitutionalChange, RelocationRequest
|
|
- **Outlet** → belongsTo → User (dealer)
|
|
- **Outlet** → hasMany → Resignation, ConstitutionalChange, RelocationRequest
|
|
- **Resignation** → belongsTo → Outlet, User (dealer)
|
|
- **ConstitutionalChange** → belongsTo → Outlet, User (dealer)
|
|
- **RelocationRequest** → belongsTo → Outlet, User (dealer)
|
|
- **FinancePayment** → belongsTo → Application, Outlet, User (dealer)
|
|
- **FnF** → belongsTo → Resignation, Outlet, User (dealer)
|
|
- **Region** → hasMany → Zone
|
|
- **Zone** → belongsTo → Region
|
|
- **Worknote** → belongsTo → User
|
|
- **Document** → belongsTo → User
|
|
- **AuditLog** → belongsTo → User
|
|
|
|
## 🚀 Priority Order for File Creation
|
|
|
|
1. **Models first** (all remaining models)
|
|
2. **Middleware** (upload, validation)
|
|
3. **Utils** (emailService, emailTemplates, helpers)
|
|
4. **Controllers** (in order: auth, outlets, constitutional, relocation, applications, finance, master, dashboard)
|
|
5. **Routes** (for each controller)
|
|
6. **Migrations** (initial-setup.js)
|
|
|
|
## 💡 Tips
|
|
|
|
- Use the resignation module as a complete reference - it has everything you need to understand the pattern
|
|
- All API endpoints are documented in back.md with request/response examples
|
|
- Database schema is fully documented in back.md
|
|
- Permission matrix in back.md shows which roles can access which endpoints
|
|
- Constants file has all ENUMs you need
|
|
- Use logger.info/error for all important actions
|
|
- Always create audit logs for create/update/delete/approve/reject actions
|
|
- Use database transactions for multi-step operations
|
|
- Send email notifications after important actions (use TODO comments for now)
|
|
|
|
## 📞 Questions to Ask Yourself
|
|
|
|
Before creating each file:
|
|
|
|
1. What is this file's purpose? (Check back.md)
|
|
2. What data does it work with? (Check database schema)
|
|
3. Who can access it? (Check permission matrix)
|
|
4. What validations are needed? (Check API documentation)
|
|
5. What side effects should happen? (Audit logs, emails, status updates)
|
|
|
|
## ✅ Success Criteria
|
|
|
|
Backend is complete when:
|
|
|
|
- [ ] All model files created and associations defined
|
|
- [ ] All controller files created with business logic
|
|
- [ ] All route files created with proper middleware
|
|
- [ ] All middleware files created
|
|
- [ ] All utility files created
|
|
- [ ] Migration file creates schema and seeds data
|
|
- [ ] Server starts without errors
|
|
- [ ] All API endpoints respond correctly
|
|
- [ ] Role-based permissions work correctly
|
|
- [ ] Database relationships are correct
|
|
- [ ] Authentication/Authorization works
|
|
- [ ] File uploads work
|
|
- [ ] Email service is configured (can use console.log for testing)
|
|
|
|
## 🎯 Final Goal
|
|
|
|
A fully functional Node.js + Express + PostgreSQL backend that:
|
|
|
|
1. ✅ Authenticates users with JWT
|
|
2. ✅ Enforces role-based permissions
|
|
3. ✅ Handles all CRUD operations for all entities
|
|
4. ✅ Manages multi-stage workflows
|
|
5. ✅ Tracks audit trails
|
|
6. ✅ Sends email notifications
|
|
7. ✅ Handles file uploads
|
|
8. ✅ Provides role-based dashboard data
|
|
9. ✅ Ready to connect to the existing frontend
|
|
10. ✅ Ready for production deployment
|
|
|
|
---
|
|
|
|
**Good luck! The backend structure is solid, patterns are clear, and documentation is comprehensive. You have everything you need to complete this successfully!** 🚀 |