TZK-2: каркас приложения, БД, вход, фандоматы, баллы и льготы
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
6fc4453beb
commit
0bdcf73b65
5
.gitignore
vendored
5
.gitignore
vendored
@ -2,3 +2,8 @@ node_modules/
|
|||||||
.env
|
.env
|
||||||
.env.local
|
.env.local
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
dist/
|
||||||
|
data/
|
||||||
|
*.db
|
||||||
|
*.db-wal
|
||||||
|
*.db-shm
|
||||||
|
|||||||
@ -1 +1,6 @@
|
|||||||
{"slug":"tazakazahstan","key":"TZK","name":"Эко-платформа","peppaUrl":"https://peppa.telecom.quest"}
|
{
|
||||||
|
"slug": "tazakazahstan",
|
||||||
|
"key": "TZK",
|
||||||
|
"name": "Эко-платформа",
|
||||||
|
"peppaUrl": "https://peppa.telecom.quest"
|
||||||
|
}
|
||||||
|
|||||||
8
biome.json
Normal file
8
biome.json
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://biomejs.dev/schemas/2.6.7/schema.json",
|
||||||
|
"vcs": { "enabled": true, "clientKind": "git", "useIgnoreFile": true },
|
||||||
|
"files": { "includes": ["**", "!dist", "!data", "!openspec", "!.agents", "!.claude"] },
|
||||||
|
"formatter": { "enabled": true, "indentStyle": "space", "indentWidth": 2, "lineWidth": 100 },
|
||||||
|
"linter": { "enabled": true, "rules": { "preset": "recommended" } },
|
||||||
|
"assist": { "enabled": true, "actions": { "source": { "organizeImports": "on" } } }
|
||||||
|
}
|
||||||
30
package.json
Normal file
30
package.json
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
{
|
||||||
|
"name": "tazakazahstan",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"private": true,
|
||||||
|
"description": "Эко-платформа «Таза Қазақстан»: экодействия, баллы и льготы партнёров",
|
||||||
|
"type": "module",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=22.18"
|
||||||
|
},
|
||||||
|
"packageManager": "pnpm@10.18.0",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "APP_ENV=${APP_ENV:-development} node --watch src/main.ts",
|
||||||
|
"start": "node dist/src/main.js",
|
||||||
|
"build": "rm -rf dist && tsc -p tsconfig.build.json",
|
||||||
|
"lint": "biome check .",
|
||||||
|
"format": "biome check --write .",
|
||||||
|
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||||
|
"test": "node --test --test-reporter=spec \"test/**/*.test.ts\"",
|
||||||
|
"db:migrate": "node src/db/migrate-cli.ts",
|
||||||
|
"demo": "node scripts/demo.ts"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@sentry/node": "^10.78.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@biomejs/biome": "2.6.7",
|
||||||
|
"@types/node": "^24.19.2",
|
||||||
|
"typescript": "5.9.3"
|
||||||
|
}
|
||||||
|
}
|
||||||
392
pnpm-lock.yaml
generated
Normal file
392
pnpm-lock.yaml
generated
Normal file
@ -0,0 +1,392 @@
|
|||||||
|
lockfileVersion: '9.0'
|
||||||
|
|
||||||
|
settings:
|
||||||
|
autoInstallPeers: true
|
||||||
|
excludeLinksFromLockfile: false
|
||||||
|
|
||||||
|
importers:
|
||||||
|
|
||||||
|
.:
|
||||||
|
dependencies:
|
||||||
|
'@sentry/node':
|
||||||
|
specifier: ^10.78.0
|
||||||
|
version: 10.78.0(@opentelemetry/core@2.12.0(@opentelemetry/api@1.9.1))
|
||||||
|
devDependencies:
|
||||||
|
'@biomejs/biome':
|
||||||
|
specifier: 2.6.7
|
||||||
|
version: 2.6.7
|
||||||
|
'@types/node':
|
||||||
|
specifier: ^24.19.2
|
||||||
|
version: 24.19.2
|
||||||
|
typescript:
|
||||||
|
specifier: 5.9.3
|
||||||
|
version: 5.9.3
|
||||||
|
|
||||||
|
packages:
|
||||||
|
|
||||||
|
'@biomejs/biome@2.6.7':
|
||||||
|
resolution: {integrity: sha512-2bT1FE6FvZZgPLFw4BjcDyRwG8Ry9zYla4X+Lw8oj2SxvqiXHiYkkEpjcrsWQrik6iYHygAa/D67YxLbVz9P1Q==}
|
||||||
|
engines: {node: '>=14.21.3'}
|
||||||
|
hasBin: true
|
||||||
|
|
||||||
|
'@biomejs/cli-android-arm64@2.6.7':
|
||||||
|
resolution: {integrity: sha512-f4fyRTl+rW6QZp+iHdZrKAKptG/xmIDijTnxWhpC1Hnzr8yvjaBm/aJ98JiMv5mMx7jL1MOu4+zwmQUzfcoKBg==}
|
||||||
|
engines: {node: '>=14.21.3'}
|
||||||
|
cpu: [arm64]
|
||||||
|
os: [android]
|
||||||
|
|
||||||
|
'@biomejs/cli-android-x64@2.6.7':
|
||||||
|
resolution: {integrity: sha512-eUdeN+mh2bwen+By1feKzpFkFGAfLG3Pxi6tbwpzMvePBwFGMd4mnE6gaxDRMiWJ1eMuc+Xhtg3ErbLLbtL5wQ==}
|
||||||
|
engines: {node: '>=14.21.3'}
|
||||||
|
cpu: [x64]
|
||||||
|
os: [android]
|
||||||
|
|
||||||
|
'@biomejs/cli-darwin-arm64@2.6.7':
|
||||||
|
resolution: {integrity: sha512-GewLcsnCsVblgnWYw5QRz5ydy9xphCtlFP37TpLKarezqwZMrH2qxrYblhY6DPOir4gnKyaqDnS/xZWIGVjaKw==}
|
||||||
|
engines: {node: '>=14.21.3'}
|
||||||
|
cpu: [arm64]
|
||||||
|
os: [darwin]
|
||||||
|
|
||||||
|
'@biomejs/cli-darwin-x64@2.6.7':
|
||||||
|
resolution: {integrity: sha512-AMPl+Q+bHjRcNUBn8gwBl+dJAnKRUWGZ7ZiJo2U8tQtdpqJ32OqvIg4cwTH+xv0jrcNVkUSE69nj57zsHZ1WBA==}
|
||||||
|
engines: {node: '>=14.21.3'}
|
||||||
|
cpu: [x64]
|
||||||
|
os: [darwin]
|
||||||
|
|
||||||
|
'@biomejs/cli-linux-arm64-musl@2.6.7':
|
||||||
|
resolution: {integrity: sha512-BIA7qVO1O15D2wVKxLTcvEWszgOqJVZRUhlksg1KQ9N0VtYCbvknV1vyjFiSrzuBT57+z59gbzhYQCinw9lRSQ==}
|
||||||
|
engines: {node: '>=14.21.3'}
|
||||||
|
cpu: [arm64]
|
||||||
|
os: [linux]
|
||||||
|
|
||||||
|
'@biomejs/cli-linux-arm64@2.6.7':
|
||||||
|
resolution: {integrity: sha512-Qa2edxQClKn17y1ASWkOOuT96K2si1nTLiPbXMOMilNJ79eNsa1as1kaSbgxOXy1kRUENw76sp4pAddneq3l8Q==}
|
||||||
|
engines: {node: '>=14.21.3'}
|
||||||
|
cpu: [arm64]
|
||||||
|
os: [linux]
|
||||||
|
|
||||||
|
'@biomejs/cli-linux-x64-musl@2.6.7':
|
||||||
|
resolution: {integrity: sha512-+AOQyCsPR4nH5L4Hjzp8T0iaHm4UxY3unjL/KUJKc/8ziLnbkbmL3adtWmQW5ERB1zi6LRA1fsjaSuf/xGnLaQ==}
|
||||||
|
engines: {node: '>=14.21.3'}
|
||||||
|
cpu: [x64]
|
||||||
|
os: [linux]
|
||||||
|
|
||||||
|
'@biomejs/cli-linux-x64@2.6.7':
|
||||||
|
resolution: {integrity: sha512-VpHQ33CPNYrlIn0vyDdRS1KUlS3AiM17FiyEE2gwU000NwzyY4MgjzVHEv2KrmMb5D9Ksm3gFkwg+IOx/ULJNQ==}
|
||||||
|
engines: {node: '>=14.21.3'}
|
||||||
|
cpu: [x64]
|
||||||
|
os: [linux]
|
||||||
|
|
||||||
|
'@biomejs/cli-win32-arm64@2.6.7':
|
||||||
|
resolution: {integrity: sha512-2nLivZfgcGMIXP/bI8w1FZP5JE2MetP+XZInyMQ7SvJBKlDoGrm/nRjN7uUi9dOaaSlpbRWkHSfb7PqcQR3nXg==}
|
||||||
|
engines: {node: '>=14.21.3'}
|
||||||
|
cpu: [arm64]
|
||||||
|
os: [win32]
|
||||||
|
|
||||||
|
'@biomejs/cli-win32-x64@2.6.7':
|
||||||
|
resolution: {integrity: sha512-uYfH+n+IAtVz3lh7m6JxdjxfJ3WCvAJDE3spHIUbU955V42oKymlhiQiu92fAhXZb7KOjvRcrfImySQbc1MFFg==}
|
||||||
|
engines: {node: '>=14.21.3'}
|
||||||
|
cpu: [x64]
|
||||||
|
os: [win32]
|
||||||
|
|
||||||
|
'@opentelemetry/api-logs@0.220.0':
|
||||||
|
resolution: {integrity: sha512-CmVa4ImJ+ynfrPMNaAXHET6Bhb44SwzmfyVJFq9ni2jgXJR/l7C6gfVFddNmHP+ZOkP9cf4f9DBe68qVLTHc9w==}
|
||||||
|
engines: {node: '>=8.0.0'}
|
||||||
|
|
||||||
|
'@opentelemetry/api@1.10.0':
|
||||||
|
resolution: {integrity: sha512-lMkyes8iHrG+mk6WH7X70MdCLI2RS0FwNBY1PyQ8UemaijE2m5mv5A0Niy3HtbYTFrgkUEQjFMXmSAk2hQDuPQ==}
|
||||||
|
engines: {node: '>=8.0.0'}
|
||||||
|
|
||||||
|
'@opentelemetry/api@1.9.1':
|
||||||
|
resolution: {integrity: sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q==}
|
||||||
|
engines: {node: '>=8.0.0'}
|
||||||
|
|
||||||
|
'@opentelemetry/core@2.12.0':
|
||||||
|
resolution: {integrity: sha512-1HsSAuvT4/my0QrXWsyXFdWjKaPeCHsismKZgEEIb8NK13LP6DrMRlsUbvD/0F9mDWK3xDom9AMv3IscxgOnOQ==}
|
||||||
|
engines: {node: ^18.19.0 || >=20.6.0}
|
||||||
|
peerDependencies:
|
||||||
|
'@opentelemetry/api': '>=1.0.0 <1.10.0'
|
||||||
|
|
||||||
|
'@opentelemetry/instrumentation@0.220.0':
|
||||||
|
resolution: {integrity: sha512-xQx3E2WxP1mDvKzxLxX+CTCtNLa560YJZ3087qYHerl2YmiKpv7AH+dAy7vmx+eVrZ5BwhfWUAVoKOoxCNHcpw==}
|
||||||
|
engines: {node: ^18.19.0 || >=20.6.0}
|
||||||
|
peerDependencies:
|
||||||
|
'@opentelemetry/api': ^1.3.0
|
||||||
|
|
||||||
|
'@opentelemetry/resources@2.12.0':
|
||||||
|
resolution: {integrity: sha512-+rSRoOdln6NhXTVcBdHSlZxJDNzwxadeweK2ltZO3tVtfp6aklABc06xclDk6ovRR+EiGgIcSbh/6NgjFhnb3A==}
|
||||||
|
engines: {node: ^18.19.0 || >=20.6.0}
|
||||||
|
peerDependencies:
|
||||||
|
'@opentelemetry/api': '>=1.3.0 <1.10.0'
|
||||||
|
|
||||||
|
'@opentelemetry/sdk-trace-base@2.12.0':
|
||||||
|
resolution: {integrity: sha512-JOERgZCxRM06FEJ5kEWxlSRChah6MmXDx3KwCruqEv/iEyLkTokCSemf2y1w8oIHtfrr8EVTpzebq/31vn2Cpg==}
|
||||||
|
engines: {node: ^18.19.0 || >=20.6.0}
|
||||||
|
deprecated: Use @opentelemetry/sdk-trace package
|
||||||
|
peerDependencies:
|
||||||
|
'@opentelemetry/api': '>=1.3.0 <1.10.0'
|
||||||
|
|
||||||
|
'@opentelemetry/sdk-trace@2.12.0':
|
||||||
|
resolution: {integrity: sha512-ImVuRQ6faOsTi1Wna88s2avgrrf/iDgXPigIeynkUhjstMuoQUDOJXgkez2j1mlU4btjXcXBGa+q7qKFYR3GsA==}
|
||||||
|
engines: {node: ^18.19.0 || >=20.6.0}
|
||||||
|
peerDependencies:
|
||||||
|
'@opentelemetry/api': '>=1.3.0 <1.10.0'
|
||||||
|
|
||||||
|
'@opentelemetry/semantic-conventions@1.45.0':
|
||||||
|
resolution: {integrity: sha512-aOP45mbcOKbQVvFWfQmgoOPT8R2iwbbbgl83k4CujGV9BrJhFr3qG55MFpwFs4YLabpuW3HhzUY9eQxPlDqaZw==}
|
||||||
|
engines: {node: '>=14'}
|
||||||
|
|
||||||
|
'@sentry/conventions@0.16.0':
|
||||||
|
resolution: {integrity: sha512-fO9PLmHdVURcSPUpWCItWAtgKiMwGdJHbovoSEyLplX5sxs2ugvI4CBPTrkkgqhObnZOD0CnWBKDzSVQYBKEyQ==}
|
||||||
|
engines: {node: '>=14'}
|
||||||
|
|
||||||
|
'@sentry/core@10.78.0':
|
||||||
|
resolution: {integrity: sha512-MMR4ME+agrjbvQ0DtTYJJypm+QlCoz9UJgWN8gjcXqlyDjYk69LwPjnaocYN1JyQMy2dx5Hk4S/Rt12gTQ5cGw==}
|
||||||
|
engines: {node: '>=18'}
|
||||||
|
|
||||||
|
'@sentry/node-core@10.78.0':
|
||||||
|
resolution: {integrity: sha512-HJ3k7xINBiiTzc/QaIRHdt5ugctVYtcZnjruTxFa2tXFJSJYhVtgCE+DzLSkHXbVAlVS/rilAMGcO9GUiIqWTQ==}
|
||||||
|
engines: {node: '>=18'}
|
||||||
|
peerDependencies:
|
||||||
|
'@opentelemetry/api': '>=1.9.0 <1.10.0'
|
||||||
|
'@opentelemetry/core': ^1.30.1 || ^2.1.0
|
||||||
|
'@opentelemetry/exporter-trace-otlp-http': '>=0.57.0 <0.300.0'
|
||||||
|
'@opentelemetry/instrumentation': '>=0.57.1 <0.300.0'
|
||||||
|
'@opentelemetry/sdk-trace-base': ^1.30.1 || ^2.1.0
|
||||||
|
peerDependenciesMeta:
|
||||||
|
'@opentelemetry/api':
|
||||||
|
optional: true
|
||||||
|
'@opentelemetry/core':
|
||||||
|
optional: true
|
||||||
|
'@opentelemetry/exporter-trace-otlp-http':
|
||||||
|
optional: true
|
||||||
|
'@opentelemetry/instrumentation':
|
||||||
|
optional: true
|
||||||
|
'@opentelemetry/sdk-trace-base':
|
||||||
|
optional: true
|
||||||
|
|
||||||
|
'@sentry/node@10.78.0':
|
||||||
|
resolution: {integrity: sha512-AE6nyehiCK6zcktrqzzBby5OCBqIL2ZwOyOLqoenczI7ufumfmcOMSpD0IVqjeIC/Kf0N0ymujqGPzqXgu9KrA==}
|
||||||
|
engines: {node: '>=18'}
|
||||||
|
|
||||||
|
'@sentry/opentelemetry@10.78.0':
|
||||||
|
resolution: {integrity: sha512-s47uqNaHres6ijiMsaoI6/DRev80vUqTqRMk0u/DfF9xAJttK7gOGqZBESr0YD2BXA21O+sUPsPeWuHlYHiScA==}
|
||||||
|
engines: {node: '>=18'}
|
||||||
|
peerDependencies:
|
||||||
|
'@opentelemetry/api': '>=1.9.0 <1.10.0'
|
||||||
|
'@opentelemetry/core': ^1.30.1 || ^2.1.0
|
||||||
|
'@opentelemetry/sdk-trace-base': ^1.30.1 || ^2.1.0
|
||||||
|
|
||||||
|
'@sentry/server-utils@10.78.0':
|
||||||
|
resolution: {integrity: sha512-MssOiA9SansFX4E51cloHZEy4bYSZyszFNWUWeIGgQiYyTN84PbPJmyLuboj26G/ycSBW2pUERPbcfjxcs7BrA==}
|
||||||
|
engines: {node: '>=18'}
|
||||||
|
|
||||||
|
'@types/node@24.19.2':
|
||||||
|
resolution: {integrity: sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==}
|
||||||
|
|
||||||
|
cjs-module-lexer@2.3.0:
|
||||||
|
resolution: {integrity: sha512-lmNyBzi6iYiqyrExTctfmjd8tInx+dHu9PBomTfH5RXS53c27JMFJgzNv5TyAnm3PgGf+MLy0+Ws41/HlVxdKQ==}
|
||||||
|
|
||||||
|
debug@4.4.3:
|
||||||
|
resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==}
|
||||||
|
engines: {node: '>=6.0'}
|
||||||
|
peerDependencies:
|
||||||
|
supports-color: '*'
|
||||||
|
peerDependenciesMeta:
|
||||||
|
supports-color:
|
||||||
|
optional: true
|
||||||
|
|
||||||
|
es-module-lexer@3.0.4:
|
||||||
|
resolution: {integrity: sha512-BldNY5mwkVu+cQ5Ymn3e6hB9Sx8XHx4ZevWbiUyZbfKxJxYO27Hf0wfzkxIaD5CAJMaGl3YspKELj0ff/7nCMA==}
|
||||||
|
|
||||||
|
import-in-the-middle@3.6.0:
|
||||||
|
resolution: {integrity: sha512-xRU7hI24S2FhucXtuZXn8EpcOjfVP6iiEQyR0USayPeaOroEmSsNlqnl95866iRdRtkHrd6Q/Z4D14R60au0+A==}
|
||||||
|
engines: {node: '>=18'}
|
||||||
|
|
||||||
|
module-details-from-path@1.0.4:
|
||||||
|
resolution: {integrity: sha512-EGWKgxALGMgzvxYF1UyGTy0HXX/2vHLkw6+NvDKW2jypWbHpjQuj4UMcqQWXHERJhVGKikolT06G3bcKe4fi7w==}
|
||||||
|
|
||||||
|
ms@2.1.3:
|
||||||
|
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
|
||||||
|
|
||||||
|
require-in-the-middle@8.0.1:
|
||||||
|
resolution: {integrity: sha512-QT7FVMXfWOYFbeRBF6nu+I6tr2Tf3u0q8RIEjNob/heKY/nh7drD/k7eeMFmSQgnTtCzLDcCu/XEnpW2wk4xCQ==}
|
||||||
|
engines: {node: '>=9.3.0 || >=8.10.0 <9.0.0'}
|
||||||
|
|
||||||
|
typescript@5.9.3:
|
||||||
|
resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==}
|
||||||
|
engines: {node: '>=14.17'}
|
||||||
|
hasBin: true
|
||||||
|
|
||||||
|
undici-types@7.24.6:
|
||||||
|
resolution: {integrity: sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==}
|
||||||
|
|
||||||
|
snapshots:
|
||||||
|
|
||||||
|
'@biomejs/biome@2.6.7':
|
||||||
|
optionalDependencies:
|
||||||
|
'@biomejs/cli-android-arm64': 2.6.7
|
||||||
|
'@biomejs/cli-android-x64': 2.6.7
|
||||||
|
'@biomejs/cli-darwin-arm64': 2.6.7
|
||||||
|
'@biomejs/cli-darwin-x64': 2.6.7
|
||||||
|
'@biomejs/cli-linux-arm64': 2.6.7
|
||||||
|
'@biomejs/cli-linux-arm64-musl': 2.6.7
|
||||||
|
'@biomejs/cli-linux-x64': 2.6.7
|
||||||
|
'@biomejs/cli-linux-x64-musl': 2.6.7
|
||||||
|
'@biomejs/cli-win32-arm64': 2.6.7
|
||||||
|
'@biomejs/cli-win32-x64': 2.6.7
|
||||||
|
|
||||||
|
'@biomejs/cli-android-arm64@2.6.7':
|
||||||
|
optional: true
|
||||||
|
|
||||||
|
'@biomejs/cli-android-x64@2.6.7':
|
||||||
|
optional: true
|
||||||
|
|
||||||
|
'@biomejs/cli-darwin-arm64@2.6.7':
|
||||||
|
optional: true
|
||||||
|
|
||||||
|
'@biomejs/cli-darwin-x64@2.6.7':
|
||||||
|
optional: true
|
||||||
|
|
||||||
|
'@biomejs/cli-linux-arm64-musl@2.6.7':
|
||||||
|
optional: true
|
||||||
|
|
||||||
|
'@biomejs/cli-linux-arm64@2.6.7':
|
||||||
|
optional: true
|
||||||
|
|
||||||
|
'@biomejs/cli-linux-x64-musl@2.6.7':
|
||||||
|
optional: true
|
||||||
|
|
||||||
|
'@biomejs/cli-linux-x64@2.6.7':
|
||||||
|
optional: true
|
||||||
|
|
||||||
|
'@biomejs/cli-win32-arm64@2.6.7':
|
||||||
|
optional: true
|
||||||
|
|
||||||
|
'@biomejs/cli-win32-x64@2.6.7':
|
||||||
|
optional: true
|
||||||
|
|
||||||
|
'@opentelemetry/api-logs@0.220.0':
|
||||||
|
dependencies:
|
||||||
|
'@opentelemetry/api': 1.10.0
|
||||||
|
|
||||||
|
'@opentelemetry/api@1.10.0': {}
|
||||||
|
|
||||||
|
'@opentelemetry/api@1.9.1': {}
|
||||||
|
|
||||||
|
'@opentelemetry/core@2.12.0(@opentelemetry/api@1.9.1)':
|
||||||
|
dependencies:
|
||||||
|
'@opentelemetry/api': 1.9.1
|
||||||
|
'@opentelemetry/semantic-conventions': 1.45.0
|
||||||
|
|
||||||
|
'@opentelemetry/instrumentation@0.220.0(@opentelemetry/api@1.9.1)':
|
||||||
|
dependencies:
|
||||||
|
'@opentelemetry/api': 1.9.1
|
||||||
|
'@opentelemetry/api-logs': 0.220.0
|
||||||
|
import-in-the-middle: 3.6.0
|
||||||
|
require-in-the-middle: 8.0.1
|
||||||
|
transitivePeerDependencies:
|
||||||
|
- supports-color
|
||||||
|
|
||||||
|
'@opentelemetry/resources@2.12.0(@opentelemetry/api@1.9.1)':
|
||||||
|
dependencies:
|
||||||
|
'@opentelemetry/api': 1.9.1
|
||||||
|
'@opentelemetry/core': 2.12.0(@opentelemetry/api@1.9.1)
|
||||||
|
'@opentelemetry/semantic-conventions': 1.45.0
|
||||||
|
|
||||||
|
'@opentelemetry/sdk-trace-base@2.12.0(@opentelemetry/api@1.9.1)':
|
||||||
|
dependencies:
|
||||||
|
'@opentelemetry/api': 1.9.1
|
||||||
|
'@opentelemetry/core': 2.12.0(@opentelemetry/api@1.9.1)
|
||||||
|
'@opentelemetry/resources': 2.12.0(@opentelemetry/api@1.9.1)
|
||||||
|
'@opentelemetry/sdk-trace': 2.12.0(@opentelemetry/api@1.9.1)
|
||||||
|
'@opentelemetry/semantic-conventions': 1.45.0
|
||||||
|
|
||||||
|
'@opentelemetry/sdk-trace@2.12.0(@opentelemetry/api@1.9.1)':
|
||||||
|
dependencies:
|
||||||
|
'@opentelemetry/api': 1.9.1
|
||||||
|
'@opentelemetry/core': 2.12.0(@opentelemetry/api@1.9.1)
|
||||||
|
'@opentelemetry/resources': 2.12.0(@opentelemetry/api@1.9.1)
|
||||||
|
'@opentelemetry/semantic-conventions': 1.45.0
|
||||||
|
|
||||||
|
'@opentelemetry/semantic-conventions@1.45.0': {}
|
||||||
|
|
||||||
|
'@sentry/conventions@0.16.0': {}
|
||||||
|
|
||||||
|
'@sentry/core@10.78.0':
|
||||||
|
dependencies:
|
||||||
|
'@sentry/conventions': 0.16.0
|
||||||
|
|
||||||
|
'@sentry/node-core@10.78.0(@opentelemetry/api@1.9.1)(@opentelemetry/core@2.12.0(@opentelemetry/api@1.9.1))(@opentelemetry/instrumentation@0.220.0(@opentelemetry/api@1.9.1))(@opentelemetry/sdk-trace-base@2.12.0(@opentelemetry/api@1.9.1))':
|
||||||
|
dependencies:
|
||||||
|
'@sentry/conventions': 0.16.0
|
||||||
|
'@sentry/core': 10.78.0
|
||||||
|
'@sentry/opentelemetry': 10.78.0(@opentelemetry/api@1.9.1)(@opentelemetry/core@2.12.0(@opentelemetry/api@1.9.1))(@opentelemetry/sdk-trace-base@2.12.0(@opentelemetry/api@1.9.1))
|
||||||
|
import-in-the-middle: 3.6.0
|
||||||
|
optionalDependencies:
|
||||||
|
'@opentelemetry/api': 1.9.1
|
||||||
|
'@opentelemetry/core': 2.12.0(@opentelemetry/api@1.9.1)
|
||||||
|
'@opentelemetry/instrumentation': 0.220.0(@opentelemetry/api@1.9.1)
|
||||||
|
'@opentelemetry/sdk-trace-base': 2.12.0(@opentelemetry/api@1.9.1)
|
||||||
|
|
||||||
|
'@sentry/node@10.78.0(@opentelemetry/core@2.12.0(@opentelemetry/api@1.9.1))':
|
||||||
|
dependencies:
|
||||||
|
'@opentelemetry/api': 1.9.1
|
||||||
|
'@opentelemetry/instrumentation': 0.220.0(@opentelemetry/api@1.9.1)
|
||||||
|
'@opentelemetry/sdk-trace-base': 2.12.0(@opentelemetry/api@1.9.1)
|
||||||
|
'@sentry/conventions': 0.16.0
|
||||||
|
'@sentry/core': 10.78.0
|
||||||
|
'@sentry/node-core': 10.78.0(@opentelemetry/api@1.9.1)(@opentelemetry/core@2.12.0(@opentelemetry/api@1.9.1))(@opentelemetry/instrumentation@0.220.0(@opentelemetry/api@1.9.1))(@opentelemetry/sdk-trace-base@2.12.0(@opentelemetry/api@1.9.1))
|
||||||
|
'@sentry/opentelemetry': 10.78.0(@opentelemetry/api@1.9.1)(@opentelemetry/core@2.12.0(@opentelemetry/api@1.9.1))(@opentelemetry/sdk-trace-base@2.12.0(@opentelemetry/api@1.9.1))
|
||||||
|
'@sentry/server-utils': 10.78.0
|
||||||
|
import-in-the-middle: 3.6.0
|
||||||
|
transitivePeerDependencies:
|
||||||
|
- '@opentelemetry/core'
|
||||||
|
- '@opentelemetry/exporter-trace-otlp-http'
|
||||||
|
- supports-color
|
||||||
|
|
||||||
|
'@sentry/opentelemetry@10.78.0(@opentelemetry/api@1.9.1)(@opentelemetry/core@2.12.0(@opentelemetry/api@1.9.1))(@opentelemetry/sdk-trace-base@2.12.0(@opentelemetry/api@1.9.1))':
|
||||||
|
dependencies:
|
||||||
|
'@opentelemetry/api': 1.9.1
|
||||||
|
'@opentelemetry/core': 2.12.0(@opentelemetry/api@1.9.1)
|
||||||
|
'@opentelemetry/sdk-trace-base': 2.12.0(@opentelemetry/api@1.9.1)
|
||||||
|
'@sentry/conventions': 0.16.0
|
||||||
|
'@sentry/core': 10.78.0
|
||||||
|
|
||||||
|
'@sentry/server-utils@10.78.0':
|
||||||
|
dependencies:
|
||||||
|
'@sentry/conventions': 0.16.0
|
||||||
|
'@sentry/core': 10.78.0
|
||||||
|
|
||||||
|
'@types/node@24.19.2':
|
||||||
|
dependencies:
|
||||||
|
undici-types: 7.24.6
|
||||||
|
|
||||||
|
cjs-module-lexer@2.3.0: {}
|
||||||
|
|
||||||
|
debug@4.4.3:
|
||||||
|
dependencies:
|
||||||
|
ms: 2.1.3
|
||||||
|
|
||||||
|
es-module-lexer@3.0.4: {}
|
||||||
|
|
||||||
|
import-in-the-middle@3.6.0:
|
||||||
|
dependencies:
|
||||||
|
cjs-module-lexer: 2.3.0
|
||||||
|
es-module-lexer: 3.0.4
|
||||||
|
module-details-from-path: 1.0.4
|
||||||
|
|
||||||
|
module-details-from-path@1.0.4: {}
|
||||||
|
|
||||||
|
ms@2.1.3: {}
|
||||||
|
|
||||||
|
require-in-the-middle@8.0.1:
|
||||||
|
dependencies:
|
||||||
|
debug: 4.4.3
|
||||||
|
module-details-from-path: 1.0.4
|
||||||
|
transitivePeerDependencies:
|
||||||
|
- supports-color
|
||||||
|
|
||||||
|
typescript@5.9.3: {}
|
||||||
|
|
||||||
|
undici-types@7.24.6: {}
|
||||||
94
src/app.ts
Normal file
94
src/app.ts
Normal file
@ -0,0 +1,94 @@
|
|||||||
|
import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
|
||||||
|
import { registerAuthRoutes } from "./auth/routes.ts";
|
||||||
|
import { type AppEnv, isDevLoginEnabled } from "./config.ts";
|
||||||
|
import type { Db } from "./db/database.ts";
|
||||||
|
import { HttpError } from "./errors.ts";
|
||||||
|
import { registerFandomatRoutes } from "./fandomats/routes.ts";
|
||||||
|
import { type RequestContext, Router } from "./http/router.ts";
|
||||||
|
import { registerPointsRoutes } from "./points/routes.ts";
|
||||||
|
import { registerRewardRoutes } from "./rewards/routes.ts";
|
||||||
|
|
||||||
|
const MAX_BODY_BYTES = 1024 * 1024;
|
||||||
|
|
||||||
|
export interface AppOptions {
|
||||||
|
db: Db;
|
||||||
|
appEnv: AppEnv;
|
||||||
|
onError?: (error: unknown) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildRouter({ db, appEnv }: AppOptions): Router {
|
||||||
|
const router = new Router();
|
||||||
|
router.get("/healthz", () => {
|
||||||
|
db.prepare("SELECT 1").get();
|
||||||
|
return { body: { status: "ok" } };
|
||||||
|
});
|
||||||
|
registerAuthRoutes(router, db, { devLogin: isDevLoginEnabled(appEnv) });
|
||||||
|
registerPointsRoutes(router, db);
|
||||||
|
registerFandomatRoutes(router, db);
|
||||||
|
registerRewardRoutes(router, db);
|
||||||
|
return router;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createApp(options: AppOptions): Server {
|
||||||
|
const router = buildRouter(options);
|
||||||
|
return createServer((req, res) => {
|
||||||
|
handle(router, req, res).catch((error: unknown) => {
|
||||||
|
options.onError?.(error);
|
||||||
|
if (!res.headersSent)
|
||||||
|
send(res, 500, { error: { code: "internal_error", message: "Внутренняя ошибка" } });
|
||||||
|
else res.end();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handle(router: Router, req: IncomingMessage, res: ServerResponse): Promise<void> {
|
||||||
|
const url = new URL(req.url ?? "/", "http://localhost");
|
||||||
|
const method = req.method ?? "GET";
|
||||||
|
const match = router.match(method, url.pathname);
|
||||||
|
try {
|
||||||
|
if (match === null) throw new HttpError(404, "not_found", "Маршрут не найден");
|
||||||
|
if (match === "method_not_allowed")
|
||||||
|
throw new HttpError(405, "method_not_allowed", "Метод не поддерживается");
|
||||||
|
const ctx: RequestContext = {
|
||||||
|
method,
|
||||||
|
path: url.pathname,
|
||||||
|
params: match.params,
|
||||||
|
headers: req.headers,
|
||||||
|
body: await readJsonBody(req),
|
||||||
|
};
|
||||||
|
const result = await match.handler(ctx);
|
||||||
|
send(res, result.status ?? 200, result.body);
|
||||||
|
} catch (error) {
|
||||||
|
if (!(error instanceof HttpError)) throw error;
|
||||||
|
send(res, error.status, {
|
||||||
|
error: { code: error.code, message: error.message, ...error.details },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function readJsonBody(req: IncomingMessage): Promise<unknown> {
|
||||||
|
const chunks: Buffer[] = [];
|
||||||
|
let size = 0;
|
||||||
|
for await (const chunk of req) {
|
||||||
|
size += (chunk as Buffer).length;
|
||||||
|
if (size > MAX_BODY_BYTES)
|
||||||
|
throw new HttpError(413, "payload_too_large", "Слишком большое тело запроса");
|
||||||
|
chunks.push(chunk as Buffer);
|
||||||
|
}
|
||||||
|
if (size === 0) return undefined;
|
||||||
|
try {
|
||||||
|
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
||||||
|
} catch {
|
||||||
|
throw new HttpError(400, "invalid_json", "Тело запроса — некорректный JSON");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function send(res: ServerResponse, status: number, body: unknown): void {
|
||||||
|
const payload = JSON.stringify(body);
|
||||||
|
res.writeHead(status, {
|
||||||
|
"content-type": "application/json; charset=utf-8",
|
||||||
|
"content-length": Buffer.byteLength(payload),
|
||||||
|
"cache-control": "no-store",
|
||||||
|
});
|
||||||
|
res.end(payload);
|
||||||
|
}
|
||||||
22
src/auth/routes.ts
Normal file
22
src/auth/routes.ts
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
import type { Db } from "../db/database.ts";
|
||||||
|
import { badRequest, forbidden, unauthorized } from "../errors.ts";
|
||||||
|
import type { Router } from "../http/router.ts";
|
||||||
|
import { authenticate, createSession, findUserByLogin, publicUser } from "./users.ts";
|
||||||
|
|
||||||
|
export function registerAuthRoutes(router: Router, db: Db, opts: { devLogin: boolean }): void {
|
||||||
|
// Тестовый вход: только development/test. В остальных средах маршрута нет — 404.
|
||||||
|
if (opts.devLogin) {
|
||||||
|
router.post("/api/auth/dev-login", (ctx) => {
|
||||||
|
const login = (ctx.body as { login?: unknown } | undefined)?.login;
|
||||||
|
if (typeof login !== "string" || login.length === 0) {
|
||||||
|
throw badRequest("validation_error", "Поле login обязательно");
|
||||||
|
}
|
||||||
|
const user = findUserByLogin(db, login);
|
||||||
|
if (!user) throw unauthorized("invalid_login", "Неизвестный тестовый пользователь");
|
||||||
|
if (user.status === "blocked") throw forbidden("user_blocked", "Пользователь заблокирован");
|
||||||
|
return { body: { token: createSession(db, user.id), user: publicUser(user) } };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
router.get("/api/me", (ctx) => ({ body: publicUser(authenticate(db, ctx)) }));
|
||||||
|
}
|
||||||
91
src/auth/users.ts
Normal file
91
src/auth/users.ts
Normal file
@ -0,0 +1,91 @@
|
|||||||
|
import { newToken, sha256 } from "../crypto.ts";
|
||||||
|
import type { Db } from "../db/database.ts";
|
||||||
|
import { forbidden, unauthorized } from "../errors.ts";
|
||||||
|
import type { RequestContext } from "../http/router.ts";
|
||||||
|
|
||||||
|
export type Role = "resident" | "partner" | "admin";
|
||||||
|
export type UserStatus = "pending" | "verified" | "blocked";
|
||||||
|
|
||||||
|
export interface User {
|
||||||
|
id: string;
|
||||||
|
login: string;
|
||||||
|
role: Role;
|
||||||
|
status: UserStatus;
|
||||||
|
displayName: string;
|
||||||
|
residentCode: string | null;
|
||||||
|
partnerId: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
||||||
|
|
||||||
|
type Row = Record<string, unknown>;
|
||||||
|
|
||||||
|
export function rowToUser(row: Row): User {
|
||||||
|
return {
|
||||||
|
id: String(row.id),
|
||||||
|
login: String(row.login),
|
||||||
|
role: row.role as Role,
|
||||||
|
status: row.status as UserStatus,
|
||||||
|
displayName: String(row.display_name),
|
||||||
|
residentCode: (row.resident_code as string | null) ?? null,
|
||||||
|
partnerId: (row.partner_id as string | null) ?? null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function findUserByLogin(db: Db, login: string): User | null {
|
||||||
|
const row = db.prepare("SELECT * FROM users WHERE login = ?").get(login);
|
||||||
|
return row ? rowToUser(row) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function findResidentByCode(db: Db, code: string): User | null {
|
||||||
|
const row = db
|
||||||
|
.prepare("SELECT * FROM users WHERE resident_code = ? AND role = 'resident'")
|
||||||
|
.get(code);
|
||||||
|
return row ? rowToUser(row) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createSession(db: Db, userId: string, now = new Date()): string {
|
||||||
|
const token = newToken();
|
||||||
|
db.prepare(
|
||||||
|
"INSERT INTO sessions (token_hash, user_id, created_at, expires_at) VALUES (?, ?, ?, ?)",
|
||||||
|
).run(
|
||||||
|
sha256(token),
|
||||||
|
userId,
|
||||||
|
now.toISOString(),
|
||||||
|
new Date(now.getTime() + SESSION_TTL_MS).toISOString(),
|
||||||
|
);
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Пользователь по заголовку `Authorization: Bearer <token>` или 401. */
|
||||||
|
export function authenticate(db: Db, ctx: RequestContext): User {
|
||||||
|
const header = ctx.headers.authorization;
|
||||||
|
const match = typeof header === "string" ? /^Bearer\s+(\S+)$/i.exec(header) : null;
|
||||||
|
if (!match?.[1]) throw unauthorized();
|
||||||
|
const row = db
|
||||||
|
.prepare(
|
||||||
|
`SELECT u.* FROM sessions s JOIN users u ON u.id = s.user_id
|
||||||
|
WHERE s.token_hash = ? AND s.expires_at > ?`,
|
||||||
|
)
|
||||||
|
.get(sha256(match[1]), new Date().toISOString());
|
||||||
|
if (!row) throw unauthorized();
|
||||||
|
const user = rowToUser(row);
|
||||||
|
if (user.status === "blocked") throw forbidden("user_blocked", "Пользователь заблокирован");
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function requireRole(user: User, role: Role): void {
|
||||||
|
if (user.role !== role) throw forbidden();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function publicUser(user: User) {
|
||||||
|
return {
|
||||||
|
id: user.id,
|
||||||
|
login: user.login,
|
||||||
|
role: user.role,
|
||||||
|
status: user.status,
|
||||||
|
displayName: user.displayName,
|
||||||
|
...(user.role === "resident" ? { residentCode: user.residentCode } : {}),
|
||||||
|
...(user.role === "partner" ? { partnerId: user.partnerId } : {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
37
src/config.ts
Normal file
37
src/config.ts
Normal file
@ -0,0 +1,37 @@
|
|||||||
|
export type AppEnv = "development" | "test" | "staging" | "production";
|
||||||
|
|
||||||
|
export interface Config {
|
||||||
|
port: number;
|
||||||
|
appEnv: AppEnv;
|
||||||
|
databasePath: string;
|
||||||
|
seedDemo: boolean;
|
||||||
|
sentry: { dsn?: string; release?: string; environment: string };
|
||||||
|
}
|
||||||
|
|
||||||
|
const APP_ENVS: readonly AppEnv[] = ["development", "test", "staging", "production"];
|
||||||
|
|
||||||
|
function parseAppEnv(value: string | undefined): AppEnv {
|
||||||
|
if (value === undefined || value === "") return "production";
|
||||||
|
if ((APP_ENVS as readonly string[]).includes(value)) return value as AppEnv;
|
||||||
|
throw new Error(`Unknown APP_ENV "${value}", expected one of: ${APP_ENVS.join(", ")}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {
|
||||||
|
const appEnv = parseAppEnv(env.APP_ENV);
|
||||||
|
return {
|
||||||
|
port: Number(env.PORT ?? 3000),
|
||||||
|
appEnv,
|
||||||
|
databasePath: env.DATABASE_PATH ?? "data/tazakazahstan.db",
|
||||||
|
seedDemo: env.SEED_DEMO === "1" || (env.SEED_DEMO === undefined && appEnv === "development"),
|
||||||
|
sentry: {
|
||||||
|
dsn: env.SENTRY_DSN || undefined,
|
||||||
|
release: env.SENTRY_RELEASE || undefined,
|
||||||
|
environment: env.SENTRY_ENVIRONMENT ?? (appEnv === "production" ? "prod" : "dev"),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Тестовый вход (dev-login) доступен только в этих средах. */
|
||||||
|
export function isDevLoginEnabled(appEnv: AppEnv): boolean {
|
||||||
|
return appEnv === "development" || appEnv === "test";
|
||||||
|
}
|
||||||
33
src/crypto.ts
Normal file
33
src/crypto.ts
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
import { createHash, randomBytes, randomInt, timingSafeEqual } from "node:crypto";
|
||||||
|
|
||||||
|
export const sha256 = (value: string): string => createHash("sha256").update(value).digest("hex");
|
||||||
|
|
||||||
|
export const newToken = (): string => randomBytes(32).toString("base64url");
|
||||||
|
|
||||||
|
export function safeEqualHex(a: string, b: string): boolean {
|
||||||
|
const ba = Buffer.from(a, "hex");
|
||||||
|
const bb = Buffer.from(b, "hex");
|
||||||
|
return ba.length === bb.length && timingSafeEqual(ba, bb);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** JSON с отсортированными ключами — для стабильного хэша содержимого запроса. */
|
||||||
|
export function canonicalJson(value: unknown): string {
|
||||||
|
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
|
||||||
|
if (value !== null && typeof value === "object") {
|
||||||
|
const entries = Object.entries(value as Record<string, unknown>)
|
||||||
|
.filter(([, v]) => v !== undefined)
|
||||||
|
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
||||||
|
return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(",")}}`;
|
||||||
|
}
|
||||||
|
return JSON.stringify(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Без похожих символов (0/O, 1/I/L), чтобы код было удобно продиктовать на кассе.
|
||||||
|
const CODE_ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789";
|
||||||
|
|
||||||
|
/** Код льготы вида `TZK-XXXX-XXXX`. */
|
||||||
|
export function newRewardCode(): string {
|
||||||
|
const part = () =>
|
||||||
|
Array.from({ length: 4 }, () => CODE_ALPHABET[randomInt(CODE_ALPHABET.length)]).join("");
|
||||||
|
return `TZK-${part()}-${part()}`;
|
||||||
|
}
|
||||||
61
src/db/database.ts
Normal file
61
src/db/database.ts
Normal file
@ -0,0 +1,61 @@
|
|||||||
|
import { mkdirSync } from "node:fs";
|
||||||
|
import { dirname } from "node:path";
|
||||||
|
import { DatabaseSync } from "node:sqlite";
|
||||||
|
import { migrations as defaultMigrations, type Migration } from "./migrations.ts";
|
||||||
|
|
||||||
|
export type Db = DatabaseSync;
|
||||||
|
|
||||||
|
export function openDatabase(path: string): Db {
|
||||||
|
if (path !== ":memory:") mkdirSync(dirname(path), { recursive: true });
|
||||||
|
const db = new DatabaseSync(path);
|
||||||
|
db.exec("PRAGMA foreign_keys = ON");
|
||||||
|
db.exec("PRAGMA busy_timeout = 5000");
|
||||||
|
if (path !== ":memory:") db.exec("PRAGMA journal_mode = WAL");
|
||||||
|
return db;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Применяет недостающие миграции; возвращает имена применённых. */
|
||||||
|
export function migrate(db: Db, migrations: Migration[] = defaultMigrations): string[] {
|
||||||
|
db.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||||
|
id INTEGER PRIMARY KEY,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
applied_at TEXT NOT NULL
|
||||||
|
)`);
|
||||||
|
const applied = new Set(
|
||||||
|
db
|
||||||
|
.prepare("SELECT id FROM schema_migrations")
|
||||||
|
.all()
|
||||||
|
.map((row) => Number(row.id)),
|
||||||
|
);
|
||||||
|
const done: string[] = [];
|
||||||
|
for (const m of [...migrations].sort((a, b) => a.id - b.id)) {
|
||||||
|
if (applied.has(m.id)) continue;
|
||||||
|
transaction(db, () => {
|
||||||
|
db.exec(m.sql);
|
||||||
|
db.prepare("INSERT INTO schema_migrations (id, name, applied_at) VALUES (?, ?, ?)").run(
|
||||||
|
m.id,
|
||||||
|
m.name,
|
||||||
|
new Date().toISOString(),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
done.push(m.name);
|
||||||
|
}
|
||||||
|
return done;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Выполняет `fn` в транзакции `BEGIN IMMEDIATE`: блокировка записи берётся сразу,
|
||||||
|
* поэтому проверка баланса и списание не могут перемежаться с другими записями.
|
||||||
|
* `fn` должна быть синхронной. Любое исключение откатывает транзакцию.
|
||||||
|
*/
|
||||||
|
export function transaction<T>(db: Db, fn: () => T): T {
|
||||||
|
db.exec("BEGIN IMMEDIATE");
|
||||||
|
try {
|
||||||
|
const result = fn();
|
||||||
|
db.exec("COMMIT");
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
if (db.isTransaction) db.exec("ROLLBACK");
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
10
src/db/migrate-cli.ts
Normal file
10
src/db/migrate-cli.ts
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
import { loadConfig } from "../config.ts";
|
||||||
|
import { migrate, openDatabase } from "./database.ts";
|
||||||
|
|
||||||
|
const config = loadConfig();
|
||||||
|
const db = openDatabase(config.databasePath);
|
||||||
|
const applied = migrate(db);
|
||||||
|
console.log(
|
||||||
|
applied.length > 0 ? `Applied migrations: ${applied.join(", ")}` : "Database is up to date",
|
||||||
|
);
|
||||||
|
db.close();
|
||||||
103
src/db/migrations.ts
Normal file
103
src/db/migrations.ts
Normal file
@ -0,0 +1,103 @@
|
|||||||
|
export interface Migration {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
sql: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Миграции применяются по порядку `id` и никогда не редактируются задним числом. */
|
||||||
|
export const migrations: Migration[] = [
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
name: "initial_fandomat_points_rewards",
|
||||||
|
sql: `
|
||||||
|
CREATE TABLE partners (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
name TEXT NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE users (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
login TEXT NOT NULL UNIQUE,
|
||||||
|
role TEXT NOT NULL CHECK (role IN ('resident', 'partner', 'admin')),
|
||||||
|
status TEXT NOT NULL CHECK (status IN ('pending', 'verified', 'blocked')),
|
||||||
|
display_name TEXT NOT NULL,
|
||||||
|
resident_code TEXT UNIQUE,
|
||||||
|
partner_id TEXT REFERENCES partners(id),
|
||||||
|
created_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE sessions (
|
||||||
|
token_hash TEXT PRIMARY KEY,
|
||||||
|
user_id TEXT NOT NULL REFERENCES users(id),
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
expires_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE fandomats (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
district TEXT NOT NULL,
|
||||||
|
address TEXT NOT NULL,
|
||||||
|
api_key_hash TEXT NOT NULL UNIQUE
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE fandomat_events (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
fandomat_id TEXT NOT NULL REFERENCES fandomats(id),
|
||||||
|
event_id TEXT NOT NULL,
|
||||||
|
payload_hash TEXT NOT NULL,
|
||||||
|
payload TEXT NOT NULL,
|
||||||
|
resident_id TEXT REFERENCES users(id),
|
||||||
|
outcome TEXT NOT NULL
|
||||||
|
CHECK (outcome IN ('credited', 'unlinked', 'ignored', 'resident_blocked')),
|
||||||
|
points INTEGER NOT NULL CHECK (points >= 0),
|
||||||
|
received_at TEXT NOT NULL,
|
||||||
|
UNIQUE (fandomat_id, event_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE point_accounts (
|
||||||
|
user_id TEXT PRIMARY KEY REFERENCES users(id),
|
||||||
|
balance INTEGER NOT NULL DEFAULT 0 CHECK (balance >= 0),
|
||||||
|
updated_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE point_ledger (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
user_id TEXT NOT NULL REFERENCES users(id),
|
||||||
|
kind TEXT NOT NULL CHECK (kind IN ('earn', 'redeem')),
|
||||||
|
delta INTEGER NOT NULL CHECK (delta <> 0),
|
||||||
|
balance_after INTEGER NOT NULL CHECK (balance_after >= 0),
|
||||||
|
source_type TEXT NOT NULL CHECK (source_type IN ('fandomat_event', 'redemption')),
|
||||||
|
source_id TEXT NOT NULL,
|
||||||
|
description TEXT NOT NULL,
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
UNIQUE (source_type, source_id)
|
||||||
|
);
|
||||||
|
CREATE INDEX point_ledger_user ON point_ledger (user_id, id);
|
||||||
|
|
||||||
|
CREATE TABLE rewards (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
partner_id TEXT NOT NULL REFERENCES partners(id),
|
||||||
|
title TEXT NOT NULL,
|
||||||
|
description TEXT NOT NULL,
|
||||||
|
cost_points INTEGER NOT NULL CHECK (cost_points > 0),
|
||||||
|
allowed_statuses TEXT NOT NULL,
|
||||||
|
stock INTEGER CHECK (stock IS NULL OR stock >= 0),
|
||||||
|
active INTEGER NOT NULL DEFAULT 1
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE redemptions (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
user_id TEXT NOT NULL REFERENCES users(id),
|
||||||
|
reward_id TEXT NOT NULL REFERENCES rewards(id),
|
||||||
|
idempotency_key TEXT NOT NULL,
|
||||||
|
code TEXT NOT NULL UNIQUE,
|
||||||
|
points INTEGER NOT NULL,
|
||||||
|
balance_after INTEGER NOT NULL,
|
||||||
|
status TEXT NOT NULL CHECK (status IN ('issued', 'used')),
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
used_at TEXT,
|
||||||
|
UNIQUE (user_id, idempotency_key)
|
||||||
|
);
|
||||||
|
`,
|
||||||
|
},
|
||||||
|
];
|
||||||
29
src/errors.ts
Normal file
29
src/errors.ts
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
/** Ошибка, которая отдаётся клиенту как `{ "error": { code, message, ...details } }`. */
|
||||||
|
export class HttpError extends Error {
|
||||||
|
readonly status: number;
|
||||||
|
readonly code: string;
|
||||||
|
readonly details: Record<string, unknown>;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
status: number,
|
||||||
|
code: string,
|
||||||
|
message: string,
|
||||||
|
details: Record<string, unknown> = {},
|
||||||
|
) {
|
||||||
|
super(message);
|
||||||
|
this.status = status;
|
||||||
|
this.code = code;
|
||||||
|
this.details = details;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const badRequest = (code: string, message: string, details?: Record<string, unknown>) =>
|
||||||
|
new HttpError(400, code, message, details);
|
||||||
|
export const unauthorized = (code = "unauthorized", message = "Требуется вход") =>
|
||||||
|
new HttpError(401, code, message);
|
||||||
|
export const forbidden = (code = "forbidden", message = "Недостаточно прав") =>
|
||||||
|
new HttpError(403, code, message);
|
||||||
|
export const notFound = (code = "not_found", message = "Не найдено") =>
|
||||||
|
new HttpError(404, code, message);
|
||||||
|
export const conflict = (code: string, message: string, details?: Record<string, unknown>) =>
|
||||||
|
new HttpError(409, code, message, details);
|
||||||
167
src/fandomats/events.ts
Normal file
167
src/fandomats/events.ts
Normal file
@ -0,0 +1,167 @@
|
|||||||
|
import { findResidentByCode } from "../auth/users.ts";
|
||||||
|
import { canonicalJson, safeEqualHex, sha256 } from "../crypto.ts";
|
||||||
|
import type { Db } from "../db/database.ts";
|
||||||
|
import { transaction } from "../db/database.ts";
|
||||||
|
import { badRequest, conflict, unauthorized } from "../errors.ts";
|
||||||
|
import { postLedgerEntry } from "../points/ledger.ts";
|
||||||
|
import { CONTAINER_TYPES, type ContainerItem, pointsForItems } from "../points/rates.ts";
|
||||||
|
|
||||||
|
export type EventOutcome = "credited" | "unlinked" | "ignored" | "resident_blocked";
|
||||||
|
|
||||||
|
export interface FandomatEvent {
|
||||||
|
eventId: string;
|
||||||
|
fandomatId: string;
|
||||||
|
status: "confirmed" | "rejected";
|
||||||
|
residentCode: string | null;
|
||||||
|
occurredAt: string | null;
|
||||||
|
items: ContainerItem[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface EventResult {
|
||||||
|
eventId: string;
|
||||||
|
fandomatId: string;
|
||||||
|
outcome: EventOutcome;
|
||||||
|
points: number;
|
||||||
|
duplicate: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const MAX_ITEMS = 50;
|
||||||
|
const ID_PATTERN = /^[A-Za-z0-9._:-]{1,100}$/;
|
||||||
|
|
||||||
|
/** Фандомат по ключу устройства (заголовок `X-Fandomat-Key`) или 401. */
|
||||||
|
export function authenticateFandomat(db: Db, key: unknown): string {
|
||||||
|
if (typeof key !== "string" || key.length === 0) throw invalidKey();
|
||||||
|
const keyHash = sha256(key);
|
||||||
|
const row = db
|
||||||
|
.prepare("SELECT id, api_key_hash FROM fandomats WHERE api_key_hash = ?")
|
||||||
|
.get(keyHash);
|
||||||
|
if (!row || !safeEqualHex(String(row.api_key_hash), keyHash)) throw invalidKey();
|
||||||
|
return String(row.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
const invalidKey = () => unauthorized("invalid_fandomat_key", "Неверный ключ фандомата");
|
||||||
|
|
||||||
|
function fail(message: string): never {
|
||||||
|
throw badRequest("validation_error", message);
|
||||||
|
}
|
||||||
|
|
||||||
|
const isInt = (v: unknown, min: number, max: number): v is number =>
|
||||||
|
typeof v === "number" && Number.isInteger(v) && v >= min && v <= max;
|
||||||
|
|
||||||
|
export function parseFandomatEvent(body: unknown): FandomatEvent {
|
||||||
|
if (body === null || typeof body !== "object" || Array.isArray(body))
|
||||||
|
fail("Ожидается JSON-объект");
|
||||||
|
const b = body as Record<string, unknown>;
|
||||||
|
if (typeof b.eventId !== "string" || !ID_PATTERN.test(b.eventId))
|
||||||
|
fail("eventId: 1–100 символов [A-Za-z0-9._:-]");
|
||||||
|
if (typeof b.fandomatId !== "string" || b.fandomatId.length === 0) fail("fandomatId обязателен");
|
||||||
|
if (b.status !== "confirmed" && b.status !== "rejected") fail("status: confirmed или rejected");
|
||||||
|
if (
|
||||||
|
b.residentCode !== undefined &&
|
||||||
|
b.residentCode !== null &&
|
||||||
|
typeof b.residentCode !== "string"
|
||||||
|
) {
|
||||||
|
fail("residentCode должен быть строкой");
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
b.occurredAt !== undefined &&
|
||||||
|
(typeof b.occurredAt !== "string" || Number.isNaN(Date.parse(b.occurredAt)))
|
||||||
|
) {
|
||||||
|
fail("occurredAt: дата в формате ISO 8601");
|
||||||
|
}
|
||||||
|
if (!Array.isArray(b.items) || b.items.length === 0 || b.items.length > MAX_ITEMS) {
|
||||||
|
fail(`items: от 1 до ${MAX_ITEMS} позиций`);
|
||||||
|
}
|
||||||
|
const items = b.items.map((raw, i): ContainerItem => {
|
||||||
|
const it = (raw ?? {}) as Record<string, unknown>;
|
||||||
|
if (!(CONTAINER_TYPES as readonly unknown[]).includes(it.type)) {
|
||||||
|
fail(`items[${i}].type: ${CONTAINER_TYPES.join(", ")}`);
|
||||||
|
}
|
||||||
|
if (!isInt(it.volumeMl, 100, 5000)) fail(`items[${i}].volumeMl: целое 100–5000`);
|
||||||
|
if (!isInt(it.count, 1, 500)) fail(`items[${i}].count: целое 1–500`);
|
||||||
|
return { type: it.type as ContainerItem["type"], volumeMl: it.volumeMl, count: it.count };
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
eventId: b.eventId,
|
||||||
|
fandomatId: b.fandomatId,
|
||||||
|
status: b.status,
|
||||||
|
residentCode: (b.residentCode as string | null | undefined) || null,
|
||||||
|
occurredAt: (b.occurredAt as string | undefined) ?? null,
|
||||||
|
items,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Обрабатывает событие ровно один раз по паре (fandomatId, eventId).
|
||||||
|
* Повтор с тем же содержимым возвращает прежний итог (`duplicate: true`), с другим — 409.
|
||||||
|
*/
|
||||||
|
export function processFandomatEvent(db: Db, event: FandomatEvent): EventResult {
|
||||||
|
const payload = canonicalJson({
|
||||||
|
status: event.status,
|
||||||
|
residentCode: event.residentCode,
|
||||||
|
occurredAt: event.occurredAt,
|
||||||
|
items: event.items,
|
||||||
|
});
|
||||||
|
const payloadHash = sha256(payload);
|
||||||
|
|
||||||
|
return transaction(db, () => {
|
||||||
|
const existing = db
|
||||||
|
.prepare(
|
||||||
|
"SELECT payload_hash, outcome, points FROM fandomat_events WHERE fandomat_id = ? AND event_id = ?",
|
||||||
|
)
|
||||||
|
.get(event.fandomatId, event.eventId);
|
||||||
|
if (existing) {
|
||||||
|
if (existing.payload_hash !== payloadHash) {
|
||||||
|
throw conflict("event_conflict", "Событие с этим eventId уже получено с другим содержимым");
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
eventId: event.eventId,
|
||||||
|
fandomatId: event.fandomatId,
|
||||||
|
outcome: existing.outcome as EventOutcome,
|
||||||
|
points: Number(existing.points),
|
||||||
|
duplicate: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const resident = event.residentCode ? findResidentByCode(db, event.residentCode) : null;
|
||||||
|
let outcome: EventOutcome;
|
||||||
|
if (event.status !== "confirmed") outcome = "ignored";
|
||||||
|
else if (!resident) outcome = "unlinked";
|
||||||
|
else if (resident.status === "blocked") outcome = "resident_blocked";
|
||||||
|
else outcome = "credited";
|
||||||
|
const points = outcome === "credited" ? pointsForItems(event.items) : 0;
|
||||||
|
|
||||||
|
db.prepare(
|
||||||
|
`INSERT INTO fandomat_events (fandomat_id, event_id, payload_hash, payload, resident_id, outcome, points, received_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||||
|
).run(
|
||||||
|
event.fandomatId,
|
||||||
|
event.eventId,
|
||||||
|
payloadHash,
|
||||||
|
payload,
|
||||||
|
resident?.id ?? null,
|
||||||
|
outcome,
|
||||||
|
points,
|
||||||
|
new Date().toISOString(),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (outcome === "credited" && resident) {
|
||||||
|
postLedgerEntry(db, {
|
||||||
|
userId: resident.id,
|
||||||
|
kind: "earn",
|
||||||
|
delta: points,
|
||||||
|
sourceType: "fandomat_event",
|
||||||
|
sourceId: `${event.fandomatId}:${event.eventId}`,
|
||||||
|
description: `Сдача тары: фандомат ${event.fandomatId}, событие ${event.eventId}`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
eventId: event.eventId,
|
||||||
|
fandomatId: event.fandomatId,
|
||||||
|
outcome,
|
||||||
|
points,
|
||||||
|
duplicate: false,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
16
src/fandomats/routes.ts
Normal file
16
src/fandomats/routes.ts
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
import type { Db } from "../db/database.ts";
|
||||||
|
import { unauthorized } from "../errors.ts";
|
||||||
|
import type { Router } from "../http/router.ts";
|
||||||
|
import { authenticateFandomat, parseFandomatEvent, processFandomatEvent } from "./events.ts";
|
||||||
|
|
||||||
|
export function registerFandomatRoutes(router: Router, db: Db): void {
|
||||||
|
router.post("/api/fandomats/events", (ctx) => {
|
||||||
|
// Сначала устройство, потом содержимое: без верного ключа ничего не разбираем и не храним.
|
||||||
|
const fandomatId = authenticateFandomat(db, ctx.headers["x-fandomat-key"]);
|
||||||
|
const claimed = (ctx.body as { fandomatId?: unknown } | undefined)?.fandomatId;
|
||||||
|
if (claimed !== fandomatId)
|
||||||
|
throw unauthorized("invalid_fandomat_key", "Неверный ключ фандомата");
|
||||||
|
const event = parseFandomatEvent(ctx.body);
|
||||||
|
return { body: processFandomatEvent(db, event) };
|
||||||
|
});
|
||||||
|
}
|
||||||
72
src/http/router.ts
Normal file
72
src/http/router.ts
Normal file
@ -0,0 +1,72 @@
|
|||||||
|
import type { IncomingHttpHeaders } from "node:http";
|
||||||
|
|
||||||
|
export interface RequestContext {
|
||||||
|
method: string;
|
||||||
|
path: string;
|
||||||
|
params: Record<string, string>;
|
||||||
|
headers: IncomingHttpHeaders;
|
||||||
|
/** Разобранное JSON-тело (undefined, если тела нет). */
|
||||||
|
body: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface HandlerResult {
|
||||||
|
status?: number;
|
||||||
|
body: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Handler = (ctx: RequestContext) => HandlerResult | Promise<HandlerResult>;
|
||||||
|
|
||||||
|
interface Route {
|
||||||
|
method: string;
|
||||||
|
pattern: RegExp;
|
||||||
|
keys: string[];
|
||||||
|
handler: Handler;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class Router {
|
||||||
|
private readonly routes: Route[] = [];
|
||||||
|
|
||||||
|
add(method: string, path: string, handler: Handler): this {
|
||||||
|
const keys: string[] = [];
|
||||||
|
const source = path
|
||||||
|
.split("/")
|
||||||
|
.map((segment) => {
|
||||||
|
if (segment.startsWith(":")) {
|
||||||
|
keys.push(segment.slice(1));
|
||||||
|
return "([^/]+)";
|
||||||
|
}
|
||||||
|
return segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||||
|
})
|
||||||
|
.join("/");
|
||||||
|
this.routes.push({ method, pattern: new RegExp(`^${source}$`), keys, handler });
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
get(path: string, handler: Handler): this {
|
||||||
|
return this.add("GET", path, handler);
|
||||||
|
}
|
||||||
|
|
||||||
|
post(path: string, handler: Handler): this {
|
||||||
|
return this.add("POST", path, handler);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `null` — путь не найден; `"method_not_allowed"` — путь есть, метода нет. */
|
||||||
|
match(
|
||||||
|
method: string,
|
||||||
|
path: string,
|
||||||
|
): { handler: Handler; params: Record<string, string> } | null | "method_not_allowed" {
|
||||||
|
let pathMatched = false;
|
||||||
|
for (const route of this.routes) {
|
||||||
|
const m = route.pattern.exec(path);
|
||||||
|
if (!m) continue;
|
||||||
|
pathMatched = true;
|
||||||
|
if (route.method !== method) continue;
|
||||||
|
const params: Record<string, string> = {};
|
||||||
|
route.keys.forEach((key, i) => {
|
||||||
|
params[key] = decodeURIComponent(m[i + 1] ?? "");
|
||||||
|
});
|
||||||
|
return { handler: route.handler, params };
|
||||||
|
}
|
||||||
|
return pathMatched ? "method_not_allowed" : null;
|
||||||
|
}
|
||||||
|
}
|
||||||
40
src/main.ts
Normal file
40
src/main.ts
Normal file
@ -0,0 +1,40 @@
|
|||||||
|
import { createApp } from "./app.ts";
|
||||||
|
import { loadConfig } from "./config.ts";
|
||||||
|
import { migrate, openDatabase } from "./db/database.ts";
|
||||||
|
import { seedDemo } from "./seed.ts";
|
||||||
|
import { captureError, initSentry } from "./sentry.ts";
|
||||||
|
|
||||||
|
const config = loadConfig();
|
||||||
|
const sentryEnabled = initSentry(config);
|
||||||
|
|
||||||
|
const db = openDatabase(config.databasePath);
|
||||||
|
const applied = migrate(db);
|
||||||
|
if (applied.length > 0) console.log(`Applied migrations: ${applied.join(", ")}`);
|
||||||
|
if (config.seedDemo) {
|
||||||
|
seedDemo(db);
|
||||||
|
console.log("Demo data seeded (demo-resident, demo-partner, FM-NURA-001, …)");
|
||||||
|
}
|
||||||
|
|
||||||
|
const server = createApp({
|
||||||
|
db,
|
||||||
|
appEnv: config.appEnv,
|
||||||
|
onError: (error) => {
|
||||||
|
console.error(error);
|
||||||
|
if (sentryEnabled) captureError(error);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
server.listen(config.port, () => {
|
||||||
|
console.log(`tazakazahstan listening on :${config.port} (APP_ENV=${config.appEnv})`);
|
||||||
|
});
|
||||||
|
|
||||||
|
function shutdown(signal: string): void {
|
||||||
|
console.log(`${signal} received, shutting down`);
|
||||||
|
server.close(() => {
|
||||||
|
db.close();
|
||||||
|
process.exit(0);
|
||||||
|
});
|
||||||
|
setTimeout(() => process.exit(1), 10_000).unref();
|
||||||
|
}
|
||||||
|
process.on("SIGTERM", () => shutdown("SIGTERM"));
|
||||||
|
process.on("SIGINT", () => shutdown("SIGINT"));
|
||||||
96
src/points/ledger.ts
Normal file
96
src/points/ledger.ts
Normal file
@ -0,0 +1,96 @@
|
|||||||
|
import type { Db } from "../db/database.ts";
|
||||||
|
|
||||||
|
export type LedgerKind = "earn" | "redeem";
|
||||||
|
export type LedgerSourceType = "fandomat_event" | "redemption";
|
||||||
|
|
||||||
|
export interface LedgerEntry {
|
||||||
|
id: number;
|
||||||
|
kind: LedgerKind;
|
||||||
|
delta: number;
|
||||||
|
balanceAfter: number;
|
||||||
|
source: { type: LedgerSourceType; id: string };
|
||||||
|
description: string;
|
||||||
|
createdAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class InsufficientPointsError extends Error {
|
||||||
|
readonly balance: number;
|
||||||
|
readonly required: number;
|
||||||
|
|
||||||
|
constructor(balance: number, required: number) {
|
||||||
|
super("Недостаточно баллов");
|
||||||
|
this.balance = balance;
|
||||||
|
this.required = required;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getBalance(db: Db, userId: string): number {
|
||||||
|
const row = db.prepare("SELECT balance FROM point_accounts WHERE user_id = ?").get(userId);
|
||||||
|
return row ? Number(row.balance) : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Записывает операцию в историю и меняет баланс. Вызывать только внутри `transaction()`:
|
||||||
|
* чтение баланса, проверка и запись должны быть атомарны.
|
||||||
|
*/
|
||||||
|
export function postLedgerEntry(
|
||||||
|
db: Db,
|
||||||
|
entry: {
|
||||||
|
userId: string;
|
||||||
|
kind: LedgerKind;
|
||||||
|
delta: number;
|
||||||
|
sourceType: LedgerSourceType;
|
||||||
|
sourceId: string;
|
||||||
|
description: string;
|
||||||
|
},
|
||||||
|
): LedgerEntry {
|
||||||
|
if (!db.isTransaction) throw new Error("postLedgerEntry must run inside a transaction");
|
||||||
|
const balance = getBalance(db, entry.userId);
|
||||||
|
const balanceAfter = balance + entry.delta;
|
||||||
|
if (balanceAfter < 0) throw new InsufficientPointsError(balance, -entry.delta);
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
const result = db
|
||||||
|
.prepare(
|
||||||
|
`INSERT INTO point_ledger (user_id, kind, delta, balance_after, source_type, source_id, description, created_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||||
|
)
|
||||||
|
.run(
|
||||||
|
entry.userId,
|
||||||
|
entry.kind,
|
||||||
|
entry.delta,
|
||||||
|
balanceAfter,
|
||||||
|
entry.sourceType,
|
||||||
|
entry.sourceId,
|
||||||
|
entry.description,
|
||||||
|
now,
|
||||||
|
);
|
||||||
|
db.prepare(
|
||||||
|
`INSERT INTO point_accounts (user_id, balance, updated_at) VALUES (?, ?, ?)
|
||||||
|
ON CONFLICT (user_id) DO UPDATE SET balance = excluded.balance, updated_at = excluded.updated_at`,
|
||||||
|
).run(entry.userId, balanceAfter, now);
|
||||||
|
return {
|
||||||
|
id: Number(result.lastInsertRowid),
|
||||||
|
kind: entry.kind,
|
||||||
|
delta: entry.delta,
|
||||||
|
balanceAfter,
|
||||||
|
source: { type: entry.sourceType, id: entry.sourceId },
|
||||||
|
description: entry.description,
|
||||||
|
createdAt: now,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** История счёта, новые записи первыми. */
|
||||||
|
export function getHistory(db: Db, userId: string, limit = 100): LedgerEntry[] {
|
||||||
|
return db
|
||||||
|
.prepare("SELECT * FROM point_ledger WHERE user_id = ? ORDER BY id DESC LIMIT ?")
|
||||||
|
.all(userId, limit)
|
||||||
|
.map((row) => ({
|
||||||
|
id: Number(row.id),
|
||||||
|
kind: row.kind as LedgerKind,
|
||||||
|
delta: Number(row.delta),
|
||||||
|
balanceAfter: Number(row.balance_after),
|
||||||
|
source: { type: row.source_type as LedgerSourceType, id: String(row.source_id) },
|
||||||
|
description: String(row.description),
|
||||||
|
createdAt: String(row.created_at),
|
||||||
|
}));
|
||||||
|
}
|
||||||
27
src/points/rates.ts
Normal file
27
src/points/rates.ts
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
export const CONTAINER_TYPES = ["pet", "aluminum", "glass"] as const;
|
||||||
|
export type ContainerType = (typeof CONTAINER_TYPES)[number];
|
||||||
|
|
||||||
|
export interface ContainerItem {
|
||||||
|
type: ContainerType;
|
||||||
|
volumeMl: number;
|
||||||
|
count: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Порог «малой» тары (включительно). */
|
||||||
|
const SMALL_MAX_ML = 500;
|
||||||
|
|
||||||
|
/** Баллы за единицу тары: [до 500 мл включительно, больше 500 мл]. Предложение для пилота. */
|
||||||
|
export const POINT_RATES: Record<ContainerType, readonly [small: number, large: number]> = {
|
||||||
|
pet: [1, 2],
|
||||||
|
aluminum: [2, 2],
|
||||||
|
glass: [2, 3],
|
||||||
|
};
|
||||||
|
|
||||||
|
export function pointsPerUnit(type: ContainerType, volumeMl: number): number {
|
||||||
|
const [small, large] = POINT_RATES[type];
|
||||||
|
return volumeMl <= SMALL_MAX_ML ? small : large;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function pointsForItems(items: readonly ContainerItem[]): number {
|
||||||
|
return items.reduce((sum, item) => sum + pointsPerUnit(item.type, item.volumeMl) * item.count, 0);
|
||||||
|
}
|
||||||
18
src/points/routes.ts
Normal file
18
src/points/routes.ts
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
import { authenticate, requireRole } from "../auth/users.ts";
|
||||||
|
import type { Db } from "../db/database.ts";
|
||||||
|
import type { Router } from "../http/router.ts";
|
||||||
|
import { getBalance, getHistory } from "./ledger.ts";
|
||||||
|
|
||||||
|
export function registerPointsRoutes(router: Router, db: Db): void {
|
||||||
|
router.get("/api/me/points", (ctx) => {
|
||||||
|
const user = authenticate(db, ctx);
|
||||||
|
requireRole(user, "resident");
|
||||||
|
// Баланс и история читаются одним снимком, чтобы не разъехаться при параллельной записи.
|
||||||
|
db.exec("BEGIN");
|
||||||
|
try {
|
||||||
|
return { body: { balance: getBalance(db, user.id), history: getHistory(db, user.id) } };
|
||||||
|
} finally {
|
||||||
|
db.exec("COMMIT");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
219
src/rewards/rewards.ts
Normal file
219
src/rewards/rewards.ts
Normal file
@ -0,0 +1,219 @@
|
|||||||
|
import { randomUUID } from "node:crypto";
|
||||||
|
import type { User, UserStatus } from "../auth/users.ts";
|
||||||
|
import { newRewardCode } from "../crypto.ts";
|
||||||
|
import type { Db } from "../db/database.ts";
|
||||||
|
import { transaction } from "../db/database.ts";
|
||||||
|
import { badRequest, conflict, forbidden, HttpError, notFound } from "../errors.ts";
|
||||||
|
import { getBalance, InsufficientPointsError, postLedgerEntry } from "../points/ledger.ts";
|
||||||
|
|
||||||
|
export type UnavailableReason = "status_not_allowed" | "out_of_stock" | "insufficient_points";
|
||||||
|
|
||||||
|
export interface Reward {
|
||||||
|
id: string;
|
||||||
|
partnerId: string;
|
||||||
|
partnerName: string;
|
||||||
|
title: string;
|
||||||
|
description: string;
|
||||||
|
costPoints: number;
|
||||||
|
allowedStatuses: UserStatus[];
|
||||||
|
stock: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Redemption {
|
||||||
|
id: string;
|
||||||
|
rewardId: string;
|
||||||
|
rewardTitle: string;
|
||||||
|
partnerName: string;
|
||||||
|
code: string;
|
||||||
|
points: number;
|
||||||
|
balanceAfter: number;
|
||||||
|
status: "issued" | "used";
|
||||||
|
createdAt: string;
|
||||||
|
usedAt: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
type Row = Record<string, unknown>;
|
||||||
|
|
||||||
|
const REWARD_SELECT = `SELECT r.*, p.name AS partner_name FROM rewards r JOIN partners p ON p.id = r.partner_id`;
|
||||||
|
|
||||||
|
function rowToReward(row: Row): Reward {
|
||||||
|
return {
|
||||||
|
id: String(row.id),
|
||||||
|
partnerId: String(row.partner_id),
|
||||||
|
partnerName: String(row.partner_name),
|
||||||
|
title: String(row.title),
|
||||||
|
description: String(row.description),
|
||||||
|
costPoints: Number(row.cost_points),
|
||||||
|
allowedStatuses: JSON.parse(String(row.allowed_statuses)) as UserStatus[],
|
||||||
|
stock: row.stock === null ? null : Number(row.stock),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const REDEMPTION_SELECT = `SELECT d.*, r.title AS reward_title, p.name AS partner_name
|
||||||
|
FROM redemptions d JOIN rewards r ON r.id = d.reward_id JOIN partners p ON p.id = r.partner_id`;
|
||||||
|
|
||||||
|
function rowToRedemption(row: Row): Redemption {
|
||||||
|
return {
|
||||||
|
id: String(row.id),
|
||||||
|
rewardId: String(row.reward_id),
|
||||||
|
rewardTitle: String(row.reward_title),
|
||||||
|
partnerName: String(row.partner_name),
|
||||||
|
code: String(row.code),
|
||||||
|
points: Number(row.points),
|
||||||
|
balanceAfter: Number(row.balance_after),
|
||||||
|
status: row.status as Redemption["status"],
|
||||||
|
createdAt: String(row.created_at),
|
||||||
|
usedAt: (row.used_at as string | null) ?? null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function unavailableReason(
|
||||||
|
reward: Reward,
|
||||||
|
user: User,
|
||||||
|
balance: number,
|
||||||
|
): UnavailableReason | null {
|
||||||
|
if (!reward.allowedStatuses.includes(user.status)) return "status_not_allowed";
|
||||||
|
if (reward.stock !== null && reward.stock <= 0) return "out_of_stock";
|
||||||
|
if (balance < reward.costPoints) return "insufficient_points";
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listRewardsFor(db: Db, user: User) {
|
||||||
|
const balance = getBalance(db, user.id);
|
||||||
|
const rewards = db
|
||||||
|
.prepare(`${REWARD_SELECT} WHERE r.active = 1 ORDER BY r.cost_points, r.title`)
|
||||||
|
.all()
|
||||||
|
.map(rowToReward)
|
||||||
|
.map((reward) => {
|
||||||
|
const reason = unavailableReason(reward, user, balance);
|
||||||
|
return {
|
||||||
|
id: reward.id,
|
||||||
|
title: reward.title,
|
||||||
|
description: reward.description,
|
||||||
|
partner: { id: reward.partnerId, name: reward.partnerName },
|
||||||
|
costPoints: reward.costPoints,
|
||||||
|
stock: reward.stock,
|
||||||
|
available: reason === null,
|
||||||
|
...(reason ? { unavailableReason: reason } : {}),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
return { balance, rewards };
|
||||||
|
}
|
||||||
|
|
||||||
|
const MAX_KEY_LENGTH = 200;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Обмен баллов на код льготы. Идемпотентен по (житель, Idempotency-Key).
|
||||||
|
* Любой отказ происходит до записи — баланс, история и остаток не меняются.
|
||||||
|
*/
|
||||||
|
export function redeemReward(
|
||||||
|
db: Db,
|
||||||
|
user: User,
|
||||||
|
rewardId: string,
|
||||||
|
idempotencyKey: unknown,
|
||||||
|
): { redemption: Redemption; duplicate: boolean } {
|
||||||
|
if (
|
||||||
|
typeof idempotencyKey !== "string" ||
|
||||||
|
idempotencyKey.length === 0 ||
|
||||||
|
idempotencyKey.length > MAX_KEY_LENGTH
|
||||||
|
) {
|
||||||
|
throw badRequest(
|
||||||
|
"idempotency_key_required",
|
||||||
|
`Нужен заголовок Idempotency-Key (1–${MAX_KEY_LENGTH} символов)`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return transaction(db, () => {
|
||||||
|
const existing = db
|
||||||
|
.prepare(`${REDEMPTION_SELECT} WHERE d.user_id = ? AND d.idempotency_key = ?`)
|
||||||
|
.get(user.id, idempotencyKey);
|
||||||
|
if (existing) {
|
||||||
|
if (existing.reward_id !== rewardId) {
|
||||||
|
throw conflict(
|
||||||
|
"idempotency_conflict",
|
||||||
|
"Этот Idempotency-Key уже использован для другой льготы",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return { redemption: rowToRedemption(existing), duplicate: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
const row = db.prepare(`${REWARD_SELECT} WHERE r.id = ? AND r.active = 1`).get(rewardId);
|
||||||
|
if (!row) throw notFound("reward_not_found", "Льгота не найдена");
|
||||||
|
const reward = rowToReward(row);
|
||||||
|
const balance = getBalance(db, user.id);
|
||||||
|
const reason = unavailableReason(reward, user, balance);
|
||||||
|
if (reason === "status_not_allowed") {
|
||||||
|
throw forbidden("status_not_allowed", "Льгота недоступна для вашего статуса");
|
||||||
|
}
|
||||||
|
if (reason === "out_of_stock") throw conflict("out_of_stock", "Коды этой льготы закончились");
|
||||||
|
if (reason === "insufficient_points") throw insufficient(balance, reward.costPoints);
|
||||||
|
|
||||||
|
const id = randomUUID();
|
||||||
|
const code = uniqueCode(db);
|
||||||
|
let balanceAfter: number;
|
||||||
|
try {
|
||||||
|
balanceAfter = postLedgerEntry(db, {
|
||||||
|
userId: user.id,
|
||||||
|
kind: "redeem",
|
||||||
|
delta: -reward.costPoints,
|
||||||
|
sourceType: "redemption",
|
||||||
|
sourceId: id,
|
||||||
|
description: `Обмен на льготу «${reward.title}» (${reward.partnerName})`,
|
||||||
|
}).balanceAfter;
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof InsufficientPointsError)
|
||||||
|
throw insufficient(error.balance, reward.costPoints);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
db.prepare(
|
||||||
|
`INSERT INTO redemptions (id, user_id, reward_id, idempotency_key, code, points, balance_after, status, created_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, 'issued', ?)`,
|
||||||
|
).run(id, user.id, reward.id, idempotencyKey, code, reward.costPoints, balanceAfter, now);
|
||||||
|
if (reward.stock !== null) {
|
||||||
|
db.prepare("UPDATE rewards SET stock = stock - 1 WHERE id = ?").run(reward.id);
|
||||||
|
}
|
||||||
|
const created = db.prepare(`${REDEMPTION_SELECT} WHERE d.id = ?`).get(id);
|
||||||
|
if (!created) throw new Error("redemption not persisted");
|
||||||
|
return { redemption: rowToRedemption(created), duplicate: false };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const insufficient = (balance: number, costPoints: number) =>
|
||||||
|
new HttpError(409, "insufficient_points", "Недостаточно баллов", { balance, costPoints });
|
||||||
|
|
||||||
|
function uniqueCode(db: Db): string {
|
||||||
|
const exists = db.prepare("SELECT 1 FROM redemptions WHERE code = ?");
|
||||||
|
for (let attempt = 0; attempt < 10; attempt++) {
|
||||||
|
const code = newRewardCode();
|
||||||
|
if (!exists.get(code)) return code;
|
||||||
|
}
|
||||||
|
throw new Error("could not generate a unique reward code");
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listRedemptions(db: Db, userId: string): Redemption[] {
|
||||||
|
return db
|
||||||
|
.prepare(`${REDEMPTION_SELECT} WHERE d.user_id = ? ORDER BY d.created_at DESC, d.rowid DESC`)
|
||||||
|
.all(userId)
|
||||||
|
.map(rowToRedemption);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Погашение кода сотрудником партнёра: issued → used. */
|
||||||
|
export function redeemCodeByPartner(db: Db, partnerUser: User, code: unknown): Redemption {
|
||||||
|
if (typeof code !== "string" || code.length === 0)
|
||||||
|
throw badRequest("validation_error", "Поле code обязательно");
|
||||||
|
return transaction(db, () => {
|
||||||
|
const row = db
|
||||||
|
.prepare(`${REDEMPTION_SELECT} WHERE d.code = ? AND r.partner_id = ?`)
|
||||||
|
.get(code.trim().toUpperCase(), partnerUser.partnerId ?? "");
|
||||||
|
if (!row) throw notFound("code_not_found", "Код не найден");
|
||||||
|
if (row.status === "used") throw conflict("code_already_used", "Код уже погашен");
|
||||||
|
db.prepare("UPDATE redemptions SET status = 'used', used_at = ? WHERE id = ?").run(
|
||||||
|
new Date().toISOString(),
|
||||||
|
String(row.id),
|
||||||
|
);
|
||||||
|
const updated = db.prepare(`${REDEMPTION_SELECT} WHERE d.id = ?`).get(String(row.id));
|
||||||
|
if (!updated) throw new Error("redemption disappeared");
|
||||||
|
return rowToRedemption(updated);
|
||||||
|
});
|
||||||
|
}
|
||||||
40
src/rewards/routes.ts
Normal file
40
src/rewards/routes.ts
Normal file
@ -0,0 +1,40 @@
|
|||||||
|
import { authenticate, requireRole } from "../auth/users.ts";
|
||||||
|
import type { Db } from "../db/database.ts";
|
||||||
|
import type { Router } from "../http/router.ts";
|
||||||
|
import { listRedemptions, listRewardsFor, redeemCodeByPartner, redeemReward } from "./rewards.ts";
|
||||||
|
|
||||||
|
export function registerRewardRoutes(router: Router, db: Db): void {
|
||||||
|
router.get("/api/rewards", (ctx) => {
|
||||||
|
const user = authenticate(db, ctx);
|
||||||
|
requireRole(user, "resident");
|
||||||
|
return { body: listRewardsFor(db, user) };
|
||||||
|
});
|
||||||
|
|
||||||
|
router.post("/api/rewards/:id/redeem", (ctx) => {
|
||||||
|
const user = authenticate(db, ctx);
|
||||||
|
requireRole(user, "resident");
|
||||||
|
const { redemption, duplicate } = redeemReward(
|
||||||
|
db,
|
||||||
|
user,
|
||||||
|
ctx.params.id ?? "",
|
||||||
|
ctx.headers["idempotency-key"],
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
status: duplicate ? 200 : 201,
|
||||||
|
body: { redemption, balance: redemption.balanceAfter, duplicate },
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
router.get("/api/me/redemptions", (ctx) => {
|
||||||
|
const user = authenticate(db, ctx);
|
||||||
|
requireRole(user, "resident");
|
||||||
|
return { body: { redemptions: listRedemptions(db, user.id) } };
|
||||||
|
});
|
||||||
|
|
||||||
|
router.post("/api/partner/redemptions/redeem-code", (ctx) => {
|
||||||
|
const user = authenticate(db, ctx);
|
||||||
|
requireRole(user, "partner");
|
||||||
|
const code = (ctx.body as { code?: unknown } | undefined)?.code;
|
||||||
|
return { body: { redemption: redeemCodeByPartner(db, user, code) } };
|
||||||
|
});
|
||||||
|
}
|
||||||
97
src/seed.ts
Normal file
97
src/seed.ts
Normal file
@ -0,0 +1,97 @@
|
|||||||
|
import { sha256 } from "./crypto.ts";
|
||||||
|
import type { Db } from "./db/database.ts";
|
||||||
|
import { transaction } from "./db/database.ts";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Демо-данные для разработки и тестовых стендов. Без реальных ИИН/БИН.
|
||||||
|
* Ключи фандоматов с префиксом `mock` — заменяются реальными при подключении оператора.
|
||||||
|
*/
|
||||||
|
export const DEMO = {
|
||||||
|
residents: [
|
||||||
|
{
|
||||||
|
id: "u-demo-resident",
|
||||||
|
login: "demo-resident",
|
||||||
|
status: "verified",
|
||||||
|
code: "R-DEMO01",
|
||||||
|
name: "Тестовый житель (Нура)",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "u-demo-pending",
|
||||||
|
login: "demo-pending",
|
||||||
|
status: "pending",
|
||||||
|
code: "R-PEND01",
|
||||||
|
name: "Тестовый житель без подтверждения",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "u-demo-blocked",
|
||||||
|
login: "demo-blocked",
|
||||||
|
status: "blocked",
|
||||||
|
code: "R-BLOCK1",
|
||||||
|
name: "Заблокированный тестовый житель",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
partner: { id: "partner-demo-cafe", name: "Тестовое кафе «Жасыл»" },
|
||||||
|
partnerUser: { id: "u-demo-partner", login: "demo-partner", name: "Кассир тестового кафе" },
|
||||||
|
admin: { id: "u-demo-admin", login: "demo-admin", name: "Тестовый администратор" },
|
||||||
|
reward: {
|
||||||
|
id: "reward-demo-coffee",
|
||||||
|
title: "Кофе в подарок",
|
||||||
|
description: "Один стакан кофе в тестовом кафе «Жасыл»",
|
||||||
|
costPoints: 10,
|
||||||
|
allowedStatuses: ["verified"],
|
||||||
|
},
|
||||||
|
fandomats: [
|
||||||
|
{
|
||||||
|
id: "FM-NURA-001",
|
||||||
|
district: "nura",
|
||||||
|
address: "Нура, тестовый адрес 1",
|
||||||
|
key: "mock-fandomat-key-nura-001",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "FM-ESIL-001",
|
||||||
|
district: "esil",
|
||||||
|
address: "Есіль, тестовый адрес 1",
|
||||||
|
key: "mock-fandomat-key-esil-001",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
/** Идемпотентно: повторный вызов ничего не меняет. */
|
||||||
|
export function seedDemo(db: Db): void {
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
transaction(db, () => {
|
||||||
|
const insertUser = db.prepare(
|
||||||
|
`INSERT OR IGNORE INTO users (id, login, role, status, display_name, resident_code, partner_id, created_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||||
|
);
|
||||||
|
db.prepare("INSERT OR IGNORE INTO partners (id, name) VALUES (?, ?)").run(
|
||||||
|
DEMO.partner.id,
|
||||||
|
DEMO.partner.name,
|
||||||
|
);
|
||||||
|
for (const r of DEMO.residents) {
|
||||||
|
insertUser.run(r.id, r.login, "resident", r.status, r.name, r.code, null, now);
|
||||||
|
}
|
||||||
|
const p = DEMO.partnerUser;
|
||||||
|
insertUser.run(p.id, p.login, "partner", "verified", p.name, null, DEMO.partner.id, now);
|
||||||
|
const a = DEMO.admin;
|
||||||
|
insertUser.run(a.id, a.login, "admin", "verified", a.name, null, null, now);
|
||||||
|
|
||||||
|
const r = DEMO.reward;
|
||||||
|
db.prepare(
|
||||||
|
`INSERT OR IGNORE INTO rewards (id, partner_id, title, description, cost_points, allowed_statuses, stock, active)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, NULL, 1)`,
|
||||||
|
).run(
|
||||||
|
r.id,
|
||||||
|
DEMO.partner.id,
|
||||||
|
r.title,
|
||||||
|
r.description,
|
||||||
|
r.costPoints,
|
||||||
|
JSON.stringify(r.allowedStatuses),
|
||||||
|
);
|
||||||
|
|
||||||
|
const insertFandomat = db.prepare(
|
||||||
|
"INSERT OR IGNORE INTO fandomats (id, district, address, api_key_hash) VALUES (?, ?, ?, ?)",
|
||||||
|
);
|
||||||
|
for (const f of DEMO.fandomats) insertFandomat.run(f.id, f.district, f.address, sha256(f.key));
|
||||||
|
});
|
||||||
|
}
|
||||||
18
src/sentry.ts
Normal file
18
src/sentry.ts
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
import * as Sentry from "@sentry/node";
|
||||||
|
import type { Config } from "./config.ts";
|
||||||
|
|
||||||
|
/** Без SENTRY_DSN SDK не инициализируется и ничего не отправляет. */
|
||||||
|
export function initSentry(config: Config): boolean {
|
||||||
|
if (!config.sentry.dsn) return false;
|
||||||
|
Sentry.init({
|
||||||
|
dsn: config.sentry.dsn,
|
||||||
|
release: config.sentry.release,
|
||||||
|
environment: config.sentry.environment,
|
||||||
|
sendDefaultPii: false,
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function captureError(error: unknown): void {
|
||||||
|
Sentry.captureException(error);
|
||||||
|
}
|
||||||
11
tsconfig.build.json
Normal file
11
tsconfig.build.json
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
{
|
||||||
|
"extends": "./tsconfig.json",
|
||||||
|
"compilerOptions": {
|
||||||
|
"noEmit": false,
|
||||||
|
"allowImportingTsExtensions": false,
|
||||||
|
"outDir": "dist",
|
||||||
|
"rootDir": ".",
|
||||||
|
"sourceMap": true
|
||||||
|
},
|
||||||
|
"include": ["src"]
|
||||||
|
}
|
||||||
20
tsconfig.json
Normal file
20
tsconfig.json
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "es2023",
|
||||||
|
"module": "nodenext",
|
||||||
|
"moduleResolution": "nodenext",
|
||||||
|
"lib": ["es2023"],
|
||||||
|
"types": ["node"],
|
||||||
|
"strict": true,
|
||||||
|
"noUncheckedIndexedAccess": true,
|
||||||
|
"noImplicitOverride": true,
|
||||||
|
"erasableSyntaxOnly": true,
|
||||||
|
"verbatimModuleSyntax": true,
|
||||||
|
"allowImportingTsExtensions": true,
|
||||||
|
"rewriteRelativeImportExtensions": true,
|
||||||
|
"resolveJsonModule": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"noEmit": true
|
||||||
|
},
|
||||||
|
"include": ["src", "test", "scripts"]
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue
Block a user