# Cherry K Backend API

Node.js / Express / MongoDB API for a dental clinic management system.

## Quick Start

```bash
npm run dev    # nodemon server.js
npm start      # pm2 start (production)
```

## Project Structure

```
app/
├── routes/       # Each file exports (app) => { app.route(...).get|post|put|delete(...) }
├── controllers/  # Handler functions exported as { list, create, get, update, remove, ... }
├── models/       # Mongoose schemas, one per file
├── middleware/   # relatedBranchMiddleware (sets req.mongoQuery), settingMiddleware
├── lib/          # verifyToken (JWT auth), catchError (async error wrapper), apiKeyHandler
├── validators/   # express-validator chains
├── helper/       # Shared utility functions
└── dashboard/    # Dashboard aggregate queries
config/           # db.js, express.js, s3Config.js, fileUploader.js
```

## Conventions

- **Route pattern**: `app.route("/api/resource").get(verifyToken, catchError(ctrl.list))`
- **Controller exports**: `{ list, create, get, update, remove }` — always wrapped with `catchError`
- **Auth**: JWT Bearer token via `verifyToken` middleware on every route
- **Soft delete**: Use `isDeleted: true` pattern; `relatedBranchMiddleware` sets `req.mongoQuery = { isDeleted: false }`
- **Branch scoping**: `req.mongoQuery` is available in every controller for filtering by branch
- **Validation**: `express-validator` in `app/validators/` + `app/utils/validations.js`
- **File uploads**: Multer + S3 via `config/fileUploader.js` and `config/s3Config.js`
- **Models** use `mongoose-sequence` for auto-increment IDs
- **Stock history**: Daily midnight job via `node-schedule` calling `updateStockHistoryForToday()`
- **Text indexes** on key collections (patients, treatments, items, etc.) — use `$text` for search
- **Time**: Use `moment-timezone` throughout

## Key Commands

| Script | Command |
|--------|---------|
| Dev server | `npm run dev` |
| Seed DB | `node seed.js` |

## Website Feature

When working on website-related features, always reference these three modules for their schemas, controllers, and routes:

- **Branch** — `app/models/branch.js` (has `imageUrls[]`, `location`, `openHoursDisplay`, `phones`, `closedDays`), `app/controllers/branchController.js` (has `getAllBranchesHeadOffice` for website), `app/routes/branchRoutes.js` (website: `GET /api/head-office/branches` — no auth), `app/validators/branchValidators.js`
- **Testimonial** — `app/models/testimonial.js`, `app/controllers/testimonialController.js`, `app/routes/testimonialRoutes.js`, `app/validators/testimonialValidators.js`
- **Staff** — `app/models/staff.js`, `app/controllers/staffController.js`, `app/routes/staffRoutes.js`, `app/validators/staffValidators.js`
