# CLAUDE.md — edendavid-backend

This file provides guidance to Claude Code (claude.ai/code) when working in the **backend** subproject.

Read the workspace-wide rules in the [root CLAUDE.md](../CLAUDE.md) first — they always apply. This file adds backend-specific commands, architecture, and conventions.

**Backend:** Node.js + Express 5 + MongoDB/Mongoose API. Git submodule (remote `EDENDAVIDGROUP/edendavid-backend`), deployed to Vercel as a serverless handler.

## Commands

```bash
npm run dev                  # nodemon on api/index.js (port from PORT env, default 3000)
npm start                    # node api/index.js (production-style local run)
npm test                     # jest --verbose (the canonical test runner)
node tests/run.js            # zero-dep smoke runner for pure-util tests (calcDiff, resolveActor, eventPatterns, …)
npm run migrate:<name>       # one-off DB migration scripts in scripts/migrations/ — see package.json for the full list
```

Jest is the primary suite. `tests/run.js` is a separate, dependency-free script kept around for utilities that don't need Jest. **Both must pass.**

## Env vars

Backend needs `MONGO_URI`, `JWT_SECRET`, `JWT_SECRET_FOR_VERIFY`, `JWT_SECRET_MFA`, `JWT_SECRET_TRUSTED`, plus integration-specific secrets (Chita, Cash Cow, SuperPharm/ZAP via Mirakl, Rivhit, Gmail OAuth, AWS S3, Stripe/PayPal, web-push). Webhook routes are guarded by `X-Integration-API-Key` (`PUBLIC_ORDER_STATUS_API_KEY`) or `Authorization: Bearer` (`WEBHOOK_BEARER_ENV`) — see [api/index.js](api/index.js).

## Architecture

**Runtime model.** [api/index.js](api/index.js) is the single Express app entrypoint and is exported as a Vercel serverless handler. When run with `node` directly (`require.main === module`), it additionally starts cron jobs, an HTTP server, and Socket.IO. The Mongo connection is cached on `global._mongoCached` so cold starts share one pool — see [config/db.js](config/db.js). Don't open new Mongoose connections in feature code.

**Auth.** [config/auth.js](config/auth.js) exports JWT middleware: `authUser`, `authAdmin` (admin or super-admin), `authSuperAdmin`, `authDriver`. Routes mounted in `api/index.js` declare their guard explicitly. Drivers and admins are both rows in the `User` model — distinguished by `role` (`admin` | `super-admin` | `driver`). Driver login is phone+SMS-OTP (`phoneOtp`); admin login is email+password with MFA. There are *five* separate JWT secrets (login, password-reset, MFA, trusted-device, attendance-confirmation); don't reuse them.

**Layered structure.** `routes/` → `controllers/` → `services/`. Models in `models/`. Cross-cutting helpers in `utils/`. External-system code lives under `integrations/` (one folder per vendor: `chita`, `cashcow`, `superPharm`, `zap`, `mirakl` shared by SP/ZAP, `rivhit`, `emailOrders`, `machsaneyHashmal`, `whatsappBiz`). Each integration owns its config, client, mapper, and service files; webhooks they expose are mounted in `api/index.js` before the admin auth guards.

**Order domain.** The `Order` model in [models/Order.js](models/Order.js) is the central aggregate — pricing, cart, status/subStatus refs, customer, `internalShipping` (driver + proof-of-delivery), `shipment` (external carrier — Chita), `orderLines` (Mirakl raw), and a `statusDetails` audit array. Status is a two-level FSM: `status` (broad — pending/in-transit/delivered/cancelled) + `subStatus` (granular: `internal-loading`, `internal-delivered`, `internal-not-delivered`, payment substatuses, etc.). `SubStatus` documents are seeded; transitions live in `services/orderStatusService.js` and `utils/orderStatusRules.js`. Recent work refactored sub-statuses into a separate model — see commit history and `scripts/migrate-substatus-architecture.js`.

