Compare commits
11 Commits
main
...
cc3dcd3f0a
| Author | SHA1 | Date | |
|---|---|---|---|
| cc3dcd3f0a | |||
| 8c8a2ccf15 | |||
| 8b341c4933 | |||
| 9dddf7562a | |||
|
|
c5f65dcb62 | ||
|
|
27d0e0149d | ||
|
|
db699822f9 | ||
|
|
2424a086e0 | ||
|
|
8f377a1fe9 | ||
|
|
a0ddef240c | ||
|
|
24b699cfc4 |
17
.claude/settings.json
Normal file
17
.claude/settings.json
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
{
|
||||||
|
"permissions": {
|
||||||
|
"allow": [
|
||||||
|
"Bash(npm run lint)",
|
||||||
|
"Bash(npm run build)",
|
||||||
|
"Bash(npm test)",
|
||||||
|
"Bash(npm run test:e2e)",
|
||||||
|
"Bash(npx jest:*)",
|
||||||
|
"Bash(npx prisma generate --config prisma7.config.ts)"
|
||||||
|
],
|
||||||
|
"deny": [
|
||||||
|
"Read(./.env)",
|
||||||
|
"Read(./.env.*)",
|
||||||
|
"Bash(cat .env*)"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
1
.gitattributes
vendored
Normal file
1
.gitattributes
vendored
Normal file
@@ -0,0 +1 @@
|
|||||||
|
* text=auto eol=lf
|
||||||
21
.gitignore
vendored
21
.gitignore
vendored
@@ -37,10 +37,8 @@ lerna-debug.log*
|
|||||||
|
|
||||||
# dotenv environment variable files
|
# dotenv environment variable files
|
||||||
.env
|
.env
|
||||||
.env.development.local
|
.env.*
|
||||||
.env.test.local
|
!.env.example
|
||||||
.env.production.local
|
|
||||||
.env.local
|
|
||||||
|
|
||||||
# temp directory
|
# temp directory
|
||||||
.temp
|
.temp
|
||||||
@@ -54,3 +52,18 @@ pids
|
|||||||
|
|
||||||
# Diagnostic reports (https://nodejs.org/api/report.html)
|
# Diagnostic reports (https://nodejs.org/api/report.html)
|
||||||
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
|
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
|
||||||
|
|
||||||
|
# Prisma client (regenerated by `prisma generate`, run on npm install)
|
||||||
|
/prisma/generated/
|
||||||
|
|
||||||
|
# AI agent skills installed from skills-lock.json (keep skills-lock.json committed)
|
||||||
|
/.agents/
|
||||||
|
/.windsurf/
|
||||||
|
/.claude/skills/
|
||||||
|
# Claude Code personal settings (.claude/settings.json stays shareable)
|
||||||
|
/.claude/settings.local.json
|
||||||
|
|
||||||
|
# Postman (skills fetched by `postman init`, personal workspace binding)
|
||||||
|
/postman/
|
||||||
|
/.postman/
|
||||||
|
/AGENTS.md
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
{
|
{
|
||||||
"singleQuote": true,
|
"singleQuote": true,
|
||||||
"trailingComma": "all"
|
"trailingComma": "all",
|
||||||
|
"printWidth": 140,
|
||||||
|
"tabWidth": 2
|
||||||
}
|
}
|
||||||
|
|||||||
94
CLAUDE.md
Normal file
94
CLAUDE.md
Normal file
@@ -0,0 +1,94 @@
|
|||||||
|
# CLAUDE.md
|
||||||
|
|
||||||
|
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||||
|
|
||||||
|
## What this is
|
||||||
|
|
||||||
|
Backend of a K-pop online shop. The real shop (catalog, stock, customers, sales) lives in **Hiboutik**, a POS/e-commerce platform; Hiboutik stays the source of truth. This backend sits in front of it as a buffer: it mirrors Hiboutik data into its own database so the storefront does not hammer the Hiboutik API with requests. It is also the place to build shop features Hiboutik does not offer, on top of the mirrored data.
|
||||||
|
|
||||||
|
Stack: NestJS 11, PostgreSQL via **Prisma 7**, Hiboutik REST API as the upstream.
|
||||||
|
|
||||||
|
## Commands
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run start:dev # watch mode (port from PORT, default 3000)
|
||||||
|
npm run build # nest build -> dist/
|
||||||
|
npm run lint # eslint --fix on src/test
|
||||||
|
npm run format # prettier (singleQuote, trailingComma all, printWidth 140)
|
||||||
|
npm test # unit tests (*.spec.ts under src/)
|
||||||
|
npx jest src/app.controller.spec.ts # single test file
|
||||||
|
npx jest -t "test name" # single test by name
|
||||||
|
npm run test:e2e # e2e tests (test/jest-e2e.json)
|
||||||
|
```
|
||||||
|
|
||||||
|
Jest runs in CommonJS: its config (in `package.json` and `test/jest-e2e.json`) transpiles the ESM-only `@nestjs/config` (`transformIgnorePatterns`) and maps `./x.js` imports to `./x` (`moduleNameMapper`) for the generated Prisma client. Keep both configs in sync. Unit tests build services directly with mocked repositories; the e2e test boots `AppModule` with `PrismaService` and `HiboutikService` overridden, so it needs neither a database nor Hiboutik.
|
||||||
|
|
||||||
|
TypeScript runs in `strict` mode and ESLint treats floating promises as errors: a deliberate fire-and-forget call is written `void promise`.
|
||||||
|
|
||||||
|
Prisma: the config file is `prisma7.config.ts` (non-default name), so pass it explicitly:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx prisma generate --config prisma7.config.ts
|
||||||
|
npx prisma migrate dev --name <name> --config prisma7.config.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
The client is generated into `prisma/generated/` (generator `prisma-client`, not the legacy `prisma-client-js`) and must be regenerated after any `schema.prisma` change. Code imports types from there, e.g. `prisma/generated/client` and `prisma/generated/models/<Model>` (`ProductCreateInput`, etc.).
|
||||||
|
|
||||||
|
## Environment
|
||||||
|
|
||||||
|
Read from `.env` (`@nestjs/config`, global): `DATABASE_URL` (used by Prisma and `PrismaService`), `HIBOUTIK_BASE_URL`, `HIBOUTIK_USERNAME`, `HIBOUTIK_PASSWORD` (HTTP Basic auth). HTTP calls to Hiboutik (`HttpModule.register` in `AppModule`) time out after 30 s, never follow redirects (the Basic auth credentials must not leave) and are capped at 50 MB. `HiboutikClient` retries a 429 three times with backoff (2/4/8 s, or the `Retry-After` delay capped at 60 s), then throws `HiboutikRateLimitError`: per-item `catch` blocks must rethrow it (`rethrowIfRateLimited`) and `syncAll` stops on it. Hiboutik allows 10,000 calls per month and 30 concurrent calls per shop.
|
||||||
|
|
||||||
|
The environment is validated at startup (`src/config/env.validation.ts`, wired in `ConfigModule.forRoot`): a missing or malformed required variable stops the app, and `HIBOUTIK_BASE_URL` must be HTTPS (Basic auth). Optional variables: `NODE_ENV` (`development`/`production`/`test`; in `production`, `DATABASE_URL` must set `sslmode=require`, `verify-ca` or `verify-full`), `PORT`, `CORS_ORIGINS` (comma-separated; CORS stays disabled when unset), `TRUST_PROXY` (number of reverse proxies, so rate limiting sees the real client IP) and `SYNC_SHUTDOWN_TIMEOUT` (seconds a stopping instance waits for its running sync, default 25; keep it below the orchestrator's grace period). Any new variable goes in `EnvironmentVariables`; the e2e test gets dummy values from `test/setup-env.ts`.
|
||||||
|
|
||||||
|
Security defaults in `main.ts`/`AppModule`: Helmet, global `ValidationPipe`, `ThrottlerGuard` on every route (60 req/min/IP; `@Throttle` for stricter limits, e.g. `POST /sync` at 5/min; counters shared by every instance in the `throttler_records` table through `ThrottlerDatabaseStorage`, one atomic upsert per request on the database clock, failing open if the database is unreachable), `AllExceptionsFilter` (unexpected errors are logged with message + stack and answered with a generic 500; deliberate `HttpException`s and 4xx HTTP-layer errors pass through), HTTP header/request timeouts (15 s / 30 s), shutdown hooks. The app is meant to run as several instances. On shutdown, `HiboutikService.beforeApplicationShutdown` refuses new syncs (503) and waits for the running one up to `SYNC_SHUTDOWN_TIMEOUT`; Prisma disconnects last, in `onApplicationShutdown` (never move it back to `onModuleDestroy`, which runs first). Long work must run in the background (like `POST /sync`), never inside a request.
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
Everything is registered as providers in a single `AppModule` (`src/app.module.ts`); new repositories/converters/services must be added there. `PrismaModule` (in `prisma/`, outside `src/`) is global.
|
||||||
|
|
||||||
|
Sync pipeline, one entity per layer:
|
||||||
|
|
||||||
|
1. **`src/hiboutik/*.hiboutik.repository.ts`** – fetch data from Hiboutik through `HiboutikClient`: `getList`, `getAllPages` (walks the `p` page param until a page smaller than 250 results, Hiboutik's page size) and `getOne` (single resource: `null` on a 404 or an empty 2xx answer, throws on anything else). `/suppliers` and `/stock_available/all_wh` are not paginated.
|
||||||
|
2. **`src/models/hiboutikDTO/`** – zod schemas of the Hiboutik payloads (snake_case, only the fields used), the DTO types being inferred from them. `HiboutikClient` validates every answer: shared field types in `hiboutik.schema.ts` turn numeric strings into numbers and empty values into `0`/`""`/`[]`; an invalid id, relation or price rejects the whole answer (so nothing is deleted). Validation errors name fields, never values.
|
||||||
|
3. **`src/models/converter/`** – classes extending abstract `Converter<Model, Dto>`; `fromHiboutik` maps a DTO to a Prisma `*CreateInput`. Relations use `connect: { hiboutikId }`.
|
||||||
|
4. **`src/database/*.database.repository.ts`** – Prisma access, mainly `upsert` keyed on the unique `hiboutikId`.
|
||||||
|
5. **`src/services/hiboutik/*.hiboutik.service.ts`** – per-entity sync orchestration; `HiboutikService.syncAll` runs them in dependency order: brands → categories → suppliers → products → customers (products `connect` to the first three by `hiboutikId`, so order matters).
|
||||||
|
|
||||||
|
Domain notes:
|
||||||
|
- Synced models carry a unique `hiboutikId` (join key with Hiboutik), except `Order` (nullable `hiboutikSaleId`), `ProductVersion` (unique `[productId, hiboutikSizeId]`) and `OrderLine`; the internal `id` is a UUID. Empty Hiboutik barcodes are stored as `null`. `ProductVersion.barcode` is indexed but **not unique** (Hiboutik may reuse a barcode).
|
||||||
|
- Hiboutik is the source of truth: brands, categories, suppliers, products and customers missing from it are deleted. Hiboutik is trusted: a 2xx answer is the truth, even an empty list (everything is then deleted). Deletion only requires that the call did not fail: `HiboutikClient` throws on HTTP errors (4xx/5xx) and `getList`/`getAllPages` also throw on a 2xx body that is not a list (a 2xx without body is an empty list), so a failed step deletes nothing. Every call goes through `getList`/`getAllPages`/`getAllPagesForSync`/`getOne` with a schema (the bare `get` is private). A paginated list that drives deletions must guard against page shifts (an item created or deleted during the walk shifts the following pages, so an item can be skipped and wrongly deleted), and be sorted on a unique key. Brands, categories and products use `getAllPagesForSync`: a list spanning several pages is walked twice and both walks are merged by id. Customers do not, as each one is fetched anyway: as a customer created or deleted during the walk shifts the pages, a stored customer missing from the list is deleted only once `GET /customer/:id` confirms it (404 or empty answer); if it still exists it is synced, if the check fails it is kept. Products are deleted before the upserts; their versions go by cascade. Each product is written in one transaction (upsert, deletion of its missing versions, version upserts), with the repositories taking an optional `Prisma.TransactionClient`. Customer addresses go by cascade with their customer; other relations (product brand/category/supplier, sub-categories, order customer) are set to null and orders are kept.
|
||||||
|
- Brands, categories and suppliers are upserted through `forEachSafely` (`src/utils/sync.ts`): a failing row is logged and skipped. Each sync step and each product/customer is in a try/catch: failures are logged, the sync goes on, and a summary is logged at the end.
|
||||||
|
- Categories form a tree: parents are linked in a second pass (`setParent`). `enabled` mirrors `category_enabled` (POS), `webEnabled` mirrors `category_enabled_www`.
|
||||||
|
- Products: `ProductVersion` rows come from `product_size_details` (barcode, price/discount overrides from `product_specific_rules`, stock from the stocks endpoint); no sizes means one version with `hiboutikSizeId: 0`. `globalStock` is the sum of available stock. `archived` mirrors `product_arch`.
|
||||||
|
- `GET /customer/:id` embeds `addresses` and `sales` (typed in `customer.hiboutik.dto.ts`); `sales` only has headers, lines come from `GET /sales/:id` (`SaleHiboutikRepository`).
|
||||||
|
- Addresses (from the embedded array): missing ones are deleted, the rest upserted via `forEachSafely`; no array means stored addresses are left untouched. Each has its own recipient fields, empty optional values stored as `null`. Company details (`taxNumber`, `companyNumber`, `legalStatus`) come from `GET /customers_addresses/:id`, only for addresses with a `company` (`null` otherwise, untouched if the call fails).
|
||||||
|
- Customers: an email or phone removed in Hiboutik is erased in database (`null`, data minimization).
|
||||||
|
- Dates: Hiboutik sends French local time without offset; `parseHiboutikDate` reads datetimes as `Europe/Paris` whatever the server time zone, and date-only values (date of birth) as midnight UTC.
|
||||||
|
- Orders come from the customer's `sales`: sales already stored as `COMPLETED` and linked to this customer are skipped (an order that lost its customer is fetched again to be linked back), the others are fetched and upserted on `hiboutikSaleId` (`source: STORE` on creation only). `status` is `COMPLETED` or `PENDING`, `orderedAt` is the completion date else the creation date. Lines are replaced on each upsert and snapshot name, version, barcode, price and Hiboutik ids; the `ProductVersion` link is optional (`SetNull`). `unitPrice` is the paid price, taxes and discount included. Quotations are skipped, anonymous sales are never synced (only customers' sales are read), and orders are never deleted.
|
||||||
|
- Shared Prisma payload types (e.g. `ProductWithVersions`) live in `prisma/customObjects/`.
|
||||||
|
|
||||||
|
## Input validation
|
||||||
|
|
||||||
|
All data coming from API clients (`@Body()`, `@Query()`, `@Param()`) must be validated with NestJS `ValidationPipe` and `class-validator` DTO classes.
|
||||||
|
|
||||||
|
- Register `ValidationPipe` globally in `main.ts` with `whitelist: true`, `forbidNonWhitelisted: true` and `transform: true` (no `if` checks by hand in controllers/services).
|
||||||
|
- Every endpoint that reads a body, query string or route param takes a dedicated input DTO class decorated with `class-validator` rules (type, length, range, format). Cap pagination (`limit`/`take`) with `@Max`. For nested payloads use `@ValidateNested()` + `@Type()`.
|
||||||
|
- Never use Prisma models or Hiboutik DTOs as input types: the `src/models/hiboutikDTO/` types describe data coming from Hiboutik, not from API clients.
|
||||||
|
|
||||||
|
## Security rules
|
||||||
|
|
||||||
|
- **Logs**: never log a raw error object, a request/response or an axios config: they carry the Hiboutik `Authorization` header (credentials). Log `(error as Error).message` and `.stack` only, as the sync services do. No personal data (emails, names, addresses, phone numbers, tax numbers) in logs: ids only. `PrismaService` uses `errorFormat: 'minimal'` because the default error format prints the query arguments; keep it.
|
||||||
|
- **SQL**: use the Prisma query API. `$queryRaw`/`$executeRaw` are allowed only as tagged templates with parameters (`` $queryRaw`... ${value}` ``); never `$queryRawUnsafe`/`$executeRawUnsafe` nor string concatenation or interpolation into SQL text.
|
||||||
|
- **Sync lock**: only one synchronization runs at a time across all instances. `HiboutikService.startSync` takes a Postgres advisory lock (`SyncLockDatabaseRepository`, dedicated `pg` connection held for the whole sync, released by Postgres itself if the process dies). Start syncs only through `startSync`, never call `syncAll` directly from a controller or a scheduler.
|
||||||
|
|
||||||
|
## API
|
||||||
|
|
||||||
|
If the Postman plugin is installed, load its `postman:api-engineer` skill before any non-trivial API engineering task (designing, implementing, mocking, testing, monitoring, documenting, deploying). Pure questions and trivial one-line edits do not need it. The local `postman/` and `.postman/` folders are generated by `postman init` and are git-ignored.
|
||||||
|
|
||||||
|
## Git workflow
|
||||||
|
|
||||||
|
The remote is a Gitea instance (`origin`). Use plain `git` or the Gitea CLI (`gt`) for pull requests and other Gitea operations.
|
||||||
|
|
||||||
|
- Never commit or push directly to the integration branch: always push changes on a `feature/<name>` branch.
|
||||||
|
- Merges go into `develop`. Until `develop` exists (early project phase), they go into `main`.
|
||||||
|
- Commit messages follow Conventional Commits (`feat(sync): ...`, `fix(db): ...`).
|
||||||
@@ -31,6 +31,14 @@
|
|||||||
$ npm install
|
$ npm install
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### AI agent skills (optional)
|
||||||
|
|
||||||
|
The Prisma skills used by Claude Code are pinned in `skills-lock.json`; the skill folders themselves are not committed. Restore them with:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$ npx skills experimental_install
|
||||||
|
```
|
||||||
|
|
||||||
## Compile and run the project
|
## Compile and run the project
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
|||||||
@@ -19,17 +19,18 @@ export default tseslint.config(
|
|||||||
},
|
},
|
||||||
sourceType: 'commonjs',
|
sourceType: 'commonjs',
|
||||||
parserOptions: {
|
parserOptions: {
|
||||||
projectService: true,
|
//projectService: true,
|
||||||
tsconfigRootDir: import.meta.dirname,
|
tsconfigRootDir: import.meta.dirname,
|
||||||
|
project: './tsconfig.json',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
rules: {
|
rules: {
|
||||||
'@typescript-eslint/no-explicit-any': 'off',
|
'@typescript-eslint/no-explicit-any': 'off',
|
||||||
'@typescript-eslint/no-floating-promises': 'warn',
|
'@typescript-eslint/no-floating-promises': 'error',
|
||||||
'@typescript-eslint/no-unsafe-argument': 'warn',
|
'@typescript-eslint/no-unsafe-argument': 'warn',
|
||||||
"prettier/prettier": ["error", { endOfLine: "auto" }],
|
"prettier/prettier": "error",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|||||||
5626
package-lock.json
generated
5626
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
54
package.json
54
package.json
@@ -6,6 +6,7 @@
|
|||||||
"private": true,
|
"private": true,
|
||||||
"license": "UNLICENSED",
|
"license": "UNLICENSED",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
"postinstall": "prisma generate --config prisma7.config.ts",
|
||||||
"build": "nest build",
|
"build": "nest build",
|
||||||
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||||
"start": "nest start",
|
"start": "nest start",
|
||||||
@@ -21,22 +22,32 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@nestjs/axios": "^4.0.1",
|
"@nestjs/axios": "^4.0.1",
|
||||||
"@nestjs/common": "^11.0.1",
|
"@nestjs/common": "^11.1.29",
|
||||||
"@nestjs/core": "^11.0.1",
|
"@nestjs/config": "^12.0.0",
|
||||||
"@nestjs/platform-express": "^11.0.1",
|
"@nestjs/core": "^11.1.29",
|
||||||
"axios": "^1.17.0",
|
"@nestjs/platform-express": "^11.1.29",
|
||||||
|
"@nestjs/throttler": "^6.7.1",
|
||||||
|
"@prisma/adapter-pg": "^7.10.0",
|
||||||
|
"@prisma/client": "^7.10.0",
|
||||||
|
"axios": "1.20.0",
|
||||||
|
"class-transformer": "^0.5.1",
|
||||||
|
"class-validator": "^0.15.1",
|
||||||
|
"helmet": "^8.3.0",
|
||||||
|
"pg": "^8.23.0",
|
||||||
"reflect-metadata": "^0.2.2",
|
"reflect-metadata": "^0.2.2",
|
||||||
"rxjs": "^7.8.1"
|
"rxjs": "^7.8.1",
|
||||||
|
"zod": "4.6.7"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/eslintrc": "^3.2.0",
|
"@eslint/eslintrc": "^3.2.0",
|
||||||
"@eslint/js": "^9.18.0",
|
"@eslint/js": "^9.18.0",
|
||||||
"@nestjs/cli": "^11.0.0",
|
"@nestjs/cli": "^12.0.11",
|
||||||
"@nestjs/schematics": "^11.0.0",
|
"@nestjs/schematics": "^11.0.0",
|
||||||
"@nestjs/testing": "^11.0.1",
|
"@nestjs/testing": "^11.1.29",
|
||||||
"@types/express": "^5.0.0",
|
"@types/express": "^5.0.0",
|
||||||
"@types/jest": "^30.0.0",
|
"@types/jest": "^30.0.0",
|
||||||
"@types/node": "^24.0.0",
|
"@types/node": "^24.0.0",
|
||||||
|
"@types/pg": "^8.23.1",
|
||||||
"@types/supertest": "^7.0.0",
|
"@types/supertest": "^7.0.0",
|
||||||
"eslint": "^9.18.0",
|
"eslint": "^9.18.0",
|
||||||
"eslint-config-prettier": "^10.0.1",
|
"eslint-config-prettier": "^10.0.1",
|
||||||
@@ -44,6 +55,7 @@
|
|||||||
"globals": "^17.0.0",
|
"globals": "^17.0.0",
|
||||||
"jest": "^30.0.0",
|
"jest": "^30.0.0",
|
||||||
"prettier": "^3.4.2",
|
"prettier": "^3.4.2",
|
||||||
|
"prisma": "^7.10.0",
|
||||||
"source-map-support": "^0.5.21",
|
"source-map-support": "^0.5.21",
|
||||||
"supertest": "^7.0.0",
|
"supertest": "^7.0.0",
|
||||||
"ts-jest": "^29.2.5",
|
"ts-jest": "^29.2.5",
|
||||||
@@ -62,12 +74,36 @@
|
|||||||
"rootDir": "src",
|
"rootDir": "src",
|
||||||
"testRegex": ".*\\.spec\\.ts$",
|
"testRegex": ".*\\.spec\\.ts$",
|
||||||
"transform": {
|
"transform": {
|
||||||
"^.+\\.(t|j)s$": "ts-jest"
|
"^.+.ts$": "ts-jest",
|
||||||
|
"^.+.js$": [
|
||||||
|
"ts-jest",
|
||||||
|
{
|
||||||
|
"tsconfig": {
|
||||||
|
"allowJs": true,
|
||||||
|
"module": "commonjs",
|
||||||
|
"moduleResolution": "node"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
},
|
},
|
||||||
"collectCoverageFrom": [
|
"collectCoverageFrom": [
|
||||||
"**/*.(t|j)s"
|
"**/*.(t|j)s"
|
||||||
],
|
],
|
||||||
"coverageDirectory": "../coverage",
|
"coverageDirectory": "../coverage",
|
||||||
"testEnvironment": "node"
|
"testEnvironment": "node",
|
||||||
|
"transformIgnorePatterns": [
|
||||||
|
"/node_modules/(?!@nestjs/config/)"
|
||||||
|
],
|
||||||
|
"moduleNameMapper": {
|
||||||
|
"^(\\.{1,2}/.*)\\.js$": "$1"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"allowScripts": {
|
||||||
|
"@parcel/watcher@2.6.0": true,
|
||||||
|
"@prisma/engines@7.10.1": true,
|
||||||
|
"prisma@7.10.1": true
|
||||||
|
},
|
||||||
|
"overrides": {
|
||||||
|
"multer": "^2.5.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
12
prisma/customObjects/prisma.custom.object.ts
Normal file
12
prisma/customObjects/prisma.custom.object.ts
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
import { Prisma } from '../generated/client';
|
||||||
|
|
||||||
|
/** Product loaded with its versions (`include: { versions: true }`). */
|
||||||
|
export type ProductWithVersions = Prisma.ProductGetPayload<{ include: { versions: true } }>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Order to save with its lines. Lines are kept apart from the nested Prisma input so that the repository can link
|
||||||
|
* them to the current catalog (`productVersion`) and replace them on update.
|
||||||
|
*/
|
||||||
|
export type OrderWithLinesInput = Omit<Prisma.OrderCreateInput, 'lines'> & {
|
||||||
|
lines: Prisma.OrderLineCreateWithoutOrderInput[];
|
||||||
|
};
|
||||||
3
prisma/migrations/migration_lock.toml
Normal file
3
prisma/migrations/migration_lock.toml
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# Please do not edit this file manually
|
||||||
|
# It should be added in your version-control system (e.g., Git)
|
||||||
|
provider = "postgresql"
|
||||||
9
prisma/prisma.module.ts
Normal file
9
prisma/prisma.module.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
import { Global, Module } from '@nestjs/common';
|
||||||
|
import { PrismaService } from './prisma.service';
|
||||||
|
|
||||||
|
@Global()
|
||||||
|
@Module({
|
||||||
|
providers: [PrismaService],
|
||||||
|
exports: [PrismaService],
|
||||||
|
})
|
||||||
|
export class PrismaModule {}
|
||||||
25
prisma/prisma.service.ts
Normal file
25
prisma/prisma.service.ts
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
import { Injectable, OnApplicationShutdown, OnModuleInit } from '@nestjs/common';
|
||||||
|
import { PrismaClient } from './generated/client';
|
||||||
|
import { PrismaPg } from '@prisma/adapter-pg';
|
||||||
|
|
||||||
|
/** Prisma client shared by the whole app (global PrismaModule), connected to `DATABASE_URL` through the pg driver adapter. */
|
||||||
|
@Injectable()
|
||||||
|
export class PrismaService extends PrismaClient implements OnModuleInit, OnApplicationShutdown {
|
||||||
|
constructor() {
|
||||||
|
const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL });
|
||||||
|
// 'minimal': by default, error messages print the query arguments (emails, names, addresses...), which end up in the logs
|
||||||
|
super({ adapter, errorFormat: 'minimal' });
|
||||||
|
}
|
||||||
|
|
||||||
|
async onModuleInit() {
|
||||||
|
await this.$connect();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Last shutdown hook (after `onModuleDestroy` and `beforeApplicationShutdown`, once the HTTP server is closed):
|
||||||
|
* a synchronization still running is waited for in `beforeApplicationShutdown` and keeps the database until then.
|
||||||
|
*/
|
||||||
|
async onApplicationShutdown() {
|
||||||
|
await this.$disconnect();
|
||||||
|
}
|
||||||
|
}
|
||||||
245
prisma/schema.prisma
Normal file
245
prisma/schema.prisma
Normal file
@@ -0,0 +1,245 @@
|
|||||||
|
// This is your Prisma schema file,
|
||||||
|
// learn more about it in the docs: https://pris.ly/d/prisma-schema
|
||||||
|
|
||||||
|
// Get a free hosted Postgres database in seconds: `npx create-db`
|
||||||
|
|
||||||
|
generator client {
|
||||||
|
provider = "prisma-client"
|
||||||
|
output = "./generated/"
|
||||||
|
}
|
||||||
|
|
||||||
|
datasource db {
|
||||||
|
provider = "postgresql"
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Product category, mirrored from Hiboutik. Categories form a tree (parent / children).
|
||||||
|
model Category {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
|
/// Enabled in the Hiboutik POS (category_enabled)
|
||||||
|
enabled Boolean @default(true)
|
||||||
|
hiboutikId Int @unique
|
||||||
|
name String
|
||||||
|
/// Display order among its siblings (category_position)
|
||||||
|
position Int @default(0)
|
||||||
|
/// Displayed on the website (category_enabled_www)
|
||||||
|
webEnabled Boolean @default(true)
|
||||||
|
|
||||||
|
/// Null for a root category
|
||||||
|
parent Category? @relation("CategoryTree", fields: [parentId], references: [id], onDelete: SetNull)
|
||||||
|
parentId String?
|
||||||
|
children Category[] @relation("CategoryTree")
|
||||||
|
|
||||||
|
products Product[]
|
||||||
|
|
||||||
|
@@map("categories")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Product brand, mirrored from Hiboutik.
|
||||||
|
model Brand {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
|
enabled Boolean @default(true)
|
||||||
|
hiboutikId Int @unique
|
||||||
|
name String
|
||||||
|
|
||||||
|
products Product[]
|
||||||
|
|
||||||
|
@@map("brands")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Product supplier, mirrored from Hiboutik.
|
||||||
|
model Supplier {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
|
enabled Boolean @default(true)
|
||||||
|
hiboutikId Int @unique
|
||||||
|
name String
|
||||||
|
|
||||||
|
products Product[]
|
||||||
|
|
||||||
|
@@map("suppliers")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Product mirrored from Hiboutik. What is actually sold is one of its versions (sizes).
|
||||||
|
model Product {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
|
/// Archived in Hiboutik (product_arch)
|
||||||
|
archived Boolean @default(false)
|
||||||
|
barcode String?
|
||||||
|
description String
|
||||||
|
/// Null when the product has no discount
|
||||||
|
discountPrice Decimal? @db.Decimal(10, 2)
|
||||||
|
/// Displayed on the website (product_display_www)
|
||||||
|
enabled Boolean @default(true)
|
||||||
|
/// Sum of the available stock of all its versions
|
||||||
|
globalStock Int @default(0)
|
||||||
|
hiboutikId Int @unique
|
||||||
|
/// Last update in Hiboutik
|
||||||
|
hiboutikUpdatedAt DateTime?
|
||||||
|
name String
|
||||||
|
price Decimal @db.Decimal(10, 2)
|
||||||
|
|
||||||
|
brand Brand? @relation(fields: [brandId], references: [id], onDelete: SetNull)
|
||||||
|
brandId String?
|
||||||
|
category Category? @relation(fields: [categoryId], references: [id], onDelete: SetNull)
|
||||||
|
categoryId String?
|
||||||
|
supplier Supplier? @relation(fields: [supplierId], references: [id], onDelete: SetNull)
|
||||||
|
supplierId String?
|
||||||
|
|
||||||
|
versions ProductVersion[]
|
||||||
|
|
||||||
|
@@map("products")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sellable version of a product: one per Hiboutik size, or a single one (hiboutikSizeId 0) for a product without sizes.
|
||||||
|
model ProductVersion {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
|
/// Not unique: Hiboutik is the source of truth and may hold the same barcode on several products
|
||||||
|
barcode String?
|
||||||
|
/// Size-specific discount, null when none
|
||||||
|
discountPrice Decimal? @db.Decimal(10, 2)
|
||||||
|
/// Hiboutik size id, 0 for a product without sizes
|
||||||
|
hiboutikSizeId Int
|
||||||
|
/// Size-specific price, null to use the product price (copy of the product price for a product without sizes)
|
||||||
|
price Decimal? @db.Decimal(10, 2)
|
||||||
|
stock Int @default(0)
|
||||||
|
/// Size name, or the product name for a product without sizes
|
||||||
|
versionName String
|
||||||
|
|
||||||
|
product Product @relation(fields: [productId], references: [id], onDelete: Cascade, onUpdate: Restrict)
|
||||||
|
productId String
|
||||||
|
|
||||||
|
orderLines OrderLine[]
|
||||||
|
|
||||||
|
@@unique([productId, hiboutikSizeId])
|
||||||
|
@@index([barcode])
|
||||||
|
@@map("productVersions")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Customer mirrored from Hiboutik.
|
||||||
|
model Customer {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
|
dateOfBirth DateTime?
|
||||||
|
/// Null when the customer has no email in Hiboutik (erased when removed there)
|
||||||
|
email String?
|
||||||
|
firstName String
|
||||||
|
hiboutikId Int @unique
|
||||||
|
/// Last update in Hiboutik
|
||||||
|
hiboutikUpdatedAt DateTime?
|
||||||
|
lastName String
|
||||||
|
phone String?
|
||||||
|
|
||||||
|
addresses CustomerAddress[]
|
||||||
|
orders Order[]
|
||||||
|
|
||||||
|
@@index([email])
|
||||||
|
@@map("customers")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Address of a customer, mirrored from Hiboutik. Its recipient (name, company, phone) can differ from the customer.
|
||||||
|
model CustomerAddress {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
|
address String
|
||||||
|
city String
|
||||||
|
company String?
|
||||||
|
/// Company registration number (SIRET...), only for an address with a company
|
||||||
|
companyNumber String?
|
||||||
|
country String
|
||||||
|
firstName String
|
||||||
|
hiboutikId Int @unique
|
||||||
|
isDefault Boolean @default(false)
|
||||||
|
lastName String
|
||||||
|
/// Company legal status (SAS, SARL...), only for an address with a company
|
||||||
|
legalStatus String?
|
||||||
|
/// Free complement (building, floor, door code...)
|
||||||
|
other String?
|
||||||
|
phone String?
|
||||||
|
state String?
|
||||||
|
/// Company VAT number, only for an address with a company
|
||||||
|
taxNumber String?
|
||||||
|
zipCode String
|
||||||
|
|
||||||
|
customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade)
|
||||||
|
customerId String
|
||||||
|
|
||||||
|
@@map("customer_addresses")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where an order was placed.
|
||||||
|
enum OrderSource {
|
||||||
|
STORE // hiboutik
|
||||||
|
WEB // site
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Order placed in store (Hiboutik sale) or on the website.
|
||||||
|
model Order {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
/// Null for a website order not (yet) sent to Hiboutik
|
||||||
|
hiboutikSaleId Int? @unique
|
||||||
|
orderedAt DateTime
|
||||||
|
source OrderSource
|
||||||
|
status String
|
||||||
|
total Decimal @db.Decimal(10, 2)
|
||||||
|
|
||||||
|
/// Null for an anonymous sale or a deleted customer
|
||||||
|
customer Customer? @relation(fields: [customerId], references: [id], onDelete: SetNull)
|
||||||
|
customerId String?
|
||||||
|
|
||||||
|
lines OrderLine[]
|
||||||
|
|
||||||
|
@@map("orders")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Line of an order.
|
||||||
|
model OrderLine {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
|
// Snapshot of the product at order time: the catalog can change or be deleted afterwards
|
||||||
|
barcode String?
|
||||||
|
hiboutikProductId Int
|
||||||
|
hiboutikSizeId Int
|
||||||
|
productName String
|
||||||
|
quantity Int
|
||||||
|
unitPrice Decimal @db.Decimal(10, 2)
|
||||||
|
versionName String
|
||||||
|
|
||||||
|
order Order @relation(fields: [orderId], references: [id], onDelete: Cascade)
|
||||||
|
orderId String
|
||||||
|
// Link to the current catalog, set to null when the version is deleted
|
||||||
|
productVersion ProductVersion? @relation(fields: [productVersionId], references: [id], onDelete: SetNull)
|
||||||
|
productVersionId String?
|
||||||
|
|
||||||
|
@@map("order_lines")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Rate limiting counter shared by every instance (ThrottlerDatabaseStorage): one fixed window per throttler key
|
||||||
|
/// (route + client IP). Not synced from Hiboutik. Rows whose window and block are over are purged regularly.
|
||||||
|
model ThrottlerRecord {
|
||||||
|
/// Key generated by the ThrottlerGuard (hash of route, throttler name and client IP)
|
||||||
|
key String @id
|
||||||
|
/// Requests counted in the current window
|
||||||
|
hits Int
|
||||||
|
/// End of the current window
|
||||||
|
expiresAt DateTime @db.Timestamptz(3)
|
||||||
|
/// End of the block once the limit was exceeded, null when not blocked
|
||||||
|
blockedUntil DateTime? @db.Timestamptz(3)
|
||||||
|
|
||||||
|
@@index([expiresAt])
|
||||||
|
@@map("throttler_records")
|
||||||
|
}
|
||||||
14
prisma7.config.ts
Normal file
14
prisma7.config.ts
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
// This file was generated by Prisma, and assumes you have installed the following:
|
||||||
|
// npm install --save-dev prisma dotenv
|
||||||
|
import 'dotenv/config';
|
||||||
|
import { defineConfig } from 'prisma/config';
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
schema: 'prisma/schema.prisma',
|
||||||
|
migrations: {
|
||||||
|
path: 'prisma/migrations',
|
||||||
|
},
|
||||||
|
datasource: {
|
||||||
|
url: process.env['DATABASE_URL'],
|
||||||
|
},
|
||||||
|
});
|
||||||
59
skills-lock.json
Normal file
59
skills-lock.json
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
{
|
||||||
|
"version": 1,
|
||||||
|
"skills": {
|
||||||
|
"prisma-cli": {
|
||||||
|
"source": "prisma/skills",
|
||||||
|
"sourceType": "github",
|
||||||
|
"skillPath": "prisma-cli/SKILL.md",
|
||||||
|
"computedHash": "b92e55aef78f6796d81433c44738a6733211a04c16e65cbad6d42c5f71092aab"
|
||||||
|
},
|
||||||
|
"prisma-client-api": {
|
||||||
|
"source": "prisma/skills",
|
||||||
|
"sourceType": "github",
|
||||||
|
"skillPath": "prisma-client-api/SKILL.md",
|
||||||
|
"computedHash": "5dcc0793337151efa73a444e5adbc7e1c24180778e83b4fe94c9109c391bd333"
|
||||||
|
},
|
||||||
|
"prisma-compute": {
|
||||||
|
"source": "prisma/skills",
|
||||||
|
"sourceType": "github",
|
||||||
|
"skillPath": "prisma-compute/SKILL.md",
|
||||||
|
"computedHash": "e5695a3c6f35428e96df30ae662716bd4c9d9074f72cc9334b3050445a1bd4e2"
|
||||||
|
},
|
||||||
|
"prisma-database-setup": {
|
||||||
|
"source": "prisma/skills",
|
||||||
|
"sourceType": "github",
|
||||||
|
"skillPath": "prisma-database-setup/SKILL.md",
|
||||||
|
"computedHash": "0911d9454bd48df3badd23a50fd90a280eabb15dcbd472c14e7b729075dadefb"
|
||||||
|
},
|
||||||
|
"prisma-driver-adapter-implementation": {
|
||||||
|
"source": "prisma/skills",
|
||||||
|
"sourceType": "github",
|
||||||
|
"skillPath": "prisma-driver-adapter-implementation/SKILL.md",
|
||||||
|
"computedHash": "07484627aea6cce4d0f94b4090ff9acc0caa7e104f9988b95abecf80132f4103"
|
||||||
|
},
|
||||||
|
"prisma-mongodb-upgrade": {
|
||||||
|
"source": "prisma/skills",
|
||||||
|
"sourceType": "github",
|
||||||
|
"skillPath": "prisma-mongodb-upgrade/SKILL.md",
|
||||||
|
"computedHash": "f9ba440e88ca4cec9801d04762296e29e99ca08cb8a8156e4f783ecf90279c8f"
|
||||||
|
},
|
||||||
|
"prisma-postgres": {
|
||||||
|
"source": "prisma/skills",
|
||||||
|
"sourceType": "github",
|
||||||
|
"skillPath": "prisma-postgres/SKILL.md",
|
||||||
|
"computedHash": "d669fbd0d8017d16c967f18b20e1c1345cd4a2a0076d762459bfef79f551f655"
|
||||||
|
},
|
||||||
|
"prisma-postgres-setup": {
|
||||||
|
"source": "prisma/skills",
|
||||||
|
"sourceType": "github",
|
||||||
|
"skillPath": "prisma-postgres-setup/SKILL.md",
|
||||||
|
"computedHash": "c89d3aa91285d8e4964fcaa5238c99a3d3c20b617e032e731cf632330a85a5a6"
|
||||||
|
},
|
||||||
|
"prisma-upgrade-v7": {
|
||||||
|
"source": "prisma/skills",
|
||||||
|
"sourceType": "github",
|
||||||
|
"skillPath": "prisma-upgrade-v7/SKILL.md",
|
||||||
|
"computedHash": "dcc6c71adca6b22f37c5bda5ac7fd63c3bb59495596a22e06a29c7c85371558f"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,22 +1,29 @@
|
|||||||
|
import { ConflictException } from '@nestjs/common';
|
||||||
import { Test, TestingModule } from '@nestjs/testing';
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
import { AppController } from './app.controller';
|
import { AppController } from './app.controller';
|
||||||
import { AppService } from './app.service';
|
import { HiboutikService } from './services/hiboutik/hiboutik.service';
|
||||||
|
|
||||||
describe('AppController', () => {
|
describe('AppController', () => {
|
||||||
let appController: AppController;
|
let controller: AppController;
|
||||||
|
const hiboutikService = { startSync: jest.fn() };
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
const app: TestingModule = await Test.createTestingModule({
|
hiboutikService.startSync.mockReset();
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
controllers: [AppController],
|
controllers: [AppController],
|
||||||
providers: [AppService],
|
providers: [{ provide: HiboutikService, useValue: hiboutikService }],
|
||||||
}).compile();
|
}).compile();
|
||||||
|
controller = module.get(AppController);
|
||||||
appController = app.get<AppController>(AppController);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('root', () => {
|
it('starts a synchronization', async () => {
|
||||||
it('should return "Hello World!"', () => {
|
hiboutikService.startSync.mockResolvedValue(true);
|
||||||
expect(appController.getHello()).toBe('Hello World!');
|
await expect(controller.hiboutikSync()).resolves.toEqual({ message: 'Hiboutik synchronization started' });
|
||||||
});
|
expect(hiboutikService.startSync).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects a synchronization when one is already running', async () => {
|
||||||
|
hiboutikService.startSync.mockResolvedValue(false);
|
||||||
|
await expect(controller.hiboutikSync()).rejects.toThrow(ConflictException);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,12 +1,23 @@
|
|||||||
import { Controller, Get } from '@nestjs/common';
|
import { ConflictException, Controller, HttpCode, HttpStatus, Post } from '@nestjs/common';
|
||||||
import { AppService } from './app.service';
|
import { Throttle } from '@nestjs/throttler';
|
||||||
|
import { HiboutikService } from './services/hiboutik/hiboutik.service';
|
||||||
|
|
||||||
@Controller()
|
@Controller()
|
||||||
export class AppController {
|
export class AppController {
|
||||||
constructor(private readonly appService: AppService) {}
|
constructor(private readonly hiboutikService: HiboutikService) {}
|
||||||
|
|
||||||
@Get()
|
/**
|
||||||
getHello(): string {
|
* Starts the synchronization in the background and answers immediately: 202, 409 if one is already running, or 503
|
||||||
return this.appService.getHello();
|
* if this instance is shutting down (another instance can take the call).
|
||||||
|
* Rate limited to 5 calls per minute: each one can trigger thousands of Hiboutik API calls.
|
||||||
|
*/
|
||||||
|
@Post('sync')
|
||||||
|
@Throttle({ default: { limit: 5, ttl: 60_000 } })
|
||||||
|
@HttpCode(HttpStatus.ACCEPTED)
|
||||||
|
async hiboutikSync() {
|
||||||
|
if (!(await this.hiboutikService.startSync())) {
|
||||||
|
throw new ConflictException('A Hiboutik synchronization is already in progress');
|
||||||
|
}
|
||||||
|
return { message: 'Hiboutik synchronization started' };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,103 @@
|
|||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
|
import { APP_FILTER, APP_GUARD } from '@nestjs/core';
|
||||||
|
import { AllExceptionsFilter } from './filters/all-exceptions.filter';
|
||||||
|
import { ThrottlerGuard, ThrottlerModule } from '@nestjs/throttler';
|
||||||
import { AppController } from './app.controller';
|
import { AppController } from './app.controller';
|
||||||
import { AppService } from './app.service';
|
import { ConfigModule } from '@nestjs/config';
|
||||||
|
import { validateEnv } from './config/env.validation';
|
||||||
|
import { HiboutikService } from './services/hiboutik/hiboutik.service';
|
||||||
|
import { CategoryHiboutikRepository } from './hiboutik/category.hiboutik.repository';
|
||||||
|
import { CategoryConverter } from './models/converter/category.converter';
|
||||||
|
import { ProductHiboutikRepository } from './hiboutik/product.hiboutik.repository';
|
||||||
|
import { HttpModule } from '@nestjs/axios';
|
||||||
|
import { CategoryDatabaseRepository } from './database/category.database.repository';
|
||||||
|
import { PrismaModule } from '../prisma/prisma.module';
|
||||||
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
|
import { ThrottlerDatabaseStorage } from './database/throttlerStorage.database.repository';
|
||||||
|
import { HiboutikClient } from './hiboutik/hiboutik.client';
|
||||||
|
import { BrandHiboutikRepository } from './hiboutik/brand.hiboutik.repository';
|
||||||
|
import { BrandDatabaseRepository } from './database/brand.database.repository';
|
||||||
|
import { BrandConverter } from './models/converter/brand.converter';
|
||||||
|
import { SupplierHiboutikRepository } from './hiboutik/supplier.hiboutik.repository';
|
||||||
|
import { SupplierDatabaseRepository } from './database/supplier.database.repository';
|
||||||
|
import { SupplierConverter } from './models/converter/supplier.converter';
|
||||||
|
import { StockHiboutikRepository } from './hiboutik/stock.hiboutik.repository';
|
||||||
|
import { ProductConverter } from './models/converter/product.converter';
|
||||||
|
import { ProductDatabaseRepository } from './database/product.database.repository';
|
||||||
|
import { ProductVersionDatabaseRepository } from './database/productVersion.database.repository';
|
||||||
|
import { CustomerHiboutikRepository } from './hiboutik/customer.hiboutik.repository';
|
||||||
|
import { CustomerDatabaseRepository } from './database/customer.database.repository';
|
||||||
|
import { CustomerConverter } from './models/converter/customer.converter';
|
||||||
|
import { OrderConverter } from './models/converter/order.converter';
|
||||||
|
import { OrderDatabaseRepository } from './database/order.database.repository';
|
||||||
|
import { SaleHiboutikRepository } from './hiboutik/sale.hiboutik.repository';
|
||||||
|
import { CustomerAddressConverter } from './models/converter/customerAddress.converter';
|
||||||
|
import { CustomerAddressDatabaseRepository } from './database/customerAddress.database.repository';
|
||||||
|
import { BrandHiboutikService } from './services/hiboutik/brand.hiboutik.service';
|
||||||
|
import { CategoryHiboutikService } from './services/hiboutik/category.hiboutik.service';
|
||||||
|
import { CustomerHiboutikService } from './services/hiboutik/customer.hiboutik.service';
|
||||||
|
import { SupplierHiboutikService } from './services/hiboutik/supplier.hiboutik.service';
|
||||||
|
import { ProductHiboutikService } from './services/hiboutik/product.hiboutik.service';
|
||||||
|
import { SyncLockDatabaseRepository } from './database/syncLock.database.repository';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [],
|
imports: [
|
||||||
|
ConfigModule.forRoot({
|
||||||
|
isGlobal: true,
|
||||||
|
validate: validateEnv,
|
||||||
|
}),
|
||||||
|
// Default rate limit for every route: 60 requests per minute per IP (stricter limits via @Throttle).
|
||||||
|
// Counters live in PostgreSQL so that every instance shares them (see ThrottlerDatabaseStorage).
|
||||||
|
ThrottlerModule.forRootAsync({
|
||||||
|
inject: [PrismaService],
|
||||||
|
useFactory: (prisma: PrismaService) => ({
|
||||||
|
throttlers: [{ ttl: 60_000, limit: 60 }],
|
||||||
|
storage: new ThrottlerDatabaseStorage(prisma),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
HttpModule.register({
|
||||||
|
timeout: 30_000,
|
||||||
|
// Hiboutik never redirects: never follow a redirect with the Basic auth credentials
|
||||||
|
maxRedirects: 0,
|
||||||
|
// A runaway answer (bug, faulty proxy) must not be loaded whole in memory
|
||||||
|
maxContentLength: 50 * 1024 * 1024,
|
||||||
|
}),
|
||||||
|
PrismaModule,
|
||||||
|
],
|
||||||
controllers: [AppController],
|
controllers: [AppController],
|
||||||
providers: [AppService],
|
providers: [
|
||||||
|
{ provide: APP_GUARD, useClass: ThrottlerGuard },
|
||||||
|
{ provide: APP_FILTER, useClass: AllExceptionsFilter },
|
||||||
|
BrandConverter,
|
||||||
|
BrandDatabaseRepository,
|
||||||
|
BrandHiboutikRepository,
|
||||||
|
BrandHiboutikService,
|
||||||
|
CategoryConverter,
|
||||||
|
CategoryDatabaseRepository,
|
||||||
|
CategoryHiboutikRepository,
|
||||||
|
CategoryHiboutikService,
|
||||||
|
CustomerAddressConverter,
|
||||||
|
CustomerAddressDatabaseRepository,
|
||||||
|
CustomerHiboutikRepository,
|
||||||
|
CustomerDatabaseRepository,
|
||||||
|
CustomerConverter,
|
||||||
|
CustomerHiboutikService,
|
||||||
|
HiboutikClient,
|
||||||
|
HiboutikService,
|
||||||
|
OrderConverter,
|
||||||
|
OrderDatabaseRepository,
|
||||||
|
ProductConverter,
|
||||||
|
ProductDatabaseRepository,
|
||||||
|
ProductHiboutikRepository,
|
||||||
|
ProductHiboutikService,
|
||||||
|
ProductVersionDatabaseRepository,
|
||||||
|
SaleHiboutikRepository,
|
||||||
|
StockHiboutikRepository,
|
||||||
|
SupplierConverter,
|
||||||
|
SupplierDatabaseRepository,
|
||||||
|
SyncLockDatabaseRepository,
|
||||||
|
SupplierHiboutikRepository,
|
||||||
|
SupplierHiboutikService,
|
||||||
|
],
|
||||||
})
|
})
|
||||||
export class AppModule {}
|
export class AppModule {}
|
||||||
|
|||||||
@@ -1,8 +0,0 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class AppService {
|
|
||||||
getHello(): string {
|
|
||||||
return 'Hello World!';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
70
src/config/env.validation.spec.ts
Normal file
70
src/config/env.validation.spec.ts
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
import 'reflect-metadata';
|
||||||
|
import { validateEnv } from './env.validation';
|
||||||
|
|
||||||
|
describe('validateEnv', () => {
|
||||||
|
const valid = {
|
||||||
|
DATABASE_URL: 'postgresql://user:secret@localhost:5432/db',
|
||||||
|
HIBOUTIK_BASE_URL: 'https://shop.hiboutik.com/api',
|
||||||
|
HIBOUTIK_USERNAME: 'user',
|
||||||
|
HIBOUTIK_PASSWORD: 'secret-password',
|
||||||
|
};
|
||||||
|
|
||||||
|
it('accepts a valid configuration and keeps every variable', () => {
|
||||||
|
const env = { ...valid, PORT: '3000', CORS_ORIGINS: 'https://shop.example.com', TRUST_PROXY: '1', OTHER: 'x' };
|
||||||
|
expect(validateEnv(env)).toBe(env);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects a missing required variable, naming it', () => {
|
||||||
|
expect(() => validateEnv({ ...valid, HIBOUTIK_PASSWORD: undefined })).toThrow(/HIBOUTIK_PASSWORD/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects a non-HTTPS Hiboutik URL', () => {
|
||||||
|
expect(() => validateEnv({ ...valid, HIBOUTIK_BASE_URL: 'http://shop.hiboutik.com/api' })).toThrow(/HIBOUTIK_BASE_URL/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects an invalid port', () => {
|
||||||
|
expect(() => validateEnv({ ...valid, PORT: 'abc' })).toThrow(/PORT/);
|
||||||
|
expect(() => validateEnv({ ...valid, PORT: '70000' })).toThrow(/PORT/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('never puts secret values in the error message', () => {
|
||||||
|
expect.assertions(2);
|
||||||
|
try {
|
||||||
|
validateEnv({ ...valid, HIBOUTIK_BASE_URL: 'http://insecure', DATABASE_URL: '' });
|
||||||
|
} catch (error) {
|
||||||
|
expect((error as Error).message).not.toContain('secret-password');
|
||||||
|
expect((error as Error).message).not.toContain('secret');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('in production', () => {
|
||||||
|
const production = { ...valid, NODE_ENV: 'production' };
|
||||||
|
|
||||||
|
it('requires an encrypted database connection', () => {
|
||||||
|
expect(() => validateEnv(production)).toThrow(/DATABASE_URL: sslmode/);
|
||||||
|
expect(() => validateEnv({ ...production, DATABASE_URL: `${valid.DATABASE_URL}?sslmode=disable` })).toThrow(/DATABASE_URL/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each(['require', 'verify-ca', 'verify-full'])('accepts sslmode=%s', (mode) => {
|
||||||
|
expect(() => validateEnv({ ...production, DATABASE_URL: `${valid.DATABASE_URL}?sslmode=${mode}` })).not.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('never puts the connection string in the error message', () => {
|
||||||
|
expect.assertions(2);
|
||||||
|
try {
|
||||||
|
validateEnv(production);
|
||||||
|
} catch (error) {
|
||||||
|
expect((error as Error).message).toContain('DATABASE_URL');
|
||||||
|
expect((error as Error).message).not.toContain('secret');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not require TLS outside production', () => {
|
||||||
|
expect(() => validateEnv({ ...valid, NODE_ENV: 'development' })).not.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects an unknown NODE_ENV', () => {
|
||||||
|
expect(() => validateEnv({ ...valid, NODE_ENV: 'prod' })).toThrow(/NODE_ENV/);
|
||||||
|
});
|
||||||
|
});
|
||||||
83
src/config/env.validation.ts
Normal file
83
src/config/env.validation.ts
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
import { plainToInstance } from 'class-transformer';
|
||||||
|
import { IsIn, IsInt, IsNotEmpty, IsOptional, IsString, IsUrl, Max, Min, validateSync } from 'class-validator';
|
||||||
|
|
||||||
|
/** `sslmode` values that encrypt the database connection (the pg driver treats them all as `verify-full`). */
|
||||||
|
const SECURE_SSL_MODES = ['require', 'verify-ca', 'verify-full'];
|
||||||
|
|
||||||
|
/** Environment variables read by the app. A missing or malformed required one stops the startup. */
|
||||||
|
export class EnvironmentVariables {
|
||||||
|
/** `production` enforces production-only rules (TLS to the database). */
|
||||||
|
@IsOptional()
|
||||||
|
@IsIn(['development', 'production', 'test'])
|
||||||
|
NODE_ENV?: string;
|
||||||
|
|
||||||
|
/** In production, `sslmode` must be require, verify-ca or verify-full: customer data must not travel in clear. */
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
DATABASE_URL!: string;
|
||||||
|
|
||||||
|
/** HTTPS only: the Hiboutik credentials are sent with HTTP Basic auth. */
|
||||||
|
@IsUrl({ protocols: ['https'], require_protocol: true })
|
||||||
|
HIBOUTIK_BASE_URL!: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
HIBOUTIK_USERNAME!: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
HIBOUTIK_PASSWORD!: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsInt()
|
||||||
|
@Min(1)
|
||||||
|
@Max(65535)
|
||||||
|
PORT?: number;
|
||||||
|
|
||||||
|
/** Comma-separated list of origins allowed by CORS. Empty or unset: CORS stays disabled. */
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
CORS_ORIGINS?: string;
|
||||||
|
|
||||||
|
/** Number of reverse proxies in front of the app (so the real client IP is used for rate limiting). Unset: no proxy. */
|
||||||
|
@IsOptional()
|
||||||
|
@IsInt()
|
||||||
|
@Min(1)
|
||||||
|
@Max(10)
|
||||||
|
TRUST_PROXY?: number;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Seconds a shutting down instance waits for its running synchronization (default 25). Keep it below the grace period
|
||||||
|
* of the orchestrator (Docker `stop_grace_period`, Kubernetes `terminationGracePeriodSeconds`), which kills afterwards.
|
||||||
|
*/
|
||||||
|
@IsOptional()
|
||||||
|
@IsInt()
|
||||||
|
@Min(0)
|
||||||
|
@Max(3600)
|
||||||
|
SYNC_SHUTDOWN_TIMEOUT?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether the connection string asks for an encrypted connection. An unparsable one does not. */
|
||||||
|
function hasSecureSslMode(databaseUrl: string): boolean {
|
||||||
|
try {
|
||||||
|
return SECURE_SSL_MODES.includes(new URL(databaseUrl).searchParams.get('sslmode') ?? '');
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `ConfigModule` validation hook: fails fast with the names of the faulty variables (never their values, they may be secrets). */
|
||||||
|
export function validateEnv(config: Record<string, unknown>): Record<string, unknown> {
|
||||||
|
const validated = plainToInstance(EnvironmentVariables, config, { enableImplicitConversion: true });
|
||||||
|
const errors = validateSync(validated, { whitelist: false });
|
||||||
|
|
||||||
|
const details = errors.map((error) => `${error.property}: ${Object.values(error.constraints ?? {}).join(', ')}`);
|
||||||
|
if (validated.NODE_ENV === 'production' && validated.DATABASE_URL && !hasSecureSslMode(validated.DATABASE_URL)) {
|
||||||
|
details.push(`DATABASE_URL: sslmode must be one of ${SECURE_SSL_MODES.join(', ')} in production`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (details.length > 0) {
|
||||||
|
throw new Error(`Invalid environment configuration:\n ${details.join('\n ')}`);
|
||||||
|
}
|
||||||
|
return config;
|
||||||
|
}
|
||||||
36
src/database/brand.database.repository.ts
Normal file
36
src/database/brand.database.repository.ts
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { PrismaService } from '../../prisma/prisma.service';
|
||||||
|
import { Brand } from '../../prisma/generated/client';
|
||||||
|
import { BrandCreateInput } from '../../prisma/generated/models/Brand';
|
||||||
|
|
||||||
|
/** Database access to brands. Rows are matched with Hiboutik by `hiboutikId`. */
|
||||||
|
@Injectable()
|
||||||
|
export class BrandDatabaseRepository {
|
||||||
|
constructor(private readonly prisma: PrismaService) {}
|
||||||
|
|
||||||
|
async getAll(): Promise<Brand[]> {
|
||||||
|
return this.prisma.brand.findMany({
|
||||||
|
orderBy: { hiboutikId: 'asc' },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Creates or updates the brand with the same `hiboutikId`. */
|
||||||
|
async upsert(brand: BrandCreateInput): Promise<Brand> {
|
||||||
|
return this.prisma.brand.upsert({
|
||||||
|
where: { hiboutikId: brand.hiboutikId },
|
||||||
|
create: brand,
|
||||||
|
update: brand,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Deletes the brands that no longer exist in Hiboutik.
|
||||||
|
* Their products are kept: the relation is set to null (onDelete: SetNull).
|
||||||
|
*/
|
||||||
|
async deleteMissing(keptHiboutikIds: number[]): Promise<number> {
|
||||||
|
const result = await this.prisma.brand.deleteMany({
|
||||||
|
where: { hiboutikId: { notIn: keptHiboutikIds } },
|
||||||
|
});
|
||||||
|
return result.count;
|
||||||
|
}
|
||||||
|
}
|
||||||
44
src/database/category.database.repository.ts
Normal file
44
src/database/category.database.repository.ts
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { PrismaService } from '../../prisma/prisma.service';
|
||||||
|
import { Category } from '../../prisma/generated/client';
|
||||||
|
import { CategoryCreateInput } from '../../prisma/generated/models/Category';
|
||||||
|
|
||||||
|
/** Database access to categories. Rows are matched with Hiboutik by `hiboutikId`. */
|
||||||
|
@Injectable()
|
||||||
|
export class CategoryDatabaseRepository {
|
||||||
|
constructor(private readonly prisma: PrismaService) {}
|
||||||
|
|
||||||
|
async getAll(): Promise<Category[]> {
|
||||||
|
return this.prisma.category.findMany({
|
||||||
|
orderBy: { hiboutikId: 'asc' },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Creates or updates the category with the same `hiboutikId`. */
|
||||||
|
async upsert(category: CategoryCreateInput): Promise<Category> {
|
||||||
|
return this.prisma.category.upsert({
|
||||||
|
where: { hiboutikId: category.hiboutikId },
|
||||||
|
create: category,
|
||||||
|
update: category,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Links a category to its parent (null for a root category). Both must already exist. */
|
||||||
|
async setParent(hiboutikId: number, parentHiboutikId: number | null): Promise<Category> {
|
||||||
|
return this.prisma.category.update({
|
||||||
|
where: { hiboutikId },
|
||||||
|
data: { parent: parentHiboutikId ? { connect: { hiboutikId: parentHiboutikId } } : { disconnect: true } },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Deletes the categories that no longer exist in Hiboutik.
|
||||||
|
* Their products and sub-categories are kept: the relation is set to null (onDelete: SetNull).
|
||||||
|
*/
|
||||||
|
async deleteMissing(keptHiboutikIds: number[]): Promise<number> {
|
||||||
|
const result = await this.prisma.category.deleteMany({
|
||||||
|
where: { hiboutikId: { notIn: keptHiboutikIds } },
|
||||||
|
});
|
||||||
|
return result.count;
|
||||||
|
}
|
||||||
|
}
|
||||||
43
src/database/customer.database.repository.ts
Normal file
43
src/database/customer.database.repository.ts
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { PrismaService } from '../../prisma/prisma.service';
|
||||||
|
import { Customer } from '../../prisma/generated/client';
|
||||||
|
import { CustomerCreateInput } from '../../prisma/generated/models/Customer';
|
||||||
|
|
||||||
|
/** Database access to customers. Rows are matched with Hiboutik by `hiboutikId`. */
|
||||||
|
@Injectable()
|
||||||
|
export class CustomerDatabaseRepository {
|
||||||
|
constructor(private readonly prisma: PrismaService) {}
|
||||||
|
|
||||||
|
async getAll(): Promise<Customer[]> {
|
||||||
|
return this.prisma.customer.findMany({
|
||||||
|
orderBy: { hiboutikId: 'asc' },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Creates or updates the customer with the same `hiboutikId`. */
|
||||||
|
async upsert(customer: CustomerCreateInput): Promise<Customer> {
|
||||||
|
return this.prisma.customer.upsert({
|
||||||
|
where: { hiboutikId: customer.hiboutikId },
|
||||||
|
create: customer,
|
||||||
|
update: customer,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async getAllHiboutikIds(): Promise<number[]> {
|
||||||
|
const customers = await this.prisma.customer.findMany({ select: { hiboutikId: true } });
|
||||||
|
return customers.map((customer) => customer.hiboutikId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Deletes customers that no longer exist in Hiboutik.
|
||||||
|
* Their addresses are deleted (onDelete: Cascade), their orders are kept with no customer (onDelete: SetNull).
|
||||||
|
*/
|
||||||
|
async deleteByHiboutikIds(hiboutikIds: number[]): Promise<number> {
|
||||||
|
if (hiboutikIds.length === 0) return 0;
|
||||||
|
|
||||||
|
const result = await this.prisma.customer.deleteMany({
|
||||||
|
where: { hiboutikId: { in: hiboutikIds } },
|
||||||
|
});
|
||||||
|
return result.count;
|
||||||
|
}
|
||||||
|
}
|
||||||
27
src/database/customerAddress.database.repository.ts
Normal file
27
src/database/customerAddress.database.repository.ts
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { PrismaService } from '../../prisma/prisma.service';
|
||||||
|
import { CustomerAddress } from '../../prisma/generated/client';
|
||||||
|
import { CustomerAddressCreateInput } from '../../prisma/generated/models/CustomerAddress';
|
||||||
|
|
||||||
|
/** Database access to customer addresses. Rows are matched with Hiboutik by `hiboutikId`. */
|
||||||
|
@Injectable()
|
||||||
|
export class CustomerAddressDatabaseRepository {
|
||||||
|
constructor(private readonly prisma: PrismaService) {}
|
||||||
|
|
||||||
|
/** Creates or updates the address with the same `hiboutikId`. */
|
||||||
|
async upsert(address: CustomerAddressCreateInput): Promise<CustomerAddress> {
|
||||||
|
return this.prisma.customerAddress.upsert({
|
||||||
|
where: { hiboutikId: address.hiboutikId },
|
||||||
|
create: address,
|
||||||
|
update: address,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Deletes the addresses of a customer that no longer exist in Hiboutik (all of them if `keptHiboutikIds` is empty). */
|
||||||
|
async deleteMissing(customerId: string, keptHiboutikIds: number[]): Promise<number> {
|
||||||
|
const result = await this.prisma.customerAddress.deleteMany({
|
||||||
|
where: { customerId, hiboutikId: { notIn: keptHiboutikIds } },
|
||||||
|
});
|
||||||
|
return result.count;
|
||||||
|
}
|
||||||
|
}
|
||||||
68
src/database/order.database.repository.ts
Normal file
68
src/database/order.database.repository.ts
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { PrismaService } from '../../prisma/prisma.service';
|
||||||
|
import { Order } from '../../prisma/generated/client';
|
||||||
|
import { OrderWithLinesInput } from '../../prisma/customObjects/prisma.custom.object';
|
||||||
|
import { OrderStatus } from '../models/orderStatus';
|
||||||
|
|
||||||
|
/** Database access to orders. Hiboutik sales are matched by `hiboutikSaleId`. */
|
||||||
|
@Injectable()
|
||||||
|
export class OrderDatabaseRepository {
|
||||||
|
constructor(private readonly prisma: PrismaService) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Among `hiboutikSaleIds`, the ones already stored as completed orders of this customer. A completed order that lost
|
||||||
|
* its customer (customer deleted, then found again in Hiboutik) is not returned, so that the sync links it back.
|
||||||
|
*/
|
||||||
|
async getCompletedSaleIds(customerHiboutikId: number, hiboutikSaleIds: number[]): Promise<Set<number>> {
|
||||||
|
if (hiboutikSaleIds.length === 0) return new Set();
|
||||||
|
|
||||||
|
const orders = await this.prisma.order.findMany({
|
||||||
|
where: {
|
||||||
|
hiboutikSaleId: { in: hiboutikSaleIds },
|
||||||
|
status: OrderStatus.COMPLETED,
|
||||||
|
customer: { is: { hiboutikId: customerHiboutikId } },
|
||||||
|
},
|
||||||
|
select: { hiboutikSaleId: true },
|
||||||
|
});
|
||||||
|
return new Set(orders.map((order) => order.hiboutikSaleId).filter((id): id is number => id !== null));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates or updates the order with the same `hiboutikSaleId`, replacing all its lines (atomically).
|
||||||
|
* Each line is linked to the current product version matching its Hiboutik product and size, if it still exists.
|
||||||
|
* On update, `source` is kept: a website order sent to Hiboutik stays WEB.
|
||||||
|
*/
|
||||||
|
async upsert(order: OrderWithLinesInput): Promise<Order> {
|
||||||
|
if (order.hiboutikSaleId == null) throw new Error('Cannot upsert an order without hiboutikSaleId');
|
||||||
|
|
||||||
|
const { lines, source, ...orderFields } = order;
|
||||||
|
const linkedLines = await this.linkToProductVersions(lines);
|
||||||
|
return this.prisma.order.upsert({
|
||||||
|
where: { hiboutikSaleId: order.hiboutikSaleId },
|
||||||
|
create: { ...orderFields, source, lines: { create: linkedLines } },
|
||||||
|
update: {
|
||||||
|
...orderFields,
|
||||||
|
// an undefined relation is ignored by Prisma on update: explicitly unlink a customer removed from the sale
|
||||||
|
customer: orderFields.customer ?? { disconnect: true },
|
||||||
|
lines: { deleteMany: {}, create: linkedLines },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private async linkToProductVersions(lines: OrderWithLinesInput['lines']): Promise<OrderWithLinesInput['lines']> {
|
||||||
|
if (lines.length === 0) return lines;
|
||||||
|
|
||||||
|
const versions = await this.prisma.productVersion.findMany({
|
||||||
|
where: {
|
||||||
|
OR: lines.map((line) => ({ hiboutikSizeId: line.hiboutikSizeId, product: { hiboutikId: line.hiboutikProductId } })),
|
||||||
|
},
|
||||||
|
select: { id: true, hiboutikSizeId: true, product: { select: { hiboutikId: true } } },
|
||||||
|
});
|
||||||
|
const versionIds = new Map(versions.map((version) => [`${version.product.hiboutikId}:${version.hiboutikSizeId}`, version.id]));
|
||||||
|
|
||||||
|
return lines.map((line) => {
|
||||||
|
const versionId = versionIds.get(`${line.hiboutikProductId}:${line.hiboutikSizeId}`);
|
||||||
|
return versionId ? { ...line, productVersion: { connect: { id: versionId } } } : line;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
47
src/database/product.database.repository.ts
Normal file
47
src/database/product.database.repository.ts
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { PrismaService } from '../../prisma/prisma.service';
|
||||||
|
import { Prisma, Product } from '../../prisma/generated/client';
|
||||||
|
import { ProductCreateInput } from '../../prisma/generated/models/Product';
|
||||||
|
|
||||||
|
/** Database access to products. Rows are matched with Hiboutik by `hiboutikId`. */
|
||||||
|
@Injectable()
|
||||||
|
export class ProductDatabaseRepository {
|
||||||
|
constructor(private readonly prisma: PrismaService) {}
|
||||||
|
|
||||||
|
async getAll(): Promise<Product[]> {
|
||||||
|
return this.prisma.product.findMany({
|
||||||
|
orderBy: { hiboutikId: 'asc' },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates or updates the product with the same `hiboutikId`. On update, the relations missing from the input are unlinked.
|
||||||
|
* @param db transaction client, to run it inside a transaction.
|
||||||
|
*/
|
||||||
|
async upsert(product: ProductCreateInput, db: Prisma.TransactionClient = this.prisma): Promise<Product> {
|
||||||
|
return db.product.upsert({
|
||||||
|
where: { hiboutikId: product.hiboutikId },
|
||||||
|
create: product,
|
||||||
|
update: {
|
||||||
|
...product,
|
||||||
|
// an undefined relation is ignored by Prisma on update: explicitly unlink relations removed in Hiboutik
|
||||||
|
brand: product.brand ?? { disconnect: true },
|
||||||
|
category: product.category ?? { disconnect: true },
|
||||||
|
supplier: product.supplier ?? { disconnect: true },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Deletes products (and their versions, by cascade).
|
||||||
|
* Order lines keep their own snapshot of the product, their link is set to null.
|
||||||
|
*/
|
||||||
|
async deleteAll(productIds: string[]): Promise<number> {
|
||||||
|
if (productIds.length === 0) return 0;
|
||||||
|
|
||||||
|
const result = await this.prisma.product.deleteMany({
|
||||||
|
where: { id: { in: productIds } },
|
||||||
|
});
|
||||||
|
return result.count;
|
||||||
|
}
|
||||||
|
}
|
||||||
44
src/database/productVersion.database.repository.ts
Normal file
44
src/database/productVersion.database.repository.ts
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { PrismaService } from '../../prisma/prisma.service';
|
||||||
|
import { Prisma, ProductVersion } from '../../prisma/generated/client';
|
||||||
|
import { ProductVersionCreateInput } from '../../prisma/generated/models/ProductVersion';
|
||||||
|
|
||||||
|
/** Database access to product versions (one per Hiboutik size), identified by their product and `hiboutikSizeId`. */
|
||||||
|
@Injectable()
|
||||||
|
export class ProductVersionDatabaseRepository {
|
||||||
|
constructor(private readonly prisma: PrismaService) {}
|
||||||
|
|
||||||
|
async getAll(): Promise<ProductVersion[]> {
|
||||||
|
return this.prisma.productVersion.findMany({
|
||||||
|
orderBy: { hiboutikSizeId: 'asc' },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates or updates the version of `productId` with the same `hiboutikSizeId`.
|
||||||
|
* @param db transaction client, to run it inside a transaction.
|
||||||
|
*/
|
||||||
|
async upsert(
|
||||||
|
productId: string,
|
||||||
|
productVersion: ProductVersionCreateInput,
|
||||||
|
db: Prisma.TransactionClient = this.prisma,
|
||||||
|
): Promise<ProductVersion> {
|
||||||
|
return db.productVersion.upsert({
|
||||||
|
where: { productId_hiboutikSizeId: { productId: productId, hiboutikSizeId: productVersion.hiboutikSizeId } },
|
||||||
|
create: productVersion,
|
||||||
|
update: productVersion,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Deletes the versions of a product that no longer exist in Hiboutik.
|
||||||
|
* Order lines keep their own snapshot of the product, their link is set to null.
|
||||||
|
* @param db transaction client, to run it inside a transaction.
|
||||||
|
*/
|
||||||
|
async deleteMissing(productId: string, keptHiboutikSizeIds: number[], db: Prisma.TransactionClient = this.prisma): Promise<number> {
|
||||||
|
const result = await db.productVersion.deleteMany({
|
||||||
|
where: { productId, hiboutikSizeId: { notIn: keptHiboutikSizeIds } },
|
||||||
|
});
|
||||||
|
return result.count;
|
||||||
|
}
|
||||||
|
}
|
||||||
36
src/database/supplier.database.repository.ts
Normal file
36
src/database/supplier.database.repository.ts
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { PrismaService } from '../../prisma/prisma.service';
|
||||||
|
import { Supplier } from '../../prisma/generated/client';
|
||||||
|
import { SupplierCreateInput } from '../../prisma/generated/models/Supplier';
|
||||||
|
|
||||||
|
/** Database access to suppliers. Rows are matched with Hiboutik by `hiboutikId`. */
|
||||||
|
@Injectable()
|
||||||
|
export class SupplierDatabaseRepository {
|
||||||
|
constructor(private readonly prisma: PrismaService) {}
|
||||||
|
|
||||||
|
async getAll(): Promise<Supplier[]> {
|
||||||
|
return this.prisma.supplier.findMany({
|
||||||
|
orderBy: { hiboutikId: 'asc' },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Creates or updates the supplier with the same `hiboutikId`. */
|
||||||
|
async upsert(supplier: SupplierCreateInput): Promise<Supplier> {
|
||||||
|
return this.prisma.supplier.upsert({
|
||||||
|
where: { hiboutikId: supplier.hiboutikId },
|
||||||
|
create: supplier,
|
||||||
|
update: supplier,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Deletes the suppliers that no longer exist in Hiboutik.
|
||||||
|
* Their products are kept: the relation is set to null (onDelete: SetNull).
|
||||||
|
*/
|
||||||
|
async deleteMissing(keptHiboutikIds: number[]): Promise<number> {
|
||||||
|
const result = await this.prisma.supplier.deleteMany({
|
||||||
|
where: { hiboutikId: { notIn: keptHiboutikIds } },
|
||||||
|
});
|
||||||
|
return result.count;
|
||||||
|
}
|
||||||
|
}
|
||||||
74
src/database/syncLock.database.repository.spec.ts
Normal file
74
src/database/syncLock.database.repository.spec.ts
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
import { Logger } from '@nestjs/common';
|
||||||
|
import { Client } from 'pg';
|
||||||
|
import { SyncLockDatabaseRepository } from './syncLock.database.repository';
|
||||||
|
|
||||||
|
jest.mock('pg', () => ({ Client: jest.fn() }));
|
||||||
|
|
||||||
|
describe('SyncLockDatabaseRepository', () => {
|
||||||
|
const client = { on: jest.fn(), connect: jest.fn(), query: jest.fn(), end: jest.fn() };
|
||||||
|
const configService = { get: jest.fn().mockReturnValue('postgresql://user:pass@localhost:5432/db') };
|
||||||
|
let repository: SyncLockDatabaseRepository;
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => undefined);
|
||||||
|
jest.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
jest.clearAllMocks();
|
||||||
|
(Client as unknown as jest.Mock).mockImplementation(() => client);
|
||||||
|
client.connect.mockResolvedValue(undefined);
|
||||||
|
client.end.mockResolvedValue(undefined);
|
||||||
|
client.query.mockResolvedValue({ rows: [{ locked: true }] });
|
||||||
|
repository = new SyncLockDatabaseRepository(configService as never);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('takes the advisory lock on a dedicated connection and keeps it open', async () => {
|
||||||
|
const release = await repository.tryAcquire();
|
||||||
|
|
||||||
|
expect(release).toEqual(expect.any(Function));
|
||||||
|
expect(Client).toHaveBeenCalledWith({ connectionString: 'postgresql://user:pass@localhost:5432/db', connectionTimeoutMillis: 10_000 });
|
||||||
|
expect(client.query).toHaveBeenCalledWith('SELECT pg_try_advisory_lock($1) AS locked', [expect.any(Number)]);
|
||||||
|
expect(client.end).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns null and closes the connection when the lock is already held', async () => {
|
||||||
|
client.query.mockResolvedValue({ rows: [{ locked: false }] });
|
||||||
|
|
||||||
|
await expect(repository.tryAcquire()).resolves.toBeNull();
|
||||||
|
|
||||||
|
expect(client.end).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('unlocks then closes the connection on release', async () => {
|
||||||
|
const release = await repository.tryAcquire();
|
||||||
|
|
||||||
|
await release!();
|
||||||
|
|
||||||
|
expect(client.query).toHaveBeenLastCalledWith('SELECT pg_advisory_unlock($1)', [expect.any(Number)]);
|
||||||
|
expect(client.end).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('still closes the connection, and does not throw, when the explicit unlock fails', async () => {
|
||||||
|
const release = await repository.tryAcquire();
|
||||||
|
client.query.mockRejectedValueOnce(new Error('connection lost'));
|
||||||
|
|
||||||
|
await expect(release!()).resolves.toBeUndefined();
|
||||||
|
|
||||||
|
expect(client.end).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('closes the connection and rethrows when the lock query fails', async () => {
|
||||||
|
client.query.mockRejectedValue(new Error('boom'));
|
||||||
|
|
||||||
|
await expect(repository.tryAcquire()).rejects.toThrow('boom');
|
||||||
|
|
||||||
|
expect(client.end).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('logs connection errors instead of leaving them unhandled', async () => {
|
||||||
|
await repository.tryAcquire();
|
||||||
|
|
||||||
|
expect(client.on).toHaveBeenCalledWith('error', expect.any(Function));
|
||||||
|
});
|
||||||
|
});
|
||||||
53
src/database/syncLock.database.repository.ts
Normal file
53
src/database/syncLock.database.repository.ts
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
import { Injectable, Logger } from '@nestjs/common';
|
||||||
|
import { ConfigService } from '@nestjs/config';
|
||||||
|
import { Client } from 'pg';
|
||||||
|
|
||||||
|
/** Arbitrary constant identifying the Hiboutik synchronization among the Postgres advisory locks of the database. */
|
||||||
|
const SYNC_LOCK_KEY = 727_001;
|
||||||
|
|
||||||
|
/** Function releasing a lock acquired with `tryAcquire`. Never throws. */
|
||||||
|
export type ReleaseLock = () => Promise<void>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cross-instance lock for the synchronization, based on a Postgres session-level advisory lock.
|
||||||
|
* It lives on its own dedicated connection (not the Prisma pool, where lock and unlock could land on different
|
||||||
|
* connections) kept open for as long as the lock is held. If the process dies, Postgres closes the connection and
|
||||||
|
* releases the lock by itself: there is never a stale lock to clean up.
|
||||||
|
*/
|
||||||
|
@Injectable()
|
||||||
|
export class SyncLockDatabaseRepository {
|
||||||
|
private readonly logger = new Logger('SyncLockDatabaseRepository');
|
||||||
|
|
||||||
|
constructor(private readonly configService: ConfigService) {}
|
||||||
|
|
||||||
|
/** @returns the function releasing the lock, or `null` if another instance (or process) already holds it. */
|
||||||
|
async tryAcquire(): Promise<ReleaseLock | null> {
|
||||||
|
// Fails fast instead of holding the POST /sync request until its 30 s timeout when the database does not answer
|
||||||
|
const client = new Client({ connectionString: this.configService.get<string>('DATABASE_URL'), connectionTimeoutMillis: 10_000 });
|
||||||
|
// A lost connection means Postgres released the lock: log it instead of crashing the process on an unhandled 'error'
|
||||||
|
client.on('error', (error) => this.logger.error(`Synchronization lock connection error: ${error.message}`));
|
||||||
|
await client.connect();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { rows } = await client.query<{ locked: boolean }>('SELECT pg_try_advisory_lock($1) AS locked', [SYNC_LOCK_KEY]);
|
||||||
|
if (!rows[0]?.locked) {
|
||||||
|
await client.end();
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
await client.end().catch(() => undefined);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
return async () => {
|
||||||
|
try {
|
||||||
|
await client.query('SELECT pg_advisory_unlock($1)', [SYNC_LOCK_KEY]);
|
||||||
|
} catch (error) {
|
||||||
|
// Ending the connection below releases the lock anyway
|
||||||
|
this.logger.warn(`Failed to unlock the synchronization lock explicitly: ${(error as Error)?.message}`);
|
||||||
|
} finally {
|
||||||
|
await client.end().catch(() => undefined);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
56
src/database/throttlerStorage.database.repository.spec.ts
Normal file
56
src/database/throttlerStorage.database.repository.spec.ts
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
import { Logger } from '@nestjs/common';
|
||||||
|
import { ThrottlerDatabaseStorage } from './throttlerStorage.database.repository';
|
||||||
|
|
||||||
|
// The SQL itself (window, block, reset) was checked on a real Postgres engine; these tests cover the TypeScript side.
|
||||||
|
describe('ThrottlerDatabaseStorage', () => {
|
||||||
|
const record = { totalHits: 2, timeToExpire: 40, isBlocked: false, timeToBlockExpire: 0 };
|
||||||
|
const prisma = { $queryRaw: jest.fn(), throttlerRecord: { deleteMany: jest.fn() } };
|
||||||
|
let logError: jest.SpyInstance;
|
||||||
|
let random: jest.Mock;
|
||||||
|
let storage: ThrottlerDatabaseStorage;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
jest.clearAllMocks();
|
||||||
|
logError = jest.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined);
|
||||||
|
prisma.$queryRaw.mockResolvedValue([record]);
|
||||||
|
prisma.throttlerRecord.deleteMany.mockResolvedValue({ count: 0 });
|
||||||
|
random = jest.fn().mockReturnValue(0.5);
|
||||||
|
storage = new ThrottlerDatabaseStorage(prisma as never, random);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns the record computed by the database, with parameters bound (never interpolated)', async () => {
|
||||||
|
await expect(storage.increment('key-hash', 60_000, 5, 30_000)).resolves.toEqual(record);
|
||||||
|
|
||||||
|
const [strings, ...values] = prisma.$queryRaw.mock.calls[0] as [TemplateStringsArray, ...unknown[]];
|
||||||
|
expect(values).toEqual(['key-hash', 60_000, 5, 30_000]);
|
||||||
|
expect(strings.join('?')).not.toContain('key-hash');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('purges the finished counters on about one request in 100', async () => {
|
||||||
|
await storage.increment('k', 60_000, 5, 60_000);
|
||||||
|
expect(prisma.throttlerRecord.deleteMany).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
random.mockReturnValue(0.001);
|
||||||
|
await storage.increment('k', 60_000, 5, 60_000);
|
||||||
|
expect(prisma.throttlerRecord.deleteMany).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('lets the request through when the database fails, logging at most once a minute', async () => {
|
||||||
|
prisma.$queryRaw.mockRejectedValue(new Error('connection refused'));
|
||||||
|
|
||||||
|
await expect(storage.increment('k', 60_000, 5, 60_000)).resolves.toMatchObject({ isBlocked: false });
|
||||||
|
await storage.increment('k', 60_000, 5, 60_000);
|
||||||
|
|
||||||
|
expect(logError).toHaveBeenCalledTimes(1);
|
||||||
|
expect(logError).toHaveBeenCalledWith(expect.stringContaining('connection refused'));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not fail the request when the purge fails', async () => {
|
||||||
|
random.mockReturnValue(0);
|
||||||
|
prisma.throttlerRecord.deleteMany.mockRejectedValue(new Error('boom'));
|
||||||
|
|
||||||
|
await expect(storage.increment('k', 60_000, 5, 60_000)).resolves.toEqual(record);
|
||||||
|
await new Promise((resolve) => setImmediate(resolve));
|
||||||
|
expect(logError).toHaveBeenCalledWith(expect.stringContaining('boom'));
|
||||||
|
});
|
||||||
|
});
|
||||||
90
src/database/throttlerStorage.database.repository.ts
Normal file
90
src/database/throttlerStorage.database.repository.ts
Normal file
@@ -0,0 +1,90 @@
|
|||||||
|
import { Logger } from '@nestjs/common';
|
||||||
|
import { ThrottlerStorage } from '@nestjs/throttler';
|
||||||
|
import { PrismaService } from '../../prisma/prisma.service';
|
||||||
|
|
||||||
|
/** Answer of {@link ThrottlerStorage.increment} (its type is not exported by the package root). */
|
||||||
|
type ThrottlerStorageRecord = Awaited<ReturnType<ThrottlerStorage['increment']>>;
|
||||||
|
|
||||||
|
/** Share of the requests that also purge the finished counters (about one in 100). */
|
||||||
|
const PURGE_PROBABILITY = 0.01;
|
||||||
|
/** At most one log line per minute while the database is unreachable (one request = one failure). */
|
||||||
|
const ERROR_LOG_INTERVAL_MS = 60_000;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rate limiting counters stored in PostgreSQL (`throttler_records`), so that every instance shares them: with an
|
||||||
|
* in-memory storage, each instance would count apart and N instances would allow N times the limit.
|
||||||
|
*
|
||||||
|
* One fixed window per key: the first request opens a window of `ttl`; past `limit` requests in it, the key is blocked
|
||||||
|
* for `blockDuration`, then a new window starts. Each request is a single atomic upsert, computed with the database
|
||||||
|
* clock (`now()`), so the instances need neither a lock nor synchronized clocks.
|
||||||
|
*
|
||||||
|
* Fails open: if the database cannot be reached, the request is let through (and the failure logged) rather than
|
||||||
|
* answered with a 500. Every endpoint needs the database anyway.
|
||||||
|
*/
|
||||||
|
export class ThrottlerDatabaseStorage implements ThrottlerStorage {
|
||||||
|
private readonly logger = new Logger('ThrottlerDatabaseStorage');
|
||||||
|
private lastErrorLogAt = 0;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly prisma: PrismaService,
|
||||||
|
private readonly random: () => number = Math.random,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/** @param ttl window length (ms) @param blockDuration block length once the limit is exceeded (ms) */
|
||||||
|
async increment(key: string, ttl: number, limit: number, blockDuration: number): Promise<ThrottlerStorageRecord> {
|
||||||
|
try {
|
||||||
|
const [record] = await this.prisma.$queryRaw<ThrottlerStorageRecord[]>`
|
||||||
|
INSERT INTO throttler_records AS r (key, hits, "expiresAt", "blockedUntil")
|
||||||
|
VALUES (${key}, 1, now() + ${ttl}::int * interval '1 millisecond', NULL)
|
||||||
|
ON CONFLICT (key) DO UPDATE SET
|
||||||
|
hits = CASE
|
||||||
|
WHEN r."blockedUntil" > now() THEN r.hits
|
||||||
|
WHEN r."expiresAt" <= now() OR r."blockedUntil" IS NOT NULL THEN 1
|
||||||
|
ELSE r.hits + 1
|
||||||
|
END,
|
||||||
|
"expiresAt" = CASE
|
||||||
|
WHEN r."blockedUntil" > now() THEN r."expiresAt"
|
||||||
|
WHEN r."expiresAt" <= now() OR r."blockedUntil" IS NOT NULL THEN EXCLUDED."expiresAt"
|
||||||
|
ELSE r."expiresAt"
|
||||||
|
END,
|
||||||
|
"blockedUntil" = CASE
|
||||||
|
WHEN r."blockedUntil" > now() THEN r."blockedUntil"
|
||||||
|
WHEN r."expiresAt" <= now() OR r."blockedUntil" IS NOT NULL THEN NULL
|
||||||
|
WHEN r.hits + 1 > ${limit}::int THEN now() + ${blockDuration}::int * interval '1 millisecond'
|
||||||
|
ELSE NULL
|
||||||
|
END
|
||||||
|
RETURNING
|
||||||
|
hits AS "totalHits",
|
||||||
|
GREATEST(0, CEIL(EXTRACT(EPOCH FROM ("expiresAt" - now()))))::int AS "timeToExpire",
|
||||||
|
COALESCE("blockedUntil" > now(), false) AS "isBlocked",
|
||||||
|
COALESCE(GREATEST(0, CEIL(EXTRACT(EPOCH FROM ("blockedUntil" - now())))), 0)::int AS "timeToBlockExpire"`;
|
||||||
|
|
||||||
|
if (this.random() < PURGE_PROBABILITY) void this.purgeFinished();
|
||||||
|
return record;
|
||||||
|
} catch (error) {
|
||||||
|
this.logFailure('Rate limiting storage unavailable, request let through', error);
|
||||||
|
return { totalHits: 0, timeToExpire: 0, isBlocked: false, timeToBlockExpire: 0 };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Deletes the counters whose window and block are both over (idempotent: every instance may run it). */
|
||||||
|
private async purgeFinished(): Promise<void> {
|
||||||
|
try {
|
||||||
|
await this.prisma.throttlerRecord.deleteMany({
|
||||||
|
where: {
|
||||||
|
expiresAt: { lt: new Date() },
|
||||||
|
OR: [{ blockedUntil: null }, { blockedUntil: { lt: new Date() } }],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
this.logFailure('Failed to purge the finished rate limiting counters', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private logFailure(message: string, error: unknown): void {
|
||||||
|
const now = Date.now();
|
||||||
|
if (now - this.lastErrorLogAt < ERROR_LOG_INTERVAL_MS) return;
|
||||||
|
this.lastErrorLogAt = now;
|
||||||
|
this.logger.error(`${message}: ${(error as Error)?.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
58
src/filters/all-exceptions.filter.spec.ts
Normal file
58
src/filters/all-exceptions.filter.spec.ts
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
import { BadRequestException, Logger } from '@nestjs/common';
|
||||||
|
import { AllExceptionsFilter } from './all-exceptions.filter';
|
||||||
|
|
||||||
|
describe('AllExceptionsFilter', () => {
|
||||||
|
const applicationRef = { reply: jest.fn(), isHeadersSent: jest.fn().mockReturnValue(false), end: jest.fn() };
|
||||||
|
const response = {};
|
||||||
|
const host = { getArgByIndex: jest.fn().mockReturnValue(response) };
|
||||||
|
let filter: AllExceptionsFilter;
|
||||||
|
let logError: jest.SpyInstance;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
jest.clearAllMocks();
|
||||||
|
logError = jest.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined);
|
||||||
|
filter = new AllExceptionsFilter(applicationRef as never);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('answers a generic 500 for an unexpected error, without leaking its message', () => {
|
||||||
|
filter.catch(new Error('relation "customer" does not exist'), host as never);
|
||||||
|
|
||||||
|
expect(applicationRef.reply).toHaveBeenCalledTimes(1);
|
||||||
|
const [, body, status] = applicationRef.reply.mock.calls[0] as [unknown, { message: string }, number];
|
||||||
|
expect(status).toBe(500);
|
||||||
|
expect(JSON.stringify(body)).not.toContain('customer');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('logs the message and stack of an unexpected error, never the raw object', () => {
|
||||||
|
const error = Object.assign(new Error('boom'), { config: { headers: { Authorization: 'Basic c2VjcmV0' } } });
|
||||||
|
|
||||||
|
filter.catch(error, host as never);
|
||||||
|
|
||||||
|
expect(logError).toHaveBeenCalledWith('Unhandled exception: boom', error.stack);
|
||||||
|
expect(JSON.stringify(logError.mock.calls)).not.toContain('c2VjcmV0');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the status and body of deliberate HTTP exceptions', () => {
|
||||||
|
filter.catch(new BadRequestException('limit must be an integer'), host as never);
|
||||||
|
|
||||||
|
const [, body, status] = applicationRef.reply.mock.calls[0] as [unknown, { message: string }, number];
|
||||||
|
expect(status).toBe(400);
|
||||||
|
expect(body.message).toBe('limit must be an integer');
|
||||||
|
expect(logError).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the 4xx of HTTP-layer errors such as a payload too large', () => {
|
||||||
|
filter.catch(Object.assign(new Error('request entity too large'), { statusCode: 413 }), host as never);
|
||||||
|
|
||||||
|
const [, , status] = applicationRef.reply.mock.calls[0] as [unknown, unknown, number];
|
||||||
|
expect(status).toBe(413);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('treats a 5xx HTTP-layer error as an unexpected one', () => {
|
||||||
|
filter.catch(Object.assign(new Error('upstream detail'), { statusCode: 502 }), host as never);
|
||||||
|
|
||||||
|
const [, body, status] = applicationRef.reply.mock.calls[0] as [unknown, unknown, number];
|
||||||
|
expect(status).toBe(500);
|
||||||
|
expect(JSON.stringify(body)).not.toContain('upstream');
|
||||||
|
});
|
||||||
|
});
|
||||||
29
src/filters/all-exceptions.filter.ts
Normal file
29
src/filters/all-exceptions.filter.ts
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
import { ArgumentsHost, Catch, HttpException, InternalServerErrorException, Logger } from '@nestjs/common';
|
||||||
|
import { BaseExceptionFilter } from '@nestjs/core';
|
||||||
|
|
||||||
|
/** Errors raised by the HTTP layer itself (malformed JSON, payload too large...) carry a 4xx `statusCode` but are not `HttpException`s. */
|
||||||
|
function isClientHttpError(exception: unknown): boolean {
|
||||||
|
const statusCode = (exception as { statusCode?: unknown } | null)?.statusCode;
|
||||||
|
return typeof statusCode === 'number' && statusCode >= 400 && statusCode < 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Last line of defence: anything that is not a deliberate HTTP error (Prisma, axios, bug...) is logged with its stack
|
||||||
|
* (message and stack only, never the raw error object: it may carry credentials) and answered with a generic 500,
|
||||||
|
* so no internal detail (SQL, table names, URLs, stack) ever reaches the client.
|
||||||
|
*/
|
||||||
|
@Catch()
|
||||||
|
export class AllExceptionsFilter extends BaseExceptionFilter {
|
||||||
|
private readonly logger = new Logger('ExceptionsFilter');
|
||||||
|
|
||||||
|
catch(exception: unknown, host: ArgumentsHost): void {
|
||||||
|
if (exception instanceof HttpException || isClientHttpError(exception)) {
|
||||||
|
super.catch(exception, host);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const error = exception as Error | undefined;
|
||||||
|
this.logger.error(`Unhandled exception: ${error?.message}`, error?.stack);
|
||||||
|
super.catch(new InternalServerErrorException(), host);
|
||||||
|
}
|
||||||
|
}
|
||||||
17
src/hiboutik/brand.hiboutik.repository.ts
Normal file
17
src/hiboutik/brand.hiboutik.repository.ts
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { HiboutikClient } from './hiboutik.client';
|
||||||
|
import { BrandHiboutikDto, brandHiboutikSchema } from '../models/hiboutikDTO/brand.hiboutik.dto';
|
||||||
|
|
||||||
|
/** Reads brands from the Hiboutik API. */
|
||||||
|
@Injectable()
|
||||||
|
export class BrandHiboutikRepository {
|
||||||
|
constructor(private readonly hiboutikClient: HiboutikClient) {}
|
||||||
|
|
||||||
|
/** Walked twice when it spans several pages: it drives the deletion of brands (see `getAllPagesForSync`). */
|
||||||
|
async getBrands(): Promise<BrandHiboutikDto[]> {
|
||||||
|
return this.hiboutikClient.getAllPagesForSync('/brands', brandHiboutikSchema, (brand) => brand.brand_id, {
|
||||||
|
order_by: 'brand_id',
|
||||||
|
sort: 'ASC',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
20
src/hiboutik/category.hiboutik.repository.ts
Normal file
20
src/hiboutik/category.hiboutik.repository.ts
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { CategoryHiboutikDto, categoryHiboutikSchema } from '../models/hiboutikDTO/category.hiboutik.dto';
|
||||||
|
import { HiboutikClient } from './hiboutik.client';
|
||||||
|
|
||||||
|
/** Reads categories from the Hiboutik API. */
|
||||||
|
@Injectable()
|
||||||
|
export class CategoryHiboutikRepository {
|
||||||
|
constructor(private readonly hiboutikClient: HiboutikClient) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sorted by id (unique, so that the pages are stable), a parent may come after its children. Walked twice when it
|
||||||
|
* spans several pages: it drives the deletion of categories (see `getAllPagesForSync`).
|
||||||
|
*/
|
||||||
|
async getCategories(): Promise<CategoryHiboutikDto[]> {
|
||||||
|
return this.hiboutikClient.getAllPagesForSync('/categories', categoryHiboutikSchema, (category) => category.category_id, {
|
||||||
|
order_by: 'category_id',
|
||||||
|
sort: 'ASC',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
53
src/hiboutik/customer.hiboutik.repository.ts
Normal file
53
src/hiboutik/customer.hiboutik.repository.ts
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { HiboutikClient } from './hiboutik.client';
|
||||||
|
import {
|
||||||
|
CustomerAddressDetailsHiboutikDto,
|
||||||
|
customerAddressDetailsHiboutikSchema,
|
||||||
|
CustomerHiboutikDto,
|
||||||
|
customerHiboutikSchema,
|
||||||
|
FullCustomerHiboutikDto,
|
||||||
|
fullCustomerHiboutikSchema,
|
||||||
|
} from '../models/hiboutikDTO/customer.hiboutik.dto';
|
||||||
|
|
||||||
|
/** Reads customers from the Hiboutik API. */
|
||||||
|
@Injectable()
|
||||||
|
export class CustomerHiboutikRepository {
|
||||||
|
constructor(private readonly hiboutikClient: HiboutikClient) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Customer summaries only: use {@link getCustomerById} for addresses and sales. Sorted by id so that the pages are
|
||||||
|
* stable, but a customer created or deleted while they are walked can still shift the following ones.
|
||||||
|
*/
|
||||||
|
async getCustomers(): Promise<CustomerHiboutikDto[]> {
|
||||||
|
return this.hiboutikClient.getAllPages('/customers', customerHiboutikSchema, {
|
||||||
|
order_by: 'customers_id',
|
||||||
|
sort: 'ASC',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Full customer, with its addresses and sales.
|
||||||
|
* @returns `null` when Hiboutik says the customer does not exist (404 or empty answer).
|
||||||
|
* @throws on any other failure: an unknown state is never taken for a deleted customer.
|
||||||
|
*/
|
||||||
|
async findCustomerById(id: number): Promise<FullCustomerHiboutikDto | null> {
|
||||||
|
return this.hiboutikClient.getOne(`/customer/${id}`, fullCustomerHiboutikSchema);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Same as {@link findCustomerById}, but a missing customer throws. */
|
||||||
|
async getCustomerById(id: number): Promise<FullCustomerHiboutikDto> {
|
||||||
|
const customer = await this.findCustomerById(id);
|
||||||
|
if (!customer) throw new Error(`Hiboutik customer ${id} not found`);
|
||||||
|
return customer;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Address with its company details.
|
||||||
|
* @throws if the address does not exist.
|
||||||
|
*/
|
||||||
|
async getAddressById(id: number): Promise<CustomerAddressDetailsHiboutikDto> {
|
||||||
|
const address = await this.hiboutikClient.getOne(`/customers_addresses/${id}`, customerAddressDetailsHiboutikSchema);
|
||||||
|
if (!address) throw new Error(`Hiboutik address ${id} not found`);
|
||||||
|
return address;
|
||||||
|
}
|
||||||
|
}
|
||||||
214
src/hiboutik/hiboutik.client.spec.ts
Normal file
214
src/hiboutik/hiboutik.client.spec.ts
Normal file
@@ -0,0 +1,214 @@
|
|||||||
|
import { AxiosError, AxiosHeaders } from 'axios';
|
||||||
|
import { of, throwError } from 'rxjs';
|
||||||
|
import { z } from 'zod';
|
||||||
|
import { HiboutikClient, HiboutikRateLimitError } from './hiboutik.client';
|
||||||
|
|
||||||
|
describe('HiboutikClient', () => {
|
||||||
|
const httpService = { get: jest.fn() };
|
||||||
|
const configService = { get: jest.fn((key: string) => (key === 'HIBOUTIK_BASE_URL' ? 'https://shop.hiboutik.test/api' : 'x')) };
|
||||||
|
const schema = z.object({ id: z.coerce.number() });
|
||||||
|
let client: HiboutikClient;
|
||||||
|
|
||||||
|
const answer = (data: unknown) => of({ data });
|
||||||
|
const httpError = (status: number) =>
|
||||||
|
throwError(
|
||||||
|
() =>
|
||||||
|
new AxiosError(`Request failed with status code ${status}`, undefined, undefined, undefined, {
|
||||||
|
status,
|
||||||
|
statusText: '',
|
||||||
|
headers: {},
|
||||||
|
config: { headers: new AxiosHeaders() },
|
||||||
|
data: null,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const page = (size: number) => Array.from({ length: size }, (_, index) => ({ id: index }));
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
jest.clearAllMocks();
|
||||||
|
client = new HiboutikClient(httpService as never, configService as never);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('getList', () => {
|
||||||
|
it('returns the list of a 2xx answer, empty or not', async () => {
|
||||||
|
httpService.get.mockReturnValueOnce(answer([{ id: 1 }])).mockReturnValueOnce(answer([]));
|
||||||
|
|
||||||
|
await expect(client.getList('/x', schema)).resolves.toEqual([{ id: 1 }]);
|
||||||
|
await expect(client.getList('/x', schema)).resolves.toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('treats a 2xx answer without body as an empty list', async () => {
|
||||||
|
httpService.get.mockReturnValueOnce(answer('')).mockReturnValueOnce(answer(null));
|
||||||
|
|
||||||
|
await expect(client.getList('/x', schema)).resolves.toEqual([]);
|
||||||
|
await expect(client.getList('/x', schema)).resolves.toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects a 2xx answer that is not a list, without leaking its content', async () => {
|
||||||
|
httpService.get.mockReturnValueOnce(answer({ error: 'secret details' }));
|
||||||
|
|
||||||
|
const result = client.getList('/x', schema);
|
||||||
|
|
||||||
|
await expect(result).rejects.toThrow('a list was expected');
|
||||||
|
await expect(result).rejects.not.toThrow('secret details');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('validates and normalizes each item', async () => {
|
||||||
|
httpService.get.mockReturnValueOnce(answer([{ id: '1', extra: true }]));
|
||||||
|
|
||||||
|
await expect(client.getList('/x', schema)).resolves.toEqual([{ id: 1 }]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects the whole list when an item is invalid, so that nothing is deleted', async () => {
|
||||||
|
httpService.get.mockReturnValueOnce(answer([{ id: 1 }, { id: 'abc' }]));
|
||||||
|
|
||||||
|
await expect(client.getList('/x', schema)).rejects.toThrow('Unexpected answer from Hiboutik /x: invalid 1.id');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('lets HTTP errors through', async () => {
|
||||||
|
httpService.get.mockReturnValueOnce(httpError(500));
|
||||||
|
|
||||||
|
await expect(client.getList('/x', schema)).rejects.toThrow('500');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('getAllPages', () => {
|
||||||
|
it('walks the pages until a short one', async () => {
|
||||||
|
httpService.get.mockReturnValueOnce(answer(page(250))).mockReturnValueOnce(answer(page(10)));
|
||||||
|
|
||||||
|
const results = await client.getAllPages('/x', schema);
|
||||||
|
|
||||||
|
expect(results).toHaveLength(260);
|
||||||
|
expect(httpService.get).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fails as a whole when a later page fails, instead of returning a truncated list', async () => {
|
||||||
|
httpService.get.mockReturnValueOnce(answer(page(250))).mockReturnValueOnce(httpError(502));
|
||||||
|
|
||||||
|
await expect(client.getAllPages('/x', schema)).rejects.toThrow('502');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('getAllPagesForSync', () => {
|
||||||
|
const idOf = (item: { id: number }) => item.id;
|
||||||
|
const ids = (from: number, to: number) => Array.from({ length: to - from + 1 }, (_, index) => ({ id: from + index }));
|
||||||
|
|
||||||
|
it('walks a list that fits in one page only once', async () => {
|
||||||
|
httpService.get.mockReturnValueOnce(answer(page(10)));
|
||||||
|
|
||||||
|
await expect(client.getAllPagesForSync('/x', schema, idOf)).resolves.toHaveLength(10);
|
||||||
|
expect(httpService.get).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('walks a multi-page list twice and keeps an item skipped by a page shift in one walk', async () => {
|
||||||
|
// First walk: item 10 is deleted right after page 1 is read, so item 250 moves to page 1 and page 2 starts at 251
|
||||||
|
httpService.get.mockReturnValueOnce(answer(ids(0, 249))).mockReturnValueOnce(answer(ids(251, 260)));
|
||||||
|
// Second walk: the list without item 10
|
||||||
|
const withoutTen = ids(0, 250).filter(({ id }) => id !== 10);
|
||||||
|
httpService.get.mockReturnValueOnce(answer(withoutTen)).mockReturnValueOnce(answer(ids(251, 260)));
|
||||||
|
|
||||||
|
const results = await client.getAllPagesForSync('/x', schema, idOf);
|
||||||
|
|
||||||
|
expect(httpService.get).toHaveBeenCalledTimes(4);
|
||||||
|
// Item 250 is kept (it would otherwise be deleted); item 10 is only deleted at the next sync
|
||||||
|
expect(results.map(idOf).sort((a, b) => a - b)).toEqual(ids(0, 260).map(idOf));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fails as a whole when the second walk fails', async () => {
|
||||||
|
httpService.get
|
||||||
|
.mockReturnValueOnce(answer(page(250)))
|
||||||
|
.mockReturnValueOnce(answer(page(10)))
|
||||||
|
.mockReturnValueOnce(httpError(502));
|
||||||
|
|
||||||
|
await expect(client.getAllPagesForSync('/x', schema, idOf)).rejects.toThrow('502');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('rate limit (429)', () => {
|
||||||
|
let sleep: jest.SpyInstance;
|
||||||
|
const tooManyRequests = (retryAfter?: string) =>
|
||||||
|
throwError(
|
||||||
|
() =>
|
||||||
|
new AxiosError('Request failed with status code 429', undefined, undefined, undefined, {
|
||||||
|
status: 429,
|
||||||
|
statusText: '',
|
||||||
|
headers: retryAfter === undefined ? {} : { 'retry-after': retryAfter },
|
||||||
|
config: { headers: new AxiosHeaders() },
|
||||||
|
data: null,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
sleep = jest.spyOn(client as unknown as { sleep: (ms: number) => Promise<void> }, 'sleep').mockResolvedValue(undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('retries with exponential backoff, then succeeds', async () => {
|
||||||
|
httpService.get
|
||||||
|
.mockReturnValueOnce(tooManyRequests())
|
||||||
|
.mockReturnValueOnce(tooManyRequests())
|
||||||
|
.mockReturnValueOnce(answer([{ id: 1 }]));
|
||||||
|
|
||||||
|
await expect(client.getList('/x', schema)).resolves.toEqual([{ id: 1 }]);
|
||||||
|
expect(sleep.mock.calls).toEqual([[2_000], [4_000]]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('waits as asked by Retry-After, capped at 60 s', async () => {
|
||||||
|
httpService.get
|
||||||
|
.mockReturnValueOnce(tooManyRequests('5'))
|
||||||
|
.mockReturnValueOnce(tooManyRequests('3600'))
|
||||||
|
.mockReturnValueOnce(answer([]));
|
||||||
|
|
||||||
|
await client.getList('/x', schema);
|
||||||
|
|
||||||
|
expect(sleep.mock.calls).toEqual([[5_000], [60_000]]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('gives up with a HiboutikRateLimitError after 3 retries', async () => {
|
||||||
|
httpService.get.mockReturnValue(tooManyRequests());
|
||||||
|
|
||||||
|
await expect(client.getList('/x', schema)).rejects.toThrow(HiboutikRateLimitError);
|
||||||
|
expect(httpService.get).toHaveBeenCalledTimes(4);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not retry other errors', async () => {
|
||||||
|
httpService.get.mockReturnValueOnce(httpError(500));
|
||||||
|
|
||||||
|
await expect(client.getList('/x', schema)).rejects.toThrow('500');
|
||||||
|
expect(sleep).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not take a rate limited single resource for a missing one', async () => {
|
||||||
|
httpService.get.mockReturnValue(tooManyRequests());
|
||||||
|
|
||||||
|
await expect(client.getOne('/x/7', schema)).rejects.toThrow(HiboutikRateLimitError);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('getOne', () => {
|
||||||
|
it('returns the single element of the answer', async () => {
|
||||||
|
httpService.get.mockReturnValueOnce(answer([{ id: '7' }]));
|
||||||
|
|
||||||
|
await expect(client.getOne('/x/7', schema)).resolves.toEqual({ id: 7 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns null when Hiboutik says the resource does not exist (404 or empty answer)', async () => {
|
||||||
|
httpService.get.mockReturnValueOnce(httpError(404)).mockReturnValueOnce(answer([])).mockReturnValueOnce(answer(''));
|
||||||
|
|
||||||
|
await expect(client.getOne('/x/7', schema)).resolves.toBeNull();
|
||||||
|
await expect(client.getOne('/x/7', schema)).resolves.toBeNull();
|
||||||
|
await expect(client.getOne('/x/7', schema)).resolves.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('throws on any other failure: an unknown state is never taken for a missing resource', async () => {
|
||||||
|
httpService.get
|
||||||
|
.mockReturnValueOnce(httpError(500))
|
||||||
|
.mockReturnValueOnce(httpError(401))
|
||||||
|
.mockReturnValueOnce(throwError(() => new Error('timeout of 30000ms exceeded')))
|
||||||
|
.mockReturnValueOnce(answer({ error: 'x' }));
|
||||||
|
|
||||||
|
await expect(client.getOne('/x/7', schema)).rejects.toThrow('500');
|
||||||
|
await expect(client.getOne('/x/7', schema)).rejects.toThrow('401');
|
||||||
|
await expect(client.getOne('/x/7', schema)).rejects.toThrow('timeout');
|
||||||
|
await expect(client.getOne('/x/7', schema)).rejects.toThrow('a list was expected');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
167
src/hiboutik/hiboutik.client.ts
Normal file
167
src/hiboutik/hiboutik.client.ts
Normal file
@@ -0,0 +1,167 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { HttpService } from '@nestjs/axios';
|
||||||
|
import { ConfigService } from '@nestjs/config';
|
||||||
|
import { isAxiosError } from 'axios';
|
||||||
|
import { firstValueFrom } from 'rxjs';
|
||||||
|
import { z } from 'zod';
|
||||||
|
import { parseHiboutik } from '../models/hiboutikDTO/hiboutik.schema';
|
||||||
|
|
||||||
|
/** Results per page of every paginated Hiboutik endpoint (see "Results per page" in the API docs). */
|
||||||
|
const HIBOUTIK_PAGE_SIZE = 250;
|
||||||
|
|
||||||
|
/** Retries of a request answered 429 (too many requests), with exponential backoff: 2 s, 4 s, 8 s. */
|
||||||
|
const RATE_LIMIT_RETRIES = 3;
|
||||||
|
const RATE_LIMIT_BASE_DELAY_MS = 2_000;
|
||||||
|
/** Cap of the wait asked by a `Retry-After` header: beyond, waiting holds the sync for nothing (monthly quota). */
|
||||||
|
const RATE_LIMIT_MAX_DELAY_MS = 60_000;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hiboutik still answers 429 after the retries: the rate limit (30 concurrent calls) or the monthly quota (10,000
|
||||||
|
* calls per shop) is reached. The synchronization must stop: every next call would fail the same way.
|
||||||
|
*/
|
||||||
|
export class HiboutikRateLimitError extends Error {
|
||||||
|
constructor(path: string) {
|
||||||
|
super(`Hiboutik rate limit reached on ${path} (still 429 after ${RATE_LIMIT_RETRIES} retries): monthly quota exhausted?`);
|
||||||
|
this.name = 'HiboutikRateLimitError';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Rethrows a {@link HiboutikRateLimitError}: for the per-item `catch` blocks of the sync, which must not swallow it. */
|
||||||
|
export function rethrowIfRateLimited(error: unknown): void {
|
||||||
|
if (error instanceof HiboutikRateLimitError) throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Wait asked by a `Retry-After` header (seconds or HTTP date), if any. */
|
||||||
|
function retryAfterMs(header: unknown): number | undefined {
|
||||||
|
if (typeof header !== 'string' || header.trim() === '') return undefined;
|
||||||
|
const seconds = Number(header);
|
||||||
|
if (Number.isFinite(seconds)) return Math.max(0, seconds * 1000);
|
||||||
|
const date = Date.parse(header);
|
||||||
|
return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Low-level HTTP client for the Hiboutik REST API: base URL and Basic auth credentials come from the environment.
|
||||||
|
* Every answer is validated against a zod schema (see `hiboutik.schema.ts`): a malformed one throws, like an HTTP error.
|
||||||
|
*/
|
||||||
|
@Injectable()
|
||||||
|
export class HiboutikClient {
|
||||||
|
private readonly baseUrl: string;
|
||||||
|
private readonly authHeader: string;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly httpService: HttpService,
|
||||||
|
private readonly configService: ConfigService,
|
||||||
|
) {
|
||||||
|
const username = this.configService.get<string>('HIBOUTIK_USERNAME') ?? '';
|
||||||
|
const password = this.configService.get<string>('HIBOUTIK_PASSWORD') ?? '';
|
||||||
|
this.authHeader = `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`;
|
||||||
|
this.baseUrl = this.configService.get<string>('HIBOUTIK_BASE_URL') ?? '';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GET on a Hiboutik path (relative to `HIBOUTIK_BASE_URL`), returns the raw response body. A 429 is retried with
|
||||||
|
* backoff (or after the `Retry-After` delay), then turns into a {@link HiboutikRateLimitError}.
|
||||||
|
*/
|
||||||
|
private async get(path: string, params?: Record<string, unknown>): Promise<unknown> {
|
||||||
|
for (let attempt = 0; ; attempt++) {
|
||||||
|
try {
|
||||||
|
const response = await firstValueFrom(
|
||||||
|
this.httpService.get<unknown>(`${this.baseUrl}${path}`, {
|
||||||
|
headers: { Authorization: this.authHeader },
|
||||||
|
params,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
return response.data;
|
||||||
|
} catch (error) {
|
||||||
|
if (!isAxiosError(error) || error.response?.status !== 429) throw error;
|
||||||
|
if (attempt >= RATE_LIMIT_RETRIES) throw new HiboutikRateLimitError(path);
|
||||||
|
|
||||||
|
const delay = retryAfterMs(error.response.headers['retry-after']) ?? RATE_LIMIT_BASE_DELAY_MS * 2 ** attempt;
|
||||||
|
await this.sleep(Math.min(delay, RATE_LIMIT_MAX_DELAY_MS));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Separate method so that tests can skip the waits. */
|
||||||
|
protected sleep(ms: number): Promise<void> {
|
||||||
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GET on a list endpoint. HTTP errors (4xx/5xx) throw, a 2xx answer without body is an empty list, and any other
|
||||||
|
* non-list body or invalid item throws: an empty list triggers deletions in the sync, so it must never be inferred
|
||||||
|
* from a malformed answer.
|
||||||
|
*/
|
||||||
|
async getList<T extends z.ZodType>(path: string, itemSchema: T, params?: Record<string, unknown>): Promise<z.output<T>[]> {
|
||||||
|
const data = await this.get(path, params);
|
||||||
|
if (data === '' || data == null) return [];
|
||||||
|
if (!Array.isArray(data)) throw new Error(`Unexpected answer from Hiboutik ${path}: a list was expected`);
|
||||||
|
return parseHiboutik(z.array(itemSchema), data, path);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetches every page of a paginated endpoint (`p` param, starting at 1) and concatenates the results.
|
||||||
|
* Only for paginated endpoints: on a non-paginated one, a full first page would loop forever on the same results.
|
||||||
|
*/
|
||||||
|
async getAllPages<T extends z.ZodType>(path: string, itemSchema: T, baseParams: Record<string, unknown> = {}): Promise<z.output<T>[]> {
|
||||||
|
return (await this.walkPages(path, itemSchema, baseParams)).items;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Same as {@link getAllPages}, for a list whose content drives deletions. An item created or deleted in Hiboutik while
|
||||||
|
* the pages are walked shifts the following pages, so an item can be skipped. When the list spans several pages, it
|
||||||
|
* is walked a second time and both walks are merged by id (the second one wins): an item is missing from the result
|
||||||
|
* only if both walks missed it. A list that fits in one page costs no extra call.
|
||||||
|
*/
|
||||||
|
async getAllPagesForSync<T extends z.ZodType>(
|
||||||
|
path: string,
|
||||||
|
itemSchema: T,
|
||||||
|
idOf: (item: z.output<T>) => number,
|
||||||
|
baseParams: Record<string, unknown> = {},
|
||||||
|
): Promise<z.output<T>[]> {
|
||||||
|
const firstWalk = await this.walkPages(path, itemSchema, baseParams);
|
||||||
|
if (firstWalk.nbPages <= 1) return firstWalk.items;
|
||||||
|
|
||||||
|
const secondWalk = await this.walkPages(path, itemSchema, baseParams);
|
||||||
|
const byId = new Map<number, z.output<T>>();
|
||||||
|
for (const item of [...firstWalk.items, ...secondWalk.items]) byId.set(idOf(item), item);
|
||||||
|
return [...byId.values()];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Walks the pages of a paginated endpoint. `nbPages` counts the pages holding results. */
|
||||||
|
private async walkPages<T extends z.ZodType>(
|
||||||
|
path: string,
|
||||||
|
itemSchema: T,
|
||||||
|
baseParams: Record<string, unknown>,
|
||||||
|
): Promise<{ items: z.output<T>[]; nbPages: number }> {
|
||||||
|
const items: z.output<T>[] = [];
|
||||||
|
let page = 1;
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
const pageData = await this.getList(path, itemSchema, { ...baseParams, p: page });
|
||||||
|
if (pageData.length === 0) break;
|
||||||
|
items.push(...pageData);
|
||||||
|
// A page smaller than the page size is the last one: no need to request an empty page
|
||||||
|
if (pageData.length < HIBOUTIK_PAGE_SIZE) break;
|
||||||
|
page++;
|
||||||
|
}
|
||||||
|
|
||||||
|
return { items, nbPages: Math.ceil(items.length / HIBOUTIK_PAGE_SIZE) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GET on a single-resource endpoint (Hiboutik answers with a one-element array).
|
||||||
|
* @returns `null` when Hiboutik says the resource does not exist: a 404, or a 2xx answer that is empty.
|
||||||
|
* @throws on any other HTTP error or malformed answer: an unknown state is never taken for a missing resource.
|
||||||
|
*/
|
||||||
|
async getOne<T extends z.ZodType>(path: string, schema: T): Promise<z.output<T> | null> {
|
||||||
|
try {
|
||||||
|
const [item] = await this.getList(path, schema);
|
||||||
|
return item ?? null;
|
||||||
|
} catch (error) {
|
||||||
|
if (isAxiosError(error) && error.response?.status === 404) return null;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
20
src/hiboutik/product.hiboutik.repository.ts
Normal file
20
src/hiboutik/product.hiboutik.repository.ts
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { HiboutikClient } from './hiboutik.client';
|
||||||
|
import { ProductHiboutikDto, productHiboutikSchema } from '../models/hiboutikDTO/product.hiboutik.dto';
|
||||||
|
|
||||||
|
/** Reads products from the Hiboutik API. */
|
||||||
|
@Injectable()
|
||||||
|
export class ProductHiboutikRepository {
|
||||||
|
constructor(private readonly hiboutikClient: HiboutikClient) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* All products, archived ones included, with their sizes and per-size rules. Walked twice when it spans several
|
||||||
|
* pages: it drives the deletion of products (see `getAllPagesForSync`).
|
||||||
|
*/
|
||||||
|
async getProducts(): Promise<ProductHiboutikDto[]> {
|
||||||
|
return this.hiboutikClient.getAllPagesForSync('/products', productHiboutikSchema, (product) => product.product_id, {
|
||||||
|
order_by: 'product_id',
|
||||||
|
sort: 'ASC',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
19
src/hiboutik/sale.hiboutik.repository.ts
Normal file
19
src/hiboutik/sale.hiboutik.repository.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { HiboutikClient } from './hiboutik.client';
|
||||||
|
import { SaleHiboutikDto, saleHiboutikSchema } from '../models/hiboutikDTO/sale.hiboutik.dto';
|
||||||
|
|
||||||
|
/** Reads sales from the Hiboutik API. */
|
||||||
|
@Injectable()
|
||||||
|
export class SaleHiboutikRepository {
|
||||||
|
constructor(private readonly hiboutikClient: HiboutikClient) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Full sale, with its lines.
|
||||||
|
* @throws if the sale does not exist.
|
||||||
|
*/
|
||||||
|
async getSaleById(id: number): Promise<SaleHiboutikDto> {
|
||||||
|
const sale = await this.hiboutikClient.getOne(`/sales/${id}`, saleHiboutikSchema);
|
||||||
|
if (!sale) throw new Error(`Hiboutik sale ${id} not found`);
|
||||||
|
return sale;
|
||||||
|
}
|
||||||
|
}
|
||||||
14
src/hiboutik/stock.hiboutik.repository.ts
Normal file
14
src/hiboutik/stock.hiboutik.repository.ts
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { HiboutikClient } from './hiboutik.client';
|
||||||
|
import { StockHiboutikDto, stockHiboutikSchema } from '../models/hiboutikDTO/stock.hiboutik.dto';
|
||||||
|
|
||||||
|
/** Reads available stocks from the Hiboutik API. */
|
||||||
|
@Injectable()
|
||||||
|
export class StockHiboutikRepository {
|
||||||
|
constructor(private readonly hiboutikClient: HiboutikClient) {}
|
||||||
|
|
||||||
|
/** Stock of every product and size, all warehouses combined. Not paginated. */
|
||||||
|
async getStocks(): Promise<StockHiboutikDto[]> {
|
||||||
|
return this.hiboutikClient.getList('/stock_available/all_wh', stockHiboutikSchema);
|
||||||
|
}
|
||||||
|
}
|
||||||
17
src/hiboutik/supplier.hiboutik.repository.ts
Normal file
17
src/hiboutik/supplier.hiboutik.repository.ts
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { HiboutikClient } from './hiboutik.client';
|
||||||
|
import { SupplierHiboutikDto, supplierHiboutikSchema } from '../models/hiboutikDTO/supplier.hiboutik.dto';
|
||||||
|
|
||||||
|
/** Reads suppliers from the Hiboutik API. */
|
||||||
|
@Injectable()
|
||||||
|
export class SupplierHiboutikRepository {
|
||||||
|
constructor(private readonly hiboutikClient: HiboutikClient) {}
|
||||||
|
|
||||||
|
/** `/suppliers` is not paginated: everything comes in one call. */
|
||||||
|
async getSuppliers(): Promise<SupplierHiboutikDto[]> {
|
||||||
|
return this.hiboutikClient.getList('/suppliers', supplierHiboutikSchema, {
|
||||||
|
order_by: 'supplier_id',
|
||||||
|
sort: 'ASC',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
34
src/main.ts
34
src/main.ts
@@ -1,8 +1,36 @@
|
|||||||
|
import { ValidationPipe } from '@nestjs/common';
|
||||||
|
import { ConfigService } from '@nestjs/config';
|
||||||
import { NestFactory } from '@nestjs/core';
|
import { NestFactory } from '@nestjs/core';
|
||||||
|
import { NestExpressApplication } from '@nestjs/platform-express';
|
||||||
|
import helmet from 'helmet';
|
||||||
import { AppModule } from './app.module';
|
import { AppModule } from './app.module';
|
||||||
|
|
||||||
async function bootstrap() {
|
async function bootstrap() {
|
||||||
const app = await NestFactory.create(AppModule);
|
const app = await NestFactory.create<NestExpressApplication>(AppModule);
|
||||||
await app.listen(process.env.PORT ?? 3000);
|
const config = app.get(ConfigService);
|
||||||
|
|
||||||
|
// Security headers (also removes X-Powered-By)
|
||||||
|
app.use(helmet());
|
||||||
|
|
||||||
|
// Behind a reverse proxy, trust its X-Forwarded-For so rate limiting sees the real client IP
|
||||||
|
const trustProxy = config.get<number>('TRUST_PROXY');
|
||||||
|
if (trustProxy) app.set('trust proxy', trustProxy);
|
||||||
|
|
||||||
|
// CORS is disabled unless origins are explicitly allowed
|
||||||
|
const origins = (config.get<string>('CORS_ORIGINS') ?? '')
|
||||||
|
.split(',')
|
||||||
|
.map((origin) => origin.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
if (origins.length > 0) app.enableCors({ origin: origins });
|
||||||
|
|
||||||
|
app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }));
|
||||||
|
|
||||||
|
// Disconnect Prisma cleanly on SIGTERM/SIGINT
|
||||||
|
app.enableShutdownHooks();
|
||||||
|
|
||||||
|
const server = await app.listen(config.get<number>('PORT') ?? 3000);
|
||||||
|
// Drop slow clients holding sockets open (Slowloris): every endpoint answers fast, POST /sync runs in the background
|
||||||
|
server.headersTimeout = 15_000;
|
||||||
|
server.requestTimeout = 30_000;
|
||||||
}
|
}
|
||||||
bootstrap();
|
void bootstrap();
|
||||||
|
|||||||
19
src/models/converter/brand.converter.ts
Normal file
19
src/models/converter/brand.converter.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { Converter } from './converter';
|
||||||
|
import { BrandHiboutikDto } from '../hiboutikDTO/brand.hiboutik.dto';
|
||||||
|
import { BrandCreateInput } from '../../../prisma/generated/models/Brand';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class BrandConverter extends Converter<BrandCreateInput, BrandHiboutikDto> {
|
||||||
|
fromHiboutik(dto: BrandHiboutikDto): BrandCreateInput {
|
||||||
|
return {
|
||||||
|
hiboutikId: dto.brand_id,
|
||||||
|
name: dto.brand_name,
|
||||||
|
enabled: dto.brand_enabled === 1,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
toHiboutik(): BrandHiboutikDto {
|
||||||
|
throw new Error('Method not implemented.');
|
||||||
|
}
|
||||||
|
}
|
||||||
22
src/models/converter/category.converter.ts
Normal file
22
src/models/converter/category.converter.ts
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { CategoryHiboutikDto } from '../hiboutikDTO/category.hiboutik.dto';
|
||||||
|
import { Converter } from './converter';
|
||||||
|
import { CategoryCreateInput } from '../../../prisma/generated/models/Category';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class CategoryConverter extends Converter<CategoryCreateInput, CategoryHiboutikDto> {
|
||||||
|
/** The parent is not set here: it is linked afterwards, once every category exists (see CategoryHiboutikService). */
|
||||||
|
fromHiboutik(hiboutikDto: CategoryHiboutikDto): CategoryCreateInput {
|
||||||
|
return {
|
||||||
|
hiboutikId: hiboutikDto.category_id,
|
||||||
|
name: hiboutikDto.category_name,
|
||||||
|
enabled: hiboutikDto.category_enabled === 1,
|
||||||
|
position: hiboutikDto.category_position,
|
||||||
|
webEnabled: hiboutikDto.category_enabled_www === 1,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
toHiboutik(): CategoryHiboutikDto {
|
||||||
|
throw new Error('Method not implemented.');
|
||||||
|
}
|
||||||
|
}
|
||||||
29
src/models/converter/converter.ts
Normal file
29
src/models/converter/converter.ts
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
/**
|
||||||
|
* Maps a Hiboutik DTO to a Prisma input, and back. One implementation per synced entity.
|
||||||
|
* @typeParam Model Prisma `*CreateInput` of the entity.
|
||||||
|
* @typeParam Dto Hiboutik payload of the entity.
|
||||||
|
*/
|
||||||
|
export abstract class Converter<Model, Dto> {
|
||||||
|
/**
|
||||||
|
* Builds the Prisma input from a Hiboutik DTO. It is used for both create and update (upsert):
|
||||||
|
* a field set to `undefined` keeps its stored value on update, `null` erases it.
|
||||||
|
*/
|
||||||
|
abstract fromHiboutik(dto: Dto): Model;
|
||||||
|
|
||||||
|
/** Not implemented yet: nothing is written back to Hiboutik. */
|
||||||
|
abstract toHiboutik(model: Model): Dto;
|
||||||
|
|
||||||
|
/** Returns [] for a missing or non-array input. */
|
||||||
|
toHiboutikList(models: Model[]): Dto[] {
|
||||||
|
if (!models || !Array.isArray(models)) return [];
|
||||||
|
|
||||||
|
return models.map((model) => this.toHiboutik(model));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Returns [] for a missing or non-array input. */
|
||||||
|
fromHiboutikList(hiboutikDtos: Dto[]): Model[] {
|
||||||
|
if (!hiboutikDtos || !Array.isArray(hiboutikDtos)) return [];
|
||||||
|
|
||||||
|
return hiboutikDtos.map((hiboutikDto) => this.fromHiboutik(hiboutikDto));
|
||||||
|
}
|
||||||
|
}
|
||||||
44
src/models/converter/customer.converter.spec.ts
Normal file
44
src/models/converter/customer.converter.spec.ts
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
import { CustomerConverter } from './customer.converter';
|
||||||
|
import { FullCustomerHiboutikDto } from '../hiboutikDTO/customer.hiboutik.dto';
|
||||||
|
|
||||||
|
const hiboutikCustomer = (overrides: Partial<FullCustomerHiboutikDto> = {}): FullCustomerHiboutikDto => ({
|
||||||
|
customers_id: 42,
|
||||||
|
first_name: 'Jane',
|
||||||
|
last_name: 'Doe',
|
||||||
|
email: 'jane@example.com',
|
||||||
|
phone: '0600000000',
|
||||||
|
date_of_birth: '1990-05-12',
|
||||||
|
updated_at: '2026-06-28 17:02:55',
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('CustomerConverter', () => {
|
||||||
|
const converter = new CustomerConverter();
|
||||||
|
|
||||||
|
it('maps a Hiboutik customer', () => {
|
||||||
|
expect(converter.fromHiboutik(hiboutikCustomer())).toEqual({
|
||||||
|
dateOfBirth: new Date('1990-05-12'),
|
||||||
|
email: 'jane@example.com',
|
||||||
|
firstName: 'Jane',
|
||||||
|
hiboutikId: 42,
|
||||||
|
// French summer time (UTC+2)
|
||||||
|
hiboutikUpdatedAt: new Date('2026-06-28T15:02:55Z'),
|
||||||
|
lastName: 'Doe',
|
||||||
|
phone: '0600000000',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ignores an invalid date of birth', () => {
|
||||||
|
expect(converter.fromHiboutik(hiboutikCustomer({ date_of_birth: '0000-00-00' })).dateOfBirth).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('erases the email when Hiboutik has none (null)', () => {
|
||||||
|
expect(converter.fromHiboutik(hiboutikCustomer({ email: '' })).email).toBeNull();
|
||||||
|
expect(converter.fromHiboutik(hiboutikCustomer({ email: ' ' })).email).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('erases the phone when Hiboutik has none (null)', () => {
|
||||||
|
expect(converter.fromHiboutik(hiboutikCustomer({ phone: '' })).phone).toBeNull();
|
||||||
|
expect(converter.fromHiboutik(hiboutikCustomer({ phone: ' ' })).phone).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
25
src/models/converter/customer.converter.ts
Normal file
25
src/models/converter/customer.converter.ts
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { Converter } from './converter';
|
||||||
|
import { CustomerCreateInput } from '../../../prisma/generated/models/Customer';
|
||||||
|
import { FullCustomerHiboutikDto } from '../hiboutikDTO/customer.hiboutik.dto';
|
||||||
|
import { parseHiboutikDate } from '../../utils/date';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class CustomerConverter extends Converter<CustomerCreateInput, FullCustomerHiboutikDto> {
|
||||||
|
fromHiboutik(dto: FullCustomerHiboutikDto): CustomerCreateInput {
|
||||||
|
return {
|
||||||
|
dateOfBirth: parseHiboutikDate(dto.date_of_birth),
|
||||||
|
// null (not undefined) so that an email removed in Hiboutik is also removed in database (data minimization)
|
||||||
|
email: dto.email.trim() || null,
|
||||||
|
firstName: dto.first_name,
|
||||||
|
hiboutikId: dto.customers_id,
|
||||||
|
hiboutikUpdatedAt: parseHiboutikDate(dto.updated_at),
|
||||||
|
lastName: dto.last_name,
|
||||||
|
// null (not undefined) so that a phone removed in Hiboutik is also removed in database
|
||||||
|
phone: dto.phone.trim() || null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
toHiboutik(): FullCustomerHiboutikDto {
|
||||||
|
throw new Error('Method not implemented.');
|
||||||
|
}
|
||||||
|
}
|
||||||
79
src/models/converter/customerAddress.converter.spec.ts
Normal file
79
src/models/converter/customerAddress.converter.spec.ts
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
import { CustomerAddressConverter } from './customerAddress.converter';
|
||||||
|
import { CustomerAddressHiboutikDto } from '../hiboutikDTO/customer.hiboutik.dto';
|
||||||
|
|
||||||
|
const hiboutikAddress = (overrides: Partial<CustomerAddressHiboutikDto> = {}): CustomerAddressHiboutikDto => ({
|
||||||
|
address_id: 7,
|
||||||
|
customers_id: 42,
|
||||||
|
first_name: 'Jane',
|
||||||
|
last_name: 'Doe',
|
||||||
|
company: 'ACME',
|
||||||
|
phone: '0600000000',
|
||||||
|
address: ' 1 rue de la Paix ',
|
||||||
|
zip_code: '75002',
|
||||||
|
city: 'Paris',
|
||||||
|
state: '',
|
||||||
|
country: 'FRA',
|
||||||
|
other: 'Bât. B',
|
||||||
|
default: 1,
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('CustomerAddressConverter', () => {
|
||||||
|
const converter = new CustomerAddressConverter();
|
||||||
|
|
||||||
|
it('maps a Hiboutik address', () => {
|
||||||
|
expect(converter.fromHiboutik(hiboutikAddress())).toEqual({
|
||||||
|
address: '1 rue de la Paix',
|
||||||
|
city: 'Paris',
|
||||||
|
company: 'ACME',
|
||||||
|
country: 'FRA',
|
||||||
|
firstName: 'Jane',
|
||||||
|
hiboutikId: 7,
|
||||||
|
isDefault: true,
|
||||||
|
lastName: 'Doe',
|
||||||
|
other: 'Bât. B',
|
||||||
|
phone: '0600000000',
|
||||||
|
state: null,
|
||||||
|
zipCode: '75002',
|
||||||
|
customer: { connect: { hiboutikId: 42 } },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('erases empty optional fields (null) and defaults empty required ones to ""', () => {
|
||||||
|
const address = converter.fromHiboutik(hiboutikAddress({ company: ' ', phone: '', other: '', first_name: '' }));
|
||||||
|
expect(address.company).toBeNull();
|
||||||
|
expect(address.phone).toBeNull();
|
||||||
|
expect(address.other).toBeNull();
|
||||||
|
expect(address.firstName).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('company details', () => {
|
||||||
|
const details = { tax_number: ' FR123 ', company_number: '12345678900012', legal_status: 'SAS', updated_at: '2026-11-01 10:00:00' };
|
||||||
|
|
||||||
|
it('maps them when fetched for an address with a company', () => {
|
||||||
|
const address = converter.fromHiboutik({ ...hiboutikAddress(), ...details });
|
||||||
|
expect(address.taxNumber).toBe('FR123');
|
||||||
|
expect(address.companyNumber).toBe('12345678900012');
|
||||||
|
expect(address.legalStatus).toBe('SAS');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('erases empty fetched values (null)', () => {
|
||||||
|
const address = converter.fromHiboutik({ ...hiboutikAddress(), ...details, tax_number: '' });
|
||||||
|
expect(address.taxNumber).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the stored ones when not fetched (undefined)', () => {
|
||||||
|
const address = converter.fromHiboutik(hiboutikAddress());
|
||||||
|
expect(address.taxNumber).toBeUndefined();
|
||||||
|
expect(address.companyNumber).toBeUndefined();
|
||||||
|
expect(address.legalStatus).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('erases them when the address has no company (null)', () => {
|
||||||
|
const address = converter.fromHiboutik({ ...hiboutikAddress({ company: '' }), ...details });
|
||||||
|
expect(address.taxNumber).toBeNull();
|
||||||
|
expect(address.companyNumber).toBeNull();
|
||||||
|
expect(address.legalStatus).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
49
src/models/converter/customerAddress.converter.ts
Normal file
49
src/models/converter/customerAddress.converter.ts
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { Converter } from './converter';
|
||||||
|
import { CustomerAddressCreateInput } from '../../../prisma/generated/models/CustomerAddress';
|
||||||
|
import { CustomerAddressDetailsHiboutikDto, CustomerAddressHiboutikDto } from '../hiboutikDTO/customer.hiboutik.dto';
|
||||||
|
|
||||||
|
/** Trimmed value, `null` when empty so that a value removed in Hiboutik is also removed in database. */
|
||||||
|
const optional = (value: string | null | undefined): string | null => value?.trim() || null;
|
||||||
|
const required = (value: string | null | undefined): string => value?.trim() ?? '';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Maps an address. Company details (tax/company number, legal status) are:
|
||||||
|
* - `null` when the address has no company,
|
||||||
|
* - mapped when `dto` comes from `GET /customers_addresses/:id` ({@link CustomerAddressDetailsHiboutikDto}),
|
||||||
|
* - `undefined` (stored values kept) when the details were not fetched.
|
||||||
|
*/
|
||||||
|
@Injectable()
|
||||||
|
export class CustomerAddressConverter extends Converter<
|
||||||
|
CustomerAddressCreateInput,
|
||||||
|
CustomerAddressHiboutikDto | CustomerAddressDetailsHiboutikDto
|
||||||
|
> {
|
||||||
|
fromHiboutik(dto: CustomerAddressHiboutikDto | CustomerAddressDetailsHiboutikDto): CustomerAddressCreateInput {
|
||||||
|
const company = optional(dto.company);
|
||||||
|
const hasDetails = 'tax_number' in dto;
|
||||||
|
const companyDetail = (value: string | null | undefined) => (!company ? null : hasDetails ? optional(value) : undefined);
|
||||||
|
const details = dto as Partial<CustomerAddressDetailsHiboutikDto>;
|
||||||
|
|
||||||
|
return {
|
||||||
|
address: required(dto.address),
|
||||||
|
city: required(dto.city),
|
||||||
|
company,
|
||||||
|
companyNumber: companyDetail(details.company_number),
|
||||||
|
country: required(dto.country),
|
||||||
|
firstName: required(dto.first_name),
|
||||||
|
hiboutikId: dto.address_id,
|
||||||
|
isDefault: dto.default === 1,
|
||||||
|
lastName: required(dto.last_name),
|
||||||
|
legalStatus: companyDetail(details.legal_status),
|
||||||
|
other: optional(dto.other),
|
||||||
|
phone: optional(dto.phone),
|
||||||
|
state: optional(dto.state),
|
||||||
|
taxNumber: companyDetail(details.tax_number),
|
||||||
|
zipCode: required(dto.zip_code),
|
||||||
|
customer: { connect: { hiboutikId: dto.customers_id } },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
toHiboutik(): CustomerAddressHiboutikDto {
|
||||||
|
throw new Error('Method not implemented.');
|
||||||
|
}
|
||||||
|
}
|
||||||
78
src/models/converter/order.converter.spec.ts
Normal file
78
src/models/converter/order.converter.spec.ts
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
import { OrderConverter } from './order.converter';
|
||||||
|
import { SaleHiboutikDto, SaleLineHiboutikDto } from '../hiboutikDTO/sale.hiboutik.dto';
|
||||||
|
|
||||||
|
const hiboutikLine = (overrides: Partial<SaleLineHiboutikDto> = {}): SaleLineHiboutikDto => ({
|
||||||
|
product_id: 746,
|
||||||
|
product_size: 1,
|
||||||
|
quantity: 2,
|
||||||
|
product_model: 'KATSEYE - WILD',
|
||||||
|
product_barcode: '2430010007467',
|
||||||
|
size_name: 'Daniela',
|
||||||
|
item_unit_gross: '17.10',
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
|
||||||
|
const hiboutikSale = (overrides: Partial<SaleHiboutikDto> = {}): SaleHiboutikDto => ({
|
||||||
|
sale_id: 5,
|
||||||
|
created_at: '2026-10-18 11:00:21',
|
||||||
|
completed_at: '2026-10-18 11:01:04',
|
||||||
|
customer_id: 1,
|
||||||
|
total: '34.20',
|
||||||
|
quotation: 0,
|
||||||
|
line_items: [hiboutikLine()],
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('OrderConverter', () => {
|
||||||
|
const converter = new OrderConverter();
|
||||||
|
|
||||||
|
it('maps a completed Hiboutik sale with its lines', () => {
|
||||||
|
expect(converter.fromHiboutik(hiboutikSale())).toEqual({
|
||||||
|
hiboutikSaleId: 5,
|
||||||
|
// French summer time (UTC+2)
|
||||||
|
orderedAt: new Date('2026-10-18T09:01:04Z'),
|
||||||
|
source: 'STORE',
|
||||||
|
status: 'COMPLETED',
|
||||||
|
total: '34.20',
|
||||||
|
customer: { connect: { hiboutikId: 1 } },
|
||||||
|
lines: [
|
||||||
|
{
|
||||||
|
barcode: '2430010007467',
|
||||||
|
hiboutikProductId: 746,
|
||||||
|
hiboutikSizeId: 1,
|
||||||
|
productName: 'KATSEYE - WILD',
|
||||||
|
quantity: 2,
|
||||||
|
unitPrice: '17.10',
|
||||||
|
versionName: 'Daniela',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('maps a sale not completed yet as PENDING, ordered at its creation date', () => {
|
||||||
|
const order = converter.fromHiboutik(hiboutikSale({ completed_at: '0000-00-00 00:00:00' }));
|
||||||
|
expect(order.status).toBe('PENDING');
|
||||||
|
expect(order.orderedAt).toEqual(new Date('2026-10-18T09:00:21Z'));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('throws when the sale has no valid date', () => {
|
||||||
|
expect(() => converter.fromHiboutik(hiboutikSale({ completed_at: '0000-00-00 00:00:00', created_at: '' }))).toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('leaves an anonymous sale without customer', () => {
|
||||||
|
expect(converter.fromHiboutik(hiboutikSale({ customer_id: 0 })).customer).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses the product name as version name and null barcode for a product without sizes', () => {
|
||||||
|
const [line] = converter.fromHiboutik(
|
||||||
|
hiboutikSale({ line_items: [hiboutikLine({ product_size: 0, size_name: '', product_barcode: '' })] }),
|
||||||
|
).lines;
|
||||||
|
expect(line.versionName).toBe('KATSEYE - WILD');
|
||||||
|
expect(line.barcode).toBeNull();
|
||||||
|
expect(line.hiboutikSizeId).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('accepts a sale without lines', () => {
|
||||||
|
expect(converter.fromHiboutik(hiboutikSale({ line_items: [] })).lines).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
48
src/models/converter/order.converter.ts
Normal file
48
src/models/converter/order.converter.ts
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { Converter } from './converter';
|
||||||
|
import { OrderSource } from '../../../prisma/generated/client';
|
||||||
|
import { OrderWithLinesInput } from '../../../prisma/customObjects/prisma.custom.object';
|
||||||
|
import { SaleHiboutikDto, SaleLineHiboutikDto } from '../hiboutikDTO/sale.hiboutik.dto';
|
||||||
|
import { parseHiboutikDate } from '../../utils/date';
|
||||||
|
import { OrderStatus } from '../orderStatus';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class OrderConverter extends Converter<OrderWithLinesInput, SaleHiboutikDto> {
|
||||||
|
/**
|
||||||
|
* Maps a Hiboutik sale to an order (source STORE) with a snapshot of its lines.
|
||||||
|
* @throws if the sale has neither a valid completion date nor a valid creation date.
|
||||||
|
*/
|
||||||
|
fromHiboutik(dto: SaleHiboutikDto): OrderWithLinesInput {
|
||||||
|
const completedAt = parseHiboutikDate(dto.completed_at);
|
||||||
|
const orderedAt = completedAt ?? parseHiboutikDate(dto.created_at);
|
||||||
|
if (!orderedAt) throw new Error(`Hiboutik sale ${dto.sale_id} has no valid date`);
|
||||||
|
|
||||||
|
return {
|
||||||
|
hiboutikSaleId: dto.sale_id,
|
||||||
|
orderedAt,
|
||||||
|
source: OrderSource.STORE,
|
||||||
|
status: completedAt ? OrderStatus.COMPLETED : OrderStatus.PENDING,
|
||||||
|
total: dto.total,
|
||||||
|
// 0 for an anonymous sale
|
||||||
|
customer: dto.customer_id > 0 ? { connect: { hiboutikId: dto.customer_id } } : undefined,
|
||||||
|
lines: dto.line_items.map((line) => this.lineFromHiboutik(line)),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private lineFromHiboutik(line: SaleLineHiboutikDto): OrderWithLinesInput['lines'][number] {
|
||||||
|
return {
|
||||||
|
barcode: line.product_barcode.trim() || null,
|
||||||
|
hiboutikProductId: line.product_id,
|
||||||
|
hiboutikSizeId: line.product_size,
|
||||||
|
productName: line.product_model,
|
||||||
|
quantity: line.quantity,
|
||||||
|
unitPrice: line.item_unit_gross,
|
||||||
|
// same rule as ProductVersion: the product name for a product without sizes
|
||||||
|
versionName: line.size_name.trim() || line.product_model,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
toHiboutik(): SaleHiboutikDto {
|
||||||
|
throw new Error('Method not implemented.');
|
||||||
|
}
|
||||||
|
}
|
||||||
59
src/models/converter/product.converter.spec.ts
Normal file
59
src/models/converter/product.converter.spec.ts
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
import { ProductConverter } from './product.converter';
|
||||||
|
import { ProductHiboutikDto } from '../hiboutikDTO/product.hiboutik.dto';
|
||||||
|
|
||||||
|
const hiboutikProduct = (overrides: Partial<ProductHiboutikDto> = {}): ProductHiboutikDto => ({
|
||||||
|
product_id: 1,
|
||||||
|
product_model: 'BOUTEILLE MÉTAL ISOTHERME 260ML BT21',
|
||||||
|
product_barcode: '8435497280048',
|
||||||
|
product_brand: 1,
|
||||||
|
product_supplier: 2,
|
||||||
|
product_price: '13.99',
|
||||||
|
product_discount_price: '0.00',
|
||||||
|
product_category: 19,
|
||||||
|
product_display_www: 0,
|
||||||
|
product_arch: 0,
|
||||||
|
products_desc: '',
|
||||||
|
updated_at: '2026-06-28 17:02:55',
|
||||||
|
product_specific_rules: [],
|
||||||
|
product_size_details: [],
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('ProductConverter', () => {
|
||||||
|
const converter = new ProductConverter();
|
||||||
|
|
||||||
|
it('maps a Hiboutik product', () => {
|
||||||
|
expect(converter.fromHiboutik(hiboutikProduct())).toEqual({
|
||||||
|
archived: false,
|
||||||
|
barcode: '8435497280048',
|
||||||
|
brand: { connect: { hiboutikId: 1 } },
|
||||||
|
category: { connect: { hiboutikId: 19 } },
|
||||||
|
description: '',
|
||||||
|
discountPrice: null,
|
||||||
|
hiboutikId: 1,
|
||||||
|
hiboutikUpdatedAt: new Date('2026-06-28T15:02:55Z'),
|
||||||
|
name: 'BOUTEILLE MÉTAL ISOTHERME 260ML BT21',
|
||||||
|
price: '13.99',
|
||||||
|
enabled: false,
|
||||||
|
supplier: { connect: { hiboutikId: 2 } },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('maps archived, web display and discount price', () => {
|
||||||
|
const product = converter.fromHiboutik(hiboutikProduct({ product_arch: 1, product_display_www: 1, product_discount_price: '9.99' }));
|
||||||
|
expect(product.archived).toBe(true);
|
||||||
|
expect(product.enabled).toBe(true);
|
||||||
|
expect(product.discountPrice).toBe('9.99');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('stores an empty barcode as null', () => {
|
||||||
|
expect(converter.fromHiboutik(hiboutikProduct({ product_barcode: '' })).barcode).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not link missing relations', () => {
|
||||||
|
const product = converter.fromHiboutik(hiboutikProduct({ product_brand: 0, product_category: 0, product_supplier: 0 }));
|
||||||
|
expect(product.brand).toBeUndefined();
|
||||||
|
expect(product.category).toBeUndefined();
|
||||||
|
expect(product.supplier).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
31
src/models/converter/product.converter.ts
Normal file
31
src/models/converter/product.converter.ts
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { Converter } from './converter';
|
||||||
|
import { ProductHiboutikDto } from '../hiboutikDTO/product.hiboutik.dto';
|
||||||
|
import { ProductCreateInput } from '../../../prisma/generated/models/Product';
|
||||||
|
import { parseHiboutikDate } from '../../utils/date';
|
||||||
|
import { parseOptionalHiboutikPrice } from '../../utils/price';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class ProductConverter extends Converter<ProductCreateInput, ProductHiboutikDto> {
|
||||||
|
/** `globalStock` and versions are not set here: they depend on the stocks endpoint (see ProductHiboutikService). */
|
||||||
|
fromHiboutik(dto: ProductHiboutikDto): ProductCreateInput {
|
||||||
|
return {
|
||||||
|
archived: dto.product_arch === 1,
|
||||||
|
barcode: dto.product_barcode || null,
|
||||||
|
brand: dto.product_brand ? { connect: { hiboutikId: dto.product_brand } } : undefined,
|
||||||
|
category: dto.product_category ? { connect: { hiboutikId: dto.product_category } } : undefined,
|
||||||
|
description: dto.products_desc,
|
||||||
|
discountPrice: parseOptionalHiboutikPrice(dto.product_discount_price),
|
||||||
|
hiboutikId: dto.product_id,
|
||||||
|
hiboutikUpdatedAt: parseHiboutikDate(dto.updated_at),
|
||||||
|
name: dto.product_model,
|
||||||
|
price: dto.product_price,
|
||||||
|
enabled: dto.product_display_www === 1,
|
||||||
|
supplier: dto.product_supplier ? { connect: { hiboutikId: dto.product_supplier } } : undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
toHiboutik(): ProductHiboutikDto {
|
||||||
|
throw new Error('Method not implemented.');
|
||||||
|
}
|
||||||
|
}
|
||||||
19
src/models/converter/supplier.converter.ts
Normal file
19
src/models/converter/supplier.converter.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { SupplierHiboutikDto } from '../hiboutikDTO/supplier.hiboutik.dto';
|
||||||
|
import { Converter } from './converter';
|
||||||
|
import { SupplierCreateInput } from '../../../prisma/generated/models/Supplier';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class SupplierConverter extends Converter<SupplierCreateInput, SupplierHiboutikDto> {
|
||||||
|
fromHiboutik(dto: SupplierHiboutikDto): SupplierCreateInput {
|
||||||
|
return {
|
||||||
|
hiboutikId: dto.supplier_id,
|
||||||
|
name: dto.supplier_name,
|
||||||
|
enabled: dto.supplier_enabled === 1,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
toHiboutik(): SupplierHiboutikDto {
|
||||||
|
throw new Error('Method not implemented.');
|
||||||
|
}
|
||||||
|
}
|
||||||
12
src/models/hiboutikDTO/brand.hiboutik.dto.ts
Normal file
12
src/models/hiboutikDTO/brand.hiboutik.dto.ts
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
import { z } from 'zod';
|
||||||
|
import { hiboutikId, hiboutikInt, hiboutikText } from './hiboutik.schema';
|
||||||
|
|
||||||
|
/** Brand as returned by Hiboutik `GET /brands` (only the fields used by the sync). */
|
||||||
|
export const brandHiboutikSchema = z.object({
|
||||||
|
brand_id: hiboutikId,
|
||||||
|
brand_name: hiboutikText,
|
||||||
|
/** 1 = enabled, 0 = disabled. */
|
||||||
|
brand_enabled: hiboutikInt,
|
||||||
|
});
|
||||||
|
|
||||||
|
export type BrandHiboutikDto = z.output<typeof brandHiboutikSchema>;
|
||||||
18
src/models/hiboutikDTO/category.hiboutik.dto.ts
Normal file
18
src/models/hiboutikDTO/category.hiboutik.dto.ts
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
import { z } from 'zod';
|
||||||
|
import { hiboutikId, hiboutikInt, hiboutikRef, hiboutikText } from './hiboutik.schema';
|
||||||
|
|
||||||
|
/** Category as returned by Hiboutik `GET /categories` (only the fields used by the sync). */
|
||||||
|
export const categoryHiboutikSchema = z.object({
|
||||||
|
category_id: hiboutikId,
|
||||||
|
category_name: hiboutikText,
|
||||||
|
/** Id of the parent category, 0 for a root category. */
|
||||||
|
category_id_parent: hiboutikRef,
|
||||||
|
/** Enabled in the POS: 1 = yes, 0 = no. */
|
||||||
|
category_enabled: hiboutikInt,
|
||||||
|
/** Displayed on the website: 1 = yes, 0 = no. */
|
||||||
|
category_enabled_www: hiboutikInt,
|
||||||
|
/** Display order among its siblings. */
|
||||||
|
category_position: hiboutikInt,
|
||||||
|
});
|
||||||
|
|
||||||
|
export type CategoryHiboutikDto = z.output<typeof categoryHiboutikSchema>;
|
||||||
65
src/models/hiboutikDTO/customer.hiboutik.dto.ts
Normal file
65
src/models/hiboutikDTO/customer.hiboutik.dto.ts
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
import { z } from 'zod';
|
||||||
|
import { hiboutikId, hiboutikInt, hiboutikOptionalList, hiboutikRef, hiboutikText } from './hiboutik.schema';
|
||||||
|
|
||||||
|
/** Customer summary as returned by Hiboutik `GET /customers`: only its id is used (no addresses nor sales). */
|
||||||
|
export const customerHiboutikSchema = z.object({
|
||||||
|
customers_id: hiboutikId,
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Address of a customer, embedded in the full customer. Name and phone can differ from the customer's. */
|
||||||
|
export const customerAddressHiboutikSchema = z.object({
|
||||||
|
address_id: hiboutikId,
|
||||||
|
first_name: hiboutikText,
|
||||||
|
last_name: hiboutikText,
|
||||||
|
phone: hiboutikText,
|
||||||
|
company: hiboutikText,
|
||||||
|
address: hiboutikText,
|
||||||
|
zip_code: hiboutikText,
|
||||||
|
city: hiboutikText,
|
||||||
|
state: hiboutikText,
|
||||||
|
country: hiboutikText,
|
||||||
|
customers_id: hiboutikRef,
|
||||||
|
/** 1 for the customer's default address. */
|
||||||
|
default: hiboutikInt,
|
||||||
|
other: hiboutikText,
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Address as returned by Hiboutik `GET /customers_addresses/:address_id`: the embedded address plus the company
|
||||||
|
* details. One API call per address, so only fetched for addresses with a company.
|
||||||
|
*/
|
||||||
|
export const customerAddressDetailsHiboutikSchema = customerAddressHiboutikSchema.extend({
|
||||||
|
tax_number: hiboutikText,
|
||||||
|
company_number: hiboutikText,
|
||||||
|
legal_status: hiboutikText,
|
||||||
|
/** French local time, "YYYY-MM-DD HH:mm:ss". */
|
||||||
|
updated_at: hiboutikText,
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Sale header embedded in the full customer: no sale lines, they come from `GET /sales/:sale_id`. */
|
||||||
|
export const customerSaleHiboutikSchema = z.object({
|
||||||
|
sale_id: hiboutikId,
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Full customer as returned by Hiboutik `GET /customer/:customers_id`, with its addresses and sales. */
|
||||||
|
export const fullCustomerHiboutikSchema = z.object({
|
||||||
|
customers_id: hiboutikId,
|
||||||
|
last_name: hiboutikText,
|
||||||
|
first_name: hiboutikText,
|
||||||
|
email: hiboutikText,
|
||||||
|
phone: hiboutikText,
|
||||||
|
/** "YYYY-MM-DD", "0000-00-00" when unknown. */
|
||||||
|
date_of_birth: hiboutikText,
|
||||||
|
/** French local time, "YYYY-MM-DD HH:mm:ss". */
|
||||||
|
updated_at: hiboutikText,
|
||||||
|
/** `undefined` when not an array: the stored addresses are then kept. */
|
||||||
|
addresses: hiboutikOptionalList(customerAddressHiboutikSchema),
|
||||||
|
/** `undefined` when not an array: the orders sync is then skipped. */
|
||||||
|
sales: hiboutikOptionalList(customerSaleHiboutikSchema),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type CustomerHiboutikDto = z.output<typeof customerHiboutikSchema>;
|
||||||
|
export type CustomerAddressHiboutikDto = z.output<typeof customerAddressHiboutikSchema>;
|
||||||
|
export type CustomerAddressDetailsHiboutikDto = z.output<typeof customerAddressDetailsHiboutikSchema>;
|
||||||
|
export type CustomerSaleHiboutikDto = z.output<typeof customerSaleHiboutikSchema>;
|
||||||
|
export type FullCustomerHiboutikDto = z.output<typeof fullCustomerHiboutikSchema>;
|
||||||
87
src/models/hiboutikDTO/hiboutik.schema.spec.ts
Normal file
87
src/models/hiboutikDTO/hiboutik.schema.spec.ts
Normal file
@@ -0,0 +1,87 @@
|
|||||||
|
import { parseHiboutik } from './hiboutik.schema';
|
||||||
|
import { customerAddressHiboutikSchema, fullCustomerHiboutikSchema } from './customer.hiboutik.dto';
|
||||||
|
import { productHiboutikSchema } from './product.hiboutik.dto';
|
||||||
|
import { saleHiboutikSchema } from './sale.hiboutik.dto';
|
||||||
|
import { stockHiboutikSchema } from './stock.hiboutik.dto';
|
||||||
|
|
||||||
|
const parse = <T extends Parameters<typeof parseHiboutik>[0]>(schema: T, data: unknown) => parseHiboutik(schema, data, '/x');
|
||||||
|
|
||||||
|
describe('Hiboutik schemas', () => {
|
||||||
|
const product = {
|
||||||
|
product_id: 1,
|
||||||
|
product_model: 'BT21 bottle',
|
||||||
|
product_barcode: '8435497280048',
|
||||||
|
product_brand: 1,
|
||||||
|
product_supplier: 2,
|
||||||
|
product_price: '13.99',
|
||||||
|
product_discount_price: '0.00',
|
||||||
|
product_category: 19,
|
||||||
|
product_display_www: 1,
|
||||||
|
product_arch: 0,
|
||||||
|
products_desc: '',
|
||||||
|
updated_at: '2026-06-28 17:02:55',
|
||||||
|
product_specific_rules: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
it('accepts ids, references and flags sent as strings', () => {
|
||||||
|
const parsed = parse(customerAddressHiboutikSchema, { address_id: ' 8 ', customers_id: '43', default: '0' });
|
||||||
|
expect(parsed.address_id).toBe(8);
|
||||||
|
expect(parsed.customers_id).toBe(43);
|
||||||
|
expect(parsed.default).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('turns empty references into 0 and empty text into ""', () => {
|
||||||
|
const parsed = parse(productHiboutikSchema, { ...product, product_brand: '', product_category: null, products_desc: null });
|
||||||
|
expect(parsed.product_brand).toBe(0);
|
||||||
|
expect(parsed.product_category).toBe(0);
|
||||||
|
expect(parsed.products_desc).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps numeric text (zip code) and prices as strings', () => {
|
||||||
|
expect(parse(customerAddressHiboutikSchema, { address_id: 1, zip_code: 75002 }).zip_code).toBe('75002');
|
||||||
|
expect(parse(productHiboutikSchema, { ...product, product_price: 13.5 }).product_price).toBe('13.5');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('defaults missing lists to [] and strips unknown fields', () => {
|
||||||
|
const parsed = parse(productHiboutikSchema, { ...product, product_specific_rules: '', product_supply_price: '7.49' });
|
||||||
|
expect(parsed.product_specific_rules).toEqual([]);
|
||||||
|
expect(parsed.product_size_details).toEqual([]);
|
||||||
|
expect(parsed).not.toHaveProperty('product_supply_price');
|
||||||
|
expect(parse(saleHiboutikSchema, { sale_id: 5, total: '0.00' }).line_items).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('leaves addresses and sales undefined when they are not arrays, so that stored data is kept', () => {
|
||||||
|
const parsed = parse(fullCustomerHiboutikSchema, { customers_id: 1, addresses: '', sales: { error: 'x' } });
|
||||||
|
expect(parsed.addresses).toBeUndefined();
|
||||||
|
expect(parsed.sales).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('parses stocks sent as decimal strings', () => {
|
||||||
|
expect(parse(stockHiboutikSchema, { product_id: '1', product_size: '0', stock_available: '3.000' })).toEqual({
|
||||||
|
product_id: 1,
|
||||||
|
product_size: 0,
|
||||||
|
stock_available: 3,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
['a missing id', { ...product, product_id: undefined }],
|
||||||
|
['a zero id', { ...product, product_id: 0 }],
|
||||||
|
['a non-numeric id', { ...product, product_id: 'abc' }],
|
||||||
|
['a negative reference', { ...product, product_brand: -1 }],
|
||||||
|
['an invalid price', { ...product, product_price: 'free' }],
|
||||||
|
['a list that is not an array', { ...product, product_size_details: { size_id: 1 } }],
|
||||||
|
])('rejects %s', (_, data) => {
|
||||||
|
expect(() => parse(productHiboutikSchema, data)).toThrow('Unexpected answer from Hiboutik /x');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('names the faulty fields, never their values', () => {
|
||||||
|
expect.assertions(2);
|
||||||
|
try {
|
||||||
|
parse(fullCustomerHiboutikSchema, { customers_id: 'jane@example.com', addresses: [{ address_id: 'Jane Doe' }] });
|
||||||
|
} catch (error) {
|
||||||
|
expect((error as Error).message).toMatch(/customers_id.*addresses\.0\.address_id/);
|
||||||
|
expect((error as Error).message).not.toMatch(/jane|Doe/i);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
58
src/models/hiboutikDTO/hiboutik.schema.ts
Normal file
58
src/models/hiboutikDTO/hiboutik.schema.ts
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Field types shared by the Hiboutik payload schemas. Hiboutik sends numbers either as JSON numbers or as numeric
|
||||||
|
* strings, and empty values as "", null or a missing key: the schemas normalize all that, so that the rest of the
|
||||||
|
* code gets real numbers and strings. Strict on what the sync relies on (identifiers, relations, prices),
|
||||||
|
* lenient (empty string) on free text.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const trimmed = (value: unknown) => (typeof value === 'string' ? value.trim() : value);
|
||||||
|
const emptyAsZero = (value: unknown) => {
|
||||||
|
const v = trimmed(value);
|
||||||
|
return v == null || v === '' ? 0 : v;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Identifier of a Hiboutik entity (join key): a positive integer. */
|
||||||
|
export const hiboutikId = z.preprocess(trimmed, z.coerce.number().int().positive());
|
||||||
|
|
||||||
|
/** Reference to another entity: its id, or 0 (also sent as "" or null) when none. */
|
||||||
|
export const hiboutikRef = z.preprocess(emptyAsZero, z.coerce.number().int().nonnegative());
|
||||||
|
|
||||||
|
/** Integer, e.g. a 1/0 flag, a position or a quantity (0 when empty). */
|
||||||
|
export const hiboutikInt = z.preprocess(emptyAsZero, z.coerce.number().int());
|
||||||
|
|
||||||
|
/** Number, e.g. a stock that may be sent as "3.000" (0 when empty). */
|
||||||
|
export const hiboutikNumber = z.preprocess(emptyAsZero, z.coerce.number());
|
||||||
|
|
||||||
|
/** Free text, "" when empty. */
|
||||||
|
export const hiboutikText = z.preprocess((value) => (value == null ? '' : typeof value === 'number' ? String(value) : value), z.string());
|
||||||
|
|
||||||
|
/** Required decimal kept as a string for Prisma `Decimal`, e.g. "13.99". */
|
||||||
|
export const hiboutikDecimal = z.preprocess(
|
||||||
|
(value) => (typeof value === 'number' ? String(value) : trimmed(value)),
|
||||||
|
z.string().regex(/^-?\d+(\.\d+)?$/, 'decimal expected'),
|
||||||
|
);
|
||||||
|
|
||||||
|
/** List that is empty when missing ("", null or no key). */
|
||||||
|
export const hiboutikList = <T extends z.ZodType>(item: T) =>
|
||||||
|
z.preprocess((value) => (value == null || value === '' ? [] : value), z.array(item));
|
||||||
|
|
||||||
|
/** List that is `undefined` when it is not an array: the caller then keeps the stored data instead of emptying it. */
|
||||||
|
export const hiboutikOptionalList = <T extends z.ZodType>(item: T) =>
|
||||||
|
z.preprocess((value) => (Array.isArray(value) ? value : undefined), z.array(item).optional());
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validates a Hiboutik payload. The error names the faulty fields (path and issue code) but never their values,
|
||||||
|
* which may be personal data.
|
||||||
|
*/
|
||||||
|
export function parseHiboutik<T extends z.ZodType>(schema: T, data: unknown, path: string): z.output<T> {
|
||||||
|
const result = schema.safeParse(data);
|
||||||
|
if (result.success) return result.data;
|
||||||
|
|
||||||
|
const issues = result.error.issues
|
||||||
|
.slice(0, 5)
|
||||||
|
.map((issue) => `${issue.path.join('.') || '(root)'} (${issue.code})`)
|
||||||
|
.join(', ');
|
||||||
|
throw new Error(`Unexpected answer from Hiboutik ${path}: invalid ${issues}`);
|
||||||
|
}
|
||||||
51
src/models/hiboutikDTO/product.hiboutik.dto.ts
Normal file
51
src/models/hiboutikDTO/product.hiboutik.dto.ts
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
import { z } from 'zod';
|
||||||
|
import { hiboutikDecimal, hiboutikId, hiboutikInt, hiboutikList, hiboutikRef, hiboutikText } from './hiboutik.schema';
|
||||||
|
|
||||||
|
/** Override of a product's values for one size. Prices are "0.00" (or missing) when not overridden. */
|
||||||
|
export const productSpecificRulesHiboutikSchema = z.object({
|
||||||
|
size_id: hiboutikRef,
|
||||||
|
product_price: hiboutikText,
|
||||||
|
product_discount_price: hiboutikText,
|
||||||
|
});
|
||||||
|
|
||||||
|
/** One size of a product (e.g. "S", "M"). */
|
||||||
|
export const productSizeDetailsHiboutikSchema = z.object({
|
||||||
|
size_id: hiboutikId,
|
||||||
|
size_name: hiboutikText,
|
||||||
|
/** Empty when the size has no barcode. */
|
||||||
|
barcode: hiboutikText,
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Product as returned by Hiboutik `GET /products`, archived products included (only the fields used by the sync). */
|
||||||
|
export const productHiboutikSchema = z.object({
|
||||||
|
product_id: hiboutikId,
|
||||||
|
/** Product name. */
|
||||||
|
product_model: hiboutikText,
|
||||||
|
/** Empty when the product has no barcode. */
|
||||||
|
product_barcode: hiboutikText,
|
||||||
|
/** Brand id, 0 when none. */
|
||||||
|
product_brand: hiboutikRef,
|
||||||
|
/** Supplier id, 0 when none. */
|
||||||
|
product_supplier: hiboutikRef,
|
||||||
|
/** e.g. "13.99". */
|
||||||
|
product_price: hiboutikDecimal,
|
||||||
|
/** "0.00" when the product has no discount. */
|
||||||
|
product_discount_price: hiboutikText,
|
||||||
|
/** Category id, 0 when none. */
|
||||||
|
product_category: hiboutikRef,
|
||||||
|
/** Displayed on the website: 1 = yes, 0 = no. */
|
||||||
|
product_display_www: hiboutikInt,
|
||||||
|
/** Archived: 1 = yes, 0 = no. */
|
||||||
|
product_arch: hiboutikInt,
|
||||||
|
products_desc: hiboutikText,
|
||||||
|
/** French local time, "YYYY-MM-DD HH:mm:ss". */
|
||||||
|
updated_at: hiboutikText,
|
||||||
|
/** Per-size overrides of the product's price, discount and barcode. */
|
||||||
|
product_specific_rules: hiboutikList(productSpecificRulesHiboutikSchema),
|
||||||
|
/** Sizes of the product; empty for a product without sizes. */
|
||||||
|
product_size_details: hiboutikList(productSizeDetailsHiboutikSchema),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type ProductSpecificRulesHiboutikDto = z.output<typeof productSpecificRulesHiboutikSchema>;
|
||||||
|
export type ProductSizeDetailsHiboutikDto = z.output<typeof productSizeDetailsHiboutikSchema>;
|
||||||
|
export type ProductHiboutikDto = z.output<typeof productHiboutikSchema>;
|
||||||
39
src/models/hiboutikDTO/sale.hiboutik.dto.ts
Normal file
39
src/models/hiboutikDTO/sale.hiboutik.dto.ts
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
import { z } from 'zod';
|
||||||
|
import { hiboutikDecimal, hiboutikId, hiboutikInt, hiboutikList, hiboutikRef, hiboutikText } from './hiboutik.schema';
|
||||||
|
|
||||||
|
/** Line of a sale: a snapshot of the product at sale time. */
|
||||||
|
export const saleLineHiboutikSchema = z.object({
|
||||||
|
product_id: hiboutikRef,
|
||||||
|
/** Hiboutik size id, 0 for a product without sizes. */
|
||||||
|
product_size: hiboutikRef,
|
||||||
|
/** Negative for a returned item. */
|
||||||
|
quantity: hiboutikInt,
|
||||||
|
product_model: hiboutikText,
|
||||||
|
product_barcode: hiboutikText,
|
||||||
|
/** Size name, empty for a product without sizes. */
|
||||||
|
size_name: hiboutikText,
|
||||||
|
/** Unit price actually paid, discount deducted, taxes included. */
|
||||||
|
item_unit_gross: hiboutikDecimal,
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sale as returned by Hiboutik `GET /sales/:sale_id`, with its lines. Only the fields used by the sync: the payload
|
||||||
|
* also carries many computed copies (dates split in parts, totals by tax, customer and store details...).
|
||||||
|
*/
|
||||||
|
export const saleHiboutikSchema = z.object({
|
||||||
|
sale_id: hiboutikId,
|
||||||
|
/** French local time, "YYYY-MM-DD HH:mm:ss". */
|
||||||
|
created_at: hiboutikText,
|
||||||
|
/** French local time, "0000-00-00 00:00:00" while the sale is not completed. */
|
||||||
|
completed_at: hiboutikText,
|
||||||
|
/** 0 for an anonymous sale. */
|
||||||
|
customer_id: hiboutikRef,
|
||||||
|
/** Taxes included. */
|
||||||
|
total: hiboutikDecimal,
|
||||||
|
/** 1 for a quotation. */
|
||||||
|
quotation: hiboutikInt,
|
||||||
|
line_items: hiboutikList(saleLineHiboutikSchema),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type SaleLineHiboutikDto = z.output<typeof saleLineHiboutikSchema>;
|
||||||
|
export type SaleHiboutikDto = z.output<typeof saleHiboutikSchema>;
|
||||||
13
src/models/hiboutikDTO/stock.hiboutik.dto.ts
Normal file
13
src/models/hiboutikDTO/stock.hiboutik.dto.ts
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
import { z } from 'zod';
|
||||||
|
import { hiboutikId, hiboutikNumber, hiboutikRef } from './hiboutik.schema';
|
||||||
|
|
||||||
|
/** Available stock of one product size, as returned by Hiboutik `GET /stock_available/all_wh` (all warehouses). */
|
||||||
|
export const stockHiboutikSchema = z.object({
|
||||||
|
product_id: hiboutikId,
|
||||||
|
/** Size id, 0 for a product without sizes. */
|
||||||
|
product_size: hiboutikRef,
|
||||||
|
/** Sent as a decimal string, e.g. "3". Stays at 0 while stock management is disabled in Hiboutik. */
|
||||||
|
stock_available: hiboutikNumber,
|
||||||
|
});
|
||||||
|
|
||||||
|
export type StockHiboutikDto = z.output<typeof stockHiboutikSchema>;
|
||||||
12
src/models/hiboutikDTO/supplier.hiboutik.dto.ts
Normal file
12
src/models/hiboutikDTO/supplier.hiboutik.dto.ts
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
import { z } from 'zod';
|
||||||
|
import { hiboutikId, hiboutikInt, hiboutikText } from './hiboutik.schema';
|
||||||
|
|
||||||
|
/** Supplier as returned by Hiboutik `GET /suppliers` (only the fields used by the sync). */
|
||||||
|
export const supplierHiboutikSchema = z.object({
|
||||||
|
supplier_id: hiboutikId,
|
||||||
|
supplier_name: hiboutikText,
|
||||||
|
/** 1 = enabled, 0 = disabled. */
|
||||||
|
supplier_enabled: hiboutikInt,
|
||||||
|
});
|
||||||
|
|
||||||
|
export type SupplierHiboutikDto = z.output<typeof supplierHiboutikSchema>;
|
||||||
9
src/models/orderStatus.ts
Normal file
9
src/models/orderStatus.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
/** Values of `Order.status`. */
|
||||||
|
export const OrderStatus = {
|
||||||
|
/** Hiboutik sale not completed (cart in progress, awaiting payment...). */
|
||||||
|
PENDING: 'PENDING',
|
||||||
|
/** Hiboutik sale completed: it no longer changes, so the sync does not fetch it again. */
|
||||||
|
COMPLETED: 'COMPLETED',
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export type OrderStatus = (typeof OrderStatus)[keyof typeof OrderStatus];
|
||||||
34
src/services/hiboutik/brand.hiboutik.service.ts
Normal file
34
src/services/hiboutik/brand.hiboutik.service.ts
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
import { Injectable, Logger } from '@nestjs/common';
|
||||||
|
import { BrandHiboutikRepository } from '../../hiboutik/brand.hiboutik.repository';
|
||||||
|
import { BrandDatabaseRepository } from '../../database/brand.database.repository';
|
||||||
|
import { BrandConverter } from '../../models/converter/brand.converter';
|
||||||
|
import { forEachSafely } from '../../utils/sync';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class BrandHiboutikService {
|
||||||
|
private readonly logger = new Logger('BrandHiboutikService');
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly brandHiboutikRepository: BrandHiboutikRepository,
|
||||||
|
private readonly brandDatabaseRepository: BrandDatabaseRepository,
|
||||||
|
private readonly brandConverter: BrandConverter,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/** Mirrors Hiboutik brands: upserts each of them, then deletes the brands missing from Hiboutik. */
|
||||||
|
async syncBrands() {
|
||||||
|
const hiboutikBrands = await this.brandHiboutikRepository.getBrands();
|
||||||
|
// One upsert per brand: an invalid brand must not prevent the others from being saved
|
||||||
|
const nbFailed = await forEachSafely(
|
||||||
|
this.brandConverter.fromHiboutikList(hiboutikBrands),
|
||||||
|
(brand) => this.brandDatabaseRepository.upsert(brand),
|
||||||
|
this.logger,
|
||||||
|
(brand) => `Hiboutik brand ${brand.hiboutikId}`,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Hiboutik is trusted: a successful (2xx) answer, even an empty list, is the truth. An HTTP error throws before this point.
|
||||||
|
const nbDeleted = await this.brandDatabaseRepository.deleteMissing(hiboutikBrands.map((dto) => dto.brand_id));
|
||||||
|
this.logger.log(
|
||||||
|
`Brands sync ended: ${hiboutikBrands.length - nbFailed}/${hiboutikBrands.length} synced, ${nbFailed} failed, ${nbDeleted} deleted.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
96
src/services/hiboutik/category.hiboutik.service.spec.ts
Normal file
96
src/services/hiboutik/category.hiboutik.service.spec.ts
Normal file
@@ -0,0 +1,96 @@
|
|||||||
|
import { Logger } from '@nestjs/common';
|
||||||
|
import { CategoryHiboutikService } from './category.hiboutik.service';
|
||||||
|
import { CategoryConverter } from '../../models/converter/category.converter';
|
||||||
|
import { CategoryHiboutikDto } from '../../models/hiboutikDTO/category.hiboutik.dto';
|
||||||
|
|
||||||
|
const hiboutikCategory = (id: number, parentId: number, overrides: Partial<CategoryHiboutikDto> = {}): CategoryHiboutikDto => ({
|
||||||
|
category_id: id,
|
||||||
|
category_name: `Category ${id}`,
|
||||||
|
category_id_parent: parentId,
|
||||||
|
category_enabled: 1,
|
||||||
|
category_enabled_www: 0,
|
||||||
|
category_position: 3,
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('CategoryHiboutikService', () => {
|
||||||
|
const categoryHiboutikRepository = { getCategories: jest.fn() };
|
||||||
|
const categoryDatabaseRepository = { upsert: jest.fn(), setParent: jest.fn(), deleteMissing: jest.fn() };
|
||||||
|
let service: CategoryHiboutikService;
|
||||||
|
let calls: string[];
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
jest.spyOn(Logger.prototype, 'log').mockImplementation(() => undefined);
|
||||||
|
jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => undefined);
|
||||||
|
jest.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
jest.clearAllMocks();
|
||||||
|
calls = [];
|
||||||
|
categoryDatabaseRepository.upsert.mockImplementation((category: { hiboutikId: number }) => {
|
||||||
|
calls.push(`upsert ${category.hiboutikId}`);
|
||||||
|
return Promise.resolve({});
|
||||||
|
});
|
||||||
|
categoryDatabaseRepository.setParent.mockImplementation((id: number) => {
|
||||||
|
calls.push(`parent ${id}`);
|
||||||
|
return Promise.resolve({});
|
||||||
|
});
|
||||||
|
categoryDatabaseRepository.deleteMissing.mockResolvedValue(0);
|
||||||
|
service = new CategoryHiboutikService(
|
||||||
|
categoryHiboutikRepository as never,
|
||||||
|
categoryDatabaseRepository as never,
|
||||||
|
new CategoryConverter(),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('stores position and web visibility', async () => {
|
||||||
|
categoryHiboutikRepository.getCategories.mockResolvedValue([hiboutikCategory(1, 0)]);
|
||||||
|
|
||||||
|
await service.syncCategories();
|
||||||
|
|
||||||
|
expect(categoryDatabaseRepository.upsert).toHaveBeenCalledWith({
|
||||||
|
hiboutikId: 1,
|
||||||
|
name: 'Category 1',
|
||||||
|
enabled: true,
|
||||||
|
position: 3,
|
||||||
|
webEnabled: false,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('links parents once every category is saved, a child being listed before its parent', async () => {
|
||||||
|
categoryHiboutikRepository.getCategories.mockResolvedValue([hiboutikCategory(2, 3), hiboutikCategory(3, 0)]);
|
||||||
|
|
||||||
|
await service.syncCategories();
|
||||||
|
|
||||||
|
expect(calls).toEqual(['upsert 2', 'upsert 3', 'parent 2', 'parent 3']);
|
||||||
|
expect(categoryDatabaseRepository.setParent).toHaveBeenCalledWith(2, 3);
|
||||||
|
expect(categoryDatabaseRepository.setParent).toHaveBeenCalledWith(3, null);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps syncing the other categories when one fails, then deletes the missing ones', async () => {
|
||||||
|
categoryHiboutikRepository.getCategories.mockResolvedValue([hiboutikCategory(1, 0), hiboutikCategory(2, 0)]);
|
||||||
|
categoryDatabaseRepository.upsert.mockRejectedValueOnce(new Error('boom'));
|
||||||
|
|
||||||
|
await expect(service.syncCategories()).resolves.toBeUndefined();
|
||||||
|
|
||||||
|
expect(categoryDatabaseRepository.upsert).toHaveBeenCalledTimes(2);
|
||||||
|
expect(categoryDatabaseRepository.deleteMissing).toHaveBeenCalledWith([1, 2]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('deletes every category when Hiboutik answers with an empty list', async () => {
|
||||||
|
categoryHiboutikRepository.getCategories.mockResolvedValue([]);
|
||||||
|
|
||||||
|
await service.syncCategories();
|
||||||
|
|
||||||
|
expect(categoryDatabaseRepository.deleteMissing).toHaveBeenCalledWith([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('deletes nothing when the Hiboutik call fails', async () => {
|
||||||
|
categoryHiboutikRepository.getCategories.mockRejectedValue(new Error('Request failed with status code 500'));
|
||||||
|
|
||||||
|
await expect(service.syncCategories()).rejects.toThrow('500');
|
||||||
|
|
||||||
|
expect(categoryDatabaseRepository.deleteMissing).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
47
src/services/hiboutik/category.hiboutik.service.ts
Normal file
47
src/services/hiboutik/category.hiboutik.service.ts
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
import { Injectable, Logger } from '@nestjs/common';
|
||||||
|
import { CategoryHiboutikRepository } from '../../hiboutik/category.hiboutik.repository';
|
||||||
|
import { CategoryDatabaseRepository } from '../../database/category.database.repository';
|
||||||
|
import { CategoryConverter } from '../../models/converter/category.converter';
|
||||||
|
import { forEachSafely } from '../../utils/sync';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class CategoryHiboutikService {
|
||||||
|
private readonly logger = new Logger('CategoryHiboutikService');
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly categoryHiboutikRepository: CategoryHiboutikRepository,
|
||||||
|
private readonly categoryDatabaseRepository: CategoryDatabaseRepository,
|
||||||
|
private readonly categoryConverter: CategoryConverter,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mirrors Hiboutik categories and their tree: upserts each of them, links them to their parent,
|
||||||
|
* then deletes the categories missing from Hiboutik.
|
||||||
|
*/
|
||||||
|
async syncCategories() {
|
||||||
|
const hiboutikCategories = await this.categoryHiboutikRepository.getCategories();
|
||||||
|
|
||||||
|
// Pass 1: categories themselves. One upsert per category: an invalid category must not prevent the others from being saved
|
||||||
|
const nbFailed = await forEachSafely(
|
||||||
|
this.categoryConverter.fromHiboutikList(hiboutikCategories),
|
||||||
|
(category) => this.categoryDatabaseRepository.upsert(category),
|
||||||
|
this.logger,
|
||||||
|
(category) => `Hiboutik category ${category.hiboutikId}`,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Pass 2: parent links, once every category exists (a child can come before its parent in Hiboutik's list)
|
||||||
|
const nbParentsFailed = await forEachSafely(
|
||||||
|
hiboutikCategories,
|
||||||
|
(dto) => this.categoryDatabaseRepository.setParent(dto.category_id, dto.category_id_parent || null),
|
||||||
|
this.logger,
|
||||||
|
(dto) => `parent of Hiboutik category ${dto.category_id}`,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Hiboutik is trusted: a successful (2xx) answer, even an empty list, is the truth. An HTTP error throws before this point.
|
||||||
|
const nbDeleted = await this.categoryDatabaseRepository.deleteMissing(hiboutikCategories.map((dto) => dto.category_id));
|
||||||
|
this.logger.log(
|
||||||
|
`Categories sync ended: ${hiboutikCategories.length - nbFailed}/${hiboutikCategories.length} synced, ${nbFailed} failed, ` +
|
||||||
|
`${nbParentsFailed} parent links failed, ${nbDeleted} deleted.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
258
src/services/hiboutik/customer.hiboutik.service.spec.ts
Normal file
258
src/services/hiboutik/customer.hiboutik.service.spec.ts
Normal file
@@ -0,0 +1,258 @@
|
|||||||
|
import { Logger } from '@nestjs/common';
|
||||||
|
import { CustomerHiboutikService } from './customer.hiboutik.service';
|
||||||
|
|
||||||
|
describe('CustomerHiboutikService', () => {
|
||||||
|
const customerHiboutikRepository = {
|
||||||
|
getCustomers: jest.fn(),
|
||||||
|
getCustomerById: jest.fn(),
|
||||||
|
findCustomerById: jest.fn(),
|
||||||
|
getAddressById: jest.fn(),
|
||||||
|
};
|
||||||
|
const customerDatabaseRepository = { upsert: jest.fn(), getAllHiboutikIds: jest.fn(), deleteByHiboutikIds: jest.fn() };
|
||||||
|
const customerConverter = { fromHiboutik: jest.fn() };
|
||||||
|
const customerAddressDatabaseRepository = { upsert: jest.fn(), deleteMissing: jest.fn() };
|
||||||
|
const customerAddressConverter = { fromHiboutik: jest.fn((dto: unknown) => dto) };
|
||||||
|
const saleHiboutikRepository = { getSaleById: jest.fn() };
|
||||||
|
const orderDatabaseRepository = { upsert: jest.fn(), getCompletedSaleIds: jest.fn() };
|
||||||
|
const orderConverter = { fromHiboutik: jest.fn((dto: unknown) => dto) };
|
||||||
|
let service: CustomerHiboutikService;
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
jest.spyOn(Logger.prototype, 'log').mockImplementation(() => undefined);
|
||||||
|
jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => undefined);
|
||||||
|
jest.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
jest.clearAllMocks();
|
||||||
|
customerHiboutikRepository.getCustomers.mockResolvedValue([]);
|
||||||
|
customerHiboutikRepository.getCustomerById.mockResolvedValue({ customers_id: 1, addresses: [] });
|
||||||
|
customerDatabaseRepository.upsert.mockResolvedValue({ id: 'customer-uuid' });
|
||||||
|
customerDatabaseRepository.getAllHiboutikIds.mockResolvedValue([]);
|
||||||
|
customerDatabaseRepository.deleteByHiboutikIds.mockImplementation((ids: number[]) => Promise.resolve(ids.length));
|
||||||
|
customerHiboutikRepository.findCustomerById.mockResolvedValue(null);
|
||||||
|
customerAddressDatabaseRepository.deleteMissing.mockResolvedValue(0);
|
||||||
|
orderDatabaseRepository.getCompletedSaleIds.mockResolvedValue(new Set());
|
||||||
|
saleHiboutikRepository.getSaleById.mockImplementation((id: number) => Promise.resolve({ sale_id: id, quotation: 0 }));
|
||||||
|
service = new CustomerHiboutikService(
|
||||||
|
customerHiboutikRepository as never,
|
||||||
|
customerDatabaseRepository as never,
|
||||||
|
customerConverter as never,
|
||||||
|
customerAddressDatabaseRepository as never,
|
||||||
|
customerAddressConverter as never,
|
||||||
|
saleHiboutikRepository as never,
|
||||||
|
orderDatabaseRepository as never,
|
||||||
|
orderConverter as never,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('deletions', () => {
|
||||||
|
it('deletes the stored customers missing from the list once Hiboutik confirms they no longer exist', async () => {
|
||||||
|
customerHiboutikRepository.getCustomers.mockResolvedValue([{ customers_id: 1 }, { customers_id: 2 }]);
|
||||||
|
customerDatabaseRepository.getAllHiboutikIds.mockResolvedValue([1, 2, 3, 4]);
|
||||||
|
|
||||||
|
await service.syncCustomers();
|
||||||
|
|
||||||
|
expect(customerHiboutikRepository.findCustomerById.mock.calls).toEqual([[3], [4]]);
|
||||||
|
expect(customerDatabaseRepository.deleteByHiboutikIds).toHaveBeenCalledWith([3, 4]);
|
||||||
|
expect(customerDatabaseRepository.upsert).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps and syncs a customer missing from the list (page shift) that still exists in Hiboutik', async () => {
|
||||||
|
customerHiboutikRepository.getCustomers.mockResolvedValue([{ customers_id: 1 }]);
|
||||||
|
customerDatabaseRepository.getAllHiboutikIds.mockResolvedValue([1, 2]);
|
||||||
|
customerHiboutikRepository.findCustomerById.mockResolvedValue({ customers_id: 2 });
|
||||||
|
|
||||||
|
await service.syncCustomers();
|
||||||
|
|
||||||
|
expect(customerDatabaseRepository.deleteByHiboutikIds).toHaveBeenCalledWith([]);
|
||||||
|
expect(customerHiboutikRepository.getCustomerById.mock.calls).toEqual([[1], [2]]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps a customer whose check fails', async () => {
|
||||||
|
customerDatabaseRepository.getAllHiboutikIds.mockResolvedValue([3, 4]);
|
||||||
|
customerHiboutikRepository.findCustomerById.mockRejectedValueOnce(new Error('Request failed with status code 500'));
|
||||||
|
|
||||||
|
await service.syncCustomers();
|
||||||
|
|
||||||
|
expect(customerDatabaseRepository.deleteByHiboutikIds).toHaveBeenCalledWith([4]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('deletes every confirmed customer when Hiboutik answers with an empty list', async () => {
|
||||||
|
customerDatabaseRepository.getAllHiboutikIds.mockResolvedValue([1, 2]);
|
||||||
|
|
||||||
|
await service.syncCustomers();
|
||||||
|
|
||||||
|
expect(customerDatabaseRepository.deleteByHiboutikIds).toHaveBeenCalledWith([1, 2]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('deletes nothing when the Hiboutik list call fails', async () => {
|
||||||
|
customerHiboutikRepository.getCustomers.mockRejectedValue(new Error('Request failed with status code 500'));
|
||||||
|
|
||||||
|
await expect(service.syncCustomers()).rejects.toThrow('500');
|
||||||
|
|
||||||
|
expect(customerDatabaseRepository.deleteByHiboutikIds).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('syncs once a customer listed twice', async () => {
|
||||||
|
customerHiboutikRepository.getCustomers.mockResolvedValue([{ customers_id: 1 }, { customers_id: 1 }]);
|
||||||
|
|
||||||
|
await service.syncCustomers();
|
||||||
|
|
||||||
|
expect(customerHiboutikRepository.getCustomerById).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps syncing the other customers when one fails', async () => {
|
||||||
|
customerHiboutikRepository.getCustomers.mockResolvedValue([{ customers_id: 1 }, { customers_id: 2 }]);
|
||||||
|
customerHiboutikRepository.getCustomerById.mockRejectedValueOnce(new Error('boom'));
|
||||||
|
|
||||||
|
await expect(service.syncCustomers()).resolves.toBeUndefined();
|
||||||
|
|
||||||
|
expect(customerDatabaseRepository.upsert).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('addresses', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
customerHiboutikRepository.getCustomers.mockResolvedValue([{ customers_id: 1 }]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('deletes the missing addresses of the customer, then upserts the others linked to it', async () => {
|
||||||
|
customerHiboutikRepository.getCustomerById.mockResolvedValue({
|
||||||
|
customers_id: 1,
|
||||||
|
addresses: [
|
||||||
|
{ address_id: 10, customers_id: 1, company: '' },
|
||||||
|
{ address_id: 11, customers_id: 999, company: '' },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
await service.syncCustomers();
|
||||||
|
|
||||||
|
expect(customerAddressDatabaseRepository.deleteMissing).toHaveBeenCalledWith('customer-uuid', [10, 11]);
|
||||||
|
expect(customerAddressDatabaseRepository.upsert).toHaveBeenCalledTimes(2);
|
||||||
|
expect(customerAddressConverter.fromHiboutik).toHaveBeenLastCalledWith({ address_id: 11, customers_id: 1, company: '' });
|
||||||
|
expect(customerAddressDatabaseRepository.deleteMissing.mock.invocationCallOrder[0]).toBeLessThan(
|
||||||
|
customerAddressDatabaseRepository.upsert.mock.invocationCallOrder[0],
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('deletes all the addresses of a customer that has none left', async () => {
|
||||||
|
await service.syncCustomers();
|
||||||
|
|
||||||
|
expect(customerAddressDatabaseRepository.deleteMissing).toHaveBeenCalledWith('customer-uuid', []);
|
||||||
|
expect(customerAddressDatabaseRepository.upsert).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the stored addresses when the payload has no addresses array', async () => {
|
||||||
|
customerHiboutikRepository.getCustomerById.mockResolvedValue({ customers_id: 1 });
|
||||||
|
|
||||||
|
await service.syncCustomers();
|
||||||
|
|
||||||
|
expect(customerAddressDatabaseRepository.deleteMissing).not.toHaveBeenCalled();
|
||||||
|
expect(customerAddressDatabaseRepository.upsert).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fetches the company details of addresses with a company only', async () => {
|
||||||
|
customerHiboutikRepository.getCustomerById.mockResolvedValue({
|
||||||
|
customers_id: 1,
|
||||||
|
addresses: [
|
||||||
|
{ address_id: 10, company: 'ACME' },
|
||||||
|
{ address_id: 11, company: ' ' },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
customerHiboutikRepository.getAddressById.mockResolvedValue({
|
||||||
|
address_id: 10,
|
||||||
|
tax_number: 'FR123',
|
||||||
|
company_number: '123',
|
||||||
|
legal_status: 'SAS',
|
||||||
|
updated_at: '2026-11-01 10:00:00',
|
||||||
|
});
|
||||||
|
|
||||||
|
await service.syncCustomers();
|
||||||
|
|
||||||
|
expect(customerHiboutikRepository.getAddressById).toHaveBeenCalledTimes(1);
|
||||||
|
expect(customerHiboutikRepository.getAddressById).toHaveBeenCalledWith(10);
|
||||||
|
expect(customerAddressConverter.fromHiboutik).toHaveBeenCalledWith({
|
||||||
|
address_id: 10,
|
||||||
|
company: 'ACME',
|
||||||
|
customers_id: 1,
|
||||||
|
tax_number: 'FR123',
|
||||||
|
company_number: '123',
|
||||||
|
legal_status: 'SAS',
|
||||||
|
updated_at: '2026-11-01 10:00:00',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('still syncs an address whose company details cannot be fetched', async () => {
|
||||||
|
customerHiboutikRepository.getCustomerById.mockResolvedValue({ customers_id: 1, addresses: [{ address_id: 10, company: 'ACME' }] });
|
||||||
|
customerHiboutikRepository.getAddressById.mockRejectedValue(new Error('boom'));
|
||||||
|
|
||||||
|
await service.syncCustomers();
|
||||||
|
|
||||||
|
expect(customerAddressConverter.fromHiboutik).toHaveBeenCalledWith({ address_id: 10, company: 'ACME', customers_id: 1 });
|
||||||
|
expect(customerAddressDatabaseRepository.upsert).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps syncing the other addresses when one fails', async () => {
|
||||||
|
customerHiboutikRepository.getCustomerById.mockResolvedValue({
|
||||||
|
customers_id: 1,
|
||||||
|
addresses: [
|
||||||
|
{ address_id: 10, company: '' },
|
||||||
|
{ address_id: 11, company: '' },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
customerAddressDatabaseRepository.upsert.mockRejectedValueOnce(new Error('boom'));
|
||||||
|
|
||||||
|
await service.syncCustomers();
|
||||||
|
|
||||||
|
expect(customerAddressDatabaseRepository.upsert).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('orders', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
customerHiboutikRepository.getCustomers.mockResolvedValue([{ customers_id: 1 }]);
|
||||||
|
customerHiboutikRepository.getCustomerById.mockResolvedValue({
|
||||||
|
customers_id: 1,
|
||||||
|
addresses: [],
|
||||||
|
sales: [{ sale_id: 5 }, { sale_id: 6 }, { sale_id: 7 }],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fetches and upserts the sales not yet stored as completed, linked to the customer', async () => {
|
||||||
|
orderDatabaseRepository.getCompletedSaleIds.mockResolvedValue(new Set([6]));
|
||||||
|
|
||||||
|
await service.syncCustomers();
|
||||||
|
|
||||||
|
expect(orderDatabaseRepository.getCompletedSaleIds).toHaveBeenCalledWith(1, [5, 6, 7]);
|
||||||
|
expect(saleHiboutikRepository.getSaleById.mock.calls.map((call: unknown[]) => call[0])).toEqual([5, 7]);
|
||||||
|
expect(orderDatabaseRepository.upsert).toHaveBeenCalledTimes(2);
|
||||||
|
expect(orderConverter.fromHiboutik).toHaveBeenCalledWith({ sale_id: 5, quotation: 0, customer_id: 1 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ignores quotations', async () => {
|
||||||
|
saleHiboutikRepository.getSaleById.mockResolvedValueOnce({ sale_id: 5, quotation: 1 });
|
||||||
|
|
||||||
|
await service.syncCustomers();
|
||||||
|
|
||||||
|
expect(orderDatabaseRepository.upsert).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps syncing the other sales when one fails', async () => {
|
||||||
|
saleHiboutikRepository.getSaleById.mockRejectedValueOnce(new Error('boom'));
|
||||||
|
|
||||||
|
await service.syncCustomers();
|
||||||
|
|
||||||
|
expect(orderDatabaseRepository.upsert).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('skips orders when the payload has no sales array', async () => {
|
||||||
|
customerHiboutikRepository.getCustomerById.mockResolvedValue({ customers_id: 1, addresses: [] });
|
||||||
|
|
||||||
|
await service.syncCustomers();
|
||||||
|
|
||||||
|
expect(saleHiboutikRepository.getSaleById).not.toHaveBeenCalled();
|
||||||
|
expect(orderDatabaseRepository.upsert).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
179
src/services/hiboutik/customer.hiboutik.service.ts
Normal file
179
src/services/hiboutik/customer.hiboutik.service.ts
Normal file
@@ -0,0 +1,179 @@
|
|||||||
|
import { Injectable, Logger } from '@nestjs/common';
|
||||||
|
import { CustomerHiboutikRepository } from '../../hiboutik/customer.hiboutik.repository';
|
||||||
|
import { CustomerDatabaseRepository } from '../../database/customer.database.repository';
|
||||||
|
import { CustomerConverter } from '../../models/converter/customer.converter';
|
||||||
|
import { CustomerAddressDatabaseRepository } from '../../database/customerAddress.database.repository';
|
||||||
|
import { CustomerAddressConverter } from '../../models/converter/customerAddress.converter';
|
||||||
|
import {
|
||||||
|
CustomerAddressDetailsHiboutikDto,
|
||||||
|
CustomerAddressHiboutikDto,
|
||||||
|
FullCustomerHiboutikDto,
|
||||||
|
} from '../../models/hiboutikDTO/customer.hiboutik.dto';
|
||||||
|
import { forEachSafely } from '../../utils/sync';
|
||||||
|
import { SaleHiboutikRepository } from '../../hiboutik/sale.hiboutik.repository';
|
||||||
|
import { OrderDatabaseRepository } from '../../database/order.database.repository';
|
||||||
|
import { OrderConverter } from '../../models/converter/order.converter';
|
||||||
|
import { rethrowIfRateLimited } from '../../hiboutik/hiboutik.client';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class CustomerHiboutikService {
|
||||||
|
private readonly logger = new Logger('CustomerHiboutikService');
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly customerHiboutikRepository: CustomerHiboutikRepository,
|
||||||
|
private readonly customerDatabaseRepository: CustomerDatabaseRepository,
|
||||||
|
private readonly customerConverter: CustomerConverter,
|
||||||
|
private readonly customerAddressDatabaseRepository: CustomerAddressDatabaseRepository,
|
||||||
|
private readonly customerAddressConverter: CustomerAddressConverter,
|
||||||
|
private readonly saleHiboutikRepository: SaleHiboutikRepository,
|
||||||
|
private readonly orderDatabaseRepository: OrderDatabaseRepository,
|
||||||
|
private readonly orderConverter: OrderConverter,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mirrors Hiboutik customers: deletes the customers Hiboutik confirms as deleted, then fetches and upserts each of
|
||||||
|
* them with its addresses and orders (one API call per customer, as the list endpoint lacks addresses and sales, plus
|
||||||
|
* one per sale not yet stored as completed).
|
||||||
|
*/
|
||||||
|
async syncCustomers() {
|
||||||
|
const hiboutikCustomers = await this.customerHiboutikRepository.getCustomers();
|
||||||
|
// A page shift can list a customer twice: sync it once
|
||||||
|
const listedIds = [...new Set(hiboutikCustomers.map((dto) => dto.customers_id))];
|
||||||
|
|
||||||
|
const { nbDeleted, unlistedIds } = await this.deleteMissingCustomers(listedIds);
|
||||||
|
const customerIds = [...listedIds, ...unlistedIds];
|
||||||
|
|
||||||
|
let nbFailed = 0;
|
||||||
|
let nbFailedAddresses = 0;
|
||||||
|
let nbFailedOrders = 0;
|
||||||
|
for (const customerId of customerIds) {
|
||||||
|
try {
|
||||||
|
const hiboutikFullCustomer = await this.customerHiboutikRepository.getCustomerById(customerId);
|
||||||
|
const customer = await this.customerDatabaseRepository.upsert(this.customerConverter.fromHiboutik(hiboutikFullCustomer));
|
||||||
|
nbFailedAddresses += await this.syncAddresses(customer.id, hiboutikFullCustomer);
|
||||||
|
nbFailedOrders += await this.syncOrders(hiboutikFullCustomer);
|
||||||
|
} catch (error) {
|
||||||
|
rethrowIfRateLimited(error);
|
||||||
|
nbFailed++;
|
||||||
|
this.logger.error(`Failed to sync Hiboutik customer ${customerId}`, (error as Error)?.stack);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.logger.log(
|
||||||
|
`Customers sync ended: ${customerIds.length - nbFailed}/${customerIds.length} synced, ${nbFailed} failed, ${nbDeleted} deleted, ` +
|
||||||
|
`${unlistedIds.length} missing from the list but still in Hiboutik, ${nbFailedAddresses} addresses failed, ${nbFailedOrders} orders failed.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Deletes the stored customers missing from the Hiboutik list, once Hiboutik confirms one by one that they no longer
|
||||||
|
* exist. The list is paginated: a customer created or deleted in Hiboutik while it is walked shifts the following
|
||||||
|
* pages, so a customer can be missing from it without being deleted. Hiboutik is trusted: a 404 or an empty 2xx
|
||||||
|
* answer is a confirmation. A customer whose check fails is kept.
|
||||||
|
* @returns the number of deleted customers, and the ids of the customers that still exist although not listed.
|
||||||
|
*/
|
||||||
|
private async deleteMissingCustomers(listedIds: number[]): Promise<{ nbDeleted: number; unlistedIds: number[] }> {
|
||||||
|
const listed = new Set(listedIds);
|
||||||
|
const missingIds = (await this.customerDatabaseRepository.getAllHiboutikIds()).filter((id) => !listed.has(id));
|
||||||
|
|
||||||
|
const deletedIds: number[] = [];
|
||||||
|
const unlistedIds: number[] = [];
|
||||||
|
for (const id of missingIds) {
|
||||||
|
try {
|
||||||
|
const customer = await this.customerHiboutikRepository.findCustomerById(id);
|
||||||
|
(customer ? unlistedIds : deletedIds).push(id);
|
||||||
|
} catch (error) {
|
||||||
|
rethrowIfRateLimited(error);
|
||||||
|
this.logger.warn(`Failed to check whether Hiboutik customer ${id} still exists, it is kept: ${(error as Error)?.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const nbDeleted = await this.customerDatabaseRepository.deleteByHiboutikIds(deletedIds);
|
||||||
|
return { nbDeleted, unlistedIds };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mirrors the addresses embedded in a full Hiboutik customer: deletes the ones missing from Hiboutik, then upserts
|
||||||
|
* each of them (a failing address is logged and skipped).
|
||||||
|
* @returns the number of failed addresses.
|
||||||
|
*/
|
||||||
|
private async syncAddresses(customerId: string, hiboutikCustomer: FullCustomerHiboutikDto): Promise<number> {
|
||||||
|
// A missing array means an unexpected payload, not a customer without addresses: keep the stored ones
|
||||||
|
if (!Array.isArray(hiboutikCustomer.addresses)) {
|
||||||
|
this.logger.warn(`Hiboutik customer ${hiboutikCustomer.customers_id} has no addresses array: addresses sync skipped.`);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.customerAddressDatabaseRepository.deleteMissing(
|
||||||
|
customerId,
|
||||||
|
hiboutikCustomer.addresses.map((dto) => dto.address_id),
|
||||||
|
);
|
||||||
|
return forEachSafely(
|
||||||
|
hiboutikCustomer.addresses,
|
||||||
|
// Linked to the parent customer, whatever the embedded customers_id says
|
||||||
|
async (dto) => {
|
||||||
|
const address = dto.company.trim() ? await this.withCompanyDetails(dto) : dto;
|
||||||
|
await this.customerAddressDatabaseRepository.upsert(
|
||||||
|
this.customerAddressConverter.fromHiboutik({ ...address, customers_id: hiboutikCustomer.customers_id }),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
this.logger,
|
||||||
|
(dto) => `Hiboutik address ${dto.address_id} of customer ${hiboutikCustomer.customers_id}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Completes an embedded address with its company details (one API call). On failure, the embedded address is returned
|
||||||
|
* as is, so the address is still synced and its stored company details are kept.
|
||||||
|
*/
|
||||||
|
private async withCompanyDetails(
|
||||||
|
dto: CustomerAddressHiboutikDto,
|
||||||
|
): Promise<CustomerAddressHiboutikDto | CustomerAddressDetailsHiboutikDto> {
|
||||||
|
try {
|
||||||
|
const details = await this.customerHiboutikRepository.getAddressById(dto.address_id);
|
||||||
|
return {
|
||||||
|
...dto,
|
||||||
|
tax_number: details.tax_number,
|
||||||
|
company_number: details.company_number,
|
||||||
|
legal_status: details.legal_status,
|
||||||
|
updated_at: details.updated_at,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
rethrowIfRateLimited(error);
|
||||||
|
this.logger.warn(`Failed to fetch company details of Hiboutik address ${dto.address_id}: ${(error as Error)?.message}`);
|
||||||
|
return dto;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mirrors the sales of a full Hiboutik customer as orders: each sale not yet stored as completed is fetched (for its
|
||||||
|
* lines) and upserted (a failing sale is logged and skipped). Quotations are ignored. Orders are never deleted.
|
||||||
|
* @returns the number of failed sales.
|
||||||
|
*/
|
||||||
|
private async syncOrders(hiboutikCustomer: FullCustomerHiboutikDto): Promise<number> {
|
||||||
|
if (!Array.isArray(hiboutikCustomer.sales)) {
|
||||||
|
this.logger.warn(`Hiboutik customer ${hiboutikCustomer.customers_id} has no sales array: orders sync skipped.`);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A completed sale no longer changes in Hiboutik: no need to fetch it again
|
||||||
|
const completedSaleIds = await this.orderDatabaseRepository.getCompletedSaleIds(
|
||||||
|
hiboutikCustomer.customers_id,
|
||||||
|
hiboutikCustomer.sales.map((dto) => dto.sale_id),
|
||||||
|
);
|
||||||
|
const salesToSync = hiboutikCustomer.sales.filter((dto) => !completedSaleIds.has(dto.sale_id));
|
||||||
|
|
||||||
|
return forEachSafely(
|
||||||
|
salesToSync,
|
||||||
|
async (dto) => {
|
||||||
|
const sale = await this.saleHiboutikRepository.getSaleById(dto.sale_id);
|
||||||
|
if (sale.quotation === 1) return;
|
||||||
|
// Linked to the parent customer, whatever the sale says
|
||||||
|
await this.orderDatabaseRepository.upsert(
|
||||||
|
this.orderConverter.fromHiboutik({ ...sale, customer_id: hiboutikCustomer.customers_id }),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
this.logger,
|
||||||
|
(dto) => `Hiboutik sale ${dto.sale_id} of customer ${hiboutikCustomer.customers_id}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
170
src/services/hiboutik/hiboutik.service.spec.ts
Normal file
170
src/services/hiboutik/hiboutik.service.spec.ts
Normal file
@@ -0,0 +1,170 @@
|
|||||||
|
import { Logger, ServiceUnavailableException } from '@nestjs/common';
|
||||||
|
import { HiboutikService } from './hiboutik.service';
|
||||||
|
import { HiboutikRateLimitError } from '../../hiboutik/hiboutik.client';
|
||||||
|
|
||||||
|
describe('HiboutikService', () => {
|
||||||
|
const brandService = { syncBrands: jest.fn() };
|
||||||
|
const categoryService = { syncCategories: jest.fn() };
|
||||||
|
const supplierService = { syncSuppliers: jest.fn() };
|
||||||
|
const productService = { syncProducts: jest.fn() };
|
||||||
|
const customerService = { syncCustomers: jest.fn() };
|
||||||
|
const syncLock = { tryAcquire: jest.fn() };
|
||||||
|
const release = jest.fn();
|
||||||
|
// SYNC_SHUTDOWN_TIMEOUT of 1 s
|
||||||
|
const configService = { get: jest.fn().mockReturnValue(1) };
|
||||||
|
let service: HiboutikService;
|
||||||
|
const flush = () => new Promise((resolve) => setImmediate(resolve));
|
||||||
|
|
||||||
|
let logWarn: jest.SpyInstance;
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
jest.spyOn(Logger.prototype, 'log').mockImplementation(() => undefined);
|
||||||
|
logWarn = jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => undefined);
|
||||||
|
jest.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
jest.clearAllMocks();
|
||||||
|
brandService.syncBrands.mockResolvedValue(undefined);
|
||||||
|
categoryService.syncCategories.mockResolvedValue(undefined);
|
||||||
|
supplierService.syncSuppliers.mockResolvedValue(undefined);
|
||||||
|
productService.syncProducts.mockResolvedValue(undefined);
|
||||||
|
customerService.syncCustomers.mockResolvedValue(undefined);
|
||||||
|
release.mockResolvedValue(undefined);
|
||||||
|
syncLock.tryAcquire.mockResolvedValue(release);
|
||||||
|
service = new HiboutikService(
|
||||||
|
brandService as never,
|
||||||
|
categoryService as never,
|
||||||
|
customerService as never,
|
||||||
|
productService as never,
|
||||||
|
supplierService as never,
|
||||||
|
syncLock as never,
|
||||||
|
configService as never,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('runs the steps in dependency order', async () => {
|
||||||
|
const order: string[] = [];
|
||||||
|
brandService.syncBrands.mockImplementation(() => Promise.resolve(order.push('brands')));
|
||||||
|
categoryService.syncCategories.mockImplementation(() => Promise.resolve(order.push('categories')));
|
||||||
|
supplierService.syncSuppliers.mockImplementation(() => Promise.resolve(order.push('suppliers')));
|
||||||
|
productService.syncProducts.mockImplementation(() => Promise.resolve(order.push('products')));
|
||||||
|
customerService.syncCustomers.mockImplementation(() => Promise.resolve(order.push('customers')));
|
||||||
|
|
||||||
|
// private method, reached through an index access on purpose
|
||||||
|
await service['syncAll']();
|
||||||
|
|
||||||
|
expect(order).toEqual(['brands', 'categories', 'suppliers', 'products', 'customers']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('continues with the next steps when one fails', async () => {
|
||||||
|
brandService.syncBrands.mockRejectedValue(new Error('boom'));
|
||||||
|
|
||||||
|
// private method, reached through an index access on purpose
|
||||||
|
await service['syncAll']();
|
||||||
|
|
||||||
|
expect(productService.syncProducts).toHaveBeenCalled();
|
||||||
|
expect(customerService.syncCustomers).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuses a second synchronization while one is running, and unlocks at the end', async () => {
|
||||||
|
let finishBrands: () => void = () => undefined;
|
||||||
|
brandService.syncBrands.mockReturnValue(new Promise<void>((resolve) => (finishBrands = resolve)));
|
||||||
|
// The lock is the only guard: the second request does not get it, even from the same instance
|
||||||
|
syncLock.tryAcquire.mockResolvedValueOnce(release).mockResolvedValueOnce(null);
|
||||||
|
|
||||||
|
await expect(service.startSync()).resolves.toBe(true);
|
||||||
|
await expect(service.startSync()).resolves.toBe(false);
|
||||||
|
expect(brandService.syncBrands).toHaveBeenCalledTimes(1);
|
||||||
|
expect(release).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
finishBrands();
|
||||||
|
await flush();
|
||||||
|
expect(release).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('starts nothing when another instance holds the lock', async () => {
|
||||||
|
syncLock.tryAcquire.mockResolvedValue(null);
|
||||||
|
|
||||||
|
await expect(service.startSync()).resolves.toBe(false);
|
||||||
|
|
||||||
|
expect(brandService.syncBrands).not.toHaveBeenCalled();
|
||||||
|
expect(release).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('starts nothing and can be retried when the lock cannot be requested', async () => {
|
||||||
|
syncLock.tryAcquire.mockRejectedValueOnce(new Error('database unreachable'));
|
||||||
|
|
||||||
|
await expect(service.startSync()).rejects.toThrow('database unreachable');
|
||||||
|
expect(brandService.syncBrands).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
await expect(service.startSync()).resolves.toBe(true);
|
||||||
|
await flush();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('releases the lock even when the synchronization crashes', async () => {
|
||||||
|
jest.spyOn(service as unknown as { syncAll: () => Promise<void> }, 'syncAll').mockRejectedValue(new Error('crash'));
|
||||||
|
|
||||||
|
await expect(service.startSync()).resolves.toBe(true);
|
||||||
|
await flush();
|
||||||
|
|
||||||
|
expect(release).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('stops the synchronization when the Hiboutik rate limit is reached', async () => {
|
||||||
|
productService.syncProducts.mockRejectedValue(new HiboutikRateLimitError('/products'));
|
||||||
|
|
||||||
|
await service['syncAll']();
|
||||||
|
|
||||||
|
expect(customerService.syncCustomers).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('shutdown', () => {
|
||||||
|
afterEach(() => {
|
||||||
|
jest.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('waits for the running synchronization to end, and refuses new ones meanwhile', async () => {
|
||||||
|
let finishBrands: () => void = () => undefined;
|
||||||
|
brandService.syncBrands.mockReturnValue(new Promise<void>((resolve) => (finishBrands = resolve)));
|
||||||
|
await service.startSync();
|
||||||
|
|
||||||
|
let shutDown = false;
|
||||||
|
const shutdown = service.beforeApplicationShutdown().then(() => (shutDown = true));
|
||||||
|
await flush();
|
||||||
|
expect(shutDown).toBe(false);
|
||||||
|
await expect(service.startSync()).rejects.toThrow(ServiceUnavailableException);
|
||||||
|
|
||||||
|
finishBrands();
|
||||||
|
await shutdown;
|
||||||
|
expect(release).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('gives up waiting after the timeout', async () => {
|
||||||
|
jest.useFakeTimers();
|
||||||
|
brandService.syncBrands.mockReturnValue(new Promise<void>(() => undefined));
|
||||||
|
await service.startSync();
|
||||||
|
|
||||||
|
const shutdown = service.beforeApplicationShutdown();
|
||||||
|
await jest.advanceTimersByTimeAsync(1_000);
|
||||||
|
|
||||||
|
await expect(shutdown).resolves.toBeUndefined();
|
||||||
|
expect(logWarn).toHaveBeenCalledWith(expect.stringContaining('did not end in time'));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns at once when no synchronization is running', async () => {
|
||||||
|
await expect(service.beforeApplicationShutdown()).resolves.toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('releases the lock and refuses when the shutdown began while the lock was requested', async () => {
|
||||||
|
syncLock.tryAcquire.mockImplementation(async () => {
|
||||||
|
await service.beforeApplicationShutdown();
|
||||||
|
return release;
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(service.startSync()).rejects.toThrow(ServiceUnavailableException);
|
||||||
|
expect(release).toHaveBeenCalledTimes(1);
|
||||||
|
expect(brandService.syncBrands).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
130
src/services/hiboutik/hiboutik.service.ts
Normal file
130
src/services/hiboutik/hiboutik.service.ts
Normal file
@@ -0,0 +1,130 @@
|
|||||||
|
import { BeforeApplicationShutdown, Injectable, Logger, ServiceUnavailableException } from '@nestjs/common';
|
||||||
|
import { ConfigService } from '@nestjs/config';
|
||||||
|
import { BrandHiboutikService } from './brand.hiboutik.service';
|
||||||
|
import { CategoryHiboutikService } from './category.hiboutik.service';
|
||||||
|
import { CustomerHiboutikService } from './customer.hiboutik.service';
|
||||||
|
import { SupplierHiboutikService } from './supplier.hiboutik.service';
|
||||||
|
import { ProductHiboutikService } from './product.hiboutik.service';
|
||||||
|
import { ReleaseLock, SyncLockDatabaseRepository } from '../../database/syncLock.database.repository';
|
||||||
|
import { HiboutikRateLimitError } from '../../hiboutik/hiboutik.client';
|
||||||
|
|
||||||
|
/** Default of `SYNC_SHUTDOWN_TIMEOUT`: below the 30 s grace period that Kubernetes gives before killing a container. */
|
||||||
|
const DEFAULT_SHUTDOWN_TIMEOUT_SECONDS = 25;
|
||||||
|
|
||||||
|
/** Entry point of the Hiboutik → database synchronization: runs each entity sync in dependency order. */
|
||||||
|
@Injectable()
|
||||||
|
export class HiboutikService implements BeforeApplicationShutdown {
|
||||||
|
private readonly logger = new Logger('HiboutikService');
|
||||||
|
private readonly shutdownTimeoutMs: number;
|
||||||
|
/** Synchronization running on this instance, if any. */
|
||||||
|
private running: Promise<void> | null = null;
|
||||||
|
private stopping = false;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly brandHiboutikService: BrandHiboutikService,
|
||||||
|
private readonly categoryHiboutikService: CategoryHiboutikService,
|
||||||
|
private readonly customerHiboutikService: CustomerHiboutikService,
|
||||||
|
private readonly productHiboutikService: ProductHiboutikService,
|
||||||
|
private readonly supplierHiboutikService: SupplierHiboutikService,
|
||||||
|
private readonly syncLock: SyncLockDatabaseRepository,
|
||||||
|
configService: ConfigService,
|
||||||
|
) {
|
||||||
|
this.shutdownTimeoutMs = (configService.get<number>('SYNC_SHUTDOWN_TIMEOUT') ?? DEFAULT_SHUTDOWN_TIMEOUT_SECONDS) * 1000;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Starts a full synchronization in the background, if no other one is running on this instance or any other.
|
||||||
|
* The Postgres advisory lock is the only guard: each request takes it on its own connection (its own session),
|
||||||
|
* so it also refuses concurrent calls on this very instance. It is held until the synchronization ends.
|
||||||
|
* @returns false if a synchronization is already running (nothing is started).
|
||||||
|
* @throws ServiceUnavailableException if this instance is shutting down (another instance can take it).
|
||||||
|
* @throws if the lock cannot be requested (e.g. database unreachable).
|
||||||
|
*/
|
||||||
|
async startSync(): Promise<boolean> {
|
||||||
|
this.refuseIfStopping();
|
||||||
|
const release = await this.syncLock.tryAcquire();
|
||||||
|
if (!release) return false;
|
||||||
|
|
||||||
|
// The shutdown may have begun while the lock was requested: it would not wait for this synchronization
|
||||||
|
if (this.stopping) {
|
||||||
|
await release();
|
||||||
|
this.refuseIfStopping();
|
||||||
|
}
|
||||||
|
|
||||||
|
this.running = this.runLocked(release).finally(() => (this.running = null));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shutdown hook: refuses new synchronizations and waits for the running one to end, up to `SYNC_SHUTDOWN_TIMEOUT`
|
||||||
|
* seconds. Runs before Prisma disconnects (`PrismaService.onApplicationShutdown`). Past the timeout, the shutdown goes
|
||||||
|
* on: the synchronization then fails on its next database call, without corrupting anything (one transaction per
|
||||||
|
* product, the lock is released by Postgres with the connection).
|
||||||
|
*/
|
||||||
|
async beforeApplicationShutdown(): Promise<void> {
|
||||||
|
this.stopping = true;
|
||||||
|
const running = this.running;
|
||||||
|
if (!running) return;
|
||||||
|
|
||||||
|
this.logger.log(`Shutdown requested: waiting for the running Hiboutik synchronization (up to ${this.shutdownTimeoutMs / 1000} s)`);
|
||||||
|
let timer: NodeJS.Timeout | undefined;
|
||||||
|
const timedOut = new Promise<true>((resolve) => (timer = setTimeout(() => resolve(true), this.shutdownTimeoutMs)));
|
||||||
|
const result = await Promise.race([running.then(() => false as const), timedOut]);
|
||||||
|
clearTimeout(timer);
|
||||||
|
|
||||||
|
if (result) {
|
||||||
|
this.logger.warn('The Hiboutik synchronization did not end in time: shutting down anyway, it will be interrupted');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private refuseIfStopping(): void {
|
||||||
|
if (this.stopping) throw new ServiceUnavailableException('This instance is shutting down, retry in a moment');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Runs the synchronization, then always releases the lock. */
|
||||||
|
private async runLocked(release: ReleaseLock): Promise<void> {
|
||||||
|
try {
|
||||||
|
await this.syncAll();
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.error('Global Hiboutik synchronization crashed', (error as Error)?.stack);
|
||||||
|
} finally {
|
||||||
|
await release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs every sync step in order. A failing step is logged and does not stop the next ones, except when the Hiboutik
|
||||||
|
* rate limit is reached: the next steps would only fail too, so the synchronization stops there.
|
||||||
|
*/
|
||||||
|
private async syncAll() {
|
||||||
|
this.logger.log('Starting global Hiboutik synchronization');
|
||||||
|
// Order matters: products connect to brands, categories and suppliers by hiboutikId.
|
||||||
|
const steps: [string, () => Promise<void>][] = [
|
||||||
|
['brands', () => this.brandHiboutikService.syncBrands()],
|
||||||
|
['categories', () => this.categoryHiboutikService.syncCategories()],
|
||||||
|
['suppliers', () => this.supplierHiboutikService.syncSuppliers()],
|
||||||
|
['products', () => this.productHiboutikService.syncProducts()],
|
||||||
|
['customers', () => this.customerHiboutikService.syncCustomers()],
|
||||||
|
];
|
||||||
|
|
||||||
|
const failedSteps: string[] = [];
|
||||||
|
for (const [name, step] of steps) {
|
||||||
|
try {
|
||||||
|
await step();
|
||||||
|
} catch (error) {
|
||||||
|
failedSteps.push(name);
|
||||||
|
if (error instanceof HiboutikRateLimitError) {
|
||||||
|
this.logger.error(`Hiboutik synchronization stopped during the ${name} step: ${error.message}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.logger.error(`Hiboutik ${name} sync failed`, (error as Error)?.stack);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (failedSteps.length > 0) {
|
||||||
|
this.logger.warn(`Global Hiboutik synchronization ended with errors (failed steps: ${failedSteps.join(', ')})`);
|
||||||
|
} else {
|
||||||
|
this.logger.log('Global Hiboutik synchronization ended successfully');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
197
src/services/hiboutik/product.hiboutik.service.spec.ts
Normal file
197
src/services/hiboutik/product.hiboutik.service.spec.ts
Normal file
@@ -0,0 +1,197 @@
|
|||||||
|
import { Logger } from '@nestjs/common';
|
||||||
|
import { ProductHiboutikService } from './product.hiboutik.service';
|
||||||
|
import { ProductConverter } from '../../models/converter/product.converter';
|
||||||
|
import { ProductHiboutikDto } from '../../models/hiboutikDTO/product.hiboutik.dto';
|
||||||
|
import { StockHiboutikDto } from '../../models/hiboutikDTO/stock.hiboutik.dto';
|
||||||
|
|
||||||
|
const hiboutikProduct = (id: number, overrides: Partial<ProductHiboutikDto> = {}): ProductHiboutikDto => ({
|
||||||
|
product_id: id,
|
||||||
|
product_model: `Product ${id}`,
|
||||||
|
product_barcode: `barcode-${id}`,
|
||||||
|
product_brand: 0,
|
||||||
|
product_supplier: 0,
|
||||||
|
product_price: '10.00',
|
||||||
|
product_discount_price: '0.00',
|
||||||
|
product_category: 0,
|
||||||
|
product_display_www: 1,
|
||||||
|
product_arch: 0,
|
||||||
|
products_desc: '',
|
||||||
|
updated_at: '2026-06-28 17:02:55',
|
||||||
|
product_specific_rules: [],
|
||||||
|
product_size_details: [],
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
|
||||||
|
const stock = (productId: number, size: number, available: number): StockHiboutikDto => ({
|
||||||
|
product_id: productId,
|
||||||
|
product_size: size,
|
||||||
|
stock_available: available,
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('ProductHiboutikService', () => {
|
||||||
|
let service: ProductHiboutikService;
|
||||||
|
let calls: string[];
|
||||||
|
const productHiboutikRepository = { getProducts: jest.fn() };
|
||||||
|
const stockHiboutikRepository = { getStocks: jest.fn() };
|
||||||
|
const productDatabaseRepository = { getAll: jest.fn(), upsert: jest.fn(), deleteAll: jest.fn() };
|
||||||
|
const productVersionDatabaseRepository = { upsert: jest.fn(), deleteMissing: jest.fn() };
|
||||||
|
// The transaction client handed to the repositories inside $transaction
|
||||||
|
const tx = { transaction: true };
|
||||||
|
const prisma = { $transaction: jest.fn() };
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
jest.spyOn(Logger.prototype, 'log').mockImplementation(() => undefined);
|
||||||
|
jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => undefined);
|
||||||
|
jest.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
jest.clearAllMocks();
|
||||||
|
calls = [];
|
||||||
|
prisma.$transaction.mockImplementation((run: (client: unknown) => Promise<unknown>) => run(tx));
|
||||||
|
stockHiboutikRepository.getStocks.mockResolvedValue([]);
|
||||||
|
productDatabaseRepository.getAll.mockResolvedValue([]);
|
||||||
|
productDatabaseRepository.deleteAll.mockImplementation((ids: string[]) => {
|
||||||
|
calls.push('deleteProducts');
|
||||||
|
return Promise.resolve(ids.length);
|
||||||
|
});
|
||||||
|
// the saved product mirrors what was upserted, like the database would
|
||||||
|
productDatabaseRepository.upsert.mockImplementation((product: { hiboutikId: number }) => {
|
||||||
|
calls.push('upsertProduct');
|
||||||
|
return Promise.resolve({ ...product, id: `uuid-${product.hiboutikId}` });
|
||||||
|
});
|
||||||
|
productVersionDatabaseRepository.deleteMissing.mockImplementation(() => {
|
||||||
|
calls.push('deleteVersions');
|
||||||
|
return Promise.resolve(0);
|
||||||
|
});
|
||||||
|
productVersionDatabaseRepository.upsert.mockImplementation(() => {
|
||||||
|
calls.push('upsertVersion');
|
||||||
|
return Promise.resolve({});
|
||||||
|
});
|
||||||
|
|
||||||
|
service = new ProductHiboutikService(
|
||||||
|
productHiboutikRepository as never,
|
||||||
|
productDatabaseRepository as never,
|
||||||
|
productVersionDatabaseRepository as never,
|
||||||
|
new ProductConverter(),
|
||||||
|
stockHiboutikRepository as never,
|
||||||
|
prisma as never,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('deletes products missing from Hiboutik, before upserting', async () => {
|
||||||
|
productHiboutikRepository.getProducts.mockResolvedValue([hiboutikProduct(1)]);
|
||||||
|
productDatabaseRepository.getAll.mockResolvedValue([
|
||||||
|
{ id: 'uuid-1', hiboutikId: 1 },
|
||||||
|
{ id: 'uuid-2', hiboutikId: 2 },
|
||||||
|
]);
|
||||||
|
|
||||||
|
await service.syncProducts();
|
||||||
|
|
||||||
|
expect(productDatabaseRepository.deleteAll).toHaveBeenCalledWith(['uuid-2']);
|
||||||
|
expect(calls[0]).toBe('deleteProducts');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('deletes every product when Hiboutik answers with an empty list', async () => {
|
||||||
|
productHiboutikRepository.getProducts.mockResolvedValue([]);
|
||||||
|
productDatabaseRepository.getAll.mockResolvedValue([{ id: 'uuid-1', hiboutikId: 1 }]);
|
||||||
|
|
||||||
|
await service.syncProducts();
|
||||||
|
|
||||||
|
expect(productDatabaseRepository.deleteAll).toHaveBeenCalledWith(['uuid-1']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('deletes nothing when the Hiboutik call fails', async () => {
|
||||||
|
productHiboutikRepository.getProducts.mockRejectedValue(new Error('Request failed with status code 500'));
|
||||||
|
productDatabaseRepository.getAll.mockResolvedValue([{ id: 'uuid-1', hiboutikId: 1 }]);
|
||||||
|
|
||||||
|
await expect(service.syncProducts()).rejects.toThrow('500');
|
||||||
|
|
||||||
|
expect(productDatabaseRepository.deleteAll).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('creates a single version for a product without sizes', async () => {
|
||||||
|
productHiboutikRepository.getProducts.mockResolvedValue([hiboutikProduct(1)]);
|
||||||
|
stockHiboutikRepository.getStocks.mockResolvedValue([stock(1, 0, 4), stock(2, 0, 99)]);
|
||||||
|
|
||||||
|
await service.syncProducts();
|
||||||
|
|
||||||
|
expect(productDatabaseRepository.upsert).toHaveBeenCalledWith(expect.objectContaining({ hiboutikId: 1, globalStock: 4 }), tx);
|
||||||
|
expect(productVersionDatabaseRepository.deleteMissing).toHaveBeenCalledWith('uuid-1', [0], tx);
|
||||||
|
expect(productVersionDatabaseRepository.upsert).toHaveBeenCalledTimes(1);
|
||||||
|
expect(productVersionDatabaseRepository.upsert).toHaveBeenCalledWith(
|
||||||
|
'uuid-1',
|
||||||
|
expect.objectContaining({ hiboutikSizeId: 0, barcode: 'barcode-1', stock: 4, versionName: 'Product 1', discountPrice: null }),
|
||||||
|
tx,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('creates one version per size, with specific rules and stocks, after deleting removed sizes', async () => {
|
||||||
|
productHiboutikRepository.getProducts.mockResolvedValue([
|
||||||
|
hiboutikProduct(1, {
|
||||||
|
product_size_details: [
|
||||||
|
{ size_id: 10, size_name: 'S', barcode: 'b-s' },
|
||||||
|
{ size_id: 11, size_name: 'M', barcode: '' },
|
||||||
|
],
|
||||||
|
product_specific_rules: [{ size_id: 10, product_price: '12.00', product_discount_price: '0.00' }],
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
stockHiboutikRepository.getStocks.mockResolvedValue([stock(1, 10, 3), stock(1, 11, 2)]);
|
||||||
|
|
||||||
|
await service.syncProducts();
|
||||||
|
|
||||||
|
expect(productDatabaseRepository.upsert).toHaveBeenCalledWith(expect.objectContaining({ globalStock: 5 }), tx);
|
||||||
|
expect(productVersionDatabaseRepository.deleteMissing).toHaveBeenCalledWith('uuid-1', [10, 11], tx);
|
||||||
|
expect(calls).toEqual(['deleteProducts', 'upsertProduct', 'deleteVersions', 'upsertVersion', 'upsertVersion']);
|
||||||
|
expect(productVersionDatabaseRepository.upsert).toHaveBeenNthCalledWith(
|
||||||
|
1,
|
||||||
|
'uuid-1',
|
||||||
|
{
|
||||||
|
barcode: 'b-s',
|
||||||
|
discountPrice: null,
|
||||||
|
hiboutikSizeId: 10,
|
||||||
|
price: '12.00',
|
||||||
|
product: { connect: { id: 'uuid-1' } },
|
||||||
|
stock: 3,
|
||||||
|
versionName: 'S',
|
||||||
|
},
|
||||||
|
tx,
|
||||||
|
);
|
||||||
|
expect(productVersionDatabaseRepository.upsert).toHaveBeenNthCalledWith(
|
||||||
|
2,
|
||||||
|
'uuid-1',
|
||||||
|
{
|
||||||
|
barcode: null,
|
||||||
|
discountPrice: null,
|
||||||
|
hiboutikSizeId: 11,
|
||||||
|
price: null,
|
||||||
|
product: { connect: { id: 'uuid-1' } },
|
||||||
|
stock: 2,
|
||||||
|
versionName: 'M',
|
||||||
|
},
|
||||||
|
tx,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps syncing the other products when one fails', async () => {
|
||||||
|
productHiboutikRepository.getProducts.mockResolvedValue([hiboutikProduct(1), hiboutikProduct(2)]);
|
||||||
|
productDatabaseRepository.upsert.mockRejectedValueOnce(new Error('boom'));
|
||||||
|
|
||||||
|
await expect(service.syncProducts()).resolves.toBeUndefined();
|
||||||
|
|
||||||
|
expect(productDatabaseRepository.upsert).toHaveBeenCalledTimes(2);
|
||||||
|
expect(productVersionDatabaseRepository.upsert).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('writes a product and its versions in one transaction per product, and counts a failed one', async () => {
|
||||||
|
productHiboutikRepository.getProducts.mockResolvedValue([hiboutikProduct(1), hiboutikProduct(2)]);
|
||||||
|
productVersionDatabaseRepository.upsert.mockRejectedValueOnce(new Error('boom'));
|
||||||
|
|
||||||
|
await expect(service.syncProducts()).resolves.toBeUndefined();
|
||||||
|
|
||||||
|
expect(prisma.$transaction).toHaveBeenCalledTimes(2);
|
||||||
|
// the failure inside the transaction is what makes Prisma roll the product back
|
||||||
|
await expect(prisma.$transaction.mock.results[0].value).rejects.toThrow('boom');
|
||||||
|
await expect(prisma.$transaction.mock.results[1].value).resolves.toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
144
src/services/hiboutik/product.hiboutik.service.ts
Normal file
144
src/services/hiboutik/product.hiboutik.service.ts
Normal file
@@ -0,0 +1,144 @@
|
|||||||
|
import { Injectable, Logger } from '@nestjs/common';
|
||||||
|
import { ProductHiboutikRepository } from '../../hiboutik/product.hiboutik.repository';
|
||||||
|
import { ProductDatabaseRepository } from '../../database/product.database.repository';
|
||||||
|
import { ProductVersionDatabaseRepository } from '../../database/productVersion.database.repository';
|
||||||
|
import { ProductConverter } from '../../models/converter/product.converter';
|
||||||
|
import { StockHiboutikRepository } from '../../hiboutik/stock.hiboutik.repository';
|
||||||
|
import { ProductHiboutikDto } from '../../models/hiboutikDTO/product.hiboutik.dto';
|
||||||
|
import { StockHiboutikDto } from '../../models/hiboutikDTO/stock.hiboutik.dto';
|
||||||
|
import { Product } from '../../../prisma/generated/client';
|
||||||
|
import { ProductVersionCreateInput } from '../../../prisma/generated/models/ProductVersion';
|
||||||
|
import { parseOptionalHiboutikPrice } from '../../utils/price';
|
||||||
|
import { PrismaService } from '../../../prisma/prisma.service';
|
||||||
|
import { rethrowIfRateLimited } from '../../hiboutik/hiboutik.client';
|
||||||
|
|
||||||
|
/** Version id used for products that have no sizes in Hiboutik. */
|
||||||
|
const NO_SIZE_ID = 0;
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class ProductHiboutikService {
|
||||||
|
private readonly logger = new Logger('ProductHiboutikService');
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly productHiboutikRepository: ProductHiboutikRepository,
|
||||||
|
private readonly productDatabaseRepository: ProductDatabaseRepository,
|
||||||
|
private readonly productVersionDatabaseRepository: ProductVersionDatabaseRepository,
|
||||||
|
private readonly productConverter: ProductConverter,
|
||||||
|
private readonly stockHiboutikRepository: StockHiboutikRepository,
|
||||||
|
private readonly prisma: PrismaService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/** Mirrors Hiboutik products, their versions (sizes) and stocks. Products missing from Hiboutik are deleted. */
|
||||||
|
async syncProducts() {
|
||||||
|
const [productsHiboutik, hiboutikStocks, existingProducts] = await Promise.all([
|
||||||
|
this.productHiboutikRepository.getProducts(),
|
||||||
|
this.stockHiboutikRepository.getStocks(),
|
||||||
|
this.productDatabaseRepository.getAll(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Deletion happens before the upserts, so that order lines of a deleted product are unlinked before anything else changes
|
||||||
|
const nbDeleted = await this.deleteMissingProducts(productsHiboutik, existingProducts);
|
||||||
|
|
||||||
|
// Grouped once by product: one pass over the stocks instead of one per product
|
||||||
|
const stocksByProduct = new Map<number, StockHiboutikDto[]>();
|
||||||
|
for (const stock of hiboutikStocks) {
|
||||||
|
const productStocks = stocksByProduct.get(stock.product_id);
|
||||||
|
if (productStocks) productStocks.push(stock);
|
||||||
|
else stocksByProduct.set(stock.product_id, [stock]);
|
||||||
|
}
|
||||||
|
|
||||||
|
let nbFailed = 0;
|
||||||
|
for (const productHiboutik of productsHiboutik) {
|
||||||
|
const hiboutikProductStocks = stocksByProduct.get(productHiboutik.product_id) ?? [];
|
||||||
|
try {
|
||||||
|
await this.updateProduct(productHiboutik, hiboutikProductStocks);
|
||||||
|
} catch (error) {
|
||||||
|
rethrowIfRateLimited(error);
|
||||||
|
nbFailed++;
|
||||||
|
this.logger.error(`Failed to sync Hiboutik product ${productHiboutik.product_id}`, (error as Error)?.stack);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.logger.log(
|
||||||
|
`Products sync ended: ${productsHiboutik.length - nbFailed}/${productsHiboutik.length} synced, ${nbFailed} failed, ${nbDeleted} deleted.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @returns the number of deleted products. */
|
||||||
|
private async deleteMissingProducts(productsHiboutik: ProductHiboutikDto[], existingProducts: Product[]): Promise<number> {
|
||||||
|
// Hiboutik is trusted: a successful (2xx) answer, even an empty list, is the truth. An HTTP error throws before this point.
|
||||||
|
const hiboutikIds = new Set(productsHiboutik.map((product) => product.product_id));
|
||||||
|
const missingProductIds = existingProducts.filter((product) => !hiboutikIds.has(product.hiboutikId)).map((product) => product.id);
|
||||||
|
return this.productDatabaseRepository.deleteAll(missingProductIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Upserts a product with its global stock, then replaces its versions, in a single transaction: on failure, nothing
|
||||||
|
* is changed (no global stock out of step with the versions).
|
||||||
|
*/
|
||||||
|
private async updateProduct(productHiboutik: ProductHiboutikDto, productStocks: StockHiboutikDto[]): Promise<void> {
|
||||||
|
const newProduct = this.productConverter.fromHiboutik(productHiboutik);
|
||||||
|
newProduct.globalStock = productStocks.reduce((sum, stock) => sum + stock.stock_available, 0);
|
||||||
|
|
||||||
|
await this.prisma.$transaction(
|
||||||
|
async (tx) => {
|
||||||
|
const savedProduct: Product = await this.productDatabaseRepository.upsert(newProduct, tx);
|
||||||
|
const versions = this.buildVersions(productHiboutik, productStocks, savedProduct);
|
||||||
|
|
||||||
|
await this.productVersionDatabaseRepository.deleteMissing(
|
||||||
|
savedProduct.id,
|
||||||
|
versions.map((version) => version.hiboutikSizeId),
|
||||||
|
tx,
|
||||||
|
);
|
||||||
|
for (const version of versions) {
|
||||||
|
await this.productVersionDatabaseRepository.upsert(savedProduct.id, version, tx);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ timeout: 15_000 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builds the versions of a product: one per Hiboutik size, or a single {@link NO_SIZE_ID} version
|
||||||
|
* copying the product's barcode, prices and stock when it has no sizes.
|
||||||
|
*/
|
||||||
|
private buildVersions(
|
||||||
|
productHiboutik: ProductHiboutikDto,
|
||||||
|
productStocks: StockHiboutikDto[],
|
||||||
|
savedProduct: Product,
|
||||||
|
): ProductVersionCreateInput[] {
|
||||||
|
const specificRules = productHiboutik.product_specific_rules;
|
||||||
|
const sizesDetails = productHiboutik.product_size_details;
|
||||||
|
|
||||||
|
if (sizesDetails.length === 0) {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
barcode: savedProduct.barcode,
|
||||||
|
discountPrice: savedProduct.discountPrice,
|
||||||
|
hiboutikSizeId: NO_SIZE_ID,
|
||||||
|
price: savedProduct.price,
|
||||||
|
product: { connect: { id: savedProduct.id } },
|
||||||
|
stock: savedProduct.globalStock,
|
||||||
|
versionName: savedProduct.name,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
return sizesDetails.map((sizeDetails) => {
|
||||||
|
const sizeId = sizeDetails.size_id;
|
||||||
|
const specificRule = specificRules.find((rule) => rule.size_id === sizeId);
|
||||||
|
const stock = productStocks.find((stock) => stock.product_size === sizeId);
|
||||||
|
// Values are always set explicitly (null / 0 rather than undefined), otherwise Prisma would keep
|
||||||
|
// the previous value on update when a rule or a stock is removed in Hiboutik.
|
||||||
|
return {
|
||||||
|
barcode: sizeDetails.barcode || null,
|
||||||
|
discountPrice: parseOptionalHiboutikPrice(specificRule?.product_discount_price),
|
||||||
|
hiboutikSizeId: sizeId,
|
||||||
|
price: parseOptionalHiboutikPrice(specificRule?.product_price),
|
||||||
|
product: { connect: { id: savedProduct.id } },
|
||||||
|
stock: stock?.stock_available ?? 0,
|
||||||
|
versionName: sizeDetails.size_name,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
34
src/services/hiboutik/supplier.hiboutik.service.ts
Normal file
34
src/services/hiboutik/supplier.hiboutik.service.ts
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
import { Injectable, Logger } from '@nestjs/common';
|
||||||
|
import { SupplierHiboutikRepository } from '../../hiboutik/supplier.hiboutik.repository';
|
||||||
|
import { SupplierDatabaseRepository } from '../../database/supplier.database.repository';
|
||||||
|
import { SupplierConverter } from '../../models/converter/supplier.converter';
|
||||||
|
import { forEachSafely } from '../../utils/sync';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class SupplierHiboutikService {
|
||||||
|
private readonly logger = new Logger('SupplierHiboutikService');
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly supplierHiboutikRepository: SupplierHiboutikRepository,
|
||||||
|
private readonly supplierDatabaseRepository: SupplierDatabaseRepository,
|
||||||
|
private readonly supplierConverter: SupplierConverter,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/** Mirrors Hiboutik suppliers: upserts each of them, then deletes the suppliers missing from Hiboutik. */
|
||||||
|
async syncSuppliers() {
|
||||||
|
const hiboutikSuppliers = await this.supplierHiboutikRepository.getSuppliers();
|
||||||
|
// One upsert per supplier: an invalid supplier must not prevent the others from being saved
|
||||||
|
const nbFailed = await forEachSafely(
|
||||||
|
this.supplierConverter.fromHiboutikList(hiboutikSuppliers),
|
||||||
|
(supplier) => this.supplierDatabaseRepository.upsert(supplier),
|
||||||
|
this.logger,
|
||||||
|
(supplier) => `Hiboutik supplier ${supplier.hiboutikId}`,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Hiboutik is trusted: a successful (2xx) answer, even an empty list, is the truth. An HTTP error throws before this point.
|
||||||
|
const nbDeleted = await this.supplierDatabaseRepository.deleteMissing(hiboutikSuppliers.map((dto) => dto.supplier_id));
|
||||||
|
this.logger.log(
|
||||||
|
`Suppliers sync ended: ${hiboutikSuppliers.length - nbFailed}/${hiboutikSuppliers.length} synced, ${nbFailed} failed, ${nbDeleted} deleted.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
35
src/utils/date.spec.ts
Normal file
35
src/utils/date.spec.ts
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
import { parseHiboutikDate } from './date';
|
||||||
|
|
||||||
|
describe('parseHiboutikDate', () => {
|
||||||
|
it('parses a Hiboutik datetime as French summer time (UTC+2)', () => {
|
||||||
|
expect(parseHiboutikDate('2026-06-28 17:02:55')).toEqual(new Date('2026-06-28T15:02:55Z'));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('parses a Hiboutik datetime as French winter time (UTC+1)', () => {
|
||||||
|
expect(parseHiboutikDate('2026-01-15 10:00:00')).toEqual(new Date('2026-01-15T09:00:00Z'));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('switches offset at the DST changes', () => {
|
||||||
|
expect(parseHiboutikDate('2026-03-29 01:59:59')).toEqual(new Date('2026-03-29T00:59:59Z'));
|
||||||
|
expect(parseHiboutikDate('2026-03-29 03:00:00')).toEqual(new Date('2026-03-29T01:00:00Z'));
|
||||||
|
expect(parseHiboutikDate('2026-10-25 03:00:00')).toEqual(new Date('2026-10-25T02:00:00Z'));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('parses a date without time as midnight UTC (calendar date)', () => {
|
||||||
|
expect(parseHiboutikDate('1990-05-12')).toEqual(new Date('1990-05-12T00:00:00Z'));
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
'',
|
||||||
|
'0000-00-00',
|
||||||
|
'0000-00-00 00:00:00',
|
||||||
|
'2026-02-30',
|
||||||
|
'2026-13-01 10:00:00',
|
||||||
|
'2026-06-28 25:00:00',
|
||||||
|
'not a date',
|
||||||
|
null,
|
||||||
|
undefined,
|
||||||
|
])('returns undefined for %p', (value) => {
|
||||||
|
expect(parseHiboutikDate(value)).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
53
src/utils/date.ts
Normal file
53
src/utils/date.ts
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
/** Time zone of the dates sent by Hiboutik: the shop's local (French) time, without any offset. */
|
||||||
|
export const HIBOUTIK_TIME_ZONE = 'Europe/Paris';
|
||||||
|
|
||||||
|
const HIBOUTIK_DATE = /^(\d{4})-(\d{2})-(\d{2})(?:[ T](\d{2}):(\d{2})(?::(\d{2}))?)?$/;
|
||||||
|
|
||||||
|
const timeZoneFormatter = new Intl.DateTimeFormat('en-US', {
|
||||||
|
timeZone: HIBOUTIK_TIME_ZONE,
|
||||||
|
hourCycle: 'h23',
|
||||||
|
year: 'numeric',
|
||||||
|
month: '2-digit',
|
||||||
|
day: '2-digit',
|
||||||
|
hour: '2-digit',
|
||||||
|
minute: '2-digit',
|
||||||
|
second: '2-digit',
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Offset (ms) of {@link HIBOUTIK_TIME_ZONE} from UTC at the given instant: +1 h in winter, +2 h in summer. */
|
||||||
|
function timeZoneOffset(instant: number): number {
|
||||||
|
const parts = Object.fromEntries(timeZoneFormatter.formatToParts(new Date(instant)).map((part) => [part.type, Number(part.value)]));
|
||||||
|
const wallClockAsUtc = Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second);
|
||||||
|
return wallClockAsUtc - instant;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parses a Hiboutik date. Returns undefined for empty or invalid dates (e.g. "0000-00-00", "2026-02-30").
|
||||||
|
* - "YYYY-MM-DD HH:mm:ss": French local time ({@link HIBOUTIK_TIME_ZONE}), whatever the time zone of the server.
|
||||||
|
* A time that is ambiguous or skipped at a DST change (02:00-03:00) resolves to a nearby valid instant.
|
||||||
|
* - "YYYY-MM-DD" (calendar date, e.g. a date of birth): midnight UTC, so that the stored date is the same day.
|
||||||
|
*/
|
||||||
|
export function parseHiboutikDate(value: string | null | undefined): Date | undefined {
|
||||||
|
const match = HIBOUTIK_DATE.exec(value?.trim() ?? '');
|
||||||
|
if (!match) return undefined;
|
||||||
|
|
||||||
|
const [year, month, day, hour, minute, second] = match.slice(1).map((part) => Number(part ?? 0));
|
||||||
|
const wallClockAsUtc = Date.UTC(year, month - 1, day, hour, minute, second);
|
||||||
|
|
||||||
|
// Rejects out-of-range values (month 0 or 13, February 30, 25:00...), which Date.UTC would silently roll over
|
||||||
|
const check = new Date(wallClockAsUtc);
|
||||||
|
const isValid =
|
||||||
|
check.getUTCFullYear() === year &&
|
||||||
|
check.getUTCMonth() === month - 1 &&
|
||||||
|
check.getUTCDate() === day &&
|
||||||
|
check.getUTCHours() === hour &&
|
||||||
|
check.getUTCMinutes() === minute &&
|
||||||
|
check.getUTCSeconds() === second;
|
||||||
|
if (!isValid) return undefined;
|
||||||
|
|
||||||
|
if (match[4] === undefined) return check;
|
||||||
|
|
||||||
|
// The offset depends on the instant itself (DST): guess it from the wall clock, then correct it once
|
||||||
|
const firstGuess = wallClockAsUtc - timeZoneOffset(wallClockAsUtc);
|
||||||
|
return new Date(wallClockAsUtc - timeZoneOffset(firstGuess));
|
||||||
|
}
|
||||||
11
src/utils/price.spec.ts
Normal file
11
src/utils/price.spec.ts
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
import { parseOptionalHiboutikPrice } from './price';
|
||||||
|
|
||||||
|
describe('parseOptionalHiboutikPrice', () => {
|
||||||
|
it('keeps a positive price', () => {
|
||||||
|
expect(parseOptionalHiboutikPrice('12.50')).toBe('12.50');
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each(['0.00', '0', '', 'abc', '-1.00', null, undefined])('returns null for %p', (value) => {
|
||||||
|
expect(parseOptionalHiboutikPrice(value)).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
10
src/utils/price.ts
Normal file
10
src/utils/price.ts
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
/**
|
||||||
|
* Parses an optional Hiboutik price (discount price, size price override).
|
||||||
|
* Hiboutik sends "0.00" when the value is not set: returns null for empty, zero or invalid values.
|
||||||
|
*/
|
||||||
|
export function parseOptionalHiboutikPrice(value: string | null | undefined): string | null {
|
||||||
|
if (!value) return null;
|
||||||
|
|
||||||
|
const price = Number(value);
|
||||||
|
return Number.isFinite(price) && price > 0 ? value : null;
|
||||||
|
}
|
||||||
30
src/utils/sync.ts
Normal file
30
src/utils/sync.ts
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
import { Logger } from '@nestjs/common';
|
||||||
|
import { rethrowIfRateLimited } from '../hiboutik/hiboutik.client';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs `action` on each item, one at a time: a failing item is logged and skipped, the others are still processed.
|
||||||
|
* A Hiboutik rate limit error stops the loop (rethrown): the next items would fail the same way.
|
||||||
|
* @param items
|
||||||
|
* @param action
|
||||||
|
* @param logger
|
||||||
|
* @param describe label of an item in the error log, e.g. "Hiboutik brand 12".
|
||||||
|
* @returns the number of failed items.
|
||||||
|
*/
|
||||||
|
export async function forEachSafely<T>(
|
||||||
|
items: T[],
|
||||||
|
action: (item: T) => Promise<unknown>,
|
||||||
|
logger: Logger,
|
||||||
|
describe: (item: T) => string,
|
||||||
|
): Promise<number> {
|
||||||
|
let nbFailed = 0;
|
||||||
|
for (const item of items) {
|
||||||
|
try {
|
||||||
|
await action(item);
|
||||||
|
} catch (error) {
|
||||||
|
rethrowIfRateLimited(error);
|
||||||
|
nbFailed++;
|
||||||
|
logger.error(`Failed to sync ${describe(item)}`, (error as Error)?.stack);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nbFailed;
|
||||||
|
}
|
||||||
@@ -3,24 +3,48 @@ import { INestApplication } from '@nestjs/common';
|
|||||||
import request from 'supertest';
|
import request from 'supertest';
|
||||||
import { App } from 'supertest/types';
|
import { App } from 'supertest/types';
|
||||||
import { AppModule } from './../src/app.module';
|
import { AppModule } from './../src/app.module';
|
||||||
|
import { HiboutikService } from './../src/services/hiboutik/hiboutik.service';
|
||||||
|
import { PrismaService } from './../prisma/prisma.service';
|
||||||
|
|
||||||
|
// Boots the real AppModule wiring, without database nor Hiboutik calls
|
||||||
describe('AppController (e2e)', () => {
|
describe('AppController (e2e)', () => {
|
||||||
let app: INestApplication<App>;
|
let app: INestApplication<App>;
|
||||||
|
const hiboutikService = { startSync: jest.fn() };
|
||||||
|
// Rate limiting counters (ThrottlerDatabaseStorage): the database answers "not blocked" unless a test says otherwise
|
||||||
|
const notBlocked = { totalHits: 1, timeToExpire: 60, isBlocked: false, timeToBlockExpire: 0 };
|
||||||
|
const prisma = { $queryRaw: jest.fn(), throttlerRecord: { deleteMany: jest.fn().mockResolvedValue({ count: 0 }) } };
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
|
hiboutikService.startSync.mockReset();
|
||||||
|
prisma.$queryRaw.mockReset().mockResolvedValue([notBlocked]);
|
||||||
const moduleFixture: TestingModule = await Test.createTestingModule({
|
const moduleFixture: TestingModule = await Test.createTestingModule({
|
||||||
imports: [AppModule],
|
imports: [AppModule],
|
||||||
}).compile();
|
})
|
||||||
|
.overrideProvider(PrismaService)
|
||||||
|
.useValue(prisma)
|
||||||
|
.overrideProvider(HiboutikService)
|
||||||
|
.useValue(hiboutikService)
|
||||||
|
.compile();
|
||||||
|
|
||||||
app = moduleFixture.createNestApplication();
|
app = moduleFixture.createNestApplication();
|
||||||
await app.init();
|
await app.init();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('/ (GET)', () => {
|
it('POST /sync starts a synchronization (202)', () => {
|
||||||
return request(app.getHttpServer())
|
hiboutikService.startSync.mockResolvedValue(true);
|
||||||
.get('/')
|
return request(app.getHttpServer()).post('/sync').expect(202).expect({ message: 'Hiboutik synchronization started' });
|
||||||
.expect(200)
|
});
|
||||||
.expect('Hello World!');
|
|
||||||
|
it('POST /sync answers 409 when a synchronization is already running', () => {
|
||||||
|
hiboutikService.startSync.mockResolvedValue(false);
|
||||||
|
return request(app.getHttpServer()).post('/sync').expect(409);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('POST /sync answers 429 when the shared rate limiting counter is blocked', async () => {
|
||||||
|
prisma.$queryRaw.mockResolvedValue([{ totalHits: 6, timeToExpire: 30, isBlocked: true, timeToBlockExpire: 30 }]);
|
||||||
|
|
||||||
|
await request(app.getHttpServer()).post('/sync').expect(429).expect('Retry-After', '30');
|
||||||
|
expect(hiboutikService.startSync).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(async () => {
|
afterEach(async () => {
|
||||||
|
|||||||
@@ -3,7 +3,22 @@
|
|||||||
"rootDir": ".",
|
"rootDir": ".",
|
||||||
"testEnvironment": "node",
|
"testEnvironment": "node",
|
||||||
"testRegex": ".e2e-spec.ts$",
|
"testRegex": ".e2e-spec.ts$",
|
||||||
|
"setupFiles": ["<rootDir>/setup-env.ts"],
|
||||||
"transform": {
|
"transform": {
|
||||||
"^.+\\.(t|j)s$": "ts-jest"
|
"^.+.ts$": "ts-jest",
|
||||||
|
"^.+.js$": [
|
||||||
|
"ts-jest",
|
||||||
|
{
|
||||||
|
"tsconfig": {
|
||||||
|
"allowJs": true,
|
||||||
|
"module": "commonjs",
|
||||||
|
"moduleResolution": "node"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"transformIgnorePatterns": ["/node_modules/(?!@nestjs/config/)"],
|
||||||
|
"moduleNameMapper": {
|
||||||
|
"^(\\.{1,2}/.*)\\.js$": "$1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
5
test/setup-env.ts
Normal file
5
test/setup-env.ts
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
// The e2e test needs neither a database nor Hiboutik, but the app validates its environment at startup: provide dummy values.
|
||||||
|
process.env.DATABASE_URL ??= 'postgresql://test:test@localhost:5432/test';
|
||||||
|
process.env.HIBOUTIK_BASE_URL ??= 'https://example.hiboutik.test/api';
|
||||||
|
process.env.HIBOUTIK_USERNAME ??= 'test';
|
||||||
|
process.env.HIBOUTIK_PASSWORD ??= 'test';
|
||||||
@@ -16,10 +16,8 @@
|
|||||||
"baseUrl": "./",
|
"baseUrl": "./",
|
||||||
"incremental": true,
|
"incremental": true,
|
||||||
"skipLibCheck": true,
|
"skipLibCheck": true,
|
||||||
"strictNullChecks": true,
|
"strict": true,
|
||||||
"forceConsistentCasingInFileNames": true,
|
"forceConsistentCasingInFileNames": true,
|
||||||
"noImplicitAny": false,
|
|
||||||
"strictBindCallApply": false,
|
|
||||||
"noFallthroughCasesInSwitch": false
|
"noFallthroughCasesInSwitch": false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user