**Order numbering.** Two fields: `orderNumber` (string — manual orders get an auto-incremented number via `mongoose-sequence`/`Counter`; third-party orders get the external source's number) and `internalOrderNumber` (global ≥8-digit ID = 2-digit `Supplier.orderSource` prefix + running counter; used as P22/Chita reference). See migration scripts in `scripts/migrations/`.

**Suppliers and integrations are data-driven.** `Supplier` documents carry `integrationType` (`api`/`excel`/`shipping`/`manual`/`email`/`accounting`), `integrationKey`, `configModule`, and `requires*` flags. The integration registry ([services/integrationRegistry.js](services/integrationRegistry.js)) and credentials service ([services/integrationCredentialsService.js](services/integrationCredentialsService.js)) bind a supplier to its concrete integration code. `UserSupplier` is the per-admin join row holding credentials and toggles (e.g. `autoStockUpdateEnabled`).

**Demo mode.** `User.isDemo` (super-admin–only flag) makes the backend skip all `api`/`shipping`/`accounting` integration calls. There is also a demo reset flow (`/api/demo` → `services/demoResetService.js`) protected by a `demoResetLock` on the user.

**Async jobs.** Long-running integration work (bulk Chita sends, Cash Cow/Mirakl syncs) goes through the Mongo-backed queue in [services/jobService.js](services/jobService.js). Worker progress writes are atomic; a sweeper marks jobs whose heartbeat went silent as `failed` (`server_restart_stale`). After a serverless cold start the queue does *not* resume runFns — operators must retrigger. Pending-correlation-id locks on `Order.shipment` prevent double-billing when a re-triggered job races a recovering one.

**Eventing.** Every meaningful business operation writes to the `Event` collection. Use the helpers in [constants/eventPatterns.js](constants/eventPatterns.js) (`entityCreated`, `entityUpdated`, `statusChanged`, `integrationExecution`) together with `buildEntitySnapshot`, `calcDiff`, and `resolveActor` so events have a consistent shape — those four utilities are also what `tests/run.js` covers.

**Bilingual text.** User-visible strings travel as `{ he, en }` objects or are emitted via `bilingual(he, en)` / `coerceToBilingual(...)` from [utils/bilingualText.js](utils/bilingualText.js). The error handler at the bottom of `api/index.js` coerces thrown `Error.message` through `coerceToBilingual`. When you write an error message in a controller, prefer `bilingual('עברית', 'English')`.

**Other notable services.** `services/shippingProviders/` is a small factory pattern with Chita as the current provider. `services/pdf/` renders order PDFs and the driver manifest. `services/importOrders/` parses Excel uploads (Alma Trade, DolceVita, Boom mappers). `services/platformEmail/` sends platform-bound emails through the shared mail server (`lib/email-sender/mailer.js`, `MAILCOW_*`); `User.notificationGmails` only reads inbound mail and must never gate a send (guard: `tests/services/platformEmailSenderGuard.test.js`). `utils/awsUploader.js` handles S3 upload (used by `/api/upload` and proof-of-delivery).

## Conventions that aren't obvious from the code

- **Cart prices are always per-unit.** Third-party imports must divide line totals by quantity before saving — `integrations/cashcow/cashcowMapper.js` (and the admin's `useOrderSubmit.js`) do this. Failing to normalize causes the UI to double-count.
- **Driver = User row with `role: 'driver'`.** They share the User collection, indexes, and validation. `phone` is unique only for drivers (partial index); `email` is unique only for admins (partial filter).
- **Webhook routes must be mounted before `authAdmin`.** See the Chita and Mahsanei Hashmal webhook mounts in `api/index.js` — they sit above `app.use('/api/chita', authAdmin, ...)` for exactly this reason.
- **Migrations are run manually.** They are not auto-applied at boot. Use `npm run migrate:<name>` or `node scripts/<name>.js` after deploying schema changes. Check `scripts/` and `migrations/` before writing a new one — there is usually a similar precedent.
- **Test scope.** Jest unit tests live in `tests/` and cover services, controllers, integrations, and utils. Pure-data utilities are *also* covered by `tests/run.js` (no jest needed). Run both when changing those utilities.
