171 Commits

Author SHA1 Message Date
NW
c0b1fb4c53 build(admin): npm ci instead of bun + arm64-capable lockfile for multi-arch
All checks were successful
Release: multi-arch Docker images / build-push (push) Successful in 26m49s
- Dockerfile: bun install -> npm ci (bun tar-extract unstable under qemu arm64)
- pin @hookform/resolvers 5.2.2 (5.7.x forces ajv@8 -> broken npm lockfile)
- package-lock.json regenerated with linux-arm64 native optionals (lightningcss, sharp, tailwindcss-oxide, parcel/watcher)
- runtime CMD stays node server.js (bun not installed in runner image)
2026-08-11 12:46:20 +01:00
NW
dcf85c94ad ci: use docker-container buildx builder (host network) — fixes DNS instability in default driver
Some checks failed
Release: multi-arch Docker images / build-push (push) Failing after 6m38s
2026-08-11 11:04:11 +01:00
NW
2744cdf6de ci: fix release checkout — dispatch uses branch ref (main/dev), version input only for image tags
Some checks failed
Release: multi-arch Docker images / build-push (push) Failing after 24s
2026-08-11 10:44:31 +01:00
NW
5c7bc242c5 ci: registry-based releases — multi-arch images built in CI, servers only pull
- release workflow: buildx multi-arch (amd64+arm64) build+push of bot and admin images to Gitea Container Registry (git.softuniq.eu/telegram-market/telegram-shop[-admin])
- docker-compose: bot/admin use registry images (IMAGE_TAG for pinning); tor-proxy stays local alpine build
- install.sh: pull from registry instead of local docker build (no native compilation on weak hardware); interactive .env setup preserved
- new buildx runner gitea-host-buildx (label buildx) on x86_64 host
- REGISTRY_TOKEN replaced with package-scoped token (write:package)
- README/VERSION/.env.example updated
2026-08-11 10:37:09 +01:00
NW
33ec420fc0 feat(admin): issue #148 — button lock + loaders on all Catalog Tree ops (double-click protection)
- busyAction global mutex guard on toggle/sort/rename/delete/add/clone
- Per-op states: togglingId, sortingId, deleting, adding, cloningId
- Switch/sort arrows/Pencil/Trash/Add/Clone disabled during ops + Loader2 spinners
- Delete dialog: Delete disabled + 'Deleting...'
- tsc clean
2026-08-10 13:24:56 +01:00
NW
cef8fbbee4 fix(admin): catalog tree — typeToPath mapping (categorys->categories, subcategorys->subcategories)
- handleToggleActive/handleDelete/handleRename/handleSort used ${type}s which produced 'categorys'/'subcategorys' -> 404
- Added typeToPath helper: category->categories, subcategory->subcategories, location->locations, product->products
2026-08-10 12:27:26 +01:00
NW
9ac7afa36e fix(admin): issue #147 — Catalog Tree city edit/delete, sort order, subcategory ops
- handleRename: city rename via /api/locations/rename-city (all rows), district via PUT /api/locations/{id}
- City-level delete: DELETE /api/locations/by-city (blocks on dependencies, 400 with counts)
- Sort order: idempotent ensureSortOrderColumns (ALTER TABLE try/catch) + PATCH /api/{type}s/{id}/sort + up/down arrows on district/category/subcategory
- Tree queries order by sort_order asc, then name
- Subcategory rename/delete verified
- tsc clean
2026-08-10 10:55:12 +01:00
NW
1b7050002e fix(admin): bulk APIs — include->select for _count (Prisma 6.19 select+include conflict) 2026-08-10 10:22:02 +01:00
NW
301763f428 feat(admin): issue #146 — photo upload with sharp crop/optimization (restore old behavior)
- POST /api/upload: FormData, 10MB limit, sharp resize 800px inside + webp@80, saves to /app/uploads, returns /uploads/url
- GET /uploads/[...path]: serves files with Content-Type, path traversal protected
- compose: ./uploads mounted in tg_shop_admin
- Dockerfile: /app/uploads created + chown nextjs
- catalog-page: file input + thumbnail preview + remove for photoUrl/hiddenPhotoUrl
- Bot resolvePhotoSource already supports /uploads/ paths — no bot changes
2026-08-10 09:38:31 +01:00
NW
792efc07ce feat(admin): issue #145 — delete-blocked hint + Deactivate/Edit alternative
- categories dialog: red hint with count + Deactivate button when products>0
- locations dialog: red hint + Deactivate button when categories/products>0
- catalog dialog: deleteError shown on 400/409; Deactivate for category/subcategory/location, Edit for product
- Deactivate calls existing PATCH toggle, closes dialog, reloads
- tsc clean
2026-08-10 08:44:12 +01:00
NW
3b8e6416c4 feat(admin): Bot Configuration — eye toggle to reveal masked values (token, secrets)
- compose: pass bot env (BOT_TOKEN, SUPPORT_LINK, ADMIN_IDS, SUPER_ADMIN_IDS, WG_*, ADMIN_*, GITEA_API_URL) to tg_shop_admin
- settings API: reads real env values; POST /api/settings reveals secret value by key (auth required)
- settings-page: eye/eye-off button on masked fields, shows real value on click (BOT_TOKEN, ADMIN_IDS, etc.)
2026-08-09 15:27:48 +01:00
NW
7ba17f2de6 fix(admin): super admin always has full seed access (commission informational only) 2026-08-09 13:56:08 +01:00
NW
d7bbb9ec6b feat(admin): issue #144 — seed phrases for regular admin, commission-gated + Mercuryo payment
- overview: commissionWallets (env) + mercuryoUrl in response
- seeds API: getAuth (regular admin), locked=true + no mnemonics when commissionDue>0, full when 0
- export-seeds: 403 when commissionDue>0
- UI: seed tab for all admins; payment block (past payments, difference, commission wallet selector, Mercuryo card button, I've paid -> record-payment); full table + CSV when unlocked
- super_admin: full access regardless (informational warning)
2026-08-09 13:44:28 +01:00
NW
d827a18ee9 feat(admin): decrypt mnemonics + balance column in seed phrases
- lib/mnemonic.ts: decryptMnemonic (same AES-256-CBC+HKDF algo as bot, uses ENCRYPTION_KEY)
- wallets/seeds API: decrypts mnemonic per user, adds balance field
- wallets/export-seeds (CSV): decrypts mnemonic, adds Balance column
- wallets-page: Balance column added to seed phrases table
- compose: ENCRYPTION_KEY passed to tg_shop_admin (same key as bot)
2026-08-09 01:23:34 +01:00
NW
d1ce76a14c fix(admin): seed phrases 500 — Prisma 6.19 rejects select+include together
- wallets/seeds: move user relation into nested select (was select+include -> PrismaClientValidationError 500)
- wallets/export-seeds: same fix (CSV export)
- Verified no other top-level select+include conflicts in api routes
- tsc clean
2026-08-09 01:05:43 +01:00
NW
d7680357af chore: repo cleanup + docs for admin API and DB schema (v1.2.8)
- remove stale docs/admin-frontend-spec.md (old Express/EJS admin), unused templates/ (SmartAdmin copy), dead scripts/sync-agents.cjs, committed dev.pid
- add docs/API.md (admin REST API reference) and docs/DATABASE.md (DB schema)
- refresh .env.example: drop stale ADMIN_PORT/SHOP_CONTAINER, add ADMIN_URL, HEALTH_PORT, DEFAULT_LANGUAGE, CHATBOT_API_*
- add npm run lint so Gitea workflows pass
- rebrand web-testing suite from APAW to telegram-shop
2026-08-09 00:22:22 +01:00
NW
338a700b3a fix(bot): issue #143 — sleep mode safety guards + super-admin seed access
- sleepGuard.js: assertShopOpen/redirectIfPaused — blocks write-flows on shop pause, redirects to AI dialog, fallback to sleep message
- Blocked: buy/pay/quantity/top-up/deposit/wallet-create when paused
- Soft redirect: catalog navigation (country/city/district/category/product) to AI on pause
- Read-only flows untouched (purchase history, balance, tx history)
- Tests: 10 sleepGuard tests (T1-T6 + alias + fallback), 42 total pass
- fix(admin): super-admin seed phrases not blocked by commission (informational only)
- wallet test mock updated for sleepGuard
2026-08-08 23:46:56 +01:00
NW
3b9aa5d541 fix(bot): issue #142 — language selection on first contact (Products/message in sleep mode)
- keyboard.products in sleep mode: language_set=0 -> language keyboard first, then AI in chosen language
- message handler in sleep mode: same language_set check before AI
- AI context verified: chat_sessions history (max 20) + LANGUAGE_INSTRUCTIONS[lang] in system prompt
- 30 tests pass
2026-08-08 21:07:33 +01:00
NW
c17e5f4099 fix(admin): Translations table — add Section header column (was shifted 1 cell left)
- Table had 4 headers (Key + 3 langs) but 5 data cells (Section rowSpan + Key + 3 langs)
- Headers were misaligned relative to data; added Section column header
2026-08-08 17:48:32 +01:00
NW
bfa21fc156 fix(ai): issue #141 — custom OpenAI-compatible providers work + language selection on first start in sleep mode
- callOllama: reasoning_effort only for provider=ollama (others returned 400 -> stub reply)
- endpoint normalization: base URL (Groq /openai/v1) -> /chat/completions appended
- reasoning block stripping: <thinking>/<think> tags + thinking/response markers (Groq qwen)
- handleStart: sleep mode + language_set=0 -> show language selection keyboard first
- handleSetLanguage: sleep mode -> AI dialog in chosen language after selection
2026-08-08 15:31:19 +01:00
NW
b352d1434c feat(admin): load LLM models from provider /models endpoint (OpenAI-compatible)
- New API /api/chatbot/models: fetches model list from configured endpoint (/models, OpenAI/Ollama format)
- Uses saved site_settings endpoint+key, or accepts endpoint/apiKey query params (unsaved custom provider)
- UI: 'Загрузить модели' button in Provider tab — loads models into select
- Manual model input always available for Custom providers
- No more hardcoded Ollama-only model list
2026-08-08 14:01:29 +01:00
NW
9bc0bffac7 fix(db): migration 014 — add users.notes column (Next.js admin Prisma requires it)
- prod DB was missing users.notes → /api/users/bulk 500 (Prisma P2022)
- Applied to prod; users + lead relations now load correctly
2026-08-08 13:26:52 +01:00
NW
c7a4463ac4 fix(admin): login redirect — full location.href=/ instead of hash, session check on mount
- window.location.href='/' after login (was window.location.hash='/' which stayed on /login#/)
- checkSession on mount: already-authenticated users skip login form
2026-08-08 13:12:52 +01:00
NW
9aa3e41c3f docs: README — remove old Express admin references, health-server port 3001, super secret 2026-08-08 12:41:34 +01:00
NW
01d75fc7b7 refactor(bot): remove old Express/EJS admin panel, add standalone health server (v1.2.7)
- Delete src/admin/ (1012 files: routes, views, public, auth) — old admin replaced by Next.js admin-next/
- Add src/healthServer.js: minimal HTTP /health on port 3001 for Docker healthcheck
- src/index.js uses startHealthServer instead of startAdminPanel
- Remove admin-dependent test (adminDeleteFeedback.test.js); 30 tests pass
- Remove ejs/express-ejs-layouts/express/cookie-parser/multer from deps
- admin-next: prisma binaryTargets for linux-arm64-openssl (arm64 prod)
- VERSION.md v1.2.7
- Bot adminHandlers (Telegram commands) kept — data preserved in shared SQLite
2026-08-08 12:22:15 +01:00
NW
b1844b1acc fix(compose): tor-proxy hardcodes tg_shop_admin:3000 — onion always serves new Next.js admin
- Old .env had ADMIN_PORT=3001/SHOP_CONTAINER=telegram_shop_prod overriding compose defaults
- Tor onion was proxying to old Express admin; now hardcoded to new Next.js admin
2026-08-08 12:05:46 +01:00
NW
a71012680a docs: README — new Next.js admin panel (admin-next/), tor schema update, project structure 2026-08-08 11:55:52 +01:00
NW
9226871eb4 fix(bot): lead race condition — INSERT OR IGNORE + reselect on UNIQUE conflict
- getOrCreateLead: INSERT OR IGNORE prevents UNIQUE constraint race (parallel messages creating same telegram_id lead)
- On changes=0, reselect existing lead instead of failing
2026-08-08 11:51:18 +01:00
NW
e202b357dc chore: ignore admin-next/.env (secrets kept on server) 2026-08-08 04:52:19 +01:00
NW
d78c7aa502 fix(admin): add openssl+curl for Prisma SQLite and healthcheck in runner stage 2026-08-08 01:39:38 +01:00
NW
a4a5fd449d feat(admin): integrate Next.js admin panel (admin-next/) from feat/nextjs-admin
- Add admin-next/: full Next.js + Prisma + shadcn admin panel (45 API routes, 76 components)
- docker-compose: tg_shop_admin service (port 3000, shared db/shop.db, prisma), bot talks to it via ADMIN_CHAT_URL=http://tg_shop_admin:3000/api/chat
- tor-proxy now proxies onion admin to tg_shop_admin:3000 (new panel)
- chatbotService: ADMIN_CHAT_URL default = http://tg_shop_admin:3000/api/chat (removed localhost:3100 anachronism)
- .env admin secrets gitignored (admin-next/.env)
2026-08-08 01:31:45 +01:00
NW
62534dbe85 feat(bot): AI-chat integration — leads, chatbot service, sleep mode + migration 013
- chatbotService: bridge to Next.js admin chat API (localhost:3100) — sleep mode, welcome, LLM replies
- leadService: lead sync from every user message, interaction logging to audit_log
- index.js: unhandled messages route to AI when chatbot_enabled; lead sync on every message
- userHandler/routes: lead capture on /start and catalog; sleep mode redirects to AI dialog
- Migration 013: leads, site_settings, chat_sessions tables (idempotent, chatbot_enabled/sleep_mode default 0)
- messageRouter.dispatch returns boolean (handled/not) for AI fallback
- gitignore db backups
2026-08-08 01:12:10 +01:00
NW
a5ea99b39b fix(admin): issue #131 — dead callback buttons prod_district_/admin_users + no-op placeholders
- prod_district_: pipe-delimited format (multi-word names safe) + handleDistrictBack shows categories (admin sees disabled locations via getLocationsByCountryAndCityAdmin)
- admin_users: handleUserListBack (viewUserPage(0) edit)
- current_page/current_quantity/no_action: no-op exact routes (no 'No handler' warns)
- Audit: all 78 generated callbacks cross-checked — no overlaps, none missing
- 48 tests pass; bump v1.2.6
2026-08-05 12:46:37 +01:00
NW
61c7a90aeb fix(bot): issue #130 — crypto deposit photo-edit 400, chat cleanup via lastInlineMessageId
- depositHandler: handleDepositInstruction + handleDepositSelectWallet use editOrSendCallback (photo-safe fallback) — fixes 'no text in the message to edit' 400
- resetUserContext deletes lastInlineMessageId (stale inline menus cleaned on Reply Keyboard nav)
- showProducts/showProfile/showBalance/showPurchases store lastInlineMessageId on sendMessage
- answerCallbackQuery verified before dispatch (v1.2.4)
- 48 tests pass; bump v1.2.5
2026-08-05 12:20:16 +01:00
NW
f90af4c78e docs(admin): frontend spec for admin panel + endpoint architecture (issue #131) 2026-08-05 12:07:56 +01:00
NW
7a97d561a5 fix(bot): issue #129 — missing shop_district_/shop_subcategory_ handlers, answerCallbackQuery timing, state.location pipe format
- Register shop_district_ (handleDistrictBack) + shop_subcategory_ (handleSubcategorySelection) in routes.js — Back button in empty categories now works
- state.location pipe-delimited with encodeURIComponent — multi-word names (Saint Petersburg) no longer break nav
- answerCallbackQuery moved to start of callback handling — no stuck spinner
- Empty city fallback (district_unknown) in Select district
- Guard against stale underscore-format state.location
- 48 tests pass; bump v1.2.4
2026-08-05 10:52:18 +01:00
NW
12c4cefc4c chore: ignore Kilo agent config files (kept on disk, system unaffected)
- Add .kilo/, kilo-meta.json, kilo.jsonc, AGENTS.md to .gitignore
- git rm --cached: files remain on disk, only removed from version control
- Agent pipeline (orchestrator, agents, capability-index) keeps working locally
2026-08-04 22:57:03 +01:00
NW
04c358eb30 chore(agents): sync agent configs — model updates to nemotron-3-super
- Update agent model assignments (nemotron-3-ultra -> nemotron-3-super) across .kilo/agents, kilo-meta.json, kilo.jsonc, capability-index.yaml
- Sync agent descriptions in KILO_SPEC.md
2026-08-04 22:55:17 +01:00
NW
b58087f37b fix(bot): issue #128 — empty category menus, duplicate country lists, DB typo+desync migration
- getCategoriesWithProductsByLocationId: filter districts to categories with real in-stock/mono products; empty → no_categories message + back button + answerCallbackQuery
- Main-menu debounce (1200ms) in routes.js for products/profile/wallets/purchases — no duplicate Select-your-country on rapid taps
- Migration 012: fix typos (Centr→Center, Chiken→Chicken, Brusel→Brussels, Sever→North) + re-enable locations that have in-stock products (desync fix)
- Tests updated (48 pass); bump v1.2.3
2026-08-04 20:53:34 +01:00
NW
5c6760b180 ci: install docker-cli in alpine job container for build/push/save steps
All checks were successful
Release: ARM64 Docker Image / build-arm64 (push) Successful in 3m14s
2026-08-04 19:21:04 +01:00
NW
eac2a0cd6c ci: use sh shell in release workflow (node:22-alpine has no bash)
Some checks failed
Release: ARM64 Docker Image / build-arm64 (push) Failing after 1m40s
2026-08-04 19:17:33 +01:00
NW
4186ebeab6 ci: fix checkout step - git in alpine + pass REGISTRY_TOKEN via env
Some checks failed
Release: ARM64 Docker Image / build-arm64 (push) Failing after 12s
2026-08-04 18:33:50 +01:00
NW
49d3f41686 ci: release workflow without GitHub actions (network blocked) - pure run steps
Some checks failed
Release: ARM64 Docker Image / build-arm64 (push) Failing after 12s
- GitHub unreachable on prod network; actions/checkout@v4 etc fail to download
- Rewrite release.yaml using only run: steps (git clone from Gitea, docker build/push)
- Clone uses REGISTRY_TOKEN (oauth2) from Gitea secrets
- Registry push is best-effort; always saves image tarball artifact
2026-08-04 18:30:35 +01:00
NW
9eca348d57 ci: ARM64 release workflow (Gitea Actions, native arm64 runner on Orange Pi)
Some checks failed
Release: ARM64 Docker Image / build-arm64 (push) Failing after 3s
- Runs on tag push (v*) on arm64 runner (orange-pi-arm64, label: arm64)
- Native ARM64 docker build (no QEMU), consistent with prod Orange Pi Zero 2
- Best-effort push to Gitea Container Registry (git.softuniq.eu/telegram-market/telegram-shop)
- Falls back to saving image tarball if registry auth unavailable
2026-08-04 18:04:05 +01:00
NW
88a15acb29 fix(admin): delete feedback alerts + informative block errors (issue #127)
- locations/categories GET pass req.query.error/success to views
- locations/categories EJS render dismissible error/success alerts (modeled on catalog.ejs)
- Delete errors include blocking counts + 'Remove X first' hints
- 🔒 lock hint on rows with linked categories/products/subcategories
- 18 new tests (adminDeleteFeedback.test.js); 48 total pass
2026-08-04 17:05:06 +01:00
NW
bd3391c111 fix(bot): issue #127 — active-state sync, disabled-entity handling, double-tap lock, state reset
- BUG-01: getActiveLocationById + product availability checks (loc_active/cat_active) — disabled locations/categories filtered from bot menus
- BUG-02: graceful redirect to main menu (location_disabled notice) when entity disabled mid-flow, no crash in handleDistrictSelection/handleProductSelection/handleBuyProduct/handlePay
- BUG-03: per-user callback lock (LOCK_MS 1500ms debounce) in utils/callbackLock.js — duplicate taps dropped
- BUG-04: resetUserContext clears tracked photo/product messages + userStates on main-menu navigation and /start
- fix: handlePay uses validated numeric quantity (was raw string) for price/stock/purchase writes
- tests: 7 new (botBugFixes.test.js), updated userProductHandler tests — 30 total pass
- bump v1.2.2
2026-08-04 15:21:55 +01:00
NW
29ab8f9d34 chore(agents): sync agent configs, models, capability index; cleanup junk
- Update agent model assignments (minimax/glm -> nemotron-3-ultra, kimi-k2.7-code, qwen3.5:397b) in .kilo/agents, kilo-meta.json, kilo.jsonc, capability-index.yaml
- Update orchestrator/agent prompts (complexity fast-path, verification tests, close-loop audit)
- Add .kilo/KILO_SPEC.md (Kilo Code specification reference)
- AGENTS.md: consolidate smartadmin agent rows
- Remove screenshot-dash.cjs (unused, contained hardcoded admin token); gitignore it
- Remove empty .kilo/milestones/
2026-08-04 14:16:41 +01:00
NW
47c698aa42 fix(admin): make catalog CRUD management visible
- Add management toolbar on /catalog with links to /locations and /categories
- Expand catalog tree by default (all levels visible, no collapsed accordion)
- Add Back to Catalog link on /locations and /categories pages
- Edit/toggle/delete buttons for locations/categories/subcategories now immediately accessible
2026-07-25 13:12:12 +01:00
NW
ca2ddefd7a feat(admin): full CRUD + enable/disable for locations, categories, subcategories
- Migration 011: add is_active INTEGER NOT NULL DEFAULT 1 to locations, categories, subcategories (idempotent)
- Admin routes: locations edit + toggle, categories toggle, subcategories edit + toggle (parallel endpoints on /catalog)
- Bot-side services: filter is_active=1 on locationService/categoryService read methods (getLocationById/getCategoryById left unfiltered for purchase display)
- Views: edit forms, toggle buttons, Active/Disabled badges, disabled row styling in locations.ejs, categories.ejs, catalog tree
- Add Categories nav item in sidebar (folder icon)
- Tests: 14 new tests for migration idempotency + service is_active filtering (23 total pass)
2026-07-19 23:22:21 +01:00
NW
776d0e8552 fix(bot): remove redundant deposit amount step, add Visa/MC label, Mercuryo auth note, enforce product completeness
- Remove deposit amount-selection step; deposit_wallet_<TYPE> now routes directly to instruction
- Add VISA / Mastercard text to Mercuryo card button (i18n en/es/de)
- Add deposit_important5: Mercuryo 1-payment-without-auth + top-up-reserve warning
- Admin validation: description + photo required on product create/update (products.js, catalogProducts.js)
- Cleanup orphan uploaded files on validation failure (catalogProducts.js)
- Bot guards: fallback to products.no_description / products.no_photo for incomplete products
- Add vitest + 7 purchase edge-case tests (src/__tests__/userProductHandler.test.js)
- Bump version to v1.2.1
2026-07-18 14:28:26 +01:00
NW
b6eb42ccfc fix: seed phrase modal, USDT address bug, CSV balance column, remove CSRF
- Fix seed phrase reveal modal: use classList instead of style.display
  to properly toggle d-none/d-flex on Bootstrap elements
- Fix USDT/USDC wallet creation bug: was using ETH address (index 0)
  instead of correct derivation path address (index 1/2)
- Add Balance column to CSV seed export
- Remove CSRF tokens from wallets.ejs (incompatible with Tor/onion)
- Super admin CSV export: no commission check required
- Audit logging for CSV seed exports
- Use window.addEventListener('load') for seed modal JS to ensure
  Bootstrap is loaded before initializing bootstrap.Modal
2026-07-14 14:50:24 +01:00
NW
d03c8419e5 feat(admin): super admin role, seed phrase viewer with QR code, CSRF disabled for Tor
- Add super admin role system (SUPER_ADMIN_SECRET env var)
  - requireSuperAuth middleware for sensitive routes
  - isSuperAdminWeb() helper for template access
  - Role badge in header (Super Admin / Admin)
  - Seed Viewer nav item visible only to super admins

- Add seed phrase viewer with QR code generation
  - GET /wallets/seed/:walletId — JSON seed phrase (super admin only)
  - GET /wallets/seed-qr/:walletId — QR PNG image (super admin only)
  - Modal UI with reveal-on-click, 60s auto-hide countdown
  - Copy-to-clipboard and download QR as PNG
  - Audit logging for every seed phrase access

- Disable CSRF completely for Tor/onion compatibility
  - csrfMiddleware no longer sets _csrf cookie
  - validateCsrf and validateCsrfFromBody are no-ops
  - res.locals.csrfToken set to empty string (prevents template errors)

- .env.example: document SUPER_ADMIN_SECRET variable
2026-07-09 16:40:15 +01:00
NW
83991f098b v1.2.0: disable CSRF for Tor, fix wallet type validation, add version history modal
- fix(admin/csrf): completely disable CSRF checks for Tor/onion compatibility
- fix(validators): add 'main' and 'bonus' to WALLET_TYPES for purchase flow
- feat(admin): add clickable version tag with version history modal in sidebar
- docs: add VERSION.md with changelog and update instructions
2026-07-08 21:59:16 +01:00
NW
4997ca75ab fix(admin): header logo alignment + sidebar version tag
- Move app-logo out of flex-grow-1 div to be direct child of app-header
  (matches SmartAdmin CSS expectations for .app-header .app-logo)
- Remove inline style padding-left from logo, rely on SCSS padding
- Remove data-prefix attribute that positioned version text absolutely
- Override .app-logo > svg.sa-icon min-width (was 11rem) to natural
  icon size (1.5rem) so icon and text align inline
- Add .logo-text class for proper text sizing and nowrap
- Fix conflicting responsive classes on header buttons
  (d-sm-block d-sm-none → d-none d-lg-block)
- Fix fullscreen button aria-label (was 'Toggle Dark Mode')
- Remove w-100 from header inner div that pushed buttons off-screen
- Replace wifi icon in nav-footer with tag icon + version text v1.0
2026-07-08 14:00:20 +01:00
NW
f0afada884 feat: Mercuryo gateway, crypto QR deposit, mono products, wallet auto-refresh
- Replace Quickex/Guardarian with Mercuryo (https://mercuryo.io/)
- Add crypto QR code payment option in deposit flow (qrcode package)
- Add is_mono product flag for digital/infinite products
- Mono products: no quantity buttons in bot, always available
- Admin wallet page: auto-refresh balances from blockchain APIs
- Migration 010: add is_mono column to products
- i18n updates for en/de/es
2026-07-08 12:08:13 +01:00
NW
2b30bc4a91 fix(admin): CSRF cookie sameSite=false for Tor, auth cookie fix, async handlers, validation 2026-07-08 12:08:08 +01:00
NW
046c40349d chore: sync all changes 2026-07-07 18:48:40 +01:00
NW
e84c2af650 fix(admin/dashboard): charts rendering + realistic demo data
- Move ApexCharts script to <head> in app-head-css.ejs for global availability
- Remove conflicting apexchartsWrapper.js module from app-scripts.ejs
- dashboard.ejs: wrap charts init in window.addEventListener('load') for correct DOM timing
- Add inline height styles to chart containers (350px, 300px, 250px)
- Add CSS min-height fallback for .apex-charts in layout.ejs
- seed.js: realistic demo data with 30-day date spread, 10 users, 30 purchases,
  12 audit log entries, 2 commission payments, 10 wallets with 7 coin types
- dashboard.js: add days30 and revenueData30 to chartData for 30-day chart
2026-07-06 19:59:56 +01:00
NW
1648336511 fix(admin/dashboard): restore layout BEFORE SortableJS init
- Reorder DOM elements from localStorage BEFORE initializing SortableJS
- Initialize Sortable AFTER layout restoration so it tracks correct DOM
- Add console.log for save/restore debugging
2026-07-06 19:22:22 +01:00
NW
bc48334269 feat(admin): draggable dashboard panels + business KPI redesign
- Dashboard: 16 business-focused panels (KPIs, charts, tables, feeds)
- New data queries: AOV, conversion rate, revenue by category, top spenders,
  purchase funnel, 30-day trend, geography, wallet totals
- ApexCharts: 30-day revenue line, category bar, funnel bar, geo bar,
  conversion mini-donut, revenue sparkline
- SortableJS: draggable panels within rows, layout saved to localStorage
- Theme persistence: body classes (nav-dark, header-fixed, etc.) saved to
  localStorage and restored on load, MutationObserver syncs all toggles
- Panel data-panel-id attributes for layout persistence
- All panels use existing SmartAdmin panel-icon/card styling
2026-07-06 19:13:05 +01:00
NW
2a34b40411 fix(admin): button icon visibility and text wrapping
- Add CSS for svg.sa-icon fill on all button variants
- white-space: nowrap + inline-flex + gap for icon buttons
- Quick Actions: d-grid → d-flex flex-wrap for horizontal layout
- btn-secondary → btn-dark for Settings button (icon visibility)
2026-07-06 19:00:25 +01:00
NW
10f8138ce2 fix(admin): add me-2 margin to sa-icon SVGs in card headers and buttons 2026-07-06 18:55:47 +01:00
NW
c149c877f3 fix(admin): localization to English + padding fixes for tables, buttons, logo 2026-07-06 18:32:22 +01:00
NW
86c4e18752 fix(admin/wallets): user list styling + full-width Owner Summary
- User list: .list-group-item-action instead of .dropdown-item for proper
  row styling, clear layout with status badge and wallet count
- Owner Summary: moved to separate full-width row outside col-md-9,
  now spans entire content area independent of user/wallet panels
2026-07-06 17:59:22 +01:00
NW
d4c476002c feat(admin): SmartAdmin template redesign + security hardening
- Migrated all admin views from inline JS string templates to EJS
- Integrated SmartAdmin template with dark sidebar, fixed header, CSS grid
- Added express-ejs-layouts for master layout wrapper
- Security:
  - CSRF protection (double-submit cookie)
  - Rate limiting on /login (5/15min)
  - Token revocation via jti + globalLogoutTimestamp
  - Re-auth (reauth_token) for destructive endpoints
  - Settings whitelist (ALLOWED_KEYS) + removed process.exit
  - Seed phrases no longer rendered in HTML (CSV export only)
  - Multer fileFilter for image uploads + safe filename generation
  - SQL injection fix (currency column allowlist)
  - Global error handler + asyncHandler wrapper
- New files: csrf.js, errorHandler.js, error.ejs, all EJS templates
- SmartAdmin assets: CSS, icons, webfonts, plugins, scripts
2026-07-06 17:42:54 +01:00
NW
8d85776135 feat: add AI-powered visual regression testing infrastructure
- Add docker-compose.web-testing.yml with vlmkit service
- Add 5 test scripts: capture, compare, pipeline, console-monitor, link-checker
- Add vrt.config.json with 3 viewports + maskSelectors
- Add package.json with @mizchi/vlmkit and Node >=24
- Add tests/README.md with VRT documentation
- Update .gitignore for test artifacts

Based on APAW issue #144 / milestone #106
2026-06-30 21:09:30 +01:00
NW
f2d4d6d3b1 docs: update README with i18n section, language support, and project structure 2026-06-25 23:54:59 +01:00
NW
7db7a20a1d feat: always show language selector on /start, add change_language button in profile
- /start now always shows language picker (removed language_set check)
- Added 'Change Language' button in profile inline keyboard
- Added handleChangeLanguage callback handler
- Added profile.change_language locale key in en/es/de
- Registered change_language callback route
2026-06-25 23:06:58 +01:00
NW
3deddbc1b1 fix: make migrations idempotent, pass checkColumnExists to all migrations 2026-06-25 22:52:59 +01:00
NW
a8bf50df24 feat: add i18n localization system (en/es/de) with admin panel
- Add i18n module with tForUser/tForLang/t functions and {{param}} interpolation
- Add 3 locale files: en.json, es.json, de.json (201 keys each)
- Add language selection on /start and /language command with flag emojis
- Localize all bot user-facing strings (handlers, keyboards, errors)
- Localize messageRouter keyboard matching via locale keys
- Add DB migrations 008 (language column) and 009 (language_set column)
- Add localization admin tab at /locales for editing translations
- Add userService.getUserLanguage/setUserLanguage methods
- Cache user object on msg.__user to avoid triple DB fetch
- Idempotent migrations with checkColumnExists guards
- Error boundary on i18n locale file loading
- Admin locales route uses AVAILABLE_LANGUAGES import
2026-06-25 21:22:32 +01:00
NW
41ff2b8769 feat: add user-friendly deposit instructions with email/password explanation 2026-06-25 20:22:05 +01:00
NW
61aab8fed6 fix: add amount param to ChangeNOW URL 2026-06-25 19:54:02 +01:00
NW
7f6d797bfd fix: replace StealthEX with ChangeNOW for wallet deposits
- URL: https://changenow.io/exchange?from=eur&to={crypto}&fiatMode=true
- Removed amount selection from URL (ChangeNOW has it in UI)
- Renamed STEALTHEX_REF to CHANGENOW_REF in config
- Updated all UI labels from StealthEX to ChangeNOW
2026-06-25 19:47:24 +01:00
NW
d44a15064f feat: add StealthEX deposit integration for wallet top-up
- New depositHandler.js: wallet selection, amount picker, instruction page with StealthEX link
- Updated topUpHandler.js: shows deposit buttons per wallet + deposit via StealthEX
- Routes: deposit_select_wallet, deposit_wallet_, deposit_amount_, deposit_copy_
- Config: STEALTHEX_REF env var for optional referral
- Fixed archived wallets filter in deposit wallet query
2026-06-25 18:55:19 +01:00
NW
fcd7f063c2 feat: show full wallet addresses with click-to-copy in admin
- Wallet addresses now shown in full (not truncated to 24 chars)
- Click on any address or seed phrase copies it to clipboard
- Green flash animation confirms copy
- Commission wallet addresses also clickable
- Seed phrases in unlocked view also clickable
- Fallback for older browsers using execCommand
2026-06-25 16:56:40 +01:00
NW
19a275b8e0 fix: close event listener brackets in catalog tree JS 2026-06-25 13:02:25 +01:00
NW
1768c6a5c4 fix: separate tree arrow (expand) from label (filter) in catalog
Arrow ▶ only toggles expand/collapse. Node label click filters products.
Forms inside tree (Add Category, Add District, etc.) no longer trigger
navigation when clicking their buttons or inputs.
2026-06-25 08:33:43 +01:00
NW
c55ec47ea0 fix: admin product form - cascading location selectors + inline category creation
- Country → City → District cascading dropdowns with filtering
- Categories filtered by selected location (show all when no location)
- 'No category? Create one' row appears when location selected
- POST /catalog/categories/json endpoint for AJAX category creation
- Product form uses location_id from dropdown (not category lookup)
- Categories populate in select after inline creation
- district fallback shows city name when district is empty
2026-06-25 08:21:41 +01:00
NW
bbf49ec546 fix: add location selectors (country/city/district) to product add/edit form
The admin product form now has cascading dropdowns for Country → City → District
that filter categories by location. Previously there was no way to select location
when adding a product — only a static tag display on edit.

- catalogProduct.js: replaced static location tags with 3 cascading selects
- catalog.js: pass locations data, init JS for cascading selects + category filtering
- catalog route: pass locations array to renderCatalog
- style.css: added .pf-location-selects styling for the dropdown row
2026-06-24 22:57:38 +01:00
NW
5a9155613e fix: location navigation uses IDs and pipe separators instead of underscore
Critical fix for product management location selection:
- Country/city callback_data now uses pipe | as separator with
  encodeURIComponent/decodeURIComponent for special chars
- District selection uses location ID (prod_loc_{id}, shop_loc_{id})
  instead of underscore-delimited country_city_district text
- Empty district names now show city name as fallback
- LocationService.getLocationsByCountryAndCity() returns id+district
  for building callback_data with location IDs
- All error handlers in admin product navigation use editOrSendCallback
  to avoid chat clutter
- Routes updated: prod_district_ → prod_loc_, shop_district_ → shop_loc_

This fixes the bug where selecting country/city/district in admin panel
or shop failed because split('_') broke on multi-word names or empty
district values.
2026-06-24 22:44:02 +01:00
NW
6ce8da257a fix: clean chat navigation — edit messages instead of sending new ones
All callback handlers now use editOrSendCallback() to edit the existing
message in-place instead of bot.sendMessage() which creates new messages
and clutters the chat. If edit fails (message too old), the old message
is deleted and a new one sent.

Added src/utils/messageUtils.js with:
- editOrSendCallback(callbackQuery, text, options) — edit or fallback
- editOrSend(chatId, messageId, text, options) — edit or fallback
- deleteAndSend(chatId, messageId, text, options) — delete then send

Fixed handlers:
- userProductHandler: handleBuyProduct errors, handlePay validation/stock errors
- userPurchaseHandler: viewPurchase errors, handleConfirmReceived errors, handlePurchaseListPage errors
- userLocationHandler: all error paths now edit in-place
- userDeletionHandler: both error paths now edit in-place
- wallet/balanceHandler: showBalance error (text command, acceptable)
- wallet/refreshHandler: user not found and refresh errors
- wallet/topUpHandler: wallet loading error
- wallet/createHandler: invalid wallet type error
- wallet/historyHandler: both transaction history error paths
- wallet/archiveHandler: archived wallets error
2026-06-24 20:45:39 +01:00
NW
8272f36253 fix: send photos from disk instead of URL - no ADMIN_URL needed
sendPhoto now sends local files from /app/uploads/ instead of requiring
a publicly accessible URL. This fixes the issue where onion addresses
and private IPs are unreachable by Telegram API servers.

- resolvePhotoSource(): http URLs pass through, relative paths resolved
  to local file path in uploads dir
- sendProductPhoto(): sends file directly, falls back to corrupt-photo.jpg
- Removed all ADMIN_URL prefix logic for photo URLs
- Works without any public IP or domain
2026-06-24 20:13:35 +01:00
NW
94300c7d35 fix: photo URLs use ADMIN_URL prefix for Telegram API + resilience improvements
- productHandler, purchaseHandler, viewHandler: prefix relative photo_url
  with ADMIN_URL so Telegram can fetch images via public URL
- bot.js: 5 retries with 5s delay on init, graceful fallback to null
- errorHandler.js: 5 retries on 404 (invalid token), stops polling
  but keeps process alive for admin panel
- config.js: BOT_TOKEN missing logs warning instead of process.exit
- index.js: bot handlers only registered when bot is available,
  admin panel always starts regardless of bot status
- adminWalletsHandler.js: replace throw with logger.warn for missing
  commission wallets (prevents container crash on startup)
- docker-compose.yml: bind admin port to all interfaces (0.0.0.0)
- README.md: updated with Tor proxy architecture, resilience docs
- install.sh: added Tor proxy status check and onion address display
2026-06-24 19:32:49 +01:00
NW
ee8c75066c fix: bind admin port to all interfaces instead of localhost only
Allows access from LAN (192.168.2.x:3001) in addition to Tor onion address.
2026-06-24 15:16:35 +01:00
NW
6aa7980ddf fix: bot no longer crashes container on invalid token
- bot.js: 5 retries with 5s delay on init, graceful fallback to null
- errorHandler.js: 5 retries on 404 (invalid token), stops polling after
  max retries but keeps process alive for admin panel
- config.js: BOT_TOKEN missing logs warning instead of process.exit
- index.js: bot handlers only registered when bot is available,
  admin panel always starts regardless of bot status
2026-06-24 15:05:44 +01:00
NW
54a2d57055 fix: replace throw with logger.warn for missing commission wallets
App crashed on startup if COMMISSION_ENABLED=true but wallet addresses
were missing. This prevented the admin panel from starting at all.
Now logs a warning instead of crashing.
2026-06-24 14:49:51 +01:00
NW
b99f70f344 fix: HiddenServiceDir must be chmod 700 for Tor
Tor requires HiddenServiceDir to be 700. Root can still read hostname
files inside 700 dirs, so the background onion-writer works fine.
2026-06-24 12:16:59 +01:00
NW
3bbda97bb9 fix: proper Tor user and directory permissions
- Add User tor to torrc for privilege dropping
- chown /var/lib/tor to tor:nogroup before Tor starts
- chmod 755 on hostname directories so root can read them
- Remove invalid chown tor:tor (tor group doesn't exist in Alpine)
2026-06-24 12:15:16 +01:00
NW
9d8d9edc00 fix: add User tor to torrc and chown data dirs
Tor refuses to start when DataDirectory is owned by root.
Added User tor directive and proper chown for /var/lib/tor and /onion-hosts.
2026-06-24 12:11:41 +01:00
NW
45d2bfbcf8 fix: newline validation bug in entrypoint.sh
echo adds trailing newline, causing false positives. Use printf and case statement instead.
2026-06-24 12:09:32 +01:00
NW
67c1436670 feat: save onion addresses to file and .env on host
- entrypoint.sh: background process writes onion-hosts.txt with SSH_ONION and ADMIN_ONION
- docker-compose.yml: bind mount tor-proxy/hosts for onion address persistence on host
- tor-proxy/get-onions.sh: reads onion addresses and updates .env with ADMIN_URL, SSH_ONION, ADMIN_ONION
- .gitignore: exclude tor-proxy/hosts/onion-hosts.txt (secret)
- tor-proxy/hosts/.gitkeep: ensure directory exists in git
2026-06-24 11:45:43 +01:00
NW
d8bfb29205 feat: add tor-proxy service for SSH and admin panel access via Tor
- Add tor-proxy/Dockerfile: Alpine + Tor with entrypoint
- Add tor-proxy/entrypoint.sh: dynamic torrc generation with env var validation
- Update docker-compose.yml: add tor-proxy service with shared tor_proxy_net network
- Two Tor hidden services: SSH (port 22) and admin panel (port 80 -> 3001)
- Update .env.example: add SSH_HOST_IP, SHOP_CONTAINER, ADMIN_PORT vars
2026-06-24 11:30:38 +01:00
NW
4aea49811c feat: multi-architecture Docker setup (x86_64 + ARM64) with one-command install
- Multi-stage Dockerfile: builder compiles native modules (better-sqlite3,
  tiny-secp256k1) under target architecture, runtime is minimal Alpine
- install.sh: POSIX sh installer (Alpine ash compatible) with architecture
  detection, Docker install, .env validation, health-check retry loop
- docker-compose.yml: removed platform locks, .env read-only mount,
  127.0.0.1 port binding, 384m mem limit (Orange Pi Zero 2 safe)
- .dockerignore: excludes node_modules, secrets, tests, .kilo
- README.md: complete rewrite with deployment docs for any device
- Verified: POSIX sh syntax (dash), Dockerfile (docker build --check),
  docker-compose (docker compose config)
2026-06-24 02:06:07 +01:00
NW
293236921c fix: show location (country, city, district) in product edit modal
- JSON endpoint now joins locations+categories+subcategories for full info
- Edit form shows location tags (country, city, district) at top
- Location hidden when adding new product (no location yet)
- All fields properly filled by fillEditForm on edit
- Category and subcategory side by side in edit form
2026-06-23 21:48:53 +01:00
NW
e00071b18a fix: restyle product edit modal with proper form layout and sections
- Product form: grouped fields with pf-group/pf-row/pf-section-title
- Modal: sticky header, scrollable body, proper padding
- Form sections: Public Photo, Hidden Content (after purchase)
- Photo fields: URL input + file upload side by side per section
- Inputs/selects/textareas: consistent sizing, focus ring
- Actions: Save + Cancel buttons with border separator
2026-06-23 21:04:00 +01:00
NW
8e52618a50 fix: make commission settings and wallets read-only for shop admin
- Commission Settings card: disabled inputs, Platform Owner badge
- Commission Wallets card: disabled inputs, Platform Owner badge
- Hidden fields carry original values so POST preserves them unchanged
- Shop admin sees values but cannot modify — only platform owner can
2026-06-23 13:23:59 +01:00
NW
33654206a0 fix: wallet page layout - sticky sidebar with scroll, full-width owner summary below
- Sidebar: sticky with height=100vh, search field, internal scroll for user list
- Owner Summary: full-width below user/wallet section, not inside right column
- Wallet main: normal flow scrolling, not fixed height
2026-06-23 13:21:04 +01:00
NW
91d7a19f0c feat: searchable sticky user sidebar with scroll for wallets page
- Added search field at top of sidebar filtering by username or telegram ID
- Sidebar is sticky (stays in view while scrolling right panel)
- Sidebar max-height matches viewport for natural scroll with hundreds of users
- Each user item has data-name/data-tgid/data-id for instant JS filtering
- Stats section scrolls naturally below user wallets
2026-06-23 13:16:35 +01:00
NW
98eb27c573 fix: lock seed phrases behind commission payment gate
- Seeds only unlock when lastPaidAmount >= currentCommission
- CSV export endpoint also checks commission before serving
- Button shows locked state with amount due when commission unpaid
- Prevents free access to encrypted mnemonics without payment
2026-06-23 13:13:43 +01:00
NW
a6d81cfe83 feat: commission tracking based on wallet balances with payment history
- Commission = 5% of total wallet balances (not sales)
- Track commission payments in commission_payments table (migration 007)
- Show 'Due Now' = current commission - last payment amount
- Record payment form with amount and optional note
- Payment history table with date, balances, commission, paid, delta
- Delta shows difference between consecutive payments (new users = more owed)
- Seed phrase unlock reminder shows the commission due amount
- Stat warning highlight when commission is due
2026-06-23 13:01:15 +01:00
NW
76daf07bb4 feat: owner summary with wallet stats, commission info and seed phrase unlock
- Added Owner Summary section below user wallets with:
  - Total wallet balance (USD) across all currencies
  - Completed sales total
  - Commission calculation (rate × sales)
  - User and wallet counts
- Wallet balances by currency table (coin, count, balance, USD)
- Commission wallets display for owner payment
- Seed phrases section: locked by default, unlock via button
- CSV export for all decrypted seed phrases
- Seed phrase decrypt uses existing WalletService.decryptMnemonic
- Preserves user selection when toggling seed unlock
2026-06-23 12:51:57 +01:00
NW
b6f21222e7 feat: wallet balances grouped by user with split layout
- Left sidebar: user list with ID, username, status icon, wallet count
- Right panel: selected user's balances + crypto wallet table
- Fix inverted status logic (0=Active, 1=Deleted, 2=Blocked)
- Admin bot: block/unblock toggle based on current user status
- Seed data: set active users to status=0 instead of status=1
- Toggle-status route: 0↔2 instead of 1↔0
2026-06-23 12:41:18 +01:00
NW
7b247075a0 fix: wallet generation crash - WalletUtils not defined, registerRoutes not called
- createHandler.js: replace WalletUtils.getNetworkName (undefined) with
  WalletHelpers.getNetworkName, add import
- index.js: call registerRoutes() to register bot message handlers
  (was imported as side-effect but function never called)
- messageRouter.js: remove debug logging
2026-06-23 12:35:12 +01:00
NW
6db770b96b feat: editable settings page with .env write and container restart
- Add settings form with all config fields (Bot, Commission, Wallets, WireGuard)
- POST handler writes .env file and restarts container via process.exit(0)
- Secrets (ENCRYPTION_KEY, ADMIN_SECRET, GITEA_TOKEN, WG_PRIVATE_KEY, WG_PRESHARED_KEY)
  are never sent to browser - masked placeholders used instead
- PRESERVE_KEYS enforced: secret keys cannot be overwritten via form
- Values sanitized: newlines stripped before writing to .env
- start.sh loads .env file before node to override Docker env_file cache
- Extract shared escapeHtml utility to escape.js (used by 6 view files)
- Update paymentWallets view to link to Settings page instead of .env
- Add .env volume mount for settings panel read/write
- Fix registerRoutes() not being called in index.js (bot menu buttons)
2026-06-23 12:32:25 +01:00
NW
935c6df1dc feat: rebuild Catalog with collapsible tree + product table + photo upload
- Left panel: collapsible tree (Country → City → District → Category → Subcategory)
  - Quick-add buttons: + City, + District, + Category, + Subcategory
  - Delete buttons with confirmation on all nodes
  - Product count badges on each node
  - Click node to filter right panel
- Right panel: Product table with Photo, Name, Category, Subcategory, Price, Stock
  - Edit (✎) and Delete (✕) buttons per row
  - Add Product modal with all fields
- Product edit form: name, price, stock, description, category, subcategory (JS filtered),
  photo_url/hidden_photo_url (URL or file upload), hidden_coordinates, hidden_description, private_data
- Multer file upload for photos stored in /uploads/
- Routes: add-city, add-district, product CRUD with photo upload
- Product JSON API for modal editing
- Responsive grid: tree (320px) + table (1fr)
2026-06-22 21:42:56 +01:00
NW
c7bf3f132c feat: unified Catalog page with Location→Category→Subcategory→Product tree
- New /catalog page with tree view: Location (🌍) → Category (📂) → Subcategory (📁) → Product
- Add/delete locations, categories, subcategories, products from one page
- JS-powered subcategory dropdown filtered by category
- Sticky sidebar with Add Location/Category/Product forms
- Responsive grid layout (tree + forms side by side, stacks on mobile)
- Navigation simplified: Catalog replaces separate Locations/Categories/Products
- Old routes still accessible for backward compatibility
- Subcategories table migration (006_subcategories.js)
- subcategory_id column added to products table
- Seed data includes subcategories (VPN, Accounts, Hardware, etc.)
2026-06-22 21:12:05 +01:00
NW
2012435370 feat: admin panel - Settings, Categories, Payment Wallets, Seed/Clear data, User Balances
- Settings page: bot token (masked), admin IDs, commission config, WireGuard status
- Categories page: CRUD with product count, delete guard
- Payment Wallets page: commission wallets display, toggle, percentage
- Users page: balance adjustment form (total_balance / bonus_balance) with audit log
- Seed & Reset page: seed demo data (5 users, 10 products, 5 wallets, 5 purchases)
  and clear all data button with confirmation
- Dashboard: flash messages for seed/clear success
- Fixed seed.js: use dynamic IDs instead of hardcoded to avoid FK violations
- Fixed seed.js: clear all tables before seeding to avoid UNIQUE constraints
2026-06-22 14:20:58 +01:00
NW
4657b1dfb5 feat: web admin panel + better-sqlite3 migration + Docker fixes
- Added Express.js admin panel on port 3001 (ADMIN_PORT env)
  - Dashboard: stats (users, products, purchases, revenue)
  - Users: list, details, ban/unban toggle
  - Products: CRUD by category
  - Wallets: list with balances
  - Purchases: history with filters
  - Audit log: view audit trail
  - Auth: token-based login with ADMIN_SECRET env var
- Migrated sqlite3 → better-sqlite3
  - database.js: async adapter (runAsync/allAsync/getAsync)
  - purchaseService.js: lastID → lastInsertRowid
  - userService.js: lastID → lastInsertRowid
  - Removed sqlite3 from package.json
- Fixed: dotenv/config import added to index.js
- Fixed: ENCRYPTION_KEY validation (32+ char hex)
- Fixed: Dockerfile multi-stage build (no python needed)
- Fixed: Docker DNS (network: host in build)
- Fixed: docker-compose port 3001, healthcheck on 3001
- Added express, cookie-parser, pino-pretty, better-sqlite3 deps
2026-06-22 10:54:01 +01:00
NW
25d8507b11 fix: Docker multi-stage build for sqlite3, health endpoint, productValidator exports
- Dockerfile: multi-stage build (builder with python3+g++ for native addons)
- Dockerfile: wireguard-tools from edge/community repo
- Dockerfile: removed USER appuser (start.sh needs root for wg-quick)
- Dockerfile: health check on port 3000
- Added /health HTTP endpoint in index.js for Docker healthcheck
- Fixed productValidator.js: added named exports (validateProductName, validateProductPrice)
- Added better-sqlite3 as fallback dependency
2026-06-22 10:18:36 +01:00
NW
49945d9d81 security(csv-export): harden mnemonic export with super admin, audit, watermark (#48)
- Add SUPER_ADMIN_IDS config (fallback to ADMIN_IDS if not set)
- Add isSuperAdmin() to middleware/auth.js
- Create auditService.js for structured audit logging (DB + pino)
- Create migration 005_audit_log.js
- Add confirmation dialog before CSV export (confirm_export_ callback)
- Check isSuperAdmin before export — block non-super admins
- Audit log every export: admin ID, wallet type, wallet count
- Add exported_by watermark column to CSV with admin telegram ID
- Notify all other super admins when export occurs
- Add SUPER_ADMIN_IDS to .env.example

8 files changed, 154 insertions, 39 deletions
2026-06-22 10:07:58 +01:00
NW
a04e60d751 feat(state): replace in-memory Map with SQLite-backed stateService (#59)
- Create src/services/stateService.js with get/set/delete/has API
- Create migration 004_user_states.js (chat_id PK, state_data JSON, updated_at)
- TTL of 24 hours — expired states auto-deleted
- Cleanup job runs every hour (setInterval)
- Replace src/context/userStates.js Map with async stateService proxy
- Add await to all 45 userStates.get/set/delete/has calls across 13 files
- Add initStates() call in index.js startup sequence
- All state survives bot restarts now

18 files changed, 172 insertions, 46 deletions
2026-06-22 10:02:57 +01:00
NW
ce1b6003cb feat(logging): replace 207 console.log/error/warn with pino structured logger (#58)
- Add pino + pino-pretty dependencies
- Create src/utils/logger.js with env-based LOG_LEVEL
- Replace all 207 console.log/error/warn calls across 46 source files
- Remove [DEBUG], [ERROR] string prefixes (levels convey this)
- Add pino redact for sensitive fields (mnemonic, privateKey, token, etc.)
- Structured logging with context objects instead of string interpolation
- NODE_ENV=production disables pino-pretty transport

49 files changed, 5601 insertions, 6056 deletions
2026-06-22 01:42:47 +01:00
NW
ba80784ae7 security(docker): remove privileged mode, SYS_MODULE; harden WireGuard (#49 #50)
- Removed privileged: true from docker-compose.yml
- Removed SYS_MODULE cap_add (kept NET_ADMIN for WireGuard)
- Removed source code bind mounts (./src, package.json)
- Removed wg0.conf and resolv.conf bind mounts (now generated from env)
- Added resource limits: mem_limit 512m, cpus 1.0
- Added healthcheck with curl
- Added non-root user appuser:appgroup in Dockerfile
- wg0.conf now generated from env vars at container startup (WG_PRIVATE_KEY, etc.)
- resolv.conf generated from WG_DNS env var
- Rotated wg0.conf — private key removed from file
- Added WG_ALLOWED_IPS to .env.example

SECURITY: Rotate WireGuard keys on server if previously used in production
2026-06-22 01:26:35 +01:00
NW
d0b26dae25 refactor(arch): replace if/else router with Map-based dispatcher (#53)
- index.js: 394→69 lines (82% reduction)
- callbackRouter.js (36 lines): Map-based dispatch with exact + prefix matching
  - Longest-prefix-first for specificity
  - Logs warning for unregistered callbacks
- messageRouter.js (27 lines): Ordered input handlers + text command Map
- routes.js (345 lines): All 59 callback routes + 9 text commands + 7 input handlers
  - Exact routes: 19 (add_wallet, back_to_balance, etc.)
  - Prefix routes: 40 (generate_wallet_, view_product_, etc.)
  - Admin text commands with isAdmin guard
  - Special cases: view_transaction_history_ page extraction
  - Input handler order preserved (location → category → import → edit → dump → bonus)
2026-06-22 01:16:34 +01:00
NW
f8123e42bb refactor(arch): split userWalletsHandler.js into 7 modular files (#52)
- 747-line monolith → 8 files (all ≤108 lines)
- balanceHandler (96 lines): showBalance, handleBackToBalance
- historyHandler (107 lines): handleTransactionHistory, handleWalletHistory
- refreshHandler (75 lines): handleRefreshBalance with balance refresh
- createHandler (94 lines): handleAddWallet, handleGenerateWallet
- topUpHandler (60 lines): handleTopUpWallet
- archiveHandler (86 lines): handleViewArchivedWallets
- helpers (19 lines): getNetworkName, getWalletAddress
- index.js (20 lines): re-exports all 11 handler methods
- Removed duplicate getBaseWalletType (now uses WalletUtils)
- Removed duplicate getNetworkName (now in helpers.js)
2026-06-22 01:11:53 +01:00
NW
4b7ed0c251 refactor(arch): split adminProductHandler.js into 13 modular files (#51)
- 1093-line monolith → 13 files (all ≤97 lines)
- navigationHandler: product management entry + country selection
- districtHandler: city + district selection
- categoryAddHandler: add category input + handler
- categoryEditHandler: edit category input + handler
- categorySelectionHandler: category selection display
- createHandler: add product prompt
- importHandler: product import (JSON/text/file)
- editStartHandler: product edit prompt
- editImportHandler: product edit import
- deleteHandler: product delete + confirm
- viewHandler: product detail view
- listHandler: product list with pagination
- productValidator: shared validation utilities
- index.js: router re-exporting all 17 handler methods
- Removed duplicate handleCategorySelection (subcategories table doesn't exist)
- Removed handleSubcategoryInput/handleAddSubcategory (references non-existent subcategories table)
2026-06-17 22:41:04 +01:00
NW
4b8144ac40 refactor(arch): split database.js into migrations + connection module (#57)
- database.js: 292→42 lines (connection + async helpers only)
- 001_initial_schema.js: 7 CREATE TABLE statements in transaction
- 002_add_columns.js: 5 ALTER TABLE checks with checkColumnExists
- 003_add_indexes.js: 6 CREATE INDEX statements
- runner.js: versioned migration runner with _meta table
- index.js: calls runMigrations() + cleanUpInvalidForeignKeys()
- ALLOWED_TABLES whitelist preserved in runner.js
- Schema version tracked in _meta table for idempotent runs
2026-06-17 22:28:11 +01:00
NW
2e8b6b5659 fix: add isAdmin delegate method to AdminHandler, fix exportCSV call in adminWalletsHandler
- AdminHandler.isAdmin() static method delegates to middleware/auth.js
  (index.js calls adminHandler.isAdmin() which needs a class method)
- adminWalletsHandler: this.exportCSV() → this.handleExportCSV(callbackQuery)
  (exportCSV doesn't exist, handleExportCSV is the correct method)
2026-06-17 22:19:40 +01:00
NW
68d83807ad refactor(arch): Phase 2 — deduplicate isAdmin, convertToUsd, getBaseWalletType
- #54: Extract isAdmin() to src/middleware/auth.js, remove duplicates from 7 admin handlers
- #55: Add WalletUtils.convertToUsd(), replace 8 switch-case blocks across 4 files
- #56: Unify getBaseWalletType() — keep only WalletUtils version (most complete),
  remove duplicates from Wallet.js and userWalletsHandler.js

New file: src/middleware/auth.js
Net: -215 lines, +80 lines

Closes: #54, #55, #56
2026-06-17 22:10:34 +01:00
NW
de415633be feat(security): Phase 1 — critical security fixes and hardening
- #42: Remove hardcoded ENCRYPTION_KEY fallback from config.js,
  add startup validation for BOT_TOKEN and ENCRYPTION_KEY length
- #43: Fix SQL injection vulnerabilities — add ALLOWED_TABLES
  whitelist in database.js, ALLOWED_USER_FIELDS in userService.js,
  validate table names before PRAGMA
- #44: Fix race condition in purchaseService.js — wrap createPurchase
  in BEGIN IMMEDIATE TRANSACTION, add atomic balance/stock checks
- #41: Move all secrets from docker-compose.yml to .env file,
  use env_file directive
- #45: Replace MD5 tx_hash with crypto.randomUUID()
- #46: Upgrade KDF from SHA-256 to HKDF for mnemonic encryption,
  add backward compatibility for legacy format
- #47: Add input validation across all handlers — walletType
  whitelist, string length limits, numeric ID checks, price bounds

New files:
- src/utils/encryption.js (HKDF key derivation)
- src/__tests__/security.test.js (SQL injection prevention tests)

Closes: #41, #42, #43, #44, #45, #46, #47
2026-06-17 21:52:49 +01:00
NW
d1503a0180 chore: ignore entire .kilo/ directory and all APAW config files
- Replace partial .kilo/ entries with single .kilo/ rule (180 files)
- Keep kilo-meta.json, kilo.jsonc, AGENTS.md ignored
- Keep .architect/ and .work/ ignored
- Remove duplicate .architect/maps/.work/ entry
2026-06-17 21:12:44 +01:00
NW
e56326fdd6 chore: add Kilo Code files to .gitignore
- Add .kilo/worktrees/, .kilo/milestone-*, .kilo/session-handoff.md
- Add .kilo/evolution-test-issue.md, .kilo/node_modules/
- Add kilo-meta.json, kilo.jsonc, AGENTS.md (project-level Kilo files)
- Add .architect/ directory (except state.json and project.json)
- Keep existing .kilo/logs/, .kilo/reports/ entries
2026-06-17 21:10:38 +01:00
NW
7e0839d8cd chore: add .env.example template and expand .gitignore for secrets
- Add .env.example with all config vars (no real secrets)
- Exclude .env, .env.*, docker-compose.override.yml
- Exclude wg/ (WireGuard configs with private keys)
- Exclude dump/, dump.zip, *.csv (sensitive exports)
- Keep .env.example tracked (!.env.example exception)
2026-06-17 20:32:26 +01:00
NW
2f3459b670 mart litle update 2025-03-06 16:13:11 +00:00
NW
0c10772261 Update Start Process 2025-03-02 11:21:35 +00:00
NW
c8b6e3ceb3 litle update 2025-02-05 16:40:00 +00:00
NW
23b7f8b4bd big update WG-TOR bot connecting 2025-02-03 09:43:25 +00:00
NW
633a27164b upgrade comission wallet function 2025-01-26 22:21:13 +00:00
NW
25c74342f9 package lock file recreate 2025-01-25 13:37:03 +00:00
NW
ae1cd45aea create functional commission 2025-01-25 13:35:22 +00:00
NW
5ec8267253 Удалить package-lock.json 2025-01-25 13:34:33 +00:00
NW
79ee8b90f0 Добавить package-lock.json 2025-01-25 13:27:14 +00:00
NW
3a58b73112 update package 2025-01-25 09:31:56 +00:00
NW
fa09e81ddf crypto mnemonic case 2025-01-25 01:13:10 +00:00
NW
24aebd0bcf update packege file 2025-01-24 18:45:35 +00:00
NW
fcd89bc345 update calculate user balance in admin section 2025-01-09 20:13:45 +00:00
NW
dd18e74529 update calculate user balance 2025-01-09 20:07:44 +00:00
NW
f9356c6bbe update user purchase list 2025-01-09 13:25:35 +00:00
NW
18647091cf minor edits to aesthetics and functionality 2025-01-08 18:26:50 +00:00
NW
5ae148a2ba update planned wallets function 2025-01-08 16:20:43 +00:00
NW
66f5251795 update check ETH USDT USDC balance function 2025-01-08 12:01:02 +00:00
NW
e64f185eda separate wallet ETH USDT USDC 2025-01-02 19:31:28 +00:00
NW
22f76c64a6 delet TRON wallet type 2025-01-02 16:19:39 +00:00
NW
c9bcb09221 udpdate wallet function 2024-12-24 09:19:14 +00:00
NW
3129525a1e update user and admin wallet function 2024-12-23 20:44:56 +00:00
NW
a970a188db new user registration function 2024-12-18 19:46:29 +00:00
NW
b224b3f331 update UserService 2024-12-18 16:16:41 +00:00
NW
bfb9a55e36 update viev balance 2024-12-17 00:19:53 +00:00
NW
4aebb4e41b update user info page 2024-12-17 00:05:59 +00:00
NW
a575f75faf user catalog navigation upgrade 2024-12-16 23:56:09 +00:00
NW
21465022b3 whallets upgrade function 2024-12-16 23:43:44 +00:00
NW
d51bc9f0b9 User start registration update function 2024-12-16 12:37:44 +00:00
NW
2cfa37ea86 fix bug back navigation 2024-12-15 02:04:43 +00:00
NW
9d9e0e80ad Bug update function 2024-12-14 23:12:36 +00:00
NW
682246675e update handleProductSelection 2024-12-14 15:06:22 +00:00
NW
2aea225e2e update back category 2024-12-14 15:02:50 +00:00
NW
d918de0386 docker file update 2024-12-14 13:46:03 +00:00
NW
12d29c66b9 Update DistrictSelection back button 2024-12-14 13:16:22 +00:00
NW
207b9a829c delet subcatecory viev line 2024-12-14 13:10:23 +00:00
NW
3843dcb094 Update handleBuyProduct 2024-12-14 13:07:46 +00:00
NW
eea5d9b9e7 revert 99137e4e97
revert Update Detailed Product Viev
2024-12-14 12:54:50 +00:00
NW
057d1536bb Check bug delet category 2024-12-14 10:47:22 +00:00
NW
99137e4e97 Update Detailed Product Viev 2024-12-14 00:37:24 +00:00
NW
a400d12d16 Delet subcategory function in handleCategorySelection 2024-12-13 18:24:24 +00:00
NW
95d5fe644d Delet Subcategory Function 2024-12-13 16:41:41 +00:00
NW
3e78e231f3 0 update adminHandlers 2024-12-13 13:41:49 +00:00
NW
13a2d67474 rewrite sampleProduct 2024-12-05 18:43:00 +00:00
1323ed5
37083ca5bc Merge pull request 'feature/user-section' (#38) from feature/user-section into main
Reviewed-on: #38
2024-12-05 18:31:21 +00:00
Artyom Ashirov
82ffa81141 account deletion 2024-12-05 21:29:32 +03:00
Artyom Ashirov
e3b82bb3dd pay with main balance 2024-12-05 16:18:27 +03:00
1323ed5
ba15d09823 Merge pull request 'main' (#36) from main into feature/user-section
Reviewed-on: #36
2024-12-04 20:12:21 +00:00
290 changed files with 55478 additions and 4808 deletions

18
.dockerignore Normal file
View File

@@ -0,0 +1,18 @@
node_modules
db
uploads
.env
.env.*
!.env.example
.git
.kilo
.architect
kilo-meta.json
kilo.jsonc
AGENTS.md
corrupt-photo.jpg
wg/config
*.log
__pycache__
**/__tests__
**/*.test.js

77
.env.example Normal file
View File

@@ -0,0 +1,77 @@
# ============================================================
# Telegram Shop - Environment Configuration (TEMPLATE)
# ============================================================
# Копируй этот файл в .env и заполни реальными значениями.
# ВНИМАНИЕ: .env файлы НЕ коммитятся — они в .gitignore.
# ============================================================
# --- Telegram Bot ---
BOT_TOKEN=your_bot_token_here
ADMIN_IDS=123456789,987654321
SUPER_ADMIN_IDS=123456789
SUPPORT_LINK=https://t.me/your_support
# --- Catalog ---
# Путь к каталогу (используется ботом; по умолчанию не требуется)
CATALOG_PATH=./catalog
# --- Encryption (ОБЯЗАТЕЛЬНО! Без этого приложение упадёт) ---
# Сгенерируй надёжный ключ: node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
ENCRYPTION_KEY=
# --- Commission ---
COMMISSION_ENABLED=true
COMMISSION_PERCENT=5
# --- Commission Wallets ---
# Начальные адреса комиссионных кошельков. Редактируются в админке (Кошельки → Edit Wallets), значения в БД имеют приоритет.
COMMISSION_WALLET_BTC=
COMMISSION_WALLET_LTC=
COMMISSION_WALLET_USDT=
COMMISSION_WALLET_USDC=
COMMISSION_WALLET_ETH=
# --- ChangeNOW Deposit Integration ---
# Optional: your ChangeNOW referral ID (leave empty if none)
CHANGENOW_REF=
# --- WireGuard ---
WG_ENABLED=false
WG_PRIVATE_KEY=
WG_PUBLIC_KEY=
WG_PRESHARED_KEY=
WG_ENDPOINT=
WG_ADDRESS=
WG_DNS=
WG_ALLOWED_IPS=0.0.0.0/0,::/0
# --- Tor Proxy ---
# SSH backend: куда Tor перенаправляет SSH (по умолчанию хост-машина)
SSH_HOST_IP=host.docker.internal
# Имя контейнера админки (onion target). Жёстко задано в docker-compose.yml как tg_shop_admin.
SHOP_CONTAINER=tg_shop_admin
# --- Admin Panel (Next.js, admin-next/) ---
# Секрет входа в админку (токен, вводится на /login)
ADMIN_SECRET=your_admin_token_here
# SUPER_ADMIN_SECRET: If set to a different value than ADMIN_SECRET, users logging in
# with this token get super_admin role (seed phrase access, commission management).
# If not set or same as ADMIN_SECRET, all admins are super admins.
SUPER_ADMIN_SECRET=
# Публичный URL админки (для фото товаров и внешних ссылок)
ADMIN_URL=http://your-host:3000
# Порт health-сервера бота (Docker healthcheck)
HEALTH_PORT=3001
# --- Bot i18n ---
# Язык по умолчанию: en / es / de
DEFAULT_LANGUAGE=en
# --- AI Chatbot (admin-next) ---
# OpenAI-совместимый endpoint и ключ (используются, если не заданы в site_settings)
CHATBOT_API_ENDPOINT=https://api.openai.com/v1
CHATBOT_API_KEY=
# --- Deploy ---
# Версия образов из Gitea Container Registry (по умолчанию latest)
IMAGE_TAG=latest

View File

@@ -0,0 +1,108 @@
name: "Release: multi-arch Docker images"
on:
push:
tags:
- "v*"
workflow_dispatch:
inputs:
version:
description: "Version tag (without v prefix)"
required: false
default: ""
jobs:
build-push:
# Buildx runner на x86_64 хосте (docker:27.5-cli + host docker.sock).
# Собирает linux/amd64 + linux/arm64 одним buildx build (qemu из коробки)
# и пушит оба образа (бот + Next.js админка) в Gitea Container Registry.
runs-on: buildx
defaults:
run:
shell: sh
env:
REGISTRY: git.softuniq.eu
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
VERSION: ""
steps:
- name: Checkout code
run: |
set -e
apk add --no-cache git curl >/dev/null 2>&1 || true
# Для push по тегу: GITHUB_REF_NAME=vX.Y.Z. Для dispatch: ветка (main/dev) — берём GITHUB_REF.
REF=${GITHUB_REF_NAME}
if [ "$REF" = "main" ] || [ "$REF" = "dev" ]; then
REF=${GITHUB_REF}
fi
echo "REF=${REF}"
cd /tmp
rm -rf release-src
git clone --depth 1 --branch "${REF}" \
"https://oauth2:${REGISTRY_TOKEN}@${REGISTRY}/Telegram-Market/telegram-shop.git" release-src
cd release-src
git rev-parse --short HEAD
- name: Extract version
run: |
if [ -n "${{ github.event.inputs.version }}" ]; then
V=${{ github.event.inputs.version }}
else
V=${GITHUB_REF_NAME#v}
fi
echo "VERSION=${V}" >> "$GITHUB_ENV"
echo "Build version: ${V}"
- name: Login to Gitea Container Registry
run: |
apk add --no-cache docker-cli >/dev/null 2>&1 || true
echo "${REGISTRY_TOKEN}" | docker login ${REGISTRY} -u oauth2 --password-stdin
- name: Prepare multi-arch builder
# docker-container driver: изолированный buildkit, host network (стабильный DNS).
# qemu-эмуляция arm64 из коробки (binfmt зарегистрирован на хосте).
run: |
set -e
docker buildx create \
--name ci-builder \
--driver docker-container \
--driver-opt network=host \
--bootstrap \
|| docker buildx inspect --builder ci-builder --bootstrap
docker buildx ls
- name: Build and push bot image (amd64 + arm64)
working-directory: /tmp/release-src
run: |
set -e
docker buildx build \
--builder ci-builder \
--platform linux/amd64,linux/arm64 \
--file ./Dockerfile \
--tag ${REGISTRY}/telegram-market/telegram-shop:${VERSION} \
--tag ${REGISTRY}/telegram-market/telegram-shop:latest \
--push \
.
- name: Build and push admin image (amd64 + arm64)
working-directory: /tmp/release-src
run: |
set -e
docker buildx build \
--builder ci-builder \
--platform linux/amd64,linux/arm64 \
--file ./admin-next/Dockerfile \
--tag ${REGISTRY}/telegram-market/telegram-shop-admin:${VERSION} \
--tag ${REGISTRY}/telegram-market/telegram-shop-admin:latest \
--push \
./admin-next
- name: Verify pushed manifests
run: |
set -e
apk add --no-cache docker-cli >/dev/null 2>&1 || true
echo "${REGISTRY_TOKEN}" | docker login ${REGISTRY} -u oauth2 --password-stdin >/dev/null 2>&1 || true
docker buildx imagetools inspect ${REGISTRY}/telegram-market/telegram-shop:${VERSION} \
| grep -E "Platform|Digest" | head -4
docker buildx imagetools inspect ${REGISTRY}/telegram-market/telegram-shop-admin:${VERSION} \
| grep -E "Platform|Digest" | head -4
docker logout ${REGISTRY} || true

38
.gitignore vendored
View File

@@ -1 +1,37 @@
db
.env
node_modules/
tests/node_modules/
tests/screenshots/
tests/visual/baseline/
tests/visual/current/
tests/visual/diff/
tests/reports/
*.log
# SmartAdmin template — copied from APAW CBS repo, not tracked in downstream projects
templates/smartadmin/
# SQLite databases — never commit
db/*.db
db/*.db-wal
db/*.db-shm
db/*.backup-*
db/*.pre-merge-*
# Root-level throwaway scripts
/*.mjs
# Production backups (contain secrets + DB snapshots — never commit)
production-backup/
# Kilo agent configuration (managed locally, not committed)
.kilo/
kilo-meta.json
kilo.jsonc
AGENTS.md
admin-next/.env
# Admin dev artifacts
admin-next/.zscripts/*.pid
admin-next/.next/
admin-next/node_modules/

View File

@@ -1,11 +1,46 @@
FROM node:22
FROM node:22-alpine AS builder
WORKDIR /app
COPY package*.json /app/
COPY src/ /app/src/
#COPY db/shop.db /app/shop.db
COPY package*.json ./
RUN npm install
RUN apk add --no-cache --virtual .build-deps \
python3 \
make \
g++ \
gcc \
linux-headers \
git \
py3-setuptools \
&& npm install --omit=dev \
&& apk del .build-deps
CMD ["node", "src/index.js"]
# ============================================================
# Runtime image
# ============================================================
FROM node:22-alpine
RUN apk add --no-cache \
bash \
bind-tools \
curl \
iptables \
iproute2 \
openresolv \
wireguard-tools
WORKDIR /app
COPY --from=builder /app/node_modules ./node_modules
COPY package*.json ./
COPY ./src ./src
COPY ./wg/start.sh /app/start.sh
RUN chmod +x /app/start.sh
RUN mkdir -p /app/db /app/uploads
EXPOSE 3001
CMD ["/bin/bash", "/app/start.sh"]

414
README.md
View File

@@ -1,90 +1,372 @@
**Универсальный Телеграмм Магазин**
# Telegram Shop Bot
**Описание проекта**:
"Универсальный Телеграмм Магазин" — это телеграмм-бот, предназначенный для организации и управления онлайн-продажами товаров и услуг через популярную платформу Telegram. Магазин включает функционал как для пользователей, так и для администраторов, обеспечивая удобное взаимодействие с товарами, балансами, кошельками и покупками.
Телеграм-бот для организации онлайн-продаж через Telegram с поддержкой криптовалют, WireGuard VPN и Tor-прокси для доступа к админ-панели через onion-адрес.
Проект включает несколько ключевых разделов для удобной работы пользователей и администраторов, а также позволяет интегрировать систему криптокошельков для расчетов, управления товарами и отслеживания покупок.
## Возможности
### Цели проекта:
- Создание удобного и универсального интерфейса для покупок через Telegram.
- Обеспечение безопасности и простоты транзакций с использованием криптовалют и традиционных средств.
- Внедрение эффективной системы управления для администраторов, с возможностью мониторинга пользователей, товаров, кошельков и комиссий.
- Реализация системы профилей с возможностью редактирования, управления балансами и удаления аккаунтов.
- Каталог товаров с категориями и фильтрацией по локациям
- Покупки с оплатой криптовалютами (BTC, ETH, LTC, USDT, USDC)
- Управление криптокошельками (создание, пополнение, баланс)
- История транзакций и покупок
- SaaS-система с автоматическим расчётом комиссий
- **Мультиязычность (i18n)** — английский, испанский, немецкий с переключением в боте
- **Новая админ-панель** (Next.js 16 + Prisma + shadcn/ui) на порту 3000: дашборд, каталог, заказы, кошельки, лиды, ИИ-чатбот, аудит, настройки
- Tor-прокси с двумя onion-сервисами (SSH + админка)
- WireGuard VPN для безопасных транзакций
---
## Быстрый старт (одна команда)
### Структура проекта:
### Требования
#### 1. **Пользовательский раздел**
Пользователи могут:
- Просматривать и покупать товары, управлять своим балансом.
- Следить за историей покупок.
- Пополнять свои криптокошельки.
- Управлять своим профилем, изменяя локацию и удаляя аккаунт.
- Любое устройство с Docker: x86_64 (PC, сервер) или ARM64 (Orange Pi, Raspberry Pi)
- 512 МБ RAM минимум (Orange Pi Zero 2 поддерживается)
#### 2. **Административный раздел**
Администраторы могут:
- Управлять пользователями: блокировать, удалять и редактировать балансы.
- Управлять товарами: добавлять, редактировать, удалять товары и категории.
- Управлять кошельками: контролировать пополнения и комиссионные платежи.
- Создавать дампы для переноса базы данных магазина.
### Установка
---
```bash
git clone <repo-url> && cd telegram-shop
bash install.sh
```
### Основной функционал:
Скрипт автоматически:
1. Определит архитектуру (x86_64 / ARM64 / ARMv7)
2. Установит Docker если не установлен
3. Создаст `.env` из шаблона
4. Интерактивно запросит недостающие переменные (BOT_TOKEN, ADMIN_IDS) и сгенерирует ключи (ENCRYPTION_KEY, ADMIN_SECRET, SUPER_ADMIN_SECRET) если они не заданы
5. Установит SHOP_ACTIVATED=false для нового магазина (стартует заблокированным)
6. Автоматически определит LAN IP и установит ADMIN_URL
7. Соберёт Docker-образ под текущую архитектуру
8. Запустит контейнер и проверит health-check
#### 1. **Покупки и товары**
- **Продукты**: Пользователи могут выбирать товары по категориям, проверять наличие средств и совершать покупки.
- **Профиль**: В разделе профиля можно изменять локацию, а также удалять аккаунт.
- **История покупок**: Пользователи могут отслеживать свои покупки с описанием товаров и статусов.
- **Кошельки**: Возможность добавлять новые криптокошельки, пополнять их через QR-коды и просматривать историю транзакций.
#### Активация магазина
После установки магазин стартует заблокированным (SHOP_ACTIVATED=false). Оператор получает onion-адрес от клиента, заходит в админку по onion/LAN, входит с SUPER_ADMIN_SECRET, добавляет комиссионные кошельки (Кошельки → Edit Wallets), настраивает бота, нажимает "Activate Shop" в Настройках.
#### 2. **Администрирование**
- **Управление пользователями**: Администратор может просматривать информацию о пользователях, управлять их балансами, блокировать или удалять аккаунты.
- **Управление товарами**: Добавление новых товаров, редактирование существующих и управление их категориями.
- **Создание дампов**: Администратор может создать дамп магазина, чтобы перенести данные на другой сервер или сохранить их для архивации.
### Ручная установка
#### 3. **Работа с криптовалютами**
- Поддержка различных типов криптокошельков (биткойн, эфириум, лайткоин и другие).
- Проверка баланса кошельков через общедоступные API.
- Управление комиссионными, которые необходимы для загрузки дампа магазина.
```bash
# 1. Клонировать
git clone <repo-url> && cd telegram-shop
---
# 2. Создать .env из шаблона
cp .env.example .env
nano .env # заполнить BOT_TOKEN, ADMIN_IDS, ENCRYPTION_KEY
### Требования к системе:
1. **Интерфейс пользователя**:
- Интуитивно понятный и удобный интерфейс для покупок.
- Легкость в управлении профилем и кошельками.
- Информация о товарах и статусах покупок должна быть легко доступна.
# 3. Запустить (образы тянутся из Gitea Container Registry, сборка не нужна)
docker compose up -d
2. **Интерфейс администратора**:
- Возможность редактировать товары, категории и управлять локациями.
- Инструменты для контроля баланса и управления пользователями.
- Функционал для создания и загрузки дампов данных.
# 4. Проверить статус
docker compose ps
curl http://localhost:3001/health # бот (health-сервер)
curl -o /dev/null -w "%{http_code}\n" http://localhost:3000/login # новая админка
```
3. **Безопасность**:
- Защищенные транзакции.
- Надежная система для хранения данных пользователей и кошельков.
- Механизмы для предотвращения мошенничества и атак.
> Образы бота и админки собираются в CI (Gitea Actions, buildx multi-arch) и публикуются в Gitea Container Registry. На сервере ничего не компилируется — только `docker compose pull`. Для пиннинга версии: `IMAGE_TAG=1.2.9 docker compose up -d`. Локальная сборка (dev): `docker compose up -d --build`.
4. **Производительность**:
- Система должна быть способна обрабатывать большое количество пользователей и транзакций одновременно.
- Пагинация данных, чтобы обеспечить быструю загрузку и обработку.
## Настройка .env
---
Скопируйте `.env.example` в `.env` и заполните:
### Риски и возможные проблемы:
1. **Зависимость от сторонних сервисов**:
- Интеграция с криптокошельками и сторонними сервисами для проверки баланса может быть подвержена сбоям, если эти сервисы не работают корректно.
| Переменная | Обязательно | Описание |
|---|---|---|
| `BOT_TOKEN` | ✅ | Токен Telegram бота (@BotFather) |
| `ADMIN_IDS` | ✅ | ID администраторов через запятую |
| `ENCRYPTION_KEY` | ✅ | Ключ шифрования (32 байта hex) |
| `ADMIN_SECRET` | ✅ | Секрет админки (вход в Next.js админку) |
| `SUPER_ADMIN_SECRET` | — | Секрет супер-админа (роль super_admin в админке) |
| `ADMIN_URL` | — | Полный URL админ-панели (для фото товаров) |
| `SUPER_ADMIN_IDS` | — | ID супер-админов |
| `SUPPORT_LINK` | — | Ссылка на поддержку |
| `DEFAULT_LANGUAGE` | — | Язык по умолчанию (`en`, `es`, `de`; по умолчанию `en`) |
| `HEALTH_PORT` | — | Порт health-сервера бота (по умолчанию 3001) |
| `SSH_HOST_IP` | — | Куда Tor перенаправляет SSH (по умолчанию host.docker.internal) |
| `SHOP_CONTAINER` | — | Имя контейнера админки (onion target; по умолчанию tg_shop_admin) |
| `CHATBOT_API_ENDPOINT` | — | OpenAI-совместимый endpoint чатбота (fallback) |
| `CHATBOT_API_KEY` | — | API-ключ чатбота (fallback) |
| `WG_ENABLED` | — | `true` / `false` (по умолчанию `false`) |
| `WG_PRIVATE_KEY` | — | Приватный ключ WireGuard |
| `WG_PUBLIC_KEY` | — | Публичный ключ WireGuard |
| `WG_PRESHARED_KEY` | — | Pre-shared ключ WireGuard |
| `WG_ENDPOINT` | — | Адрес сервера WireGuard |
| `WG_ADDRESS` | — | Адрес интерфейса WireGuard |
| `WG_DNS` | — | DNS для WireGuard |
| `SHOP_ACTIVATED` | — | Флаг активации магазина. false = магазин заблокирован до активации супер-админом в админке (Настройки → Shop Activation). |
2. **Поддержка разных криптовалют**:
- Необходимо следить за изменениями в протоколах криптовалют и своевременно обновлять систему.
Генерация ключа шифрования:
```bash
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
```
3. **Безопасность и защита данных**:
- Важно следить за актуальностью средств защиты данных и предотвратить утечку информации о пользователях и их балансе.
## Tor Proxy
---
Проект включает Tor-прокси для доступа к SSH и админ-панели через onion-адреса.
### Заключение:
**Универсальный Телеграмм Магазин** предоставляет эффективное решение для организации торговых процессов в Telegram, с возможностью работы с криптовалютами и традиционными средствами. Проект ориентирован на пользователей, которые ценят удобство, безопасность и скорость совершения покупок. Для администраторов — это мощный инструмент для управления товаром, пользователями и финансовыми потоками магазина.
### Архитектура
```
Internet → Tor Network → tor-proxy контейнер
├── Onion #1 :22 → хост SSH
└── Onion #2 :80 → tg_shop_admin:3000
(новая Next.js админка, через Docker сеть tor_proxy_net)
```
Новая админ-панель (`admin-next/`, Next.js 16 + Prisma + shadcn/ui):
- Работает на порту 3000 (контейнер `tg_shop_admin`)
- Использует **ту же SQLite БД**, что и бот (`db/shop.db`) — любые изменения мгновенно видны боту и наоборот
- Вход по токену `ADMIN_SECRET` / `SUPER_ADMIN_SECRET` (из `.env`)
- ИИ-чатбот: настройки в БД (`site_settings` ключи `chatbot_*`), бот обращается к `/api/chat` контейнера админки
### Файлы Tor-прокси
| Файл | Назначение |
|---|---|
| `tor-proxy/Dockerfile` | Alpine + Tor образ |
| `tor-proxy/entrypoint.sh` | Генерация torrc из env vars, валидация, запись onion-адресов |
| `tor-proxy/get-onions.sh` | Скрипт чтения onion-адресов и обновления .env |
| `tor-proxy/hosts/` | Директория для onion-hosts.txt (bind mount) |
### После запуска
Onion-адреса автоматически сохраняются в `tor-proxy/hosts/onion-hosts.txt`. Обновить `.env`:
```bash
./tor-proxy/get-onions.sh
```
Вывод:
```
============================================================
Onion services
============================================================
SSH : xxxxx.onion (port 22 -> host SSH)
Admin : yyyyy.onion (port 80 -> tg_shop_admin:3000)
============================================================
Usage:
SSH : torify ssh user@xxxxx.onion
Admin : open http://yyyyy.onion in Tor Browser
```
### Переменные Tor
| Переменная | По умолчанию | Описание |
|---|---|---|
| `SSH_HOST_IP` | `host.docker.internal` | Куда Tor перенаправляет SSH |
| `SHOP_CONTAINER` | `tg_shop_admin` | Контейнер админки (onion target) |
| `ADMIN_PORT` | `3000` | Порт админки |
## Поддерживаемые устройства
| Устройство | Архитектура | RAM | Статус |
|---|---|---|---|
| PC / Сервер | x86_64 | ≥ 512 МБ | ✅ |
| Orange Pi Zero 2 | ARM64 (H616) | 512 МБ | ✅ |
| Raspberry Pi 4 | ARM64 | ≥ 1 ГБ | ✅ |
| Raspberry Pi 3 | ARM64 | 1 ГБ | ✅ |
| Raspberry Pi 2 | ARMv7 | 1 ГБ | ✅ |
Docker автоматически собирает нативные модули (`better-sqlite3`, `tiny-secp256k1`) под архитектуру хоста.
## Архитектура Docker
```
┌──────────────────────────────────────────────────────────┐
│ docker-compose │
│ │
│ ┌────────────────────────┐ ┌─────────────────────────┐ │
│ │ telegram_shop_prod │ │ tor-proxy │ │
│ │ (node:22-alpine) │ │ (alpine:3.18 + tor) │ │
│ │ │ │ │ │
│ │ Port 3001 ──────────────┼── Бот (health-сервер) │ │
│ │ Bot + Health Server │ HiddenService :80 → админка 3000│
│ │ │ HiddenService :22 → SSH │
│ │ │ │ │ │
│ │ Net: default │ │ Net: default + proxy_net │ │
│ │ + tor_proxy_net │ │ │ │
│ └────────────────────────┘ └─────────────────────────┘ │
│ │ │ │
│ Volumes: Volumes: │
│ db/, uploads/, .env tor_data, hosts/ │
└──────────────────────────────────────────────────────────┘
```
### Сети Docker
| Сеть | Назначение |
|---|---|
| `default` | Внутренняя связь между контейнерами |
| `tor_proxy_net` | Связь tor-proxy ↔ telegram_shop_prod |
## Команды управления
```bash
# Запуск
docker compose up -d
# Пересборка (dev-сборка локально) или обновление до новой версии из registry
docker compose up -d --build # dev: собрать локально
IMAGE_TAG=1.2.9 docker compose up -d # prod: взять конкретную версию из registry
# Логи
docker compose logs -f
# Логи конкретного сервиса
docker compose logs -f tor-proxy
docker compose logs -f telegram_shop_prod
# Стоп
docker compose down
# Рестарт
docker compose restart
# Статус
docker compose ps
# Health-check
curl http://localhost:3001/health
# Onion-адреса
docker exec tor-proxy cat /var/lib/tor/ssh/hostname
docker exec tor-proxy cat /var/lib/tor/admin/hostname
# Обновить .env с onion-адресами
./tor-proxy/get-onions.sh
```
## WireGuard
WireGuard по умолчанию отключен (`WG_ENABLED=false`). Для включения:
1. Установите `WG_ENABLED=true` в `.env`
2. Заполните ключи WireGuard в `.env`
3. Перезапустите: `docker compose restart`
Контейнер требует `NET_ADMIN` и `sysctl net.ipv4.conf.all.src_valid_mark=1` для WireGuard. Эти привилегии заданы в `docker-compose.yml`.
## Мультиязычность (i18n)
Бот поддерживает 3 языка: **🇬🇧 English**, **🇪🇸 Español**, **🇩🇪 Deutsch**.
### Как это работает
- **`/start`** — всегда показывает выбор языка с флагами
- **`/language`** — команда для смены языка в любой момент
- **Профиль** — кнопка «🌐 Change Language» рядом с «Set Location»
- Выбранный язык сохраняется в БД (`users.language`) и используется во всех сообщениях
- Интерполяция: `t('key', { param: value })``{{param}}` в строках
- Fallback: запрошенный язык → English → ключ
### Структура i18n
```
src/i18n/
├── index.js # tForUser(), tForLang(), LANGUAGE_NAMES, AVAILABLE_LANGUAGES
└── locales/
├── en.json # 201 ключ, английский
├── es.json # 201 ключ, испанский
└── de.json # 201 ключ, немецкий
```
### Админ-панель локализации
Вкладка «Локализация» в админ-панели (`/locales`) позволяет просматривать и редактировать все ключи перевода в таблице с сохранением в JSON-файлы.
### Добавление нового языка
1. Создать `src/i18n/locales/<code>.json` по шаблону `en.json`
2. Добавить код в `AVAILABLE_LANGUAGES` и `LANGUAGE_NAMES` в `src/i18n/index.js`
3. Язык автоматически появится в выборе при `/start` и `/language`
## Безопасность
- `.env` монтируется только для чтения (`:ro`)
- Порт 3001 (бот, health-сервер) и 3000 (админка) доступны из LAN и через Tor onion
- Onion-адреса сохраняются в volume (персистентность при перезапуске)
- Tor hidden services с валидацией env vars
- Новая админка (`admin-next/`): вход по токену, `ADMIN_SECRET`/`SUPER_ADMIN_SECRET` из `.env`
- Секреты админки (`admin-next/.env`) исключены из git (`.gitignore`)
- Нативные модули компилируются в builder-стейдже
- `devDependencies` не попадают в production-образ
- Тестовые файлы исключены из Docker-образа (`.dockerignore`)
- `node_modules` хоста не попадают в образ (`.dockerignore`)
## Устойчивость к ошибкам
- Бот не крашит контейнер при невалидном `BOT_TOKEN`: 5 попыток с задержкой 5с, затем бот отключается, админка продолжает работать
- Комиссионные кошельки не обязательны для старта: при отсутствии логируется предупреждение
- При потере связи с Telegram API: polling ошибки логируются, процесс продолжает работать
## Структура проекта
```
├── src/ # Telegram-бот (Node.js)
│ ├── config/ # Конфигурация (БД, крипто)
│ ├── context/ # Контекст и состояния бота
│ ├── handlers/ # Обработчики команд
│ │ ├── adminHandlers/ # Обработчики админа (Telegram)
│ │ └── userHandlers/ # Обработчики пользователя
│ ├── i18n/ # Интернационализация
│ │ ├── index.js # tForUser(), tForLang(), LANGUAGE_NAMES
│ │ └── locales/ # en.json, es.json, de.json
│ ├── middleware/ # Промежуточные обработчики
│ ├── migrations/ # Миграции БД (001014)
│ ├── models/ # Модели данных
│ ├── router/ # Роутинг callback/text бота
│ ├── services/ # Бизнес-логика (вкл. chatbotService, leadService)
│ ├── utils/ # Утилиты (логирование, валидация, ошибки)
│ ├── __tests__/ # Юнит-тесты (vitest)
│ ├── healthServer.js # Минимальный HTTP /health (Docker healthcheck)
│ └── index.js # Точка входа
├── admin-next/ # Админ-панель (Next.js 16 + Prisma + shadcn/ui)
│ ├── prisma/schema.prisma # Схема БД (та же SQLite, что у бота)
│ ├── src/app/api/ # 45 API-роутов (см. docs/API.md)
│ ├── src/components/ # UI-компоненты (dashboard, wallets, leads...)
│ └── Dockerfile # Multi-stage Next.js standalone
├── docs/ # Документация
│ ├── API.md # Справочник REST API админки
│ └── DATABASE.md # Структура БД (схема, связи, примечания)
├── tor-proxy/ # Tor прокси для SSH и админки
│ ├── Dockerfile # Alpine + Tor образ
│ ├── entrypoint.sh # Генерация torrc, валидация env vars
│ ├── get-onions.sh # Скрипт обновления .env с onion-адресами
│ └── hosts/ # Директория для onion-hosts.txt
├── wg/ # WireGuard конфигурация
│ └── start.sh # Скрипт запуска контейнера
├── tests/ # Web-тестирование (visual regression, E2E)
│ ├── scripts/ # Скрипты тестов (Playwright, pixelmatch)
│ └── visual/ # baseline/current/diff скриншоты
├── docker/ # Дополнительные compose-конфиги (web-testing)
├── db/ # SQLite база данных (volume)
├── uploads/ # Загруженные фото (volume)
├── Dockerfile # Multi-stage сборка магазина
├── docker-compose.yml # Конфигурация трёх контейнеров (бот, админка, tor)
├── install.sh # Установщик (POSIX sh)
├── .dockerignore # Исключения из образа
├── .env.example # Шаблон переменных
└── package.json
```
## Документация
| Документ | Содержание |
|---|---|
| [`docs/API.md`](docs/API.md) | Справочник REST API админ-панели: все эндпоинты, методы, query-параметры, коды ошибок |
| [`docs/DATABASE.md`](docs/DATABASE.md) | Структура БД: таблицы, колонки, связи, примечания |
| [`VERSION.md`](VERSION.md) | История версий и changelog |
## Разработка
```bash
# Установка зависимостей
npm install
# Запуск в режиме разработки
npm run dev
# Тесты
npm test
```
## Лицензия
MIT

93
VERSION.md Normal file
View File

@@ -0,0 +1,93 @@
# Telegram Shop — Version History
## How to update version
1. Edit this file (`VERSION.md`)
2. Add new entry under `## Changelog`
3. Commit all changes together
## Current Version
**v1.2.9** — 2026-08-11
## Changelog
### v1.2.9 — 2026-08-11
- **ci**: релиз переведён на Gitea Container Registry — образы бота и админки собираются в CI (Gitea Actions, buildx multi-arch linux/amd64+arm64 на x86_64 хосте) и пушатся как `git.softuniq.eu/telegram-market/telegram-shop` и `.../telegram-shop-admin`
- **deploy**: `docker-compose.yml` больше не собирает образы на сервере — бот и админка тянутся из registry (`IMAGE_TAG` для пиннинга версии); tor-proxy остаётся локальной сборкой (минимальный alpine)
- **install**: `install.sh` не компилирует нативный код на слабом железе — только `docker compose pull` + `up -d` (Orange Pi / RPi)
- **ci**: добавлен новый buildx-runner `gitea-host-buildx` (label `buildx`) — сборка multi-arch вместо нативной ARM64 сборки на Orange Pi
- **ci**: `REGISTRY_TOKEN` обновлён на package-токен (`write:package`) — теперь push в registry проходит без ошибок авторизации
### v1.2.8 — 2026-08-09
- **chore**: repo cleanup — removed stale `docs/admin-frontend-spec.md` (old Express/EJS admin), unused `templates/` (SmartAdmin copy), dead `scripts/sync-agents.cjs`, committed `admin-next/.zscripts/dev.pid`
- **docs**: added `docs/API.md` (admin REST API reference) and `docs/DATABASE.md` (DB schema); README structure updated
- **env**: `.env.example` refreshed — removed stale `ADMIN_PORT`/`SHOP_CONTAINER` defaults, added `ADMIN_URL`, `HEALTH_PORT`, `DEFAULT_LANGUAGE`, `CHATBOT_API_ENDPOINT`, `CHATBOT_API_KEY`
- **ci**: added `npm run lint` script (syntax check of `src/`) so Gitea workflows no longer fail
- **chore**: rebranded web-testing suite from APAW to telegram-shop (package name, container names)
### v1.2.7 — 2026-08-08
- **refactor**: Remove old Express/EJS admin panel (replaced by Next.js admin in admin-next/); bot now has standalone health server; SUPER_ADMIN_SECRET for admin auth
### v1.2.6 — 2026-08-05
- **fix**: dead admin callback buttons — `prod_district_` (Back to Categories after adding category, pipe-delimited format) and `admin_users` (Back to User List) now registered
- **fix**: no-op placeholder buttons (`current_page`, `current_quantity`, `no_action`) no longer log "No handler" warns
- **fix**: `getLocationsByCountryAndCityAdmin` added (admin sees disabled locations in nav)
- **audit**: all 78 generated callback_data cross-checked against registered routes — no overlaps, none missing
### v1.2.5 — 2026-08-05
- **fix**: crypto deposit error — handleDepositInstruction/handleDepositSelectWallet use editOrSendCallback (photo-safe fallback, fixes "no text in the message to edit" 400)
- **fix**: chat clutter — lastInlineMessageId tracked in showProducts/showProfile/showBalance/showPurchases and deleted in resetUserContext
- **verify**: answerCallbackQuery before dispatch in all callback paths (v1.2.4)
### v1.2.4 — 2026-08-05
- **fix**: missing `shop_district_` / `shop_subcategory_` callback handlers — Back button in empty categories now works (handleDistrictBack)
- **fix**: state.location pipe-delimited (encodeURIComponent) — multi-word names (Saint Petersburg) no longer break navigation
- **fix**: answerCallbackQuery moved to start of callback handling — no stuck "clock" spinner on buttons
- **fix**: empty city fallback in "Select district in :" (district_unknown)
- **fix**: guard against stale underscore-format state.location in handleDistrictBack
### v1.2.3 — 2026-08-04
- **fix**: empty category menus — districts with no in-stock products show "No products available in this district" (getCategoriesWithProductsByLocationId filters by real stock/mono)
- **fix**: duplicate "Select your country" messages on rapid Products tap — 1200ms main-menu debounce in routes.js
- **fix**: DB typos + desync — migration 012 (Centr→Center, Chiken→Chicken, Brusel→Brussels, Sever→North) and re-enables locations that actually have in-stock products
- **fix**: answerCallbackQuery on no_categories branch (no stuck loading spinner)
### v1.2.2 — 2026-08-04
- **fix**: BUG-01 — disabled locations/categories/subcategories filtered from bot menus (getActiveLocationById, is_active checks)
- **fix**: BUG-02 — graceful handling of disabled entity during purchase flow (location_disabled notice + main-menu redirect, no crash)
- **fix**: BUG-03 — per-user callback lock (1500ms debounce) prevents duplicate messages on double-tap
- **fix**: BUG-04 — resetUserContext clears stale inline keyboards/state on main-menu navigation and /start
- **fix**: handlePay uses validated numeric quantity for price/stock/purchase writes (was raw string)
- **fix**: Admin delete feedback — locations/categories pages now render error/success alerts; delete errors include blocking counts + hints; 🔒 lock hint on rows with links
### v1.2.1 — 2026-07-18
- **refactor**: Removed deposit amount-selection step (redundant); deposit_wallet_ now goes directly to Mercuryo instructions
- **feat**: Updated Mercuryo button text to include VISA/Mastercard branding in all locales
- **feat**: Added deposit_important5 note about Mercuryo authorization limits and top-up reserve
- **fix**: Enforced description + photo required in admin product create/update routes (products.js, catalogProducts.js)
- **fix**: Added defensive guards in bot purchase display — description fallback and no-photo placeholder (userProductHandler.js)
- **feat**: Added i18n keys `products.no_description` and `products.no_photo` in en/es/de
- **fix**: Marked description and photo fields as required in admin forms (product-edit.ejs, products.ejs, catalog modal)
- **feat**: Added edit + enable/disable (toggle is_active) UI for locations, categories, and subcategories in admin views (locations.ejs, categories.ejs, catalog.js buildTreeHtml)
- **feat**: Added Categories nav item in admin sidebar (generated-navigation.ejs)
### v1.2.0 — 2026-07-08
- **fix**: Disabled CSRF checks in admin panel for Tor / onion zone compatibility
- **fix**: Fixed "Invalid wallet type" error in Telegram bot purchase flow (`main`/`bonus` types added to validator)
- **feat**: Added version history modal in admin sidebar
### v1.1.0 — 2026-07-02
- **feat**: Mercuryo gateway integration, crypto QR deposit, mono products, wallet auto-refresh
- **fix**: CSRF cookie `sameSite=false` for Tor, auth cookie fix, async handlers
- **feat**: Draggable dashboard panels + business KPI redesign
- **fix**: SmartAdmin template redesign + security hardening
### v1.0.0 — 2026-06-24
- **feat**: Initial release — Telegram shop bot with admin panel
- **feat**: Crypto wallets (BTC, LTC, ETH, USDT, USDC)
- **feat**: Product catalog with locations, categories, subcategories
- **feat**: Purchase system with hidden content delivery
- **feat**: Admin panel with dashboard, wallets, users, purchases, audit log
- **feat**: Tor proxy support (.onion access)
- **feat**: i18n localization (en/es/de)

27
admin-next/.dockerignore Executable file
View File

@@ -0,0 +1,27 @@
node_modules
.next
.git
git
*.md
db/*.db
db/*.db-journal
tool-results/
agent-ctx/
.zscripts/
screenshot-*.png
keepalive.js
seed-standalone.ts
standalone-server.js
gitea-*.json
*.log
dev.log
server.log
.env
.dev
tests/
examples/
mini-services/
upload/
download/
Claude.md
.claude

175
admin-next/.zscripts/build.sh Executable file
View File

@@ -0,0 +1,175 @@
#!/bin/bash
# 将 stderr 重定向到 stdout避免 execute_command 因为 stderr 输出而报错
exec 2>&1
set -e
# 获取脚本所在目录(.zscripts 目录,即 workspace-agent/.zscripts
# 使用 $0 获取脚本路径(兼容 sh 和 bash
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# Next.js 项目路径
NEXTJS_PROJECT_DIR="/home/z/my-project"
# 检查 Next.js 项目目录是否存在
if [ ! -d "$NEXTJS_PROJECT_DIR" ]; then
echo "❌ 错误: Next.js 项目目录不存在: $NEXTJS_PROJECT_DIR"
exit 1
fi
echo "🚀 开始构建 Next.js 应用和 mini-services..."
echo "📁 Next.js 项目路径: $NEXTJS_PROJECT_DIR"
# 切换到 Next.js 项目目录
cd "$NEXTJS_PROJECT_DIR" || exit 1
# 设置环境变量
export NEXT_TELEMETRY_DISABLED=1
BUILD_DIR="/tmp/build_fullstack_$BUILD_ID"
echo "📁 清理并创建构建目录: $BUILD_DIR"
mkdir -p "$BUILD_DIR"
# 安装依赖
echo "📦 安装依赖..."
bun install
# 构建 Next.js 应用
echo "🔨 构建 Next.js 应用..."
bun run build
# 校验 standalone 服务端入口是否生成(部署成功率守卫)。
# Next 仅在 next.config 含 output:"standalone" 时产出 .next/standalone/server.js。
# 若用户/AI 编辑项目时改写或删除了该配置bun run build 仍会成功static 照常
# 产出、退出码 0但 standalone 缺失——打出的包里没有 server.js部署到 FC 后
# start.sh 找不到 next-service-dist/server.js → 不启动 Next → Caddy:81 反代空的
# 3000 → FC 健康检查 120s 超时失败(线上 warmup_412 / FunctionNotStarted 的主因)。
# 这里做一次自愈:仅在确实缺失时,给 next.config 补回 output:"standalone" 并重建。
# 正常项目(已生成 server.js整段跳过不读写任何用户文件。
if [ ! -f ".next/standalone/server.js" ]; then
echo "⚠️ 构建未产出 .next/standalone/server.js开始自愈 next.config 的 output 配置..."
NEXT_CONFIG_FILE="$(ls next.config.ts next.config.js next.config.mjs next.config.cjs 2>/dev/null | head -1)"
if [ -z "$NEXT_CONFIG_FILE" ]; then
echo "❌ 构建失败:未找到 next.config.*,无法生成 standalone 部署产物。"
exit 1
fi
if grep -Eq "output\s*:\s*['\"]standalone['\"]" "$NEXT_CONFIG_FILE"; then
# 已声明 standalone 却仍没产出 server.js说明不是配置缺失可能 build 真
# 出错、自定义 distDir 等)。不臆改用户配置,直接失败并暴露原因。
echo "❌ 构建失败:$NEXT_CONFIG_FILE 已含 output:\"standalone\",但仍未生成 .next/standalone/server.js。"
echo " 请检查上方构建日志中的报错或项目自定义的构建配置。"
exit 1
fi
if grep -Eq "output\s*:\s*['\"]" "$NEXT_CONFIG_FILE"; then
# 已显式声明了其它 output如 "export" 静态导出 / "standalone" 之外的值)。
# "export" 与本部署模型standalone + 自定义 server互斥——不能注入第二个
# output 覆盖用户意图JS 对象重复 key 后者生效,注入也无效)。明确失败。
echo "❌ 构建失败:$NEXT_CONFIG_FILE 已声明非 standalone 的 output如 \"export\" 静态导出),与当前部署模型不兼容。"
echo " 当前部署需要 output:\"standalone\"。请改为 standalone或确认该项目是否应走静态托管而非部署沙箱。"
exit 1
fi
echo "🔧 检测到 $NEXT_CONFIG_FILE 缺少 output:\"standalone\",自动注入后重新构建..."
cp "$NEXT_CONFIG_FILE" "${NEXT_CONFIG_FILE}.zbak"
# 在第一个配置对象字面量起始的 { 之后插入 output:"standalone"
# 覆盖脚手架常见写法const nextConfig...= { / export default { / module.exports = {
perl -0pi -e 's/((?:const\s+\w+[^=]*=|export\s+default|module\.exports\s*=)\s*\{)/$1\n output: "standalone",/' "$NEXT_CONFIG_FILE"
if ! grep -Eq "output\s*:\s*['\"]standalone['\"]" "$NEXT_CONFIG_FILE"; then
echo "❌ 未能匹配到可注入的配置对象next.config 写法非常规,需人工添加 output:\"standalone\"。"
echo " 当前 $NEXT_CONFIG_FILE 内容:"
cat "$NEXT_CONFIG_FILE"
mv "${NEXT_CONFIG_FILE}.zbak" "$NEXT_CONFIG_FILE"
exit 1
fi
echo "🔨 已注入 output:\"standalone\",重新构建..."
bun run build
if [ ! -f ".next/standalone/server.js" ]; then
echo "❌ 注入 output:\"standalone\" 并重建后,仍未生成 .next/standalone/server.js。"
exit 1
fi
echo "✅ 自愈成功standalone 服务端入口已生成。"
fi
# 构建 mini-services
# 检查 Next.js 项目目录下是否有 mini-services 目录
if [ -d "$NEXTJS_PROJECT_DIR/mini-services" ]; then
echo "🔨 构建 mini-services..."
# 使用 workspace-agent 目录下的 mini-services 脚本
sh "$SCRIPT_DIR/mini-services-install.sh"
sh "$SCRIPT_DIR/mini-services-build.sh"
# 复制 mini-services-start.sh 到 mini-services-dist 目录
echo " - 复制 mini-services-start.sh 到 $BUILD_DIR"
cp "$SCRIPT_DIR/mini-services-start.sh" "$BUILD_DIR/mini-services-start.sh"
chmod +x "$BUILD_DIR/mini-services-start.sh"
else
echo " mini-services 目录不存在,跳过"
fi
# 将所有构建产物复制到临时构建目录
echo "📦 收集构建产物到 $BUILD_DIR..."
# 复制 Next.js standalone 构建输出
if [ -d ".next/standalone" ]; then
echo " - 复制 .next/standalone"
cp -r .next/standalone "$BUILD_DIR/next-service-dist/"
fi
# 复制 Next.js 静态文件
if [ -d ".next/static" ]; then
echo " - 复制 .next/static"
mkdir -p "$BUILD_DIR/next-service-dist/.next"
cp -r .next/static "$BUILD_DIR/next-service-dist/.next/"
fi
# 复制 public 目录
if [ -d "public" ]; then
echo " - 复制 public"
cp -r public "$BUILD_DIR/next-service-dist/"
fi
# Python 不继承 workspace-agent 的 /home/z/.venv。若项目包含 Python 源码或
# 依赖清单,在构建期将生产依赖固化到产物,并保持 Python 源码的项目相对路径。
PROJECT_DIR="$NEXTJS_PROJECT_DIR" BUILD_DIR="$BUILD_DIR" \
bash "$SCRIPT_DIR/python-runtime-build.sh"
# 有 Preview 数据库时复制现有数据;没有时直接在部署产物中初始化空库。
# 模板源码不携带 db/custom.db不能依赖 dev.sh 必须在 Deploy 前成功运行过。
PROJECT_DIR="$NEXTJS_PROJECT_DIR" BUILD_DIR="$BUILD_DIR" \
bash "$SCRIPT_DIR/database-runtime-build.sh"
# 复制 Caddyfile如果存在
if [ -f "Caddyfile" ]; then
echo " - 复制 Caddyfile"
cp Caddyfile "$BUILD_DIR/"
else
echo " Caddyfile 不存在,跳过"
fi
# 复制 start.sh 脚本
echo " - 复制 start.sh 到 $BUILD_DIR"
cp "$SCRIPT_DIR/start.sh" "$BUILD_DIR/start.sh"
chmod +x "$BUILD_DIR/start.sh"
# 打包到 $BUILD_DIR.tar.gz
PACKAGE_FILE="${BUILD_DIR}.tar.gz"
echo ""
echo "📦 打包构建产物到 $PACKAGE_FILE..."
cd "$BUILD_DIR" || exit 1
tar -czf "$PACKAGE_FILE" .
cd - > /dev/null || exit 1
# # 清理临时目录
# rm -rf "$BUILD_DIR"
echo ""
echo "✅ 构建完成!所有产物已打包到 $PACKAGE_FILE"
echo "📊 打包文件大小:"
ls -lh "$PACKAGE_FILE"

View File

@@ -0,0 +1,33 @@
#!/bin/bash
set -euo pipefail
PROJECT_DIR="${PROJECT_DIR:-/home/z/my-project}"
BUILD_DIR="${BUILD_DIR:?BUILD_DIR is required}"
SOURCE_DB_DIR="$PROJECT_DIR/db"
SOURCE_DB_PATH="$SOURCE_DB_DIR/custom.db"
TARGET_DB_DIR="$BUILD_DIR/db"
TARGET_DB_PATH="$TARGET_DB_DIR/custom.db"
mkdir -p "$TARGET_DB_DIR"
if [ -f "$SOURCE_DB_PATH" ]; then
echo "🗄️ 复制 Preview 数据库到构建产物..."
cp -a "$SOURCE_DB_DIR/." "$TARGET_DB_DIR/"
else
echo " 未找到 Preview 数据库 db/custom.db将初始化空的生产数据库"
fi
echo "🗄️ 同步构建产物中的数据库结构..."
(
cd "$PROJECT_DIR"
DATABASE_URL="file:$TARGET_DB_PATH" bun run db:push
)
if [ ! -f "$TARGET_DB_PATH" ]; then
echo "❌ 数据库初始化命令执行成功,但未生成 $TARGET_DB_PATH"
exit 1
fi
echo "✅ 构建产物数据库已准备完成"
ls -lah "$TARGET_DB_DIR"

154
admin-next/.zscripts/dev.sh Executable file
View File

@@ -0,0 +1,154 @@
#!/bin/bash
set -euo pipefail
# 获取脚本所在目录(.zscripts
# 使用 $0 获取脚本路径(与 build.sh 保持一致)
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
log_step_start() {
local step_name="$1"
echo "=========================================="
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Starting: $step_name"
echo "=========================================="
export STEP_START_TIME
STEP_START_TIME=$(date +%s)
}
log_step_end() {
local step_name="${1:-Unknown step}"
local end_time
end_time=$(date +%s)
local duration=$((end_time - STEP_START_TIME))
echo "=========================================="
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Completed: $step_name"
echo "[LOG] Step: $step_name | Duration: ${duration}s"
echo "=========================================="
echo ""
}
start_mini_services() {
local mini_services_dir="$PROJECT_DIR/mini-services"
local started_count=0
log_step_start "Starting mini-services"
if [ ! -d "$mini_services_dir" ]; then
echo "Mini-services directory not found, skipping..."
log_step_end "Starting mini-services"
return 0
fi
echo "Found mini-services directory, scanning for sub-services..."
for service_dir in "$mini_services_dir"/*; do
if [ ! -d "$service_dir" ]; then
continue
fi
local service_name
service_name=$(basename "$service_dir")
echo "Checking service: $service_name"
if [ ! -f "$service_dir/package.json" ]; then
echo "[$service_name] No package.json found, skipping..."
continue
fi
if ! grep -q '"dev"' "$service_dir/package.json"; then
echo "[$service_name] No dev script found, skipping..."
continue
fi
echo "Starting $service_name in background..."
(
cd "$service_dir"
echo "[$service_name] Installing dependencies..."
bun install
echo "[$service_name] Running bun run dev..."
exec bun run dev
) >"$PROJECT_DIR/.zscripts/mini-service-${service_name}.log" 2>&1 &
local service_pid=$!
echo "[$service_name] Started in background (PID: $service_pid)"
echo "[$service_name] Log: $PROJECT_DIR/.zscripts/mini-service-${service_name}.log"
disown "$service_pid" 2>/dev/null || true
started_count=$((started_count + 1))
done
echo "Mini-services startup completed. Started $started_count service(s)."
log_step_end "Starting mini-services"
}
wait_for_service() {
local host="$1"
local port="$2"
local service_name="$3"
local max_attempts="${4:-60}"
local attempt=1
echo "Waiting for $service_name to be ready on $host:$port..."
while [ "$attempt" -le "$max_attempts" ]; do
if curl -s --connect-timeout 2 --max-time 5 "http://$host:$port" >/dev/null 2>&1; then
echo "$service_name is ready!"
return 0
fi
echo "Attempt $attempt/$max_attempts: $service_name not ready yet, waiting..."
sleep 1
attempt=$((attempt + 1))
done
echo "ERROR: $service_name failed to start within $max_attempts seconds"
return 1
}
cleanup() {
if [ -n "${DEV_PID:-}" ] && kill -0 "$DEV_PID" >/dev/null 2>&1; then
echo "Stopping Next.js dev server (PID: $DEV_PID)..."
kill "$DEV_PID" >/dev/null 2>&1 || true
fi
}
trap cleanup EXIT INT TERM
cd "$PROJECT_DIR"
if ! command -v bun >/dev/null 2>&1; then
echo "ERROR: bun is not installed or not in PATH"
exit 1
fi
log_step_start "bun install"
echo "[BUN] Installing dependencies..."
bun install
log_step_end "bun install"
log_step_start "bun run db:push"
echo "[BUN] Setting up database..."
bun run db:push
log_step_end "bun run db:push"
log_step_start "Starting Next.js dev server"
echo "[BUN] Starting development server..."
bun run dev &
DEV_PID=$!
log_step_end "Starting Next.js dev server"
log_step_start "Waiting for Next.js dev server"
wait_for_service "localhost" "3000" "Next.js dev server"
log_step_end "Waiting for Next.js dev server"
log_step_start "Health check"
echo "[BUN] Performing health check..."
curl -fsS localhost:3000 >/dev/null
echo "[BUN] Health check passed"
log_step_end "Health check"
start_mini_services
echo "Next.js dev server is running in background (PID: $DEV_PID)."
echo "Use 'kill $DEV_PID' to stop it."
disown "$DEV_PID" 2>/dev/null || true
unset DEV_PID

View File

@@ -0,0 +1,78 @@
#!/bin/bash
# 配置项
ROOT_DIR="/home/z/my-project/mini-services"
DIST_DIR="/tmp/build_fullstack_$BUILD_ID/mini-services-dist"
main() {
echo "🚀 开始批量构建..."
# 检查 rootdir 是否存在
if [ ! -d "$ROOT_DIR" ]; then
echo " 目录 $ROOT_DIR 不存在,跳过构建"
return
fi
# 创建输出目录(如果不存在)
mkdir -p "$DIST_DIR"
# 统计变量
success_count=0
fail_count=0
# 遍历 mini-services 目录下的所有文件夹
for dir in "$ROOT_DIR"/*; do
# 检查是否是目录且包含 package.json
if [ -d "$dir" ] && [ -f "$dir/package.json" ]; then
project_name=$(basename "$dir")
# 智能查找入口文件 (按优先级查找)
entry_path=""
for entry in "src/index.ts" "index.ts" "src/index.js" "index.js"; do
if [ -f "$dir/$entry" ]; then
entry_path="$dir/$entry"
break
fi
done
if [ -z "$entry_path" ]; then
echo "⚠️ 跳过 $project_name: 未找到入口文件 (index.ts/js)"
continue
fi
echo ""
echo "📦 正在构建: $project_name..."
# 使用 bun build CLI 构建
output_file="$DIST_DIR/mini-service-$project_name.js"
if bun build "$entry_path" \
--outfile "$output_file" \
--target bun \
--minify; then
echo "$project_name 构建成功 -> $output_file"
success_count=$((success_count + 1))
else
echo "$project_name 构建失败"
fail_count=$((fail_count + 1))
fi
fi
done
if [ -f ./.zscripts/mini-services-start.sh ]; then
cp ./.zscripts/mini-services-start.sh "$DIST_DIR/mini-services-start.sh"
chmod +x "$DIST_DIR/mini-services-start.sh"
fi
echo ""
echo "🎉 所有任务完成!"
if [ $success_count -gt 0 ] || [ $fail_count -gt 0 ]; then
echo "✅ 成功: $success_count"
if [ $fail_count -gt 0 ]; then
echo "❌ 失败: $fail_count"
fi
fi
}
main

View File

@@ -0,0 +1,65 @@
#!/bin/bash
# 配置项
ROOT_DIR="/home/z/my-project/mini-services"
main() {
echo "🚀 开始批量安装依赖..."
# 检查 rootdir 是否存在
if [ ! -d "$ROOT_DIR" ]; then
echo " 目录 $ROOT_DIR 不存在,跳过安装"
return
fi
# 统计变量
success_count=0
fail_count=0
failed_projects=""
# 遍历 mini-services 目录下的所有文件夹
for dir in "$ROOT_DIR"/*; do
# 检查是否是目录且包含 package.json
if [ -d "$dir" ] && [ -f "$dir/package.json" ]; then
project_name=$(basename "$dir")
echo ""
echo "📦 正在安装依赖: $project_name..."
# 进入项目目录并执行 bun install
if (cd "$dir" && bun install); then
echo "$project_name 依赖安装成功"
success_count=$((success_count + 1))
else
echo "$project_name 依赖安装失败"
fail_count=$((fail_count + 1))
if [ -z "$failed_projects" ]; then
failed_projects="$project_name"
else
failed_projects="$failed_projects $project_name"
fi
fi
fi
done
# 汇总结果
echo ""
echo "=================================================="
if [ $success_count -gt 0 ] || [ $fail_count -gt 0 ]; then
echo "🎉 安装完成!"
echo "✅ 成功: $success_count"
if [ $fail_count -gt 0 ]; then
echo "❌ 失败: $fail_count"
echo ""
echo "失败的项目:"
for project in $failed_projects; do
echo " - $project"
done
fi
else
echo " 未找到任何包含 package.json 的项目"
fi
echo "=================================================="
}
main

View File

@@ -0,0 +1,123 @@
#!/bin/sh
# 配置项
DIST_DIR="./mini-services-dist"
# 存储所有子进程的 PID
pids=""
# 清理函数:优雅关闭所有服务
cleanup() {
echo ""
echo "🛑 正在关闭所有服务..."
# 发送 SIGTERM 信号给所有子进程
for pid in $pids; do
if kill -0 "$pid" 2>/dev/null; then
service_name=$(ps -p "$pid" -o comm= 2>/dev/null || echo "unknown")
echo " 关闭进程 $pid ($service_name)..."
kill -TERM "$pid" 2>/dev/null
fi
done
# 等待所有进程退出(最多等待 5 秒)
sleep 1
for pid in $pids; do
if kill -0 "$pid" 2>/dev/null; then
# 如果还在运行,等待最多 4 秒
timeout=4
while [ $timeout -gt 0 ] && kill -0 "$pid" 2>/dev/null; do
sleep 1
timeout=$((timeout - 1))
done
# 如果仍然在运行,强制关闭
if kill -0 "$pid" 2>/dev/null; then
echo " 强制关闭进程 $pid..."
kill -KILL "$pid" 2>/dev/null
fi
fi
done
echo "✅ 所有服务已关闭"
}
main() {
echo "🚀 开始启动所有 mini services..."
# 检查 dist 目录是否存在
if [ ! -d "$DIST_DIR" ]; then
echo " 目录 $DIST_DIR 不存在"
return
fi
# 查找所有 mini-service-*.js 文件
service_files=""
for file in "$DIST_DIR"/mini-service-*.js; do
if [ -f "$file" ]; then
if [ -z "$service_files" ]; then
service_files="$file"
else
service_files="$service_files $file"
fi
fi
done
# 计算服务文件数量
service_count=0
for file in $service_files; do
service_count=$((service_count + 1))
done
if [ $service_count -eq 0 ]; then
echo " 未找到任何 mini service 文件"
return
fi
echo "📦 找到 $service_count 个服务,开始启动..."
echo ""
# 启动每个服务
for file in $service_files; do
service_name=$(basename "$file" .js | sed 's/mini-service-//')
echo "▶️ 启动服务: $service_name..."
# 使用 bun 运行服务(后台运行)
bun "$file" &
pid=$!
if [ -z "$pids" ]; then
pids="$pid"
else
pids="$pids $pid"
fi
# 等待一小段时间检查进程是否成功启动
sleep 0.5
if ! kill -0 "$pid" 2>/dev/null; then
echo "$service_name 启动失败"
# 从字符串中移除失败的 PID
pids=$(echo "$pids" | sed "s/\b$pid\b//" | sed 's/ */ /g' | sed 's/^ *//' | sed 's/ *$//')
else
echo "$service_name 已启动 (PID: $pid)"
fi
done
# 计算运行中的服务数量
running_count=0
for pid in $pids; do
if kill -0 "$pid" 2>/dev/null; then
running_count=$((running_count + 1))
fi
done
echo ""
echo "🎉 所有服务已启动!共 $running_count 个服务正在运行"
echo ""
echo "💡 按 Ctrl+C 停止所有服务"
echo ""
# 等待所有后台进程
wait
}
main

View File

@@ -0,0 +1,120 @@
#!/bin/bash
set -euo pipefail
PROJECT_DIR="${PROJECT_DIR:-/home/z/my-project}"
BUILD_DIR="${BUILD_DIR:?BUILD_DIR is required}"
PYTHON_VERSION="${PYTHON_VERSION:-3.12}"
NEXT_DIST_DIR="$BUILD_DIR/next-service-dist"
PYTHON_RUNTIME_DIR="$BUILD_DIR/python-runtime"
PYTHON_PACKAGES_DIR="$PYTHON_RUNTIME_DIR/site-packages"
has_python_sources() {
find "$PROJECT_DIR" \
\( -type d \( -name '.git' \
-o -name '.next' \
-o -name '.venv' \
-o -name 'node_modules' \
-o -name '__pycache__' \
-o -name 'mini-services' \
-o -name 'upload' \
-o -name 'download' \
\) -prune \) \
-o -type f \( -name '*.py' -o -name '*.pyi' \) -print -quit | grep -q .
}
if ! has_python_sources \
&& [ ! -f "$PROJECT_DIR/requirements.txt" ] \
&& [ ! -f "$PROJECT_DIR/pyproject.toml" ]; then
echo " 未检测到 Python 源码或依赖清单,跳过 Python runtime 构建"
exit 0
fi
if ! command -v uv >/dev/null 2>&1; then
echo "❌ 检测到 Python 项目,但构建环境中没有 uv"
exit 1
fi
echo "🐍 检测到 Python runtime目标版本: $PYTHON_VERSION"
mkdir -p "$NEXT_DIST_DIR" "$PYTHON_PACKAGES_DIR"
install_requirements() {
local requirements_file="$1"
local target_dir="${2:-$PYTHON_PACKAGES_DIR}"
if [ ! -s "$requirements_file" ]; then
echo " Python 依赖清单为空,跳过依赖安装"
return 0
fi
echo "📦 根据 $(basename "$requirements_file") 固化 Python 生产依赖..."
uv pip install \
--python "$PYTHON_VERSION" \
--target "$target_dir" \
--requirements "$requirements_file"
# --target 生成的 console scripts 会保留构建机 Python 的绝对 shebang。
# 改成 Runner 内可解析的 python并由 start scripts 将该 bin 目录加入 PATH。
if [ -d "$target_dir/bin" ]; then
for script in "$target_dir"/bin/*; do
[ -f "$script" ] || continue
perl -0pi -e 's/\A#![^\n]*python[^\n]*\n/#!\/usr\/bin\/env python\n/' "$script"
done
fi
}
install_pyproject() {
local project_dir="$1"
local target_dir="$2"
local output_name="$3"
local requirements_file="$PYTHON_RUNTIME_DIR/$output_name"
if [ -f "$project_dir/uv.lock" ]; then
uv export \
--project "$project_dir" \
--frozen \
--no-dev \
--no-emit-project \
--format requirements.txt \
--output-file "$requirements_file"
else
uv pip compile \
"$project_dir/pyproject.toml" \
--python-version "$PYTHON_VERSION" \
--output-file "$requirements_file"
fi
install_requirements "$requirements_file" "$target_dir"
}
if [ -f "$PROJECT_DIR/pyproject.toml" ] && [ -f "$PROJECT_DIR/uv.lock" ]; then
echo "🔒 使用 pyproject.toml + uv.lock 导出生产依赖..."
install_pyproject "$PROJECT_DIR" "$PYTHON_PACKAGES_DIR" "requirements.lock.txt"
elif [ -f "$PROJECT_DIR/requirements.txt" ]; then
cp "$PROJECT_DIR/requirements.txt" "$PYTHON_RUNTIME_DIR/requirements.txt"
install_requirements "$PYTHON_RUNTIME_DIR/requirements.txt"
elif [ -f "$PROJECT_DIR/pyproject.toml" ]; then
echo "📦 pyproject.toml 未配套 uv.lock解析生产依赖..."
install_pyproject "$PROJECT_DIR" "$PYTHON_PACKAGES_DIR" "requirements.txt"
else
echo "⚠️ 检测到 Python 源码,但没有 requirements.txt 或 pyproject.toml仅支持 Python 标准库"
fi
if has_python_sources; then
echo "📄 复制 Python 源码到部署项目,保持相对路径..."
(
cd "$PROJECT_DIR"
find . \
\( -type d \( -name '.git' \
-o -name '.next' \
-o -name '.venv' \
-o -name 'node_modules' \
-o -name '__pycache__' \
-o -name 'mini-services' \
-o -name 'upload' \
-o -name 'download' \
\) -prune \) \
-o -type f \( -name '*.py' -o -name '*.pyi' \) -print0 \
| tar --null -T - -cf -
) | tar -C "$NEXT_DIST_DIR" -xf -
fi
echo "✅ Python runtime 已固化到部署产物"

145
admin-next/.zscripts/start.sh Executable file
View File

@@ -0,0 +1,145 @@
#!/bin/sh
set -e
# 获取脚本所在目录
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
BUILD_DIR="$SCRIPT_DIR"
# 存储所有子进程的 PID
pids=""
# 清理函数:优雅关闭所有服务
cleanup() {
echo ""
echo "🛑 正在关闭所有服务..."
# 发送 SIGTERM 信号给所有子进程
for pid in $pids; do
if kill -0 "$pid" 2>/dev/null; then
service_name=$(ps -p "$pid" -o comm= 2>/dev/null || echo "unknown")
echo " 关闭进程 $pid ($service_name)..."
kill -TERM "$pid" 2>/dev/null
fi
done
# 等待所有进程退出(最多等待 5 秒)
sleep 1
for pid in $pids; do
if kill -0 "$pid" 2>/dev/null; then
# 如果还在运行,等待最多 4 秒
timeout=4
while [ $timeout -gt 0 ] && kill -0 "$pid" 2>/dev/null; do
sleep 1
timeout=$((timeout - 1))
done
# 如果仍然在运行,强制关闭
if kill -0 "$pid" 2>/dev/null; then
echo " 强制关闭进程 $pid..."
kill -KILL "$pid" 2>/dev/null
fi
fi
done
echo "✅ 所有服务已关闭"
exit 0
}
echo "🚀 开始启动所有服务..."
echo ""
# 切换到构建目录
cd "$BUILD_DIR" || exit 1
ls -lah
DEFAULT_PACKAGED_DB_PATH="/app/db/custom.db"
DEFAULT_PACKAGED_DATABASE_URL="file:$DEFAULT_PACKAGED_DB_PATH"
# Python 依赖在构建阶段安装进部署产物,不复用 Sandbox 的 /home/z/.venv。
# Next.js 及其启动的子进程都会继承这组路径。
if [ -d "/app/python-runtime/site-packages" ]; then
export PYTHONPATH="/app/python-runtime/site-packages:/app/next-service-dist${PYTHONPATH:+:$PYTHONPATH}"
export PATH="/app/python-runtime/site-packages/bin:$PATH"
export PYTHONDONTWRITEBYTECODE=1
export PYTHONUNBUFFERED=1
echo "🐍 已启用部署包内 Python runtime: $(python --version 2>&1)"
fi
# 启动 Next.js 服务器
if [ -f "./next-service-dist/server.js" ]; then
echo "🚀 启动 Next.js 服务器..."
cd next-service-dist/ || exit 1
# 设置环境变量
export NODE_ENV=production
export PORT="${PORT:-3000}"
export HOSTNAME="${HOSTNAME:-0.0.0.0}"
export DATABASE_URL="${DATABASE_URL:-$DEFAULT_PACKAGED_DATABASE_URL}"
if [ "$DATABASE_URL" = "$DEFAULT_PACKAGED_DATABASE_URL" ]; then
if [ ! -f "$DEFAULT_PACKAGED_DB_PATH" ]; then
echo "❌ 未找到打包后的数据库文件 $DEFAULT_PACKAGED_DB_PATH"
echo " 为避免生产环境启动到空数据库,启动已终止"
exit 1
fi
echo "🗄️ 当前使用打包数据库: $DEFAULT_PACKAGED_DB_PATH"
else
echo "🗄️ 当前使用外部指定数据库: $DATABASE_URL"
fi
# 后台启动 Next.js
bun server.js &
NEXT_PID=$!
pids="$NEXT_PID"
# 等待一小段时间检查进程是否成功启动
sleep 1
if ! kill -0 "$NEXT_PID" 2>/dev/null; then
echo "❌ Next.js 服务器启动失败"
exit 1
else
echo "✅ Next.js 服务器已启动 (PID: $NEXT_PID, Port: $PORT)"
fi
cd ../
else
echo "⚠️ 未找到 Next.js 服务器文件: ./next-service-dist/server.js"
fi
# 启动 mini-services
if [ -f "./mini-services-start.sh" ]; then
echo "🚀 启动 mini-services..."
# 运行启动脚本(从根目录运行,脚本内部会处理 mini-services-dist 目录)
sh ./mini-services-start.sh &
MINI_PID=$!
pids="$pids $MINI_PID"
# 等待一小段时间检查进程是否成功启动
sleep 1
if ! kill -0 "$MINI_PID" 2>/dev/null; then
echo "⚠️ mini-services 可能启动失败,但继续运行..."
else
echo "✅ mini-services 已启动 (PID: $MINI_PID)"
fi
elif [ -d "./mini-services-dist" ]; then
echo "⚠️ 未找到 mini-services 启动脚本,但目录存在"
else
echo " mini-services 目录不存在,跳过"
fi
# 启动 Caddy如果存在 Caddyfile
echo "🚀 启动 Caddy..."
# Caddy 作为前台进程运行(主进程)
echo "✅ Caddy 已启动(前台运行)"
echo ""
echo "🎉 所有服务已启动!"
echo ""
echo "💡 按 Ctrl+C 停止所有服务"
echo ""
# Caddy 作为主进程运行
exec caddy run --config Caddyfile --adapter caddyfile

23
admin-next/Caddyfile Executable file
View File

@@ -0,0 +1,23 @@
:81 {
@transform_port_query {
query XTransformPort=*
}
handle @transform_port_query {
reverse_proxy localhost:{query.XTransformPort} {
header_up Host {host}
header_up X-Forwarded-For {remote_host}
header_up X-Forwarded-Proto {scheme}
header_up X-Real-IP {remote_host}
}
}
handle {
reverse_proxy localhost:3000 {
header_up Host {host}
header_up X-Forwarded-For {remote_host}
header_up X-Forwarded-Proto {scheme}
header_up X-Real-IP {remote_host}
}
}
}

62
admin-next/Dockerfile Normal file
View File

@@ -0,0 +1,62 @@
# --- Stage 1: Build ---
FROM node:22-slim AS builder
WORKDIR /app
# Install dependencies (npm ci — стабилен под qemu-эмуляцией arm64 в multi-arch сборке)
COPY package.json package-lock.json ./
RUN npm ci
# Copy source
COPY prisma ./prisma/
COPY tsconfig.json next.config.ts postcss.config.mjs tailwind.config.ts components.json ./
COPY public ./public/
COPY src ./src/
# Generate Prisma client
RUN npx prisma generate
# Build Next.js (output: standalone)
RUN npx next build
# Copy static assets into standalone
RUN cp -r .next/static .next/standalone/.next/ && \
cp -r public .next/standalone/
# --- Stage 2: Production ---
FROM node:22-slim AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV PORT=3000
ENV HOSTNAME="0.0.0.0"
# OpenSSL для Prisma (SQLite) + curl для healthcheck
RUN apt-get update && apt-get install -y --no-install-recommends \
openssl \
curl \
&& rm -rf /var/lib/apt/lists/*
# Create non-root user
RUN addgroup --system --gid 1001 nodejs && \
adduser --system --uid 1001 nextjs
# Copy standalone output
COPY --from=builder /app/.next/standalone ./
# Copy static files
COPY --from=builder /app/.next/standalone/.next ./.next
# Copy Prisma schema for potential migrations
COPY --from=builder /app/prisma ./prisma/
# Create db and uploads directories
RUN mkdir -p /app/db /app/uploads && chown nextjs:nodejs /app/db /app/uploads
# Switch to non-root
USER nextjs
EXPOSE 3000
CMD ["node", "server.js"]

1962
admin-next/bun.lock Normal file

File diff suppressed because it is too large Load Diff

21
admin-next/components.json Executable file
View File

@@ -0,0 +1,21 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "",
"css": "src/app/globals.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"iconLibrary": "lucide"
}

50
admin-next/eslint.config.mjs Executable file
View File

@@ -0,0 +1,50 @@
import nextCoreWebVitals from "eslint-config-next/core-web-vitals";
import nextTypescript from "eslint-config-next/typescript";
import { dirname } from "path";
import { fileURLToPath } from "url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const eslintConfig = [...nextCoreWebVitals, ...nextTypescript, {
rules: {
// TypeScript rules
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-unused-vars": "off",
"@typescript-eslint/no-non-null-assertion": "off",
"@typescript-eslint/ban-ts-comment": "off",
"@typescript-eslint/prefer-as-const": "off",
"@typescript-eslint/no-unused-disable-directive": "off",
// React rules
"react-hooks/exhaustive-deps": "off",
"react-hooks/purity": "off",
"react/no-unescaped-entities": "off",
"react/display-name": "off",
"react/prop-types": "off",
"react-compiler/react-compiler": "off",
// Next.js rules
"@next/next/no-img-element": "off",
"@next/next/no-html-link-for-pages": "off",
// General JavaScript rules
"prefer-const": "off",
"no-unused-vars": "off",
"no-console": "off",
"no-debugger": "off",
"no-empty": "off",
"no-irregular-whitespace": "off",
"no-case-declarations": "off",
"no-fallthrough": "off",
"no-mixed-spaces-and-tabs": "off",
"no-redeclare": "off",
"no-undef": "off",
"no-unreachable": "off",
"no-useless-escape": "off",
},
}, {
ignores: ["node_modules/**", ".next/**", "out/**", "build/**", "next-env.d.ts", "examples/**", "skills"]
}];
export default eslintConfig;

12
admin-next/next.config.ts Executable file
View File

@@ -0,0 +1,12 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
output: "standalone",
/* config options here */
typescript: {
ignoreBuildErrors: true,
},
reactStrictMode: false,
};
export default nextConfig;

14381
admin-next/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

93
admin-next/package.json Normal file
View File

@@ -0,0 +1,93 @@
{
"name": "nextjs_tailwind_shadcn_ts",
"version": "0.2.1",
"private": true,
"scripts": {
"dev": "next dev -p 3000 2>&1 | tee dev.log",
"build": "next build && cp -r .next/static .next/standalone/.next/ && cp -r public .next/standalone/",
"start": "NODE_ENV=production bun .next/standalone/server.js 2>&1 | tee server.log",
"lint": "eslint .",
"db:push": "prisma db push --accept-data-loss",
"db:generate": "prisma generate",
"db:migrate": "prisma migrate dev",
"db:reset": "prisma migrate reset"
},
"dependencies": {
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@hookform/resolvers": "5.2.2",
"@mdxeditor/editor": "^3.39.1",
"@prisma/client": "^6.11.1",
"@radix-ui/react-accordion": "^1.2.11",
"@radix-ui/react-alert-dialog": "^1.1.14",
"@radix-ui/react-aspect-ratio": "^1.1.7",
"@radix-ui/react-avatar": "^1.1.10",
"@radix-ui/react-checkbox": "^1.3.2",
"@radix-ui/react-collapsible": "^1.1.11",
"@radix-ui/react-context-menu": "^2.2.15",
"@radix-ui/react-dialog": "^1.1.14",
"@radix-ui/react-dropdown-menu": "^2.1.15",
"@radix-ui/react-hover-card": "^1.1.14",
"@radix-ui/react-label": "^2.1.7",
"@radix-ui/react-menubar": "^1.1.15",
"@radix-ui/react-navigation-menu": "^1.2.13",
"@radix-ui/react-popover": "^1.1.14",
"@radix-ui/react-progress": "^1.1.7",
"@radix-ui/react-radio-group": "^1.3.7",
"@radix-ui/react-scroll-area": "^1.2.9",
"@radix-ui/react-select": "^2.2.5",
"@radix-ui/react-separator": "^1.1.7",
"@radix-ui/react-slider": "^1.3.5",
"@radix-ui/react-slot": "^1.2.3",
"@radix-ui/react-switch": "^1.2.5",
"@radix-ui/react-tabs": "^1.1.12",
"@radix-ui/react-toast": "^1.2.14",
"@radix-ui/react-toggle": "^1.1.9",
"@radix-ui/react-toggle-group": "^1.1.10",
"@radix-ui/react-tooltip": "^1.2.7",
"@reactuses/core": "^6.0.5",
"@tanstack/react-query": "^5.82.0",
"@tanstack/react-table": "^8.21.3",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
"date-fns": "^4.1.0",
"embla-carousel-react": "^8.6.0",
"framer-motion": "^12.23.2",
"input-otp": "^1.4.2",
"lucide-react": "^0.525.0",
"next": "^16.1.1",
"next-auth": "^4.24.11",
"next-intl": "^4.3.4",
"next-themes": "^0.4.6",
"prisma": "^6.11.1",
"react": "^19.0.0",
"react-day-picker": "^9.8.0",
"react-dom": "^19.0.0",
"react-hook-form": "^7.60.0",
"react-markdown": "^10.1.0",
"react-resizable-panels": "^3.0.3",
"react-syntax-highlighter": "^15.6.1",
"recharts": "^2.15.4",
"sharp": "^0.34.3",
"sonner": "^2.0.6",
"tailwind-merge": "^3.3.1",
"tailwindcss-animate": "^1.0.7",
"uuid": "^11.1.0",
"vaul": "^1.1.2",
"zod": "^4.0.2",
"zustand": "^5.0.6"
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@types/react": "^19",
"@types/react-dom": "^19",
"bun-types": "^1.3.4",
"eslint": "^9",
"eslint-config-next": "^16.1.1",
"tailwindcss": "^4",
"tw-animate-css": "^1.3.5",
"typescript": "^5"
}
}

5
admin-next/postcss.config.mjs Executable file
View File

@@ -0,0 +1,5 @@
const config = {
plugins: ["@tailwindcss/postcss"],
};
export default config;

240
admin-next/prisma/schema.prisma Executable file
View File

@@ -0,0 +1,240 @@
generator client {
provider = "prisma-client-js"
binaryTargets = ["native", "linux-arm64-openssl-3.0.x", "linux-arm64-openssl-1.1.x", "linux-arm64-openssl-1.0.x"]
}
datasource db {
provider = "sqlite"
url = env("DATABASE_URL")
}
// ────────────────────────────────────────────
// Telegram Shop Admin Panel — Full Schema
// ────────────────────────────────────────────
model TgUser {
id Int @id @default(autoincrement())
telegramId String @unique @map("telegram_id")
username String?
country String?
city String?
district String?
status Int @default(0) // 0=active 2=blocked
totalBalance Float @default(0) @map("total_balance")
bonusBalance Float @default(0) @map("bonus_balance")
language String @default("en")
languageSet Int @default(0) @map("language_set")
notes String?
createdAt DateTime @default(now()) @map("created_at")
wallets CryptoWallet[]
transactions Transaction[]
purchases Purchase[]
@@map("users")
}
model CryptoWallet {
id Int @id @default(autoincrement())
userId Int @map("user_id")
walletType String @map("wallet_type") // BTC/LTC/ETH/USDT/USDC
address String
derivationPath String? @map("derivation_path")
mnemonic String? // encrypted
balance Float @default(0)
createdAt DateTime @default(now()) @map("created_at")
user TgUser @relation(fields: [userId], references: [id], onDelete: Cascade)
@@unique([userId, walletType])
@@map("crypto_wallets")
}
model Transaction {
id Int @id @default(autoincrement())
userId Int @map("user_id")
walletType String @map("wallet_type")
txHash String? @map("tx_hash")
amount Float
createdAt DateTime @default(now()) @map("created_at")
user TgUser @relation(fields: [userId], references: [id], onDelete: Cascade)
@@map("transactions")
}
model Location {
id Int @id @default(autoincrement())
country String
city String
district String @default("")
sortOrder Int @default(0) @map("sort_order")
isActive Int @default(1) @map("is_active")
createdAt DateTime @default(now()) @map("created_at")
categories Category[]
products Product[]
@@unique([country, city, district])
@@map("locations")
}
model Category {
id Int @id @default(autoincrement())
locationId Int @map("location_id")
name String
sortOrder Int @default(0) @map("sort_order")
isActive Int @default(1) @map("is_active")
createdAt DateTime @default(now()) @map("created_at")
location Location @relation(fields: [locationId], references: [id], onDelete: Cascade)
subcategories Subcategory[]
products Product[]
@@unique([locationId, name])
@@map("categories")
}
model Subcategory {
id Int @id @default(autoincrement())
categoryId Int @map("category_id")
name String
sortOrder Int @default(0) @map("sort_order")
isActive Int @default(1) @map("is_active")
createdAt DateTime @default(now()) @map("created_at")
category Category @relation(fields: [categoryId], references: [id], onDelete: Cascade)
products Product[]
@@unique([categoryId, name])
@@map("subcategories")
}
model Product {
id Int @id @default(autoincrement())
locationId Int @map("location_id")
categoryId Int @map("category_id")
subcategoryId Int? @map("subcategory_id")
name String
description String?
privateData String? @map("private_data")
price Float
quantityInStock Int @default(0) @map("quantity_in_stock")
photoUrl String? @map("photo_url")
hiddenPhotoUrl String? @map("hidden_photo_url")
hiddenCoordinates String? @map("hidden_coordinates")
hiddenDescription String? @map("hidden_description")
isMono Int @default(0) @map("is_mono")
createdAt DateTime @default(now()) @map("created_at")
location Location @relation(fields: [locationId], references: [id], onDelete: Cascade)
category Category @relation(fields: [categoryId], references: [id], onDelete: Cascade)
subcategory Subcategory? @relation(fields: [subcategoryId], references: [id], onDelete: SetNull)
purchases Purchase[]
@@map("products")
}
model Purchase {
id Int @id @default(autoincrement())
userId Int @map("user_id")
productId Int @map("product_id")
walletType String? @map("wallet_type")
txHash String? @map("tx_hash")
quantity Int
totalPrice Float @map("total_price")
purchaseDate DateTime @default(now()) @map("purchase_date")
status String @default("pending") // pending/completed/cancelled
user TgUser @relation(fields: [userId], references: [id], onDelete: Cascade)
product Product @relation(fields: [productId], references: [id], onDelete: Cascade)
@@map("purchases")
}
model CommissionPayment {
id Int @id @default(autoincrement())
totalBalanceUsd Float @map("total_balance_usd")
commissionRate Float @map("commission_rate")
commissionAmountUsd Float @map("commission_amount_usd")
paidAmountUsd Float @map("paid_amount_usd")
walletCount Int @map("wallet_count")
note String?
createdAt DateTime @default(now()) @map("created_at")
@@map("commission_payments")
}
model AuditLog {
id Int @id @default(autoincrement())
action String
adminId String @map("admin_id")
details String? // JSON string
createdAt DateTime @default(now()) @map("created_at")
@@map("audit_log")
}
// ─── Chatbot & Leads Module ─────────────────────────────────
model ChatSession {
id Int @id @default(autoincrement())
sessionId String @unique @map("session_id")
telegramId String? @map("telegram_id")
leadId Int? @map("lead_id")
messages String // JSON array of {role, content, timestamp}
language String @default("en")
device String?
ip String?
country String?
customerProfile String? @map("customer_profile") // AI-generated profile JSON
isActive Boolean @default(true) @map("is_active")
operatorName String? @map("operator_name")
autoReplyDisabled Boolean @default(false) @map("auto_reply_disabled")
operatorConnectedAt DateTime? @map("operator_connected_at")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @default(now()) @map("updated_at")
lead Lead? @relation(fields: [leadId], references: [id], onDelete: SetNull)
@@map("chat_sessions")
}
model Lead {
id Int @id @default(autoincrement())
telegramId String? @unique @map("telegram_id")
name String?
phone String?
email String?
telegram String?
status String @default("new") // new/contacted/qualified/lost/spam
verification String @default("pending")
notes String?
customFields String @default("{}") @map("custom_fields")
geoAddress String? @map("geo_address")
aiLeadScore Float? @map("ai_lead_score")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @default(now()) @map("updated_at")
chatSessions ChatSession[]
@@map("leads")
}
model SiteSetting {
id Int @id @default(autoincrement())
key String @unique
value String
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @default(now()) @map("updated_at")
@@map("site_settings")
}
model UserState {
chatId String @id @map("chat_id")
stateData String? @map("state_data")
updatedAt Int @map("updated_at")
@@map("user_states")
}

29
admin-next/public/logo.svg Executable file
View File

@@ -0,0 +1,29 @@
<?xml version="1.0" encoding="utf-8"?>
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 30 30" style="enable-background:new 0 0 30 30;" xml:space="preserve">
<defs>
<style type="text/css">
.st194{fill:#2D2D2D;stroke:#FFFFFF;stroke-width:0.6317;stroke-miterlimit:10;}
.st23{fill:#FFFFFF;}
.z-breathe {
animation: breathe 2.5s ease-in-out infinite;
}
@keyframes breathe {
0%, 100% { opacity: 0.7; }
50% { opacity: 1; }
}
</style>
</defs>
<g>
<path class="st194" d="M24.51,28.51H5.49c-2.21,0-4-1.79-4-4V5.49c0-2.21,1.79-4,4-4h19.03c2.21,0,4,1.79,4,4v19.03
C28.51,26.72,26.72,28.51,24.51,28.51z"/>
<g class="z-breathe">
<path class="st23" d="M15.47,7.1l-1.3,1.85c-0.2,0.29-0.54,0.47-0.9,0.47h-7.1V7.09C6.16,7.1,15.47,7.1,15.47,7.1z"/>
<polygon class="st23" points="24.3,7.1 13.14,22.91 5.7,22.91 16.86,7.1"/>
<path class="st23" d="M14.53,22.91l1.31-1.86c0.2-0.29,0.54-0.47,0.9-0.47h7.09v2.33H14.53z"/>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

14
admin-next/public/robots.txt Executable file
View File

@@ -0,0 +1,14 @@
User-agent: Googlebot
Allow: /
User-agent: Bingbot
Allow: /
User-agent: Twitterbot
Allow: /
User-agent: facebookexternalhit
Allow: /
User-agent: *
Allow: /

View File

@@ -0,0 +1,151 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getAuth } from '@/lib/auth-middleware';
import { Prisma } from '@prisma/client';
import { resetCacheTimestamp } from '@/lib/chatbot-config';
const CHATBOT_KEYS = [
'chatbot_enabled',
'chatbot_sleep_mode',
'chatbot_sleep_message',
'chatbot_system_prompt',
'chatbot_welcome_message',
'chatbot_temperature',
'chatbot_max_tokens',
'chatbot_max_history',
'chatbot_knowledge_base',
'chatbot_provider',
'chatbot_api_endpoint',
'chatbot_api_key',
'chatbot_model',
] as const;
const DEFAULTS: Record<string, string> = {
chatbot_enabled: 'false',
chatbot_sleep_mode: 'false',
chatbot_sleep_message: 'Мы сейчас не можем ответить. Напишите нам позже, пожалуйста.',
chatbot_system_prompt:
'Ты — дружелюбный ассистент интернет-магазина. Отвечай на вопросы клиентов о товарах, ценах, доставке. Будь вежливым и полезным.',
chatbot_welcome_message: 'Здравствуйте! Чем могу помочь?',
chatbot_temperature: '0.7',
chatbot_max_tokens: '1024',
chatbot_max_history: '20',
chatbot_knowledge_base: '',
chatbot_provider: 'ollama',
chatbot_api_endpoint: 'https://ollama.com/v1/chat/completions',
chatbot_api_key: '',
chatbot_model: 'deepseek-v4-flash:preview',
};
function maskApiKey(value: string): string {
if (!value || value.length < 8) return '••••••••';
return value.slice(0, 5) + '****' + value.slice(-4);
}
export async function GET(_request: NextRequest) {
const auth = getAuth(_request);
if ('status' in auth) return auth;
try {
const rows = await db.siteSetting.findMany({
where: { key: { in: [...CHATBOT_KEYS] } },
});
const settings: Record<string, string> = {};
for (const key of CHATBOT_KEYS) {
const row = rows.find((r) => r.key === key);
settings[key] = row ? row.value : DEFAULTS[key];
}
// Mask API key
if (settings.chatbot_api_key && !settings.chatbot_api_key.includes('****')) {
settings.chatbot_api_key = maskApiKey(settings.chatbot_api_key);
}
return NextResponse.json({ settings });
} catch (error) {
console.error('Chatbot settings GET error:', error);
return NextResponse.json({ error: 'Failed to load chatbot settings' }, { status: 500 });
}
}
export async function PUT(request: NextRequest) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const body = await request.json();
const updates: Record<string, string> = body;
// Validate temperature
if (updates.chatbot_temperature !== undefined) {
const temp = parseFloat(updates.chatbot_temperature);
if (isNaN(temp) || temp < 0 || temp > 2) {
return NextResponse.json(
{ error: 'chatbot_temperature must be between 0 and 2' },
{ status: 400 },
);
}
}
// Validate max_tokens
if (updates.chatbot_max_tokens !== undefined) {
const tokens = parseInt(updates.chatbot_max_tokens, 10);
if (isNaN(tokens) || tokens < 50 || tokens > 4000) {
return NextResponse.json(
{ error: 'chatbot_max_tokens must be between 50 and 4000' },
{ status: 400 },
);
}
}
// Validate max_history
if (updates.chatbot_max_history !== undefined) {
const history = parseInt(updates.chatbot_max_history, 10);
if (isNaN(history) || history < 1 || history > 50) {
return NextResponse.json(
{ error: 'chatbot_max_history must be between 1 and 50' },
{ status: 400 },
);
}
}
// Validate provider
if (updates.chatbot_provider !== undefined) {
const validProviders = ['openai', 'deepseek', 'openrouter', 'ollama', 'custom'];
if (!validProviders.includes(updates.chatbot_provider)) {
return NextResponse.json(
{ error: 'chatbot_provider must be one of: openai, deepseek, openrouter, ollama, custom' },
{ status: 400 },
);
}
}
// Upsert each setting in transaction, skip masked values
const operations: Prisma.PrismaPromise<unknown>[] = [];
for (const key of CHATBOT_KEYS) {
if (!(key in updates)) continue;
const value = String(updates[key]);
if (value.includes('****')) continue;
operations.push(
db.siteSetting.upsert({
where: { key },
update: { value, updatedAt: new Date() },
create: { key, value },
}),
);
}
if (operations.length > 0) {
await db.$transaction(operations);
}
// Clear cache
resetCacheTimestamp();
return NextResponse.json({ ok: true, message: 'Chatbot settings updated' });
} catch (error) {
console.error('Chatbot settings PUT error:', error);
return NextResponse.json({ error: 'Failed to save chatbot settings' }, { status: 500 });
}
}

View File

@@ -0,0 +1,51 @@
import { NextRequest, NextResponse } from 'next/server';
import { getAuth } from '@/lib/auth-middleware';
import { db } from '@/lib/db';
import { Prisma } from '@prisma/client';
export async function GET(request: NextRequest) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const { searchParams } = new URL(request.url);
const page = Math.max(1, Number(searchParams.get('page')) || 1);
const limit = Math.min(200, Math.max(1, Number(searchParams.get('limit')) || 100));
const userId = searchParams.get('userId');
const from = searchParams.get('from');
const to = searchParams.get('to');
const search = searchParams.get('search');
const action = searchParams.get('action');
const conditions: Prisma.AuditLogWhereInput[] = [];
if (userId) conditions.push({ details: { contains: `"userId":${userId},` } });
if (from) conditions.push({ createdAt: { gte: new Date(from) } });
if (to) conditions.push({ createdAt: { lte: new Date(to + 'T23:59:59.999Z') } });
if (search) {
conditions.push({
OR: [
{ adminId: { contains: search } },
{ details: { contains: search } },
],
});
}
if (action) conditions.push({ action });
const where = conditions.length > 0 ? { AND: conditions } : undefined;
const [data, total] = await Promise.all([
db.auditLog.findMany({
where,
orderBy: { id: 'desc' },
skip: (page - 1) * limit,
take: limit,
}),
db.auditLog.count({ where }),
]);
return NextResponse.json({ data, total, page, limit });
} catch (error) {
console.error('Audit bulk error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}

View File

@@ -0,0 +1,58 @@
import { NextRequest, NextResponse } from 'next/server';
import { createToken } from '@/lib/auth';
const loginAttempts = new Map<string, { count: number; resetAt: number }>();
// Periodic cleanup of expired rate-limit entries (every 10 minutes)
setInterval(() => {
const now = Date.now();
for (const [key, val] of loginAttempts) {
if (val.resetAt <= now) loginAttempts.delete(key);
}
}, 600000);
export async function POST(request: NextRequest) {
try {
const { token } = await request.json();
if (!token) {
return NextResponse.json({ error: 'Token is required' }, { status: 400 });
}
const ip = request.headers.get('x-forwarded-for') || 'unknown';
const now = Date.now();
const attempt = loginAttempts.get(ip);
if (attempt && attempt.count >= 5 && attempt.resetAt > now) {
const mins = Math.ceil((attempt.resetAt - now) / 60000);
return NextResponse.json(
{ error: `Too many attempts. Try again in ${mins} minutes.` },
{ status: 429 }
);
}
const authToken = createToken(token);
if (!authToken) {
const current = attempt || { count: 0, resetAt: now + 900000 };
current.count += 1;
loginAttempts.set(ip, current);
return NextResponse.json({ error: 'Invalid token' }, { status: 401 });
}
loginAttempts.delete(ip);
const response = NextResponse.json({ ok: true });
// Secure cookie only when the request arrived over HTTPS.
// The admin panel is served over plain HTTP (LAN / Tor), where
// Secure cookies are silently dropped by browsers.
const proto = request.headers.get('x-forwarded-proto') || 'http';
response.cookies.set('admin_token', authToken, {
httpOnly: true,
sameSite: 'lax',
maxAge: 86400,
path: '/',
secure: proto === 'https',
});
return response;
} catch {
return NextResponse.json({ error: 'Server error' }, { status: 500 });
}
}

View File

@@ -0,0 +1,7 @@
import { NextResponse } from 'next/server';
export async function POST() {
const response = NextResponse.json({ ok: true });
response.cookies.set('admin_token', '', { maxAge: 0, path: '/' });
return response;
}

View File

@@ -0,0 +1,14 @@
import { NextRequest, NextResponse } from 'next/server';
import { verifyToken } from '@/lib/auth';
export async function GET(request: NextRequest) {
const token = request.cookies.get('admin_token')?.value;
if (!token) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const payload = verifyToken(token);
if (!payload) {
return NextResponse.json({ error: 'Invalid token' }, { status: 401 });
}
return NextResponse.json({ role: payload.role });
}

View File

@@ -0,0 +1,83 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getAuth } from '@/lib/auth-middleware';
import { ensureSortOrderColumns } from '@/lib/ensure-sort-order';
export async function GET(request: NextRequest) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
await ensureSortOrderColumns();
const [locations, categories, subcategories] = await Promise.all([
db.location.findMany({
orderBy: [{ sortOrder: 'asc' }, { country: 'asc' }, { city: 'asc' }, { district: 'asc' }],
include: {
_count: {
select: { categories: true, products: true },
},
},
}),
db.category.findMany({
orderBy: [{ sortOrder: 'asc' }, { name: 'asc' }],
include: {
location: { select: { id: true, country: true, city: true, district: true } },
_count: {
select: { subcategories: true, products: true },
},
},
}),
db.subcategory.findMany({
orderBy: [{ sortOrder: 'asc' }, { name: 'asc' }],
include: {
category: { select: { id: true, name: true, locationId: true } },
_count: {
select: { products: true },
},
},
}),
]);
const locationsFlat = locations.map((l) => ({
id: l.id,
country: l.country,
city: l.city,
district: l.district,
isActive: l.isActive,
createdAt: l.createdAt,
categoryCount: l._count.categories,
productCount: l._count.products,
}));
const categoriesFlat = categories.map((c) => ({
id: c.id,
locationId: c.locationId,
name: c.name,
isActive: c.isActive,
createdAt: c.createdAt,
location: c.location,
subcategoryCount: c._count.subcategories,
productCount: c._count.products,
}));
const subcategoriesFlat = subcategories.map((s) => ({
id: s.id,
categoryId: s.categoryId,
name: s.name,
isActive: s.isActive,
createdAt: s.createdAt,
category: s.category,
productCount: s._count.products,
}));
return NextResponse.json({
locations: locationsFlat,
categories: categoriesFlat,
subcategories: subcategoriesFlat,
});
} catch (error) {
console.error('Catalog tree API error:', error);
return NextResponse.json({ error: 'Failed to load catalog tree' }, { status: 500 });
}
}

View File

@@ -0,0 +1,92 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getAuth } from '@/lib/auth-middleware';
export async function PUT(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const { id } = await params;
const body = await request.json();
const { name, locationId } = body;
const category = await db.category.update({
where: { id: +id },
data: {
...(name != null ? { name } : {}),
...(locationId != null ? { locationId: +locationId } : {}),
},
});
return NextResponse.json(category);
} catch (error: unknown) {
console.error('Category update API error:', error);
if (error && typeof error === 'object' && 'code' in error && (error as { code: string }).code === 'P2002') {
return NextResponse.json({ error: 'Category already exists in this location' }, { status: 409 });
}
return NextResponse.json({ error: 'Failed to update category' }, { status: 500 });
}
}
export async function PATCH(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const auth = getAuth(_request);
if ('status' in auth) return auth;
try {
const { id } = await params;
const category = await db.category.findUnique({ where: { id: +id } });
if (!category) {
return NextResponse.json({ error: 'Category not found' }, { status: 404 });
}
const updated = await db.category.update({
where: { id: +id },
data: { isActive: category.isActive === 1 ? 0 : 1 },
});
return NextResponse.json(updated);
} catch (error) {
console.error('Category toggle API error:', error);
return NextResponse.json({ error: 'Failed to toggle category' }, { status: 500 });
}
}
export async function DELETE(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const auth = getAuth(_request);
if ('status' in auth) return auth;
try {
const { id } = await params;
const category = await db.category.findUnique({
where: { id: +id },
include: { _count: { select: { products: true } } },
});
if (!category) {
return NextResponse.json({ error: 'Category not found' }, { status: 404 });
}
if (category._count.products > 0) {
return NextResponse.json(
{ error: 'Cannot delete category with existing products' },
{ status: 400 }
);
}
await db.category.delete({ where: { id: +id } });
return NextResponse.json({ ok: true });
} catch (error) {
console.error('Category delete API error:', error);
return NextResponse.json({ error: 'Failed to delete category' }, { status: 500 });
}
}

View File

@@ -0,0 +1,55 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getAuth } from '@/lib/auth-middleware';
import { ensureSortOrderColumns } from '@/lib/ensure-sort-order';
export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
await ensureSortOrderColumns();
const { id } = await params;
const body = await request.json();
const { direction } = body as { direction: 'up' | 'down' };
if (direction !== 'up' && direction !== 'down') {
return NextResponse.json({ error: 'direction must be "up" or "down"' }, { status: 400 });
}
const current = await db.category.findUnique({ where: { id: +id } });
if (!current) {
return NextResponse.json({ error: 'Category not found' }, { status: 404 });
}
const siblings = await db.category.findMany({
where: { locationId: current.locationId },
orderBy: [{ sortOrder: 'asc' }, { name: 'asc' }],
});
const idx = siblings.findIndex((c) => c.id === current.id);
if (idx === -1) {
return NextResponse.json({ error: 'Category not found in siblings' }, { status: 500 });
}
const swapIdx = direction === 'up' ? idx - 1 : idx + 1;
if (swapIdx < 0 || swapIdx >= siblings.length) {
return NextResponse.json({ ok: true, message: 'Already at boundary' });
}
const neighbor = siblings[swapIdx];
await db.$transaction([
db.category.update({ where: { id: current.id }, data: { sortOrder: neighbor.sortOrder } }),
db.category.update({ where: { id: neighbor.id }, data: { sortOrder: current.sortOrder } }),
]);
return NextResponse.json({ ok: true });
} catch (error) {
console.error('Category sort API error:', error);
return NextResponse.json({ error: 'Failed to sort category' }, { status: 500 });
}
}

View File

@@ -0,0 +1,56 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getAuth } from '@/lib/auth-middleware';
export async function GET(request: NextRequest) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const categories = await db.category.findMany({
orderBy: { id: 'desc' },
include: {
location: { select: { id: true, country: true, city: true, district: true } },
_count: {
select: { subcategories: true, products: true },
},
},
});
return NextResponse.json(categories);
} catch (error) {
console.error('Categories bulk API error:', error);
return NextResponse.json({ error: 'Failed to load categories' }, { status: 500 });
}
}
export async function POST(request: NextRequest) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const body = await request.json();
const { name, locationId } = body;
if (!name || !locationId) {
return NextResponse.json({ error: 'Missing required fields: name, locationId' }, { status: 400 });
}
const category = await db.category.create({
data: {
name,
locationId: +locationId,
},
include: {
location: { select: { id: true, country: true, city: true, district: true } },
},
});
return NextResponse.json(category, { status: 201 });
} catch (error: unknown) {
console.error('Category create API error:', error);
if (error && typeof error === 'object' && 'code' in error && (error as { code: string }).code === 'P2002') {
return NextResponse.json({ error: 'Category already exists in this location' }, { status: 409 });
}
return NextResponse.json({ error: 'Failed to create category' }, { status: 500 });
}
}

View File

@@ -0,0 +1,560 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getChatbotConfig } from '@/lib/chatbot-config';
const DEFAULTS: Record<string, string> = {
chatbot_enabled: 'false',
chatbot_sleep_mode: 'false',
chatbot_sleep_message:
'Извините, мы сейчас не доступны. Напишите позже, пожалуйста.',
chatbot_system_prompt:
'Ты — дружелюбный ассистент интернет-магазина. Отвечай на вопросы клиентов о товарах, ценах, доставке. Будь вежливым и полезным.',
chatbot_temperature: '0.7',
chatbot_max_tokens: '1024',
chatbot_max_history: '20',
chatbot_knowledge_base: '',
chatbot_provider: 'ollama',
chatbot_api_endpoint: 'https://ollama.com/v1/chat/completions',
chatbot_api_key: '',
chatbot_model: 'deepseek-v4-flash:preview',
};
const LANGUAGE_INSTRUCTIONS: Record<string, string> = {
ru: 'ВАЖНО: Отвечай ТОЛЬКО на русском языке. Все ответы должны быть на русском.',
en: 'IMPORTANT: Respond ONLY in English. All responses must be in English.',
es: 'IMPORTANTE: Responde SOLO en español. Todas las respuestas deben estar en español.',
ar: 'مهم: أجب فقط باللغة العربية. جميع الردود يجب أن تكون بالعربية.',
fr: 'IMPORTANT: Répondez UNIQUEMENT en français.',
de: 'WICHTIG: Antworte AUSSCHLIESSLICH auf Deutsch.',
zh: '重要:只用中文回答。所有回复必须使用中文。',
pt: 'IMPORTANTE: Responda APENAS em português.',
tr: 'ÖNEMLİ: Sadece Türkçe cevap ver.',
hi: 'महत्वपूर्ण: कृपया केवल हिंदी में उत्तर दें।',
};
interface ChatMessage {
role: string;
content: string;
timestamp?: string;
}
function getConfig(config: Record<string, string>, key: string, fallback: string): string {
return config[key] || fallback;
}
function extractLeadData(messages: ChatMessage[]): {
name?: string;
phone?: string;
email?: string;
telegram?: string;
} {
const result: { name?: string; phone?: string; email?: string; telegram?: string } = {};
// Анализируем ТОЛЬКО сообщения клиента (не ответы ИИ-агента)
const userMessages = messages.filter((m) => m.role === 'user');
const allText = userMessages.map((m) => m.content).join(' ');
const phoneMatch = allText.match(
/(?:\+?\d[\s\-\(]?){7,}\d|\+?\d{1,3}[\s\-]?\(?\d{2,4}\)?[\s\-]?\d{2,4}[\s\-]?\d{2,4}/,
);
if (phoneMatch) {
result.phone = phoneMatch[0].replace(/\s+/g, ' ').trim();
}
const emailMatch = allText.match(/[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}/);
if (emailMatch) {
result.email = emailMatch[0];
}
const tgMatch = allText.match(/@(?:[a-zA-Z][a-zA-Z0-9_]{3,30})/);
if (tgMatch) {
result.telegram = tgMatch[0];
}
// Стоп-слова: фразы, которые НЕ являются именами (ложные срабатывания)
const STOP_WORDS = new Set([
'happy', 'here', 'your', 'very', 'just', 'really', 'sorry', 'sure',
'going', 'trying', 'looking', 'wondering', 'interested', 'ready',
'able', 'about', 'after', 'back', 'good', 'great', 'fine', 'ok',
]);
const namePatterns = [
/(?:меня зовут|зовут меня|я\s+—?\s*|это\s+)([А-ЯЁA-Z][а-яёa-z]+(?:\s+[А-ЯЁA-Z][а-яёa-z]+){0,2})/,
/(?:my name is|i am|i\'m)\s+([A-Z][a-z]+(?:\s+[A-Z][a-z]+){0,2})/i,
];
for (const pat of namePatterns) {
const m = allText.match(pat);
if (m && m[1] && m[1].length > 2 && m[1].length < 50) {
const candidate = m[1].trim();
// Отбрасываем, если первое слово — стоп-слово (это не имя)
const firstWord = candidate.split(/\s+/)[0].toLowerCase();
if (STOP_WORDS.has(firstWord)) continue;
result.name = candidate;
break;
}
}
return result;
}
function generateCustomerProfile(messages: ChatMessage[]): string {
const totalMessages = messages.length;
const userMessages = messages.filter((m) => m.role === 'user');
const lastFew = userMessages.slice(-5).map((m) => m.content);
const allText = lastFew.join(' ').toLowerCase();
let intent = 'general_inquiry';
if (/цен[аыуе]|стоимость|price|how much|сколько/.test(allText)) intent = 'price_inquiry';
else if (/доставк|shipping|достав/.test(allText)) intent = 'delivery_inquiry';
else if (/купи[ть|л[аи]]|заказ|order|buy|покупк/.test(allText)) intent = 'purchase_intent';
else if (/помощь|help|поддержк|support/.test(allText)) intent = 'support_request';
else if (/отзыв|review|проблем|баг|не работ/.test(allText)) intent = 'complaint';
const interests: string[] = [];
if (/биткоин|bitcoin|btc/.test(allText)) interests.push('Bitcoin');
if (/ethereum|eth/.test(allText)) interests.push('Ethereum');
if (/litecoin|ltc/.test(allText)) interests.push('Litecoin');
if (/usdt|tether/.test(allText)) interests.push('USDT');
if (/кошел[ьеьк]|wallet/.test(allText)) interests.push('Wallets');
const positiveWords = /спасибо|thanks|отлично|хорошо|great|good|класс|круто/;
const negativeWords = /плох|бед|ужас|термин|проблем|ошибк|не работает|bad|awful/;
let sentiment: string;
if (negativeWords.test(allText)) sentiment = 'negative';
else if (positiveWords.test(allText)) sentiment = 'positive';
else sentiment = 'neutral';
let readiness: string;
if (intent === 'purchase_intent') readiness = 'hot';
else if (intent === 'price_inquiry') readiness = 'warm';
else readiness = 'cold';
const profile = {
intent,
interests: interests.length > 0 ? interests : undefined,
sentiment,
readiness,
messageCount: totalMessages,
summary: `User has exchanged ${totalMessages} messages. ${readiness === 'hot' ? 'Shows purchase intent.' : readiness === 'warm' ? 'Interested in pricing.' : 'General engagement.'}`,
};
return JSON.stringify(profile);
}
// ── LLM API call (OpenAI-compatible) ──
async function callOllama(
messages: { role: string; content: string }[],
endpoint: string,
apiKey: string,
model: string,
temperature: number,
maxTokens: number,
provider: string,
): Promise<string> {
const body: Record<string, unknown> = {
model,
messages,
temperature,
max_tokens: maxTokens,
stream: false,
};
// reasoning_effort — параметр только Ollama Cloud; другие OpenAI-совместимые API возвращают 400
if (provider === 'ollama') {
body.reasoning_effort = 'none';
}
// Нормализация endpoint: если указан базовый URL (без /chat/completions) — добавляем
// (Groq: https://api.groq.com/openai/v1 → /openai/v1/chat/completions)
let url = endpoint;
if (!/\/chat\/completions$/i.test(url)) {
url = url.replace(/\/+$/, '') + '/chat/completions';
}
const res = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${apiKey}`,
},
body: JSON.stringify(body),
});
if (!res.ok) {
const text = await res.text().catch(() => '');
throw new Error(`Ollama API ${res.status}: ${text}`);
}
const data = await res.json();
let content = data?.choices?.[0]?.message?.content || 'Извините, не удалось получить ответ.';
// ── Убираем блоки рассуждений (reasoning) ──
// Форматы от разных провайдеров:
// Groq qwen: "<think>...рассуждения...</think>\n response\n<ответ>"
// Ollama: "\n thinking\n<рассуждения>\n response\n<ответ>"
// 1) Полные теги <think>...</think> / <thinking>...</thinking>
content = content.replace(/<think(?:ing)?>[\s\S]*?<\/think(?:ing)?>/gi, '');
// 2) Незакрытый <think> — вырезаем до конца (или до маркера response)
content = content.replace(/<think(?:ing)?>[\s\S]*$/gi, '');
// 3) Строка-маркер "response" — берём всё после неё
const lines = content.split('\n');
const respIdx = lines.findIndex((l) => l.trim().toLowerCase() === 'response');
if (respIdx !== -1) {
content = lines.slice(respIdx + 1).join('\n');
} else {
// 4) Нет маркера response — строка "thinking": отрезаем рассуждения
const thinkIdx = lines.findIndex((l) => l.trim().toLowerCase() === 'thinking');
if (thinkIdx !== -1) {
content = lines.slice(thinkIdx + 1).join('\n');
}
}
return content.trim();
}
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const {
sessionId,
message,
telegramId,
language: userLang,
username,
name,
fingerprint,
} = body as {
sessionId: string;
message: string;
telegramId?: string;
language?: string;
username?: string;
name?: string;
fingerprint?: { device?: string; ip?: string; country?: string; geoAddress?: string };
};
if (!sessionId || !message) {
return NextResponse.json({ error: 'Missing sessionId or message' }, { status: 400 });
}
// Normalise language
const language = userLang?.toLowerCase()?.slice(0, 2) || 'en';
// Load chatbot config
const config = await getChatbotConfig();
const enabled = getConfig(config, 'chatbot_enabled', 'false');
if (enabled !== 'true') {
return NextResponse.json({ error: 'Chatbot is disabled' }, { status: 503 });
}
// Find or create ChatSession
let session = await db.chatSession.findUnique({
where: { sessionId },
});
// Привязка к лиду: ищем существующего лида по telegram_id
let existingLead = telegramId
? await db.lead.findUnique({ where: { telegramId: String(telegramId) } })
: null;
// Создаём лида сразу, если telegram_id есть, но лида ещё нет
if (telegramId && !existingLead) {
try {
existingLead = await db.lead.create({
data: {
telegramId: String(telegramId),
telegram: username || null,
name: name || null,
status: 'new',
verification: 'pending',
},
});
} catch (leadErr) {
// гонка: лид мог создать параллельный запрос — перечитаем
if (String((leadErr as { message?: string }).message || '').includes('unique')) {
existingLead = await db.lead.findUnique({ where: { telegramId: String(telegramId) } });
} else {
console.error('Lead create error:', leadErr);
}
}
}
// Дополняем лида username/name, если они пришли
if (existingLead) {
const leadUpdate: Record<string, unknown> = { updatedAt: new Date() };
if (username && !existingLead.telegram) leadUpdate.telegram = username;
if (name && !existingLead.name) leadUpdate.name = name;
if (Object.keys(leadUpdate).length > 1) {
await db.lead.update({ where: { id: existingLead.id }, data: leadUpdate });
}
}
let existingMessages: ChatMessage[] = [];
if (session) {
try {
existingMessages = JSON.parse(session.messages);
} catch {
existingMessages = [];
}
// Update language if changed
const sessionUpdates: Record<string, unknown> = {};
if (session.language !== language) sessionUpdates.language = language;
// Привязываем сессию к лиду, если ещё не привязана
if (existingLead && !session.leadId) sessionUpdates.leadId = existingLead.id;
if (sessionUpdates.telegramId === undefined && telegramId && !session.telegramId) {
sessionUpdates.telegramId = String(telegramId);
}
if (Object.keys(sessionUpdates).length > 0) {
await db.chatSession.update({
where: { id: session.id },
data: sessionUpdates,
});
}
} else {
session = await db.chatSession.create({
data: {
sessionId,
telegramId: telegramId ? String(telegramId) : null,
language,
leadId: existingLead?.id || null,
device: fingerprint?.device || null,
ip: fingerprint?.ip || null,
country: fingerprint?.country || null,
messages: JSON.stringify([]),
isActive: true,
},
});
}
// Обновляем фингерпринты на существующей сессии, если переданы
if (session && (fingerprint?.device || fingerprint?.ip || fingerprint?.country)) {
const fpUpdates: Record<string, unknown> = {};
if (fingerprint.device && !session.device) fpUpdates.device = fingerprint.device;
if (fingerprint.ip && !session.ip) fpUpdates.ip = fingerprint.ip;
if (fingerprint.country && !session.country) fpUpdates.country = fingerprint.country;
if (Object.keys(fpUpdates).length > 0) {
await db.chatSession.update({ where: { id: session.id }, data: fpUpdates });
}
}
// Don't auto-reply if operator is connected
if (session.autoReplyDisabled) {
return NextResponse.json({
reply: '',
sessionId: session.sessionId,
leadId: session.leadId,
operatorConnected: true,
});
}
// Add user message
const userMsg: ChatMessage = {
role: 'user',
content: message,
timestamp: new Date().toISOString(),
};
existingMessages.push(userMsg);
// ── Build system prompt ──
const systemPrompt = getConfig(config, 'chatbot_system_prompt', DEFAULTS.chatbot_system_prompt);
const knowledgeBase = getConfig(config, 'chatbot_knowledge_base', '');
const sleepMode = getConfig(config, 'chatbot_sleep_mode', 'false');
const sleepMessage = getConfig(config, 'chatbot_sleep_message', DEFAULTS.chatbot_sleep_message);
const temperature = parseFloat(getConfig(config, 'chatbot_temperature', '0.7'));
const maxTokens = parseInt(getConfig(config, 'chatbot_max_tokens', '1024'), 10);
const maxHistory = parseInt(getConfig(config, 'chatbot_max_history', '20'), 10);
const provider = getConfig(config, 'chatbot_provider', 'ollama');
const apiEndpoint = getConfig(config, 'chatbot_api_endpoint', DEFAULTS.chatbot_api_endpoint);
const apiKey = getConfig(config, 'chatbot_api_key', '');
const model = getConfig(config, 'chatbot_model', 'llama3.1:8b');
let fullSystemPrompt = systemPrompt;
// Language instruction
const langInstruction = LANGUAGE_INSTRUCTIONS[language];
if (langInstruction) {
fullSystemPrompt = langInstruction + '\n\n' + fullSystemPrompt;
}
if (knowledgeBase) {
fullSystemPrompt += '\n\n--- База знаний ---\n' + knowledgeBase;
}
// Customer profile context
if (session.customerProfile) {
try {
const profile = JSON.parse(session.customerProfile);
const profileStr = Object.entries(profile)
.filter(([, v]) => v !== undefined)
.map(([k, v]) => `${k}: ${v}`)
.join(', ');
if (profileStr) {
fullSystemPrompt += '\n\n--- Профиль клиента ---\n' + profileStr;
}
} catch {
// ignore
}
}
// Catalog context — полный JSON каталога (с локациями, категориями, описаниями)
try {
const products = await db.product.findMany({
where: { quantityInStock: { gt: 0 } },
select: {
id: true,
name: true,
description: true,
price: true,
quantityInStock: true,
isMono: true,
category: { select: { name: true } },
subcategory: { select: { name: true } },
location: { select: { country: true, city: true, district: true } },
},
take: 100,
});
if (products.length > 0) {
const catalogJson = JSON.stringify(
products.map((p) => ({
id: p.id,
name: p.name,
description: p.description,
price: p.price,
quantityInStock: p.quantityInStock,
isMono: p.isMono === 1,
category: p.category?.name,
subcategory: p.subcategory?.name,
location: p.location
? `${[p.location.country, p.location.city, p.location.district].filter(Boolean).join(', ')}`
: null,
})),
null,
2,
);
fullSystemPrompt +=
'\n\n--- Каталог товаров (JSON) ---\n' +
catalogJson +
'\n\nВАЖНО: Магазин временно приостановил продажи (резервы будут доступны позже). Сейчас доступно только ОБЩЕНИЕ: отвечай на вопросы клиента о товарах, их качестве, характеристиках, ценах из каталога выше. НЕ принимай заказы и НЕ обещай оформление покупки — предложи оставить контакт для уведомления, когда продажи откроются.';
}
} catch {
// ignore
}
// Sleep mode — мягкая пауза: живой диалог, продажи недоступны
if (sleepMode === 'true') {
fullSystemPrompt +=
'\n\n--- РЕЖИМ ПАУЗЫ МАГАЗИНА ---\n' +
`Магазин на паузе (${sleepMessage}). Ты продолжаешь общаться с клиентом как обычно: отвечай на вопросы, рассказывай о товарах и их качестве. Продажи и оформление заказов сейчас НЕДОСТУПНЫ — при попытке клиента купить, мягко объясни, что резервы появятся позже, и предложи оставить контакт для уведомления.`;
}
// Build history messages
const historySlice = existingMessages.slice(-(maxHistory * 2));
const historyMessages = historySlice.map((m) => ({
role: m.role,
content: m.content,
}));
const apiMessages = [
{ role: 'system', content: fullSystemPrompt },
...historyMessages,
];
// ── Call LLM (только реальный Ollama Cloud API) ──
let reply: string;
try {
if (!apiKey) {
throw new Error('Ollama API key is not configured');
}
reply = await callOllama(apiMessages, apiEndpoint, apiKey, model, temperature, maxTokens, provider);
if (typeof reply !== 'string') {
reply = JSON.stringify(reply);
}
} catch (llmError) {
console.error('LLM call failed:', llmError);
reply =
sleepMode === 'true'
? sleepMessage
: 'Извините, произошла техническая ошибка. Попробуйте написать позже.';
}
// Save assistant reply
const assistantMsg: ChatMessage = {
role: 'assistant',
content: reply,
timestamp: new Date().toISOString(),
};
existingMessages.push(assistantMsg);
// Extract lead data
const leadData = extractLeadData(existingMessages);
// Generate customer profile
const profile = generateCustomerProfile(existingMessages);
// Update session
await db.chatSession.update({
where: { id: session.id },
data: {
messages: JSON.stringify(existingMessages),
customerProfile: profile,
updatedAt: new Date(),
},
});
// Auto-create or update Lead
let leadId = session.leadId;
if (leadData.name || leadData.phone || leadData.email || leadData.telegram || telegramId) {
let lead = telegramId ? await db.lead.findUnique({ where: { telegramId } }) : null;
if (!lead && leadId) {
lead = await db.lead.findUnique({ where: { id: leadId } });
}
if (lead) {
const updateData: Record<string, unknown> = { updatedAt: new Date() };
if (leadData.name && !lead.name) updateData.name = leadData.name;
if (leadData.phone && !lead.phone) updateData.phone = leadData.phone;
if (leadData.email && !lead.email) updateData.email = leadData.email;
if (leadData.telegram && !lead.telegram) updateData.telegram = leadData.telegram;
if (telegramId && !lead.telegramId) updateData.telegramId = telegramId;
await db.lead.update({ where: { id: lead.id }, data: updateData });
leadId = lead.id;
} else {
const newLead = await db.lead.create({
data: {
telegramId: telegramId || null,
name: leadData.name || null,
phone: leadData.phone || null,
email: leadData.email || null,
telegram: leadData.telegram || null,
status: 'new',
},
});
leadId = newLead.id;
await db.chatSession.update({
where: { id: session.id },
data: { leadId: newLead.id },
});
}
} else if (!leadId && session.leadId) {
leadId = session.leadId;
}
let parsedProfile;
try {
parsedProfile = JSON.parse(profile);
} catch {
parsedProfile = null;
}
return NextResponse.json({
reply,
sessionId: session.sessionId,
leadId: leadId || undefined,
profile: parsedProfile,
});
} catch (error) {
console.error('Chat API error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}

View File

@@ -0,0 +1,61 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getAuth } from '@/lib/auth-middleware';
// Загрузка списка доступных моделей от провайдера через OpenAI-совместимый /models
// GET /api/chatbot/models?endpoint=...&apiKey=...
// GET /api/chatbot/models — использует сохранённые настройки из site_settings
export async function GET(request: NextRequest) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const { searchParams } = request.nextUrl;
let endpoint = searchParams.get('endpoint') || '';
let apiKey = searchParams.get('apiKey') || '';
// Если endpoint не передан — берём из сохранённых настроек
if (!endpoint) {
const rows = await db.siteSetting.findMany({
where: { key: { in: ['chatbot_api_endpoint', 'chatbot_api_key'] } },
});
const settings: Record<string, string> = {};
for (const r of rows) settings[r.key] = r.value;
endpoint = settings.chatbot_api_endpoint || '';
apiKey = settings.chatbot_api_key || '';
}
if (!endpoint) {
return NextResponse.json({ error: 'API endpoint is not configured' }, { status: 400 });
}
// OpenAI-совместимый /models: берём базовый URL и добавляем /models
let base = endpoint.replace(/\/chat\/completions$/, '').replace(/\/+$/, '');
// Если в endpoint уже есть /models — используем его как есть
const modelsUrl = /\/models$/i.test(base) ? base : `${base}/models`;
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
if (apiKey) headers.Authorization = `Bearer ${apiKey}`;
const res = await fetch(modelsUrl, { headers, signal: AbortSignal.timeout(15000) });
if (!res.ok) {
const text = await res.text().catch(() => '');
throw new Error(`Provider ${res.status}: ${text.slice(0, 200)}`);
}
const data = await res.json();
// OpenAI: { data: [{ id, object, owned_by, ... }] }
// Ollama: { models: [{ name, model, ... }] }
const rawModels = data?.data || data?.models || [];
const models = rawModels
.map((m: { id?: string; name?: string; model?: string }) => m.id || m.name || m.model || '')
.filter((id: string) => typeof id === 'string' && id.trim().length > 0)
.sort();
return NextResponse.json({ models, source: modelsUrl });
} catch (error) {
const msg = error instanceof Error ? error.message : 'Failed to load models';
return NextResponse.json({ error: msg }, { status: 500 });
}
}

View File

@@ -0,0 +1,61 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getAuth } from '@/lib/auth-middleware';
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const auth = getAuth(_request);
if ('status' in auth) return auth;
try {
const { id } = await params;
const leadId = parseInt(id, 10);
if (isNaN(leadId)) {
return NextResponse.json({ error: 'Invalid lead ID' }, { status: 400 });
}
const lead = await db.lead.findUnique({ where: { id: leadId } });
if (!lead) {
return NextResponse.json({ error: 'Lead not found' }, { status: 404 });
}
// Активность лида = audit_log по admin_id (telegram_id)
const adminId = lead.telegramId;
if (!adminId) {
return NextResponse.json({ hourly: Array(24).fill(0), yearly: {}, total: 0 });
}
const logs = await db.auditLog.findMany({
where: { adminId },
select: { createdAt: true, action: true },
orderBy: { createdAt: 'asc' },
});
// Почасовая активность (0-23)
const hourly = Array(24).fill(0);
// Годовая активность: { "YYYY-MM-DD": count }
const yearly: Record<string, number> = {};
for (const log of logs) {
const d = new Date(log.createdAt);
hourly[d.getHours()] += 1;
const key = d.toISOString().slice(0, 10);
yearly[key] = (yearly[key] || 0) + 1;
}
return NextResponse.json({
hourly,
yearly,
total: logs.length,
actions: logs.reduce<Record<string, number>>((acc, l) => {
acc[l.action] = (acc[l.action] || 0) + 1;
return acc;
}, {}),
});
} catch (error) {
console.error('Lead activity API error:', error);
return NextResponse.json({ error: 'Failed to load activity' }, { status: 500 });
}
}

View File

@@ -0,0 +1,132 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getAuth } from '@/lib/auth-middleware';
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const auth = getAuth(_request);
if ('status' in auth) return auth;
try {
const { id } = await params;
const leadId = parseInt(id, 10);
if (isNaN(leadId)) {
return NextResponse.json({ error: 'Invalid lead ID' }, { status: 400 });
}
const lead = await db.lead.findUnique({
where: { id: leadId },
include: {
chatSessions: {
select: {
id: true,
sessionId: true,
isActive: true,
createdAt: true,
customerProfile: true,
},
orderBy: { createdAt: 'desc' },
},
},
});
if (!lead) {
return NextResponse.json({ error: 'Lead not found' }, { status: 404 });
}
// Связанный пользователь (users) — единая сущность по telegram_id:
// баланс, покупки, кошельки, страна/город, статус
let user: Awaited<ReturnType<typeof db.tgUser.findUnique>> | null = null;
if (lead.telegramId) {
user = await db.tgUser.findUnique({
where: { telegramId: lead.telegramId },
include: {
_count: { select: { wallets: true, purchases: true } },
purchases: {
take: 20,
orderBy: { purchaseDate: 'desc' },
include: { product: { select: { name: true } } },
},
wallets: {
select: { id: true, walletType: true, address: true, balance: true },
},
},
});
}
return NextResponse.json({ lead, user });
} catch (error) {
console.error('Lead GET error:', error);
return NextResponse.json({ error: 'Failed to load lead' }, { status: 500 });
}
}
export async function PUT(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const { id } = await params;
const leadId = parseInt(id, 10);
if (isNaN(leadId)) {
return NextResponse.json({ error: 'Invalid lead ID' }, { status: 400 });
}
const body = await request.json();
const { status, notes, customFields } = body;
const existing = await db.lead.findUnique({ where: { id: leadId } });
if (!existing) {
return NextResponse.json({ error: 'Lead not found' }, { status: 404 });
}
const validStatuses = ['new', 'contacted', 'qualified', 'lost', 'spam'];
const updateData: Record<string, unknown> = { updatedAt: new Date() };
if (status !== undefined) {
if (!validStatuses.includes(status)) {
return NextResponse.json(
{ error: `Status must be one of: ${validStatuses.join(', ')}` },
{ status: 400 },
);
}
updateData.status = status;
}
if (notes !== undefined) {
updateData.notes = notes;
}
if (customFields !== undefined) {
updateData.customFields =
typeof customFields === 'string' ? customFields : JSON.stringify(customFields);
}
const lead = await db.lead.update({
where: { id: leadId },
data: updateData,
});
// Audit log
await db.auditLog.create({
data: {
action: 'lead_update',
adminId: auth.role || 'unknown',
details: JSON.stringify({
leadId,
changes: body,
}),
},
});
return NextResponse.json({ lead });
} catch (error) {
console.error('Lead PUT error:', error);
return NextResponse.json({ error: 'Failed to update lead' }, { status: 500 });
}
}

View File

@@ -0,0 +1,67 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getAuth } from '@/lib/auth-middleware';
interface ChatMessage {
role: string;
content: string;
timestamp?: string;
}
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const auth = getAuth(_request);
if ('status' in auth) return auth;
try {
const { id } = await params;
const leadId = parseInt(id, 10);
if (isNaN(leadId)) {
return NextResponse.json({ error: 'Invalid lead ID' }, { status: 400 });
}
const lead = await db.lead.findUnique({ where: { id: leadId } });
if (!lead) {
return NextResponse.json({ error: 'Lead not found' }, { status: 404 });
}
const sessions = await db.chatSession.findMany({
where: { leadId },
orderBy: { createdAt: 'desc' },
});
// Parse messages JSON for each session
const sessionsWithMessages = sessions.map((session) => {
let messages: ChatMessage[] = [];
try {
messages = JSON.parse(session.messages);
} catch {
messages = [];
}
return {
id: session.id,
sessionId: session.sessionId,
telegramId: session.telegramId,
isActive: session.isActive,
operatorName: session.operatorName,
autoReplyDisabled: session.autoReplyDisabled,
operatorConnectedAt: session.operatorConnectedAt,
customerProfile: session.customerProfile,
device: session.device,
ip: session.ip,
country: session.country,
createdAt: session.createdAt,
updatedAt: session.updatedAt,
messages,
};
});
return NextResponse.json({ sessions: sessionsWithMessages });
} catch (error) {
console.error('Lead sessions GET error:', error);
return NextResponse.json({ error: 'Failed to load sessions' }, { status: 500 });
}
}

View File

@@ -0,0 +1,91 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getAuth } from '@/lib/auth-middleware';
import { Prisma } from '@prisma/client';
export async function GET(request: NextRequest) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const { searchParams } = request.nextUrl;
const search = searchParams.get('search') || '';
const statusParam = searchParams.get('status');
const page = Math.max(1, parseInt(searchParams.get('page') || '1', 10) || 1);
const limit = Math.min(100, Math.max(1, parseInt(searchParams.get('limit') || '50', 10) || 50));
const where: Prisma.LeadWhereInput = {};
if (search) {
where.OR = [
{ name: { contains: search } },
{ phone: { contains: search } },
{ email: { contains: search } },
{ telegram: { contains: search } },
{ telegramId: { contains: search } },
];
}
if (statusParam !== null && statusParam !== '') {
where.status = statusParam;
}
const [total, leads] = await Promise.all([
db.lead.count({ where }),
db.lead.findMany({
where,
select: {
_count: {
select: { chatSessions: true },
},
},
orderBy: { createdAt: 'desc' },
skip: (page - 1) * limit,
take: limit,
}),
]);
// Обогащаем лидов данными связанных пользователей (баланс, покупки, страна)
type LinkedUser = Prisma.TgUserGetPayload<{
select: {
id: true;
username: true;
totalBalance: true;
bonusBalance: true;
status: true;
country: true;
city: true;
_count: { select: { purchases: true } };
};
}> | null;
const enrichedLeads = await Promise.all(
leads.map(async (lead) => {
let user: LinkedUser = null;
if (lead.telegramId) {
user = await db.tgUser.findUnique({
where: { telegramId: lead.telegramId },
select: {
id: true,
username: true,
totalBalance: true,
bonusBalance: true,
status: true,
country: true,
city: true,
_count: { select: { purchases: true } },
},
});
}
return { ...lead, user };
}),
);
const totalPages = Math.max(1, Math.ceil(total / limit));
return NextResponse.json({ leads: enrichedLeads, total, page, totalPages });
} catch (error) {
console.error('Leads bulk API error:', error);
return NextResponse.json({ error: 'Failed to load leads' }, { status: 500 });
}
}

View File

@@ -0,0 +1,303 @@
import { NextRequest, NextResponse } from 'next/server';
import { getAuth } from '@/lib/auth-middleware';
const LOCALES: Record<string, Record<string, Record<string, string>>> = {
en: {
bot: {
start: 'Welcome to the shop! Use the menu below to navigate.',
help: '🆘 *Help*\n\nBrowse our catalog, add items to cart, and pay with crypto.\n\nUse the keyboard buttons below to get started.',
language_set: '✅ Language set to English.',
language_choose: '🌍 Choose your language:',
},
profile: {
title: '👤 *Your Profile*',
balance_main: '💰 Main Balance',
balance_bonus: '🎁 Bonus Balance',
registered: '📅 Registered',
location: '📍 Location',
language: '🌐 Language',
status_active: '✅ Active',
status_blocked: '🚫 Blocked',
status_deleted: '🗑 Deleted',
back: '🔙 Back',
},
products: {
title: '🛍 *Products*',
catalog: '📦 Catalog',
empty: 'No products available in this category.',
price: 'Price',
stock: 'In stock',
out_of_stock: 'Out of stock',
buy: '🛒 Buy',
unlimited: '♾ Unlimited',
photo_hidden: '🔒 Hidden content available after purchase',
add_to_cart: ' Add to Cart',
view_cart: '🛒 View Cart',
},
purchase: {
title: '🧾 *Purchase*',
confirm: 'Confirm purchase?',
quantity: 'Quantity',
total: 'Total',
currency_select: 'Select payment currency',
pay: '💳 Pay',
pending: '⏳ Pending',
completed: '✅ Completed',
cancelled: '❌ Cancelled',
history: '📜 Purchase History',
no_purchases: 'No purchases yet.',
tx_hash: 'TX Hash',
},
wallet: {
title: '👛 *Wallets*',
balance: 'Balance',
address: 'Address',
type: 'Type',
add_wallet: ' Add Wallet',
deposit: '💵 Deposit',
withdraw: '💸 Withdraw',
no_wallets: 'No wallets connected.',
copy_address: '📋 Copy Address',
copied: '✅ Address copied!',
},
location: {
title: '📍 *Location*',
choose_country: 'Choose your country:',
choose_city: 'Choose your city:',
choose_district: 'Choose your district:',
set_location: '📌 Set Location',
current: 'Current location',
update: '🔄 Update Location',
not_set: 'Location not set',
},
deletion: {
title: '⚠️ *Account Deletion*',
confirm: 'Are you sure you want to delete your account?',
warning: 'This action is irreversible. All your data, wallets, and purchase history will be permanently deleted.',
confirm_btn: '🗑 Delete My Account',
cancel: '❌ Cancel',
success: '✅ Account deleted successfully.',
error: '❌ Failed to delete account. Please try again.',
},
keyboard: {
catalog: '📦 Catalog',
cart: '🛒 Cart',
profile: '👤 Profile',
wallet: '👛 Wallet',
settings: '⚙ Settings',
help: '❓ Help',
back: '🔙 Back',
home: '🏠 Home',
next: '▶️ Next',
prev: '◀️ Prev',
cancel: '✖ Cancel',
confirm: '✅ Confirm',
},
},
es: {
bot: {
start: '¡Bienvenido a la tienda! Usa el menú de abajo para navegar.',
help: '🆘 *Ayuda*\n\nNavega por nuestro catálogo, añade artículos al carrito y paga con cripto.\n\nUsa los botones de abajo para comenzar.',
language_set: '✅ Idioma configurado a Español.',
language_choose: '🌍 Elige tu idioma:',
},
profile: {
title: '👤 *Tu Perfil*',
balance_main: '💰 Saldo Principal',
balance_bonus: '🎁 Saldo de Bonificación',
registered: '📅 Registrado',
location: '📍 Ubicación',
language: '🌐 Idioma',
status_active: '✅ Activo',
status_blocked: '🚫 Bloqueado',
status_deleted: '🗑 Eliminado',
back: '🔙 Volver',
},
products: {
title: '🛍 *Productos*',
catalog: '📦 Catálogo',
empty: 'No hay productos en esta categoría.',
price: 'Precio',
stock: 'En stock',
out_of_stock: 'Agotado',
buy: '🛒 Comprar',
unlimited: '♾ Ilimitado',
photo_hidden: '🔒 Contenido oculto disponible después de la compra',
add_to_cart: ' Añadir al Carrito',
view_cart: '🛒 Ver Carrito',
},
purchase: {
title: '🧾 *Compra*',
confirm: '¿Confirmar compra?',
quantity: 'Cantidad',
total: 'Total',
currency_select: 'Selecciona moneda de pago',
pay: '💳 Pagar',
pending: '⏳ Pendiente',
completed: '✅ Completado',
cancelled: '❌ Cancelado',
history: '📜 Historial de Compras',
no_purchases: 'Sin compras aún.',
tx_hash: 'Hash TX',
},
wallet: {
title: '👛 *Billeteras*',
balance: 'Saldo',
address: 'Dirección',
type: 'Tipo',
add_wallet: ' Añadir Billetera',
deposit: '💵 Depositar',
withdraw: '💸 Retirar',
no_wallets: 'Sin billeteras conectadas.',
copy_address: '📋 Copiar Dirección',
copied: '✅ ¡Dirección copiada!',
},
location: {
title: '📍 *Ubicación*',
choose_country: 'Elige tu país:',
choose_city: 'Elige tu ciudad:',
choose_district: 'Elige tu distrito:',
set_location: '📌 Establecer Ubicación',
current: 'Ubicación actual',
update: '🔄 Actualizar Ubicación',
not_set: 'Ubicación no establecida',
},
deletion: {
title: '⚠️ *Eliminación de Cuenta*',
confirm: '¿Estás seguro de que quieres eliminar tu cuenta?',
warning: 'Esta acción es irreversible. Todos tus datos, billeteras e historial de compras serán eliminados permanentemente.',
confirm_btn: '🗑 Eliminar Mi Cuenta',
cancel: '❌ Cancelar',
success: '✅ Cuenta eliminada exitosamente.',
error: '❌ Error al eliminar la cuenta. Inténtalo de nuevo.',
},
keyboard: {
catalog: '📦 Catálogo',
cart: '🛒 Carrito',
profile: '👤 Perfil',
wallet: '👛 Billetera',
settings: '⚙ Ajustes',
help: '❓ Ayuda',
back: '🔙 Volver',
home: '🏠 Inicio',
next: '▶️ Siguiente',
prev: '◀️ Anterior',
cancel: '✖ Cancelar',
confirm: '✅ Confirmar',
},
},
de: {
bot: {
start: 'Willkommen im Shop! Nutze das Menü unten zum Navigieren.',
help: '🆘 *Hilfe*\n\nDurchsuche unseren Katalog, füge Artikel zum Warenkorb hinzu und zahle mit Krypto.\n\nNutze die Tasten unten, um loszulegen.',
language_set: '✅ Sprache auf Deutsch eingestellt.',
language_choose: '🌍 Wähle deine Sprache:',
},
profile: {
title: '👤 *Dein Profil*',
balance_main: '💰 Hauptguthaben',
balance_bonus: '🎁 Bonusguthaben',
registered: '📅 Registriert am',
location: '📍 Standort',
language: '🌐 Sprache',
status_active: '✅ Aktiv',
status_blocked: '🚫 Gesperrt',
status_deleted: '🗑 Gelöscht',
back: '🔙 Zurück',
},
products: {
title: '🛍 *Produkte*',
catalog: '📦 Katalog',
empty: 'Keine Produkte in dieser Kategorie.',
price: 'Preis',
stock: 'Auf Lager',
out_of_stock: 'Ausverkauft',
buy: '🛒 Kaufen',
unlimited: '♾ Unbegrenzt',
photo_hidden: '🔒 Versteckter Inhalt nach dem Kauf verfügbar',
add_to_cart: ' In den Warenkorb',
view_cart: '🛒 Warenkorb ansehen',
},
purchase: {
title: '🧾 *Kauf*',
confirm: 'Kauf bestätigen?',
quantity: 'Menge',
total: 'Gesamt',
currency_select: 'Zahlungswährung wählen',
pay: '💳 Bezahlen',
pending: '⏳ Ausstehend',
completed: '✅ Abgeschlossen',
cancelled: '❌ Storniert',
history: '📜 Kaufhistorie',
no_purchases: 'Noch keine Käufe.',
tx_hash: 'TX Hash',
},
wallet: {
title: '👛 *Wallets*',
balance: 'Guthaben',
address: 'Adresse',
type: 'Typ',
add_wallet: ' Wallet hinzufügen',
deposit: '💵 Einzahlen',
withdraw: '💸 Auszahlen',
no_wallets: 'Keine Wallets verbunden.',
copy_address: '📋 Adresse kopieren',
copied: '✅ Adresse kopiert!',
},
location: {
title: '📍 *Standort*',
choose_country: 'Wähle dein Land:',
choose_city: 'Wähle deine Stadt:',
choose_district: 'Wähle deinen Bezirk:',
set_location: '📌 Standort festlegen',
current: 'Aktueller Standort',
update: '🔄 Standort aktualisieren',
not_set: 'Standort nicht festgelegt',
},
deletion: {
title: '⚠️ *Kontolöschung*',
confirm: 'Bist du sicher, dass du dein Konto löschen möchtest?',
warning: 'Diese Aktion ist irreversibel. Alle deine Daten, Wallets und Kaufhistorie werden dauerhaft gelöscht.',
confirm_btn: '🗑 Mein Konto löschen',
cancel: '❌ Abbrechen',
success: '✅ Konto erfolgreich gelöscht.',
error: '❌ Fehler beim Löschen des Kontos. Bitte versuche es erneut.',
},
keyboard: {
catalog: '📦 Katalog',
cart: '🛒 Warenkorb',
profile: '👤 Profil',
wallet: '👛 Wallet',
settings: '⚙ Einstellungen',
help: '❓ Hilfe',
back: '🔙 Zurück',
home: '🏠 Startseite',
next: '▶️ Weiter',
prev: '◀️ Zurück',
cancel: '✖ Abbrechen',
confirm: '✅ Bestätigen',
},
},
};
export async function GET(_request: NextRequest) {
const auth = getAuth(_request);
if ('status' in auth) return auth;
return NextResponse.json(LOCALES);
}
export async function PUT(request: NextRequest) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const body = await request.json();
const { lang, key, value } = body;
if (!lang || !key) {
return NextResponse.json({ error: 'Missing lang or key' }, { status: 400 });
}
return NextResponse.json({ ok: true });
} catch {
return NextResponse.json({ error: 'Invalid request' }, { status: 400 });
}
}

View File

@@ -0,0 +1,93 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getAuth } from '@/lib/auth-middleware';
export async function PUT(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const { id } = await params;
const body = await request.json();
const { country, city, district } = body;
const location = await db.location.update({
where: { id: +id },
data: {
...(country != null ? { country } : {}),
...(city != null ? { city } : {}),
...(district != null ? { district } : {}),
},
});
return NextResponse.json(location);
} catch (error: unknown) {
console.error('Location update API error:', error);
if (error && typeof error === 'object' && 'code' in error && (error as { code: string }).code === 'P2002') {
return NextResponse.json({ error: 'Location already exists' }, { status: 409 });
}
return NextResponse.json({ error: 'Failed to update location' }, { status: 500 });
}
}
export async function PATCH(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const auth = getAuth(_request);
if ('status' in auth) return auth;
try {
const { id } = await params;
const location = await db.location.findUnique({ where: { id: +id } });
if (!location) {
return NextResponse.json({ error: 'Location not found' }, { status: 404 });
}
const updated = await db.location.update({
where: { id: +id },
data: { isActive: location.isActive === 1 ? 0 : 1 },
});
return NextResponse.json(updated);
} catch (error) {
console.error('Location toggle API error:', error);
return NextResponse.json({ error: 'Failed to toggle location' }, { status: 500 });
}
}
export async function DELETE(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const auth = getAuth(_request);
if ('status' in auth) return auth;
try {
const { id } = await params;
const location = await db.location.findUnique({
where: { id: +id },
include: { _count: { select: { categories: true, products: true } } },
});
if (!location) {
return NextResponse.json({ error: 'Location not found' }, { status: 404 });
}
if (location._count.categories > 0 || location._count.products > 0) {
return NextResponse.json(
{ error: 'Cannot delete location with existing categories or products' },
{ status: 400 }
);
}
await db.location.delete({ where: { id: +id } });
return NextResponse.json({ ok: true });
} catch (error) {
console.error('Location delete API error:', error);
return NextResponse.json({ error: 'Failed to delete location' }, { status: 500 });
}
}

View File

@@ -0,0 +1,57 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getAuth } from '@/lib/auth-middleware';
import { ensureSortOrderColumns } from '@/lib/ensure-sort-order';
export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
await ensureSortOrderColumns();
const { id } = await params;
const body = await request.json();
const { direction } = body as { direction: 'up' | 'down' };
if (direction !== 'up' && direction !== 'down') {
return NextResponse.json({ error: 'direction must be "up" or "down"' }, { status: 400 });
}
const current = await db.location.findUnique({ where: { id: +id } });
if (!current) {
return NextResponse.json({ error: 'Location not found' }, { status: 404 });
}
// Find all locations in the same country+city, ordered by sort_order then name
const siblings = await db.location.findMany({
where: { country: current.country, city: current.city },
orderBy: [{ sortOrder: 'asc' }, { district: 'asc' }],
});
const idx = siblings.findIndex((l) => l.id === current.id);
if (idx === -1) {
return NextResponse.json({ error: 'Location not found in siblings' }, { status: 500 });
}
const swapIdx = direction === 'up' ? idx - 1 : idx + 1;
if (swapIdx < 0 || swapIdx >= siblings.length) {
return NextResponse.json({ ok: true, message: 'Already at boundary' });
}
const neighbor = siblings[swapIdx];
// Swap sort_order values
await db.$transaction([
db.location.update({ where: { id: current.id }, data: { sortOrder: neighbor.sortOrder } }),
db.location.update({ where: { id: neighbor.id }, data: { sortOrder: current.sortOrder } }),
]);
return NextResponse.json({ ok: true });
} catch (error) {
console.error('Location sort API error:', error);
return NextResponse.json({ error: 'Failed to sort location' }, { status: 500 });
}
}

View File

@@ -0,0 +1,53 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getAuth } from '@/lib/auth-middleware';
export async function GET(request: NextRequest) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const locations = await db.location.findMany({
orderBy: { id: 'desc' },
include: {
_count: {
select: { categories: true, products: true },
},
},
});
return NextResponse.json(locations);
} catch (error) {
console.error('Locations bulk API error:', error);
return NextResponse.json({ error: 'Failed to load locations' }, { status: 500 });
}
}
export async function POST(request: NextRequest) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const body = await request.json();
const { country, city, district } = body;
if (!country || !city) {
return NextResponse.json({ error: 'Missing required fields: country, city' }, { status: 400 });
}
const location = await db.location.create({
data: {
country,
city,
district: district || '',
},
});
return NextResponse.json(location, { status: 201 });
} catch (error: unknown) {
console.error('Location create API error:', error);
if (error && typeof error === 'object' && 'code' in error && (error as { code: string }).code === 'P2002') {
return NextResponse.json({ error: 'Location already exists' }, { status: 409 });
}
return NextResponse.json({ error: 'Failed to create location' }, { status: 500 });
}
}

View File

@@ -0,0 +1,50 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getAuth } from '@/lib/auth-middleware';
export async function DELETE(request: NextRequest) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const { searchParams } = new URL(request.url);
const country = searchParams.get('country');
const city = searchParams.get('city');
if (!country || !city) {
return NextResponse.json(
{ error: 'Missing required query params: country, city' },
{ status: 400 }
);
}
const locations = await db.location.findMany({
where: { country, city },
include: { _count: { select: { categories: true, products: true } } },
});
if (locations.length === 0) {
return NextResponse.json({ error: 'No locations found for this city' }, { status: 404 });
}
const totalCategories = locations.reduce((sum, l) => sum + l._count.categories, 0);
const totalProducts = locations.reduce((sum, l) => sum + l._count.products, 0);
if (totalCategories > 0 || totalProducts > 0) {
return NextResponse.json(
{
error: `Cannot delete city with existing categories (${totalCategories}) or products (${totalProducts})`,
},
{ status: 400 }
);
}
const ids = locations.map((l) => l.id);
await db.location.deleteMany({ where: { id: { in: ids } } });
return NextResponse.json({ ok: true, deleted: ids.length });
} catch (error) {
console.error('Delete city API error:', error);
return NextResponse.json({ error: 'Failed to delete city' }, { status: 500 });
}
}

View File

@@ -0,0 +1,41 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getAuth } from '@/lib/auth-middleware';
export async function PUT(request: NextRequest) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const body = await request.json();
const { country, oldCity, newCity } = body;
if (!country || !oldCity || !newCity) {
return NextResponse.json(
{ error: 'Missing required fields: country, oldCity, newCity' },
{ status: 400 }
);
}
const updated = await db.location.updateMany({
where: { country, city: oldCity },
data: { city: newCity },
});
return NextResponse.json({ ok: true, updated: updated.count });
} catch (error: unknown) {
console.error('Rename city API error:', error);
if (
error &&
typeof error === 'object' &&
'code' in error &&
(error as { code: string }).code === 'P2002'
) {
return NextResponse.json(
{ error: 'City already exists in this country' },
{ status: 409 }
);
}
return NextResponse.json({ error: 'Failed to rename city' }, { status: 500 });
}
}

View File

@@ -0,0 +1,91 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getAuth } from '@/lib/auth-middleware';
export async function POST(request: NextRequest) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const body = await request.json();
const { sessionId, action, operatorName } = body as {
sessionId: string;
action: 'connect' | 'disconnect';
operatorName: string;
};
if (!sessionId || !action || !operatorName) {
return NextResponse.json(
{ error: 'Missing sessionId, action, or operatorName' },
{ status: 400 },
);
}
if (action !== 'connect' && action !== 'disconnect') {
return NextResponse.json(
{ error: 'Action must be "connect" or "disconnect"' },
{ status: 400 },
);
}
const session = await db.chatSession.findUnique({ where: { sessionId } });
if (!session) {
return NextResponse.json({ error: 'Session not found' }, { status: 404 });
}
let updated;
if (action === 'connect') {
updated = await db.chatSession.update({
where: { sessionId },
data: {
autoReplyDisabled: true,
operatorName,
operatorConnectedAt: new Date(),
updatedAt: new Date(),
},
});
// Audit log
await db.auditLog.create({
data: {
action: 'operator_connect',
adminId: auth.role || 'unknown',
details: JSON.stringify({ sessionId, operatorName }),
},
});
} else {
updated = await db.chatSession.update({
where: { sessionId },
data: {
autoReplyDisabled: false,
operatorName: null,
operatorConnectedAt: null,
updatedAt: new Date(),
},
});
// Audit log
await db.auditLog.create({
data: {
action: 'operator_disconnect',
adminId: auth.role || 'unknown',
details: JSON.stringify({ sessionId }),
},
});
}
return NextResponse.json({
ok: true,
session: {
sessionId: updated.sessionId,
autoReplyDisabled: updated.autoReplyDisabled,
operatorName: updated.operatorName,
operatorConnectedAt: updated.operatorConnectedAt,
},
});
} catch (error) {
console.error('Operator API error:', error);
return NextResponse.json({ error: 'Failed to process operator action' }, { status: 500 });
}
}

View File

@@ -0,0 +1,48 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getAuth } from '@/lib/auth-middleware';
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const { id } = await params;
const productId = +id;
const original = await db.product.findUnique({ where: { id: productId } });
if (!original) {
return NextResponse.json({ error: 'Product not found' }, { status: 404 });
}
const cloned = await db.product.create({
data: {
locationId: original.locationId,
categoryId: original.categoryId,
subcategoryId: original.subcategoryId,
name: `${original.name} (Copy)`,
description: original.description,
privateData: original.privateData,
price: original.price,
quantityInStock: original.quantityInStock,
photoUrl: original.photoUrl,
hiddenPhotoUrl: original.hiddenPhotoUrl,
hiddenCoordinates: original.hiddenCoordinates,
hiddenDescription: original.hiddenDescription,
isMono: original.isMono,
},
include: {
category: { select: { id: true, name: true } },
subcategory: { select: { id: true, name: true } },
},
});
return NextResponse.json(cloned);
} catch (error) {
console.error('Product clone API error:', error);
return NextResponse.json({ error: 'Failed to clone product' }, { status: 500 });
}
}

View File

@@ -0,0 +1,126 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getAuth } from '@/lib/auth-middleware';
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const auth = getAuth(_request);
if ('status' in auth) return auth;
try {
const { id } = await params;
const product = await db.product.findUnique({
where: { id: +id },
include: {
category: true,
subcategory: true,
location: true,
},
});
if (!product) {
return NextResponse.json({ error: 'Product not found' }, { status: 404 });
}
return NextResponse.json(product);
} catch (error) {
console.error('Product detail API error:', error);
return NextResponse.json({ error: 'Failed to load product' }, { status: 500 });
}
}
export async function PUT(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const { id } = await params;
const existing = await db.product.findUnique({ where: { id: +id } });
if (!existing) {
return NextResponse.json({ error: 'Product not found' }, { status: 404 });
}
const body = await request.json();
const {
locationId,
categoryId,
subcategoryId,
name,
description,
privateData,
price,
quantityInStock,
photoUrl,
hiddenPhotoUrl,
hiddenCoordinates,
hiddenDescription,
isMono,
} = body;
const isMonoFlag = isMono === 1 || isMono === true ? 1 : 0;
const finalStock = isMonoFlag ? 999999 : (quantityInStock ?? existing.quantityInStock);
const product = await db.product.update({
where: { id: +id },
data: {
...(locationId != null ? { locationId: +locationId } : {}),
...(categoryId != null ? { categoryId: +categoryId } : {}),
subcategoryId: subcategoryId ? +subcategoryId : null,
...(name != null ? { name } : {}),
description: description != null ? description : existing.description,
privateData: privateData != null ? privateData : existing.privateData,
...(price != null ? { price: +price } : {}),
quantityInStock: finalStock,
photoUrl: photoUrl != null ? photoUrl : existing.photoUrl,
hiddenPhotoUrl: hiddenPhotoUrl != null ? hiddenPhotoUrl : existing.hiddenPhotoUrl,
hiddenCoordinates: hiddenCoordinates != null ? hiddenCoordinates : existing.hiddenCoordinates,
hiddenDescription: hiddenDescription != null ? hiddenDescription : existing.hiddenDescription,
isMono: isMonoFlag,
},
include: {
category: { select: { id: true, name: true } },
subcategory: { select: { id: true, name: true } },
location: { select: { id: true, country: true, city: true, district: true } },
},
});
return NextResponse.json(product);
} catch (error) {
console.error('Product update API error:', error);
return NextResponse.json({ error: 'Failed to update product' }, { status: 500 });
}
}
export async function DELETE(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const auth = getAuth(_request);
if ('status' in auth) return auth;
try {
const { id } = await params;
const productId = +id;
const purchaseCount = await db.purchase.count({
where: { productId },
});
if (purchaseCount > 0) {
return NextResponse.json(
{ error: `Cannot delete product with ${purchaseCount} existing purchase(s). Cancel or delete purchases first.` },
{ status: 400 }
);
}
await db.product.delete({ where: { id: productId } });
return NextResponse.json({ ok: true });
} catch (error) {
console.error('Product delete API error:', error);
return NextResponse.json({ error: 'Failed to delete product' }, { status: 500 });
}
}

View File

@@ -0,0 +1,63 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getAuth } from '@/lib/auth-middleware';
export async function POST(request: NextRequest) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const body = await request.json();
const {
locationId,
categoryId,
subcategoryId,
name,
description,
privateData,
price,
quantityInStock,
photoUrl,
hiddenPhotoUrl,
hiddenCoordinates,
hiddenDescription,
isMono,
} = body;
if (!locationId || !categoryId || !name || price == null) {
return NextResponse.json({ error: 'Missing required fields: locationId, categoryId, name, price' }, { status: 400 });
}
const isMonoFlag = isMono === 1 || isMono === true ? 1 : 0;
const finalStock = isMonoFlag ? 999999 : (quantityInStock || 0);
const product = await db.product.create({
data: {
locationId: +locationId,
categoryId: +categoryId,
subcategoryId: subcategoryId ? +subcategoryId : null,
name,
description: description || null,
privateData: privateData || null,
price: +price,
quantityInStock: finalStock,
photoUrl: photoUrl || null,
hiddenPhotoUrl: hiddenPhotoUrl || null,
hiddenCoordinates: hiddenCoordinates || null,
hiddenDescription: hiddenDescription || null,
isMono: isMonoFlag,
},
include: {
category: { select: { id: true, name: true } },
subcategory: { select: { id: true, name: true } },
location: { select: { id: true, country: true, city: true, district: true } },
},
});
return NextResponse.json(product, { status: 201 });
} catch (error: unknown) {
console.error('Product add API error:', error);
const msg = error instanceof Error ? error.message : 'Failed to create product';
return NextResponse.json({ error: msg }, { status: 500 });
}
}

View File

@@ -0,0 +1,59 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getAuth } from '@/lib/auth-middleware';
import { Prisma } from '@prisma/client';
export async function GET(request: NextRequest) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const { searchParams } = request.nextUrl;
const loc = searchParams.get('loc');
const cat = searchParams.get('cat');
const sub = searchParams.get('sub');
const search = searchParams.get('search') || '';
const page = Math.max(1, parseInt(searchParams.get('page') || '1', 10) || 1);
const limit = Math.min(100, Math.max(1, parseInt(searchParams.get('limit') || '50', 10) || 50));
const where: Prisma.ProductWhereInput = {};
if (loc) where.locationId = +loc;
if (cat) where.categoryId = +cat;
if (sub) where.subcategoryId = +sub;
if (search) {
where.name = { contains: search };
}
const [total, data] = await Promise.all([
db.product.count({ where }),
db.product.findMany({
where,
select: {
id: true,
name: true,
description: true,
privateData: true,
price: true,
quantityInStock: true,
photoUrl: true,
hiddenPhotoUrl: true,
hiddenCoordinates: true,
hiddenDescription: true,
isMono: true,
createdAt: true,
category: { select: { id: true, name: true } },
subcategory: { select: { id: true, name: true } },
location: { select: { id: true, country: true, city: true, district: true } },
},
orderBy: { id: 'desc' },
skip: (page - 1) * limit,
take: limit,
}),
]);
return NextResponse.json({ data, total, page, limit });
} catch (error) {
console.error('Products bulk API error:', error);
return NextResponse.json({ error: 'Failed to load products' }, { status: 500 });
}
}

View File

@@ -0,0 +1,77 @@
import { NextRequest, NextResponse } from 'next/server';
import { getAuth } from '@/lib/auth-middleware';
import { db } from '@/lib/db';
const VALID_STATUSES = ['completed', 'cancelled'] as const;
type ValidStatus = (typeof VALID_STATUSES)[number];
function isValidStatus(value: string): value is ValidStatus {
return (VALID_STATUSES as readonly string[]).includes(value);
}
export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const { id } = await params;
const purchaseId = parseInt(id, 10);
if (isNaN(purchaseId)) {
return NextResponse.json({ error: 'Invalid purchase ID' }, { status: 400 });
}
const body = await request.json();
const { status } = body as { status?: string };
if (!status || !isValidStatus(status)) {
return NextResponse.json(
{ error: 'Invalid status. Must be "completed" or "cancelled".' },
{ status: 400 }
);
}
const oldPurchase = await db.purchase.findUnique({
where: { id: purchaseId },
include: { product: { select: { name: true } } },
});
if (!oldPurchase) {
return NextResponse.json({ error: 'Purchase not found' }, { status: 404 });
}
if (oldPurchase.status !== 'pending') {
return NextResponse.json(
{ error: 'Only pending purchases can be updated' },
{ status: 400 }
);
}
await db.purchase.update({
where: { id: purchaseId },
data: { status },
});
await db.auditLog.create({
data: {
action: 'purchase_status_change',
adminId: auth.role,
details: JSON.stringify({
purchaseId,
oldStatus: oldPurchase.status,
newStatus: status,
productName: oldPurchase.product.name,
}),
},
});
return NextResponse.json({ ok: true });
} catch (error) {
console.error('Purchase status update error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}

View File

@@ -0,0 +1,36 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getAuth } from '@/lib/auth-middleware';
export async function POST(request: NextRequest) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const body = await request.json();
const { purchaseIds, status } = body as { purchaseIds: number[]; status: 'completed' | 'cancelled' };
if (!Array.isArray(purchaseIds) || purchaseIds.length === 0) {
return NextResponse.json({ error: 'purchaseIds must be a non-empty array' }, { status: 400 });
}
if (status !== 'completed' && status !== 'cancelled') {
return NextResponse.json({ error: 'status must be "completed" or "cancelled"' }, { status: 400 });
}
const result = await db.purchase.updateMany({
where: {
id: { in: purchaseIds },
status: 'pending',
},
data: { status },
});
return NextResponse.json({
updated: result.count,
message: `${result.count} purchase(s) ${status === 'completed' ? 'approved' : 'cancelled'}`,
});
} catch (error) {
console.error('Batch purchase status update error:', error);
return NextResponse.json({ error: 'Failed to update purchase statuses' }, { status: 500 });
}
}

View File

@@ -0,0 +1,62 @@
import { NextRequest, NextResponse } from 'next/server';
import { getAuth } from '@/lib/auth-middleware';
import { db } from '@/lib/db';
import { Prisma } from '@prisma/client';
export async function GET(request: NextRequest) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const { searchParams } = new URL(request.url);
const status = searchParams.get('status') || '';
const from = searchParams.get('from');
const to = searchParams.get('to');
const page = Math.max(1, Number(searchParams.get('page')) || 1);
const limit = Math.min(100, Math.max(1, Number(searchParams.get('limit')) || 50));
const conditions: Prisma.PurchaseWhereInput[] = [];
if (status) conditions.push({ status });
if (from) conditions.push({ purchaseDate: { gte: new Date(from) } });
if (to) conditions.push({ purchaseDate: { lte: new Date(to + 'T23:59:59.999Z') } });
const where = conditions.length > 0 ? { AND: conditions } : undefined;
const [data, total] = await Promise.all([
db.purchase.findMany({
where,
select: {
id: true,
userId: true,
productId: true,
walletType: true,
txHash: true,
quantity: true,
totalPrice: true,
purchaseDate: true,
status: true,
user: {
select: {
username: true,
telegramId: true,
},
},
product: {
select: {
name: true,
},
},
},
orderBy: { id: 'desc' },
skip: (page - 1) * limit,
take: limit,
}),
db.purchase.count({ where }),
]);
return NextResponse.json({ data, total, page, limit });
} catch (error) {
console.error('Purchases bulk error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}

View File

@@ -0,0 +1,5 @@
import { NextResponse } from "next/server";
export async function GET() {
return NextResponse.json({ message: "Hello, world!" });
}

View File

@@ -0,0 +1,58 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { verifyReAuth } from '@/lib/auth';
export async function POST(request: NextRequest) {
const body = await request.json();
const { reauthToken } = body;
if (!reauthToken || !verifyReAuth(reauthToken)) {
return NextResponse.json({ error: 'Invalid reauth token' }, { status: 403 });
}
try {
// Create audit log BEFORE deleting
try {
await db.auditLog.create({
data: {
action: 'clear_all',
adminId: 'system',
details: JSON.stringify({ message: 'Clearing all data' }),
},
});
} catch {
// ignore
}
// Delete all data in correct order
await db.purchase.deleteMany();
await db.transaction.deleteMany();
await db.cryptoWallet.deleteMany();
await db.auditLog.deleteMany();
await db.userState.deleteMany();
await db.product.deleteMany();
await db.subcategory.deleteMany();
await db.category.deleteMany();
await db.commissionPayment.deleteMany();
await db.tgUser.deleteMany();
await db.location.deleteMany();
// Reset autoincrement
const tables = [
'purchases', 'transactions', 'crypto_wallets', 'audit_log', 'user_states',
'products', 'subcategories', 'categories', 'commission_payments',
'users', 'locations',
];
for (const t of tables) {
try {
await db.$executeRawUnsafe(`DELETE FROM sqlite_sequence WHERE name='${t}';`);
} catch {
// ignore
}
}
return NextResponse.json({ ok: true });
} catch (error) {
console.error('Seed clear error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}

View File

@@ -0,0 +1,16 @@
import { NextRequest, NextResponse } from 'next/server';
import { getAuth } from '@/lib/auth-middleware';
import { db } from '@/lib/db';
export async function GET(_request: NextRequest) {
const auth = getAuth(_request);
if ('status' in auth) return auth;
try {
const count = await db.tgUser.count();
return NextResponse.json({ seeded: count > 0 });
} catch (error) {
console.error('Seed data check error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}

View File

@@ -0,0 +1,319 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { verifyReAuth } from '@/lib/auth';
function daysAgo(n: number) {
return new Date(Date.now() - n * 86400000);
}
function randInt(min: number, max: number) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function randFloat(min: number, max: number, decimals: number) {
return parseFloat((Math.random() * (max - min) + min).toFixed(decimals));
}
function pick<T>(arr: T[]): T {
return arr[Math.floor(Math.random() * arr.length)];
}
function seededShuffle<T>(arr: T[]): T[] {
const result = [...arr];
for (let i = result.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[result[i], result[j]] = [result[j], result[i]];
}
return result;
}
export async function POST(request: NextRequest) {
const body = await request.json();
const { reauthToken } = body;
if (!reauthToken || !verifyReAuth(reauthToken)) {
return NextResponse.json({ error: 'Invalid reauth token' }, { status: 403 });
}
try {
// Create audit log entry before clearing
try {
await db.auditLog.create({
data: {
action: 'seed_demo',
adminId: 'system',
details: JSON.stringify({ message: 'Seeding demo data — original Telegram Shop structure' }),
},
});
} catch {
// ignore if table doesn't exist yet
}
// ── Clear all tables in correct FK order ──
const tableOrder = [
'purchase', 'transaction', 'cryptoWallet', 'auditLog', 'userState',
'product', 'subcategory', 'category', 'commissionPayment',
];
for (const model of tableOrder) {
await (db as unknown as Record<string, { deleteMany: () => Promise<unknown> }>)[model].deleteMany();
}
await db.tgUser.deleteMany();
await db.location.deleteMany();
// Reset autoincrement via raw SQL (SQLite)
const tables = [
'purchases', 'transactions', 'crypto_wallets', 'audit_log', 'user_states',
'products', 'subcategories', 'categories', 'users', 'locations', 'commission_payments',
];
for (const t of tables) {
try {
await db.$executeRawUnsafe(`DELETE FROM sqlite_sequence WHERE name='${t}';`);
} catch {
// ignore
}
}
// ──────────────────────────────────────
// LOCATIONS (3)
// ──────────────────────────────────────
const locMoscow = await db.location.create({
data: { country: 'Russia', city: 'Moscow', district: 'Center' },
});
const locSPb = await db.location.create({
data: { country: 'Russia', city: 'Saint Petersburg', district: 'North' },
});
const locBerlin = await db.location.create({
data: { country: 'Germany', city: 'Berlin', district: 'Mitte' },
});
// ──────────────────────────────────────
// CATEGORIES (5)
// ──────────────────────────────────────
const catDigital = await db.category.create({
data: { name: 'Digital', locationId: locMoscow.id },
});
const catPhysical = await db.category.create({
data: { name: 'Physical', locationId: locMoscow.id },
});
const catPremium = await db.category.create({
data: { name: 'Premium', locationId: locSPb.id },
});
const catVIP = await db.category.create({
data: { name: 'VIP', locationId: locSPb.id },
});
const catStandard = await db.category.create({
data: { name: 'Standard', locationId: locBerlin.id },
});
// ──────────────────────────────────────
// SUBCATEGORIES (10)
// ──────────────────────────────────────
const subVPN = await db.subcategory.create({ data: { name: 'VPN', categoryId: catDigital.id } });
const subAccounts = await db.subcategory.create({ data: { name: 'Accounts', categoryId: catDigital.id } });
const subSoftware = await db.subcategory.create({ data: { name: 'Software', categoryId: catDigital.id } });
const subHardware = await db.subcategory.create({ data: { name: 'Hardware', categoryId: catPhysical.id } });
const subAccessories = await db.subcategory.create({ data: { name: 'Accessories', categoryId: catPhysical.id } });
const subAnnual = await db.subcategory.create({ data: { name: 'Annual', categoryId: catPremium.id } });
const subMonthly = await db.subcategory.create({ data: { name: 'Monthly', categoryId: catPremium.id } });
const subLifetime = await db.subcategory.create({ data: { name: 'Lifetime', categoryId: catVIP.id } });
const subExpress = await db.subcategory.create({ data: { name: 'Express', categoryId: catVIP.id } });
const subBasic = await db.subcategory.create({ data: { name: 'Basic', categoryId: catStandard.id } });
const subStarter = await db.subcategory.create({ data: { name: 'Starter', categoryId: catStandard.id } });
// ──────────────────────────────────────
// USERS (10) — spread created_at across last 30 days
// ──────────────────────────────────────
const userData = [
{ username: 'alice', telegramId: '1001', country: 'Russia', city: 'Moscow', district: 'Center', totalBalance: 150.00, bonusBalance: 25.00, daysAgo: 28 },
{ username: 'bob', telegramId: '1002', country: 'Russia', city: 'Moscow', district: 'Center', totalBalance: 85.50, bonusBalance: 10.00, daysAgo: 25 },
{ username: 'charlie', telegramId: '1003', country: 'Russia', city: 'Saint Petersburg', district: 'North', totalBalance: 320.75, bonusBalance: 50.00, daysAgo: 22 },
{ username: 'diana', telegramId: '1004', country: 'Germany', city: 'Berlin', district: 'Mitte', totalBalance: 45.00, bonusBalance: 5.00, daysAgo: 20 },
{ username: 'evan', telegramId: '1005', country: 'Germany', city: 'Berlin', district: 'Mitte', totalBalance: 0.00, bonusBalance: 0.00, daysAgo: 18 },
{ username: 'frank', telegramId: '1006', country: 'Russia', city: 'Moscow', district: 'Center', totalBalance: 210.00, bonusBalance: 30.00, daysAgo: 15 },
{ username: 'grace', telegramId: '1007', country: 'Russia', city: 'Saint Petersburg', district: 'North', totalBalance: 75.25, bonusBalance: 15.00, daysAgo: 12 },
{ username: 'henry', telegramId: '1008', country: 'Germany', city: 'Berlin', district: 'Mitte', totalBalance: 500.00, bonusBalance: 100.00, daysAgo: 9 },
{ username: 'iris', telegramId: '1009', country: 'Russia', city: 'Moscow', district: 'Center', totalBalance: 0.00, bonusBalance: 0.00, daysAgo: 5 },
{ username: 'jack', telegramId: '1010', country: 'Germany', city: 'Berlin', district: 'Mitte', totalBalance: 33.00, bonusBalance: 5.00, daysAgo: 2 },
];
const users = [];
for (const u of userData) {
const user = await db.tgUser.create({
data: {
telegramId: u.telegramId,
username: u.username,
country: u.country,
city: u.city,
district: u.district,
totalBalance: u.totalBalance,
bonusBalance: u.bonusBalance,
createdAt: daysAgo(u.daysAgo),
},
});
users.push(user);
}
// Lookup map for user references
const userMap = new Map(users.map((u) => [u.username, u]));
// ──────────────────────────────────────
// PRODUCTS (10)
// ──────────────────────────────────────
const productsData = [
{ name: 'VPN Subscription 30d', price: 9.99, stock: 100, locationId: locMoscow.id, categoryId: catDigital.id, subcategoryId: subVPN.id },
{ name: 'VPN Subscription 90d', price: 24.99, stock: 50, locationId: locMoscow.id, categoryId: catDigital.id, subcategoryId: subAccounts.id },
{ name: 'USB Drive 64GB', price: 29.99, stock: 25, locationId: locMoscow.id, categoryId: catPhysical.id, subcategoryId: subHardware.id },
{ name: 'Premium Account 1 Year', price: 99.99, stock: 10, locationId: locSPb.id, categoryId: catPremium.id, subcategoryId: subAnnual.id },
{ name: 'VIP Access Lifetime', price: 199.99, stock: 5, locationId: locSPb.id, categoryId: catVIP.id, subcategoryId: subLifetime.id },
{ name: 'Premium Account 6 Months', price: 59.99, stock: 20, locationId: locSPb.id, categoryId: catPremium.id, subcategoryId: subMonthly.id },
{ name: 'Standard Package', price: 14.99, stock: 200, locationId: locBerlin.id, categoryId: catStandard.id, subcategoryId: subBasic.id },
{ name: 'Security Toolkit', price: 49.99, stock: 30, locationId: locMoscow.id, categoryId: catDigital.id, subcategoryId: subSoftware.id },
{ name: 'VIP Express Pass', price: 39.99, stock: 15, locationId: locSPb.id, categoryId: catVIP.id, subcategoryId: subExpress.id },
{ name: 'Starter Kit', price: 4.99, stock: 500, locationId: locBerlin.id, categoryId: catStandard.id, subcategoryId: subStarter.id },
];
const products = [];
for (const p of productsData) {
const product = await db.product.create({
data: {
name: p.name,
price: p.price,
quantityInStock: p.stock,
locationId: p.locationId,
categoryId: p.categoryId,
subcategoryId: p.subcategoryId,
},
});
products.push(product);
}
// ──────────────────────────────────────
// PURCHASES (25-30) — 70% completed, 20% pending, 10% cancelled
// ──────────────────────────────────────
const purchaseCount = randInt(25, 30);
const walletTypes = ['BTC', 'ETH', 'LTC', 'USDT', 'USDC'];
const statuses: string[] = [];
for (let i = 0; i < purchaseCount; i++) {
const r = Math.random();
if (r < 0.7) statuses.push('completed');
else if (r < 0.9) statuses.push('pending');
else statuses.push('cancelled');
}
const shuffledUsers = seededShuffle(users);
const shuffledProducts = seededShuffle(products);
for (let i = 0; i < purchaseCount; i++) {
const user = shuffledUsers[i % shuffledUsers.length];
const product = shuffledProducts[i % shuffledProducts.length];
const qty = randInt(1, 3);
const purchaseDate = daysAgo(randInt(0, 29));
const wType = pick(walletTypes);
const txHash = statuses[i] === 'completed'
? `0x${Array.from({ length: 64 }, () => randInt(0, 15).toString(16)).join('')}`
: null;
await db.purchase.create({
data: {
userId: user.id,
productId: product.id,
quantity: qty,
totalPrice: parseFloat((product.price * qty).toFixed(2)),
walletType: wType,
txHash,
purchaseDate,
status: statuses[i],
},
});
}
// ──────────────────────────────────────
// CRYPTO WALLETS (10) — exact user/type assignments
// ──────────────────────────────────────
const walletAssignments = [
{ username: 'alice', type: 'BTC' },
{ username: 'alice', type: 'ETH' },
{ username: 'bob', type: 'BTC' },
{ username: 'charlie', type: 'LTC' },
{ username: 'diana', type: 'ETH' },
{ username: 'frank', type: 'XRP' },
{ username: 'grace', type: 'BCH' },
{ username: 'henry', type: 'DOGE' },
{ username: 'iris', type: 'BTC' },
{ username: 'jack', type: 'USDT' },
];
for (const w of walletAssignments) {
const user = userMap.get(w.username)!;
const addr = `0x${Array.from({ length: 40 }, () => randInt(0, 15).toString(16)).join('')}`;
await db.cryptoWallet.create({
data: {
userId: user.id,
walletType: w.type,
address: addr,
balance: randFloat(0.001, 5.0, 8),
},
});
}
// ──────────────────────────────────────
// COMMISSION PAYMENTS (2)
// ──────────────────────────────────────
await db.commissionPayment.create({
data: {
totalBalanceUsd: 4825.50,
commissionRate: 0.05,
commissionAmountUsd: 241.28,
paidAmountUsd: 200.00,
walletCount: 8,
note: 'Monthly commission payment — June',
createdAt: daysAgo(15),
},
});
await db.commissionPayment.create({
data: {
totalBalanceUsd: 5310.75,
commissionRate: 0.05,
commissionAmountUsd: 265.54,
paidAmountUsd: 241.28,
walletCount: 10,
note: 'Monthly commission payment — July',
createdAt: daysAgo(3),
},
});
// ──────────────────────────────────────
// AUDIT LOG (12 entries matching original project)
// ──────────────────────────────────────
const auditEntries = [
{ action: 'login', adminId: 'admin_1', details: JSON.stringify({ ip: '192.168.1.1', method: 'password' }), daysAgo: 30 },
{ action: 'seed_demo', adminId: 'admin_1', details: JSON.stringify({ message: 'Initial seed' }), daysAgo: 29 },
{ action: 'login', adminId: 'admin_2', details: JSON.stringify({ ip: '10.0.0.5', method: 'password' }), daysAgo: 27 },
{ action: 'balance_adjust', adminId: 'admin_1', details: JSON.stringify({ userId: 1, field: 'total_balance', old: 0, new: 150.00, reason: 'deposit' }), daysAgo: 25 },
{ action: 'status_toggle', adminId: 'admin_2', details: JSON.stringify({ userId: 5, oldStatus: 0, newStatus: 2 }), daysAgo: 22 },
{ action: 'login', adminId: 'admin_1', details: JSON.stringify({ ip: '172.16.0.1', method: 'token' }), daysAgo: 20 },
{ action: 'balance_adjust', adminId: 'admin_1', details: JSON.stringify({ userId: 3, field: 'bonus_balance', old: 25.00, new: 50.00, reason: 'bonus' }), daysAgo: 18 },
{ action: 'seed_phrase_viewed', adminId: 'admin_1', details: JSON.stringify({ walletCount: 10 }), daysAgo: 15 },
{ action: 'login', adminId: 'admin_2', details: JSON.stringify({ ip: '192.168.1.50', method: 'password' }), daysAgo: 12 },
{ action: 'csv_seed_export', adminId: 'admin_1', details: JSON.stringify({ walletCount: 10, filename: 'seeds_export.csv' }), daysAgo: 10 },
{ action: 'balance_adjust', adminId: 'admin_2', details: JSON.stringify({ userId: 8, field: 'total_balance', old: 300.00, new: 500.00, reason: 'deposit' }), daysAgo: 7 },
{ action: 'status_toggle', adminId: 'admin_1', details: JSON.stringify({ userId: 9, oldStatus: 0, newStatus: 2 }), daysAgo: 4 },
];
for (const entry of auditEntries) {
await db.auditLog.create({
data: {
action: entry.action,
adminId: entry.adminId,
details: entry.details,
createdAt: daysAgo(entry.daysAgo),
},
});
}
return NextResponse.json({ ok: true });
} catch (error) {
console.error('Seed demo error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}

View File

@@ -0,0 +1,56 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getAuth } from '@/lib/auth-middleware';
export async function GET(request: NextRequest) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const [
users,
wallets,
purchases,
categories,
subcategories,
locations,
products,
auditLogs,
commissionPayments,
userStates,
] = await Promise.all([
db.tgUser.findMany(),
db.cryptoWallet.findMany(),
db.purchase.findMany(),
db.category.findMany(),
db.subcategory.findMany(),
db.location.findMany(),
db.product.findMany(),
db.auditLog.findMany(),
db.commissionPayment.findMany(),
db.userState.findMany(),
]);
const exportData = {
exportedAt: new Date().toISOString(),
version: 1,
data: {
users,
wallets,
purchases,
categories,
subcategories,
locations,
products,
auditLogs,
commissionPayments,
userStates,
},
};
return NextResponse.json(exportData);
} catch (error) {
console.error('Export API error:', error);
return NextResponse.json({ error: 'Failed to export data' }, { status: 500 });
}
}

View File

@@ -0,0 +1,14 @@
import { NextRequest, NextResponse } from 'next/server';
import { requireSuperAuth } from '@/lib/auth-middleware';
export async function POST(request: NextRequest) {
const auth = requireSuperAuth(request);
if ('status' in auth) return auth;
try {
const _body = await request.json();
return NextResponse.json({ ok: true, message: 'Import not yet implemented' });
} catch {
return NextResponse.json({ error: 'Invalid request body' }, { status: 400 });
}
}

View File

@@ -0,0 +1,94 @@
import { NextRequest, NextResponse } from 'next/server';
import { getAuth } from '@/lib/auth-middleware';
// Настройки бота из env (прокинуты через docker-compose).
// Значения секретов маскируются на фронте; reveal-эндпоинт отдаёт их только авторизованному админу.
function readSettings(): Record<string, string | boolean> {
return {
BOT_TOKEN: process.env.BOT_TOKEN || '',
SUPPORT_LINK: process.env.SUPPORT_LINK || '',
ADMIN_IDS: process.env.ADMIN_IDS || '',
SUPER_ADMIN_IDS: process.env.SUPER_ADMIN_IDS || '',
WG_ENABLED: process.env.WG_ENABLED === 'true',
WG_ENDPOINT: process.env.WG_ENDPOINT || '',
WG_ADDRESS: process.env.WG_ADDRESS || '',
WG_PUBLIC_KEY: process.env.WG_PUBLIC_KEY || '',
WG_DNS: process.env.WG_DNS || '',
ADMIN_PORT: process.env.ADMIN_PORT || '3000',
ADMIN_URL: process.env.ADMIN_URL || '',
CATALOG_PATH: process.env.CATALOG_PATH || '/catalog',
GITEA_API_URL: process.env.GITEA_API_URL || '',
};
}
// Ключи, которые маскируются в UI (просмотр только через глазик)
const MASKED = ['BOT_TOKEN', 'ADMIN_SECRET', 'GITEA_TOKEN', 'WG_PRIVATE_KEY', 'WG_PRESHARED_KEY', 'ENCRYPTION_KEY', 'SUPER_ADMIN_IDS', 'ADMIN_IDS'];
// Реальные значения секретов (для глазика) — доступны админу
function readSecrets(): Record<string, string> {
return {
BOT_TOKEN: process.env.BOT_TOKEN || '',
ADMIN_SECRET: process.env.ADMIN_SECRET || '',
SUPER_ADMIN_SECRET: process.env.SUPER_ADMIN_SECRET || '',
GITEA_TOKEN: process.env.GITEA_TOKEN || '',
ENCRYPTION_KEY: process.env.ENCRYPTION_KEY || '',
WG_PRIVATE_KEY: process.env.WG_PRIVATE_KEY || '',
WG_PRESHARED_KEY: process.env.WG_PRESHARED_KEY || '',
};
}
export async function GET(_request: NextRequest) {
const auth = getAuth(_request);
if ('status' in auth) return auth;
return NextResponse.json({ ...readSettings(), _masked: MASKED });
}
// Показать реальное значение секрета по ключу (для кнопки-глазика)
export async function POST(request: NextRequest) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const body = await request.json();
const { key } = body;
if (!key) {
return NextResponse.json({ error: 'Missing key' }, { status: 400 });
}
const secrets = readSecrets();
if (key in secrets) {
return NextResponse.json({ key, value: secrets[key] });
}
// Несекретные ключи — из обычных настроек
const settings = readSettings();
if (key in settings) {
return NextResponse.json({ key, value: settings[key] });
}
return NextResponse.json({ error: 'Unknown key' }, { status: 400 });
} catch {
return NextResponse.json({ error: 'Invalid request' }, { status: 400 });
}
}
export async function PUT(request: NextRequest) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const body = await request.json();
const { key, value } = body;
if (!key) {
return NextResponse.json({ error: 'Missing key' }, { status: 400 });
}
// В контейнере env read-only — фиксируем, что сохранение требует рестарта с новым env
const settings = readSettings();
if (key in settings || key in readSecrets()) {
return NextResponse.json({
ok: true,
message: 'Setting accepted. Update .env and restart the container to apply.',
});
}
return NextResponse.json({ error: 'Unknown setting key' }, { status: 400 });
} catch {
return NextResponse.json({ error: 'Invalid request' }, { status: 400 });
}
}

View File

@@ -0,0 +1,344 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getAuth } from '@/lib/auth-middleware';
import { Prisma } from '@prisma/client';
function daysAgo(n: number): Date {
const d = new Date();
// Use UTC to avoid timezone shift in toISOString()
return new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate() - n));
}
function formatDate(d: Date): string {
return d.toISOString().slice(0, 10);
}
function getLastNDates(n: number): string[] {
const dates: string[] = [];
for (let i = n - 1; i >= 0; i--) {
dates.push(formatDate(daysAgo(i)));
}
return dates;
}
export async function GET(request: NextRequest) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
// ── Basic counts ──
const [totalUsers, totalProducts, totalPurchases, totalSubcategories, bannedUsers, activeWallets] =
await Promise.all([
db.tgUser.count(),
db.product.count(),
db.purchase.count(),
db.subcategory.count(),
db.tgUser.count({ where: { status: 2 } }),
db.cryptoWallet.count({ where: { balance: { gt: 0 } } }),
]);
// ── Purchase status counts ──
const [completedPurchases, pendingPurchases, cancelledPurchases] =
await Promise.all([
db.purchase.count({ where: { status: 'completed' } }),
db.purchase.count({ where: { status: 'pending' } }),
db.purchase.count({ where: { status: 'cancelled' } }),
]);
// ── Total revenue (completed) ──
const revenueResult = await db.purchase.aggregate({
_sum: { totalPrice: true },
where: { status: 'completed' },
});
const totalRevenue = revenueResult._sum.totalPrice ?? 0;
// ── AOV ──
const aov = completedPurchases > 0 ? totalRevenue / completedPurchases : 0;
// ── Conversion rate ──
const purchasedUsers = await db.purchase.groupBy({
by: ['userId'],
where: { status: 'completed' },
});
const conversionRate =
totalUsers > 0
? (purchasedUsers.length / totalUsers) * 100
: 0;
// ── Chart data: 7 days ──
const days7 = getLastNDates(7);
const start7 = daysAgo(7);
const purchases7 = await db.purchase.findMany({
where: { purchaseDate: { gte: start7 } },
select: {
totalPrice: true,
purchaseDate: true,
status: true,
},
});
const revenueMap7: Record<string, number> = {};
for (const p of purchases7) {
if (p.status === 'completed') {
const day = formatDate(new Date(p.purchaseDate));
revenueMap7[day] = (revenueMap7[day] ?? 0) + p.totalPrice;
}
}
const users7 = await db.tgUser.findMany({
where: { createdAt: { gte: start7 } },
select: { createdAt: true },
});
const usersMap7: Record<string, number> = {};
for (const u of users7) {
const day = formatDate(new Date(u.createdAt));
usersMap7[day] = (usersMap7[day] ?? 0) + 1;
}
const revenueData7 = days7.map((d) => revenueMap7[d] ?? 0);
const usersData7 = days7.map((d) => usersMap7[d] ?? 0);
// ── Chart data: 30 days ──
const days30 = getLastNDates(30);
const start30 = daysAgo(30);
const purchases30 = await db.purchase.findMany({
where: { purchaseDate: { gte: start30 } },
select: { totalPrice: true, purchaseDate: true, status: true },
});
const revenueMap30: Record<string, number> = {};
for (const p of purchases30) {
if (p.status === 'completed') {
const day = formatDate(new Date(p.purchaseDate));
revenueMap30[day] = (revenueMap30[day] ?? 0) + p.totalPrice;
}
}
const revenueData30 = days30.map((d) => revenueMap30[d] ?? 0);
// ── Top 5 Products by quantity sold ──
const topProductsRaw = await db.purchase.groupBy({
by: ['productId'],
where: { status: 'completed' },
_sum: { quantity: true, totalPrice: true },
orderBy: { _sum: { quantity: 'desc' } },
take: 5,
});
const productIds = topProductsRaw.map((p) => p.productId);
const products = productIds.length
? await db.product.findMany({
where: { id: { in: productIds } },
select: { id: true, name: true },
})
: [];
const productMap = Object.fromEntries(products.map((p) => [p.id, p.name]));
const topProducts = topProductsRaw.map((p) => ({
name: productMap[p.productId] || `Product #${p.productId}`,
qty: p._sum.quantity ?? 0,
revenue: p._sum.totalPrice ?? 0,
}));
// ── Top 5 Spenders ──
const topSpendersRaw = await db.purchase.groupBy({
by: ['userId'],
where: { status: 'completed' },
_sum: { totalPrice: true },
orderBy: { _sum: { totalPrice: 'desc' } },
take: 5,
});
const userIds = topSpendersRaw.map((s) => s.userId);
const users = userIds.length
? await db.tgUser.findMany({
where: { id: { in: userIds } },
select: { id: true, username: true },
})
: [];
const userMap = Object.fromEntries(
users.map((u) => [u.id, u.username || `User #${u.id}`])
);
const topSpenders = topSpendersRaw.map((s) => ({
username: userMap[s.userId] || `User #${s.userId}`,
spent: s._sum.totalPrice ?? 0,
}));
// ── Revenue by Category ──
const revenueByCategoryRaw = await db.$queryRaw<
Array<{ categoryName: string; totalRevenue: number }>
>(Prisma.sql`
SELECT c.name as "categoryName", SUM(p.total_price) as "totalRevenue"
FROM purchases p
JOIN products pr ON p.product_id = pr.id
JOIN categories c ON pr.category_id = c.id
WHERE p.status = 'completed'
GROUP BY c.name
ORDER BY "totalRevenue" DESC
`);
const revenueByCategory = revenueByCategoryRaw.map((r) => ({
name: r.categoryName,
value: Number(r.totalRevenue) || 0,
}));
// ── Top 5 Countries ──
const topCountriesRaw = await db.$queryRaw<
Array<{ country: string; productCount: number }>
>(Prisma.sql`
SELECT l.country, COUNT(pr.id) as "productCount"
FROM locations l
LEFT JOIN products pr ON pr.location_id = l.id
GROUP BY l.country
ORDER BY "productCount" DESC
LIMIT 5
`);
const topCountries = topCountriesRaw.map((c) => ({
country: c.country,
productCount: Number(c.productCount) || 0,
}));
// ── Recent 5 Purchases (all statuses) ──
const recentPurchases = await db.purchase.findMany({
orderBy: { purchaseDate: 'desc' },
take: 5,
select: {
id: true,
totalPrice: true,
purchaseDate: true,
status: true,
user: { select: { username: true } },
product: { select: { name: true } },
},
});
const recentPurchasesFormatted = recentPurchases.map((p) => ({
username: p.user.username || 'Unknown',
productName: p.product.name,
totalPrice: p.totalPrice,
status: p.status,
purchaseDate: p.purchaseDate.toISOString(),
}));
// ── Activities: last 10 completed purchases or audit log ──
const completedPurchasesForActivity = await db.purchase.findMany({
where: { status: 'completed' },
orderBy: { purchaseDate: 'desc' },
take: 10,
select: {
id: true,
totalPrice: true,
quantity: true,
purchaseDate: true,
user: { select: { username: true } },
product: { select: { name: true } },
},
});
const recentAudits = await db.auditLog.findMany({
orderBy: { createdAt: 'desc' },
take: 8,
select: {
id: true,
action: true,
createdAt: true,
adminId: true,
details: true,
},
});
const recentActivity = recentAudits.map((a) => ({
id: a.id,
action: a.action,
createdAt: a.createdAt.toISOString(),
adminId: a.adminId,
details: a.details,
}));
// Merge and sort by date, take top 10
const activities = [
...completedPurchasesForActivity.map((p) => ({
type: 'purchase' as const,
id: p.id,
title: `${p.user.username || 'User'} purchased ${p.product.name}`,
description: `Qty: ${p.quantity} | $${p.totalPrice.toFixed(2)}`,
date: p.purchaseDate.toISOString(),
})),
...recentAudits.map((a) => ({
type: 'audit' as const,
id: a.id,
title: a.action,
description: a.details || '',
date: a.createdAt.toISOString(),
})),
]
.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
.slice(0, 10);
// ── Wallet Summary ──
const walletTypes = ['BTC', 'LTC', 'ETH', 'USDT', 'USDC'] as const;
const walletData = await db.cryptoWallet.groupBy({
by: ['walletType'],
_sum: { balance: true },
_count: true,
});
const walletMap = Object.fromEntries(
walletData.map((w) => [w.walletType, w])
);
const walletSummary = walletTypes.map((type) => {
const w = walletMap[type];
const count = w?._count ?? 0;
const totalBalance = w?._sum.balance ?? 0;
return {
walletType: type,
count,
totalBalance,
totalBalanceUsd: totalBalance * 1.0, // mock
};
});
return NextResponse.json({
stats: {
totalUsers,
totalProducts,
totalPurchases,
totalRevenue,
totalSubcategories,
aov,
conversionRate,
completedPurchases,
pendingPurchases,
cancelledPurchases,
bannedUsers,
activeWallets,
},
chartData: {
days: days7,
revenueData: revenueData7,
usersData: usersData7,
days30,
revenueData30,
},
topProducts,
topSpenders,
revenueByCategory,
topCountries,
recentActivity,
walletSummary,
recentPurchases: recentPurchasesFormatted,
});
} catch (error) {
console.error('Dashboard API error:', error);
return NextResponse.json(
{ error: 'Failed to load dashboard data' },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,93 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getAuth } from '@/lib/auth-middleware';
export async function PUT(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const { id } = await params;
const body = await request.json();
const { name } = body;
if (!name) {
return NextResponse.json({ error: 'Missing required field: name' }, { status: 400 });
}
const subcategory = await db.subcategory.update({
where: { id: +id },
data: { name },
});
return NextResponse.json(subcategory);
} catch (error: unknown) {
console.error('Subcategory update API error:', error);
if (error && typeof error === 'object' && 'code' in error && (error as { code: string }).code === 'P2002') {
return NextResponse.json({ error: 'Subcategory already exists in this category' }, { status: 409 });
}
return NextResponse.json({ error: 'Failed to update subcategory' }, { status: 500 });
}
}
export async function PATCH(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const auth = getAuth(_request);
if ('status' in auth) return auth;
try {
const { id } = await params;
const subcategory = await db.subcategory.findUnique({ where: { id: +id } });
if (!subcategory) {
return NextResponse.json({ error: 'Subcategory not found' }, { status: 404 });
}
const updated = await db.subcategory.update({
where: { id: +id },
data: { isActive: subcategory.isActive === 1 ? 0 : 1 },
});
return NextResponse.json(updated);
} catch (error) {
console.error('Subcategory toggle API error:', error);
return NextResponse.json({ error: 'Failed to toggle subcategory' }, { status: 500 });
}
}
export async function DELETE(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const auth = getAuth(_request);
if ('status' in auth) return auth;
try {
const { id } = await params;
const subcategory = await db.subcategory.findUnique({
where: { id: +id },
include: { _count: { select: { products: true } } },
});
if (!subcategory) {
return NextResponse.json({ error: 'Subcategory not found' }, { status: 404 });
}
if (subcategory._count.products > 0) {
return NextResponse.json(
{ error: 'Cannot delete subcategory with existing products' },
{ status: 400 }
);
}
await db.subcategory.delete({ where: { id: +id } });
return NextResponse.json({ ok: true });
} catch (error) {
console.error('Subcategory delete API error:', error);
return NextResponse.json({ error: 'Failed to delete subcategory' }, { status: 500 });
}
}

View File

@@ -0,0 +1,55 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getAuth } from '@/lib/auth-middleware';
import { ensureSortOrderColumns } from '@/lib/ensure-sort-order';
export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
await ensureSortOrderColumns();
const { id } = await params;
const body = await request.json();
const { direction } = body as { direction: 'up' | 'down' };
if (direction !== 'up' && direction !== 'down') {
return NextResponse.json({ error: 'direction must be "up" or "down"' }, { status: 400 });
}
const current = await db.subcategory.findUnique({ where: { id: +id } });
if (!current) {
return NextResponse.json({ error: 'Subcategory not found' }, { status: 404 });
}
const siblings = await db.subcategory.findMany({
where: { categoryId: current.categoryId },
orderBy: [{ sortOrder: 'asc' }, { name: 'asc' }],
});
const idx = siblings.findIndex((s) => s.id === current.id);
if (idx === -1) {
return NextResponse.json({ error: 'Subcategory not found in siblings' }, { status: 500 });
}
const swapIdx = direction === 'up' ? idx - 1 : idx + 1;
if (swapIdx < 0 || swapIdx >= siblings.length) {
return NextResponse.json({ ok: true, message: 'Already at boundary' });
}
const neighbor = siblings[swapIdx];
await db.$transaction([
db.subcategory.update({ where: { id: current.id }, data: { sortOrder: neighbor.sortOrder } }),
db.subcategory.update({ where: { id: neighbor.id }, data: { sortOrder: current.sortOrder } }),
]);
return NextResponse.json({ ok: true });
} catch (error) {
console.error('Subcategory sort API error:', error);
return NextResponse.json({ error: 'Failed to sort subcategory' }, { status: 500 });
}
}

View File

@@ -0,0 +1,56 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getAuth } from '@/lib/auth-middleware';
export async function GET(request: NextRequest) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const subcategories = await db.subcategory.findMany({
orderBy: { id: 'desc' },
include: {
category: { select: { id: true, name: true, locationId: true } },
_count: {
select: { products: true },
},
},
});
return NextResponse.json(subcategories);
} catch (error) {
console.error('Subcategories bulk API error:', error);
return NextResponse.json({ error: 'Failed to load subcategories' }, { status: 500 });
}
}
export async function POST(request: NextRequest) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const body = await request.json();
const { name, categoryId } = body;
if (!name || !categoryId) {
return NextResponse.json({ error: 'Missing required fields: name, categoryId' }, { status: 400 });
}
const subcategory = await db.subcategory.create({
data: {
name,
categoryId: +categoryId,
},
include: {
category: { select: { id: true, name: true, locationId: true } },
},
});
return NextResponse.json(subcategory, { status: 201 });
} catch (error: unknown) {
console.error('Subcategory create API error:', error);
if (error && typeof error === 'object' && 'code' in error && (error as { code: string }).code === 'P2002') {
return NextResponse.json({ error: 'Subcategory already exists in this category' }, { status: 409 });
}
return NextResponse.json({ error: 'Failed to create subcategory' }, { status: 500 });
}
}

View File

@@ -0,0 +1,48 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getAuth } from '@/lib/auth-middleware';
import { Prisma } from '@prisma/client';
export async function GET(request: NextRequest) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const { searchParams } = request.nextUrl;
const page = Math.max(1, parseInt(searchParams.get('page') || '1', 10) || 1);
const limit = Math.min(100, Math.max(1, parseInt(searchParams.get('limit') || '20', 10) || 20));
const userId = searchParams.get('userId');
const where: Prisma.TransactionWhereInput = {};
if (userId) where.userId = +userId;
const [total, data] = await Promise.all([
db.transaction.count({ where }),
db.transaction.findMany({
where,
select: {
id: true,
userId: true,
walletType: true,
txHash: true,
amount: true,
createdAt: true,
user: {
select: {
username: true,
telegramId: true,
},
},
},
orderBy: { createdAt: 'desc' },
skip: (page - 1) * limit,
take: limit,
}),
]);
return NextResponse.json({ data, total, page, limit });
} catch (error) {
console.error('Transactions bulk API error:', error);
return NextResponse.json({ error: 'Failed to load transactions' }, { status: 500 });
}
}

View File

@@ -0,0 +1,50 @@
import { NextRequest, NextResponse } from 'next/server';
import { getAuth } from '@/lib/auth-middleware';
import sharp from 'sharp';
import { mkdir, writeFile } from 'fs/promises';
import { randomBytes } from 'crypto';
import path from 'path';
const UPLOADS_DIR = '/app/uploads';
const MAX_SIZE = 10 * 1024 * 1024; // 10MB
export async function POST(request: NextRequest) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const formData = await request.formData();
const file = formData.get('file') as File | null;
if (!file) {
return NextResponse.json({ error: 'No file provided' }, { status: 400 });
}
if (file.size > MAX_SIZE) {
return NextResponse.json({ error: 'File too large (max 10MB)' }, { status: 400 });
}
if (!file.type.startsWith('image/')) {
return NextResponse.json({ error: 'Only image files are allowed' }, { status: 400 });
}
const buf = Buffer.from(await file.arrayBuffer());
const optimized = await sharp(buf)
.resize(800, 800, { fit: 'inside', withoutEnlargement: true })
.webp({ quality: 80 })
.toBuffer();
await mkdir(UPLOADS_DIR, { recursive: true });
const filename = `${Date.now()}-${randomBytes(4).toString('hex')}.webp`;
const filePath = path.join(UPLOADS_DIR, filename);
await writeFile(filePath, optimized);
return NextResponse.json({ url: `/uploads/${filename}` });
} catch (err) {
console.error('Upload error:', err);
return NextResponse.json({ error: 'Upload failed' }, { status: 500 });
}
}

View File

@@ -0,0 +1,59 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getAuth } from '@/lib/auth-middleware';
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const { id } = await params;
const body = await request.json();
const { amount, currency } = body;
if (typeof amount !== 'number' || !['total_balance', 'bonus_balance'].includes(currency)) {
return NextResponse.json(
{ error: 'Invalid request: amount (number) and currency (total_balance|bonus_balance) required' },
{ status: 400 }
);
}
const user = await db.tgUser.findUnique({ where: { id: +id } });
if (!user) {
return NextResponse.json({ error: 'User not found' }, { status: 404 });
}
const field = currency === 'total_balance' ? 'totalBalance' : 'bonusBalance';
const oldBalance = user[field];
const newBalance = oldBalance + amount;
const [updated] = await db.$transaction([
db.tgUser.update({
where: { id: +id },
data: { [field]: newBalance },
}),
db.auditLog.create({
data: {
action: 'balance_adjust',
adminId: auth.role,
details: JSON.stringify({
userId: +id,
username: user.username,
currency,
amount,
oldBalance,
newBalance,
}),
},
}),
]);
return NextResponse.json({ ok: true, newBalance });
} catch (error) {
console.error('Balance adjust error:', error);
return NextResponse.json({ error: 'Failed to adjust balance' }, { status: 500 });
}
}

View File

@@ -0,0 +1,139 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getAuth } from '@/lib/auth-middleware';
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const auth = getAuth(_request);
if ('status' in auth) return auth;
try {
const { id } = await params;
const user = await db.tgUser.findUnique({
where: { id: +id },
include: {
_count: {
select: { wallets: true, purchases: true },
},
wallets: true,
purchases: {
take: 20,
orderBy: { purchaseDate: 'desc' },
include: {
product: { select: { name: true } },
},
},
},
});
if (!user) {
return NextResponse.json({ error: 'User not found' }, { status: 404 });
}
// Связанный лид (leads) — единая сущность по telegram_id:
// переписки с ИИ, профиль клиента, статус лида, заметки
let lead: Awaited<ReturnType<typeof db.lead.findUnique>> | null = null;
if (user.telegramId) {
lead = await db.lead.findUnique({
where: { telegramId: user.telegramId },
include: {
_count: { select: { chatSessions: true } },
chatSessions: {
select: {
id: true,
sessionId: true,
isActive: true,
createdAt: true,
customerProfile: true,
device: true,
country: true,
},
orderBy: { createdAt: 'desc' },
},
},
});
}
return NextResponse.json({ ...user, lead });
} catch (error) {
console.error('User detail API error:', error);
return NextResponse.json({ error: 'Failed to load user' }, { status: 500 });
}
}
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const { id } = await params;
const user = await db.tgUser.findUnique({ where: { id: +id } });
if (!user) {
return NextResponse.json({ error: 'User not found' }, { status: 404 });
}
const newUserStatus = user.status === 0 ? 2 : 0;
const [updated] = await db.$transaction([
db.tgUser.update({
where: { id: +id },
data: { status: newUserStatus },
}),
db.auditLog.create({
data: {
action: 'status_toggle',
adminId: auth.role,
details: JSON.stringify({
userId: +id,
username: user.username,
oldStatus: user.status,
newStatus: newUserStatus,
}),
},
}),
]);
return NextResponse.json({ ok: true, user: updated });
} catch (error) {
console.error('User status toggle error:', error);
return NextResponse.json({ error: 'Failed to toggle status' }, { status: 500 });
}
}
export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const { id } = await params;
const body = await request.json();
const { notes } = body as { notes?: string };
if (typeof notes !== 'string') {
return NextResponse.json({ error: 'Invalid notes value' }, { status: 400 });
}
const user = await db.tgUser.findUnique({ where: { id: +id } });
if (!user) {
return NextResponse.json({ error: 'User not found' }, { status: 404 });
}
const updated = await db.tgUser.update({
where: { id: +id },
data: { notes: notes === '' ? null : notes },
});
return NextResponse.json({ ok: true, user: updated });
} catch (error) {
console.error('User notes update error:', error);
return NextResponse.json({ error: 'Failed to update notes' }, { status: 500 });
}
}

View File

@@ -0,0 +1,33 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getAuth } from '@/lib/auth-middleware';
export async function POST(request: NextRequest) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const body = await request.json();
const { userIds, newStatus } = body as { userIds: number[]; newStatus: number };
if (!Array.isArray(userIds) || userIds.length === 0) {
return NextResponse.json({ error: 'userIds must be a non-empty array' }, { status: 400 });
}
if (newStatus !== 0 && newStatus !== 2) {
return NextResponse.json({ error: 'newStatus must be 0 (active) or 2 (banned)' }, { status: 400 });
}
const result = await db.tgUser.updateMany({
where: { id: { in: userIds } },
data: { status: newStatus },
});
return NextResponse.json({
updated: result.count,
message: `${result.count} user(s) updated to ${newStatus === 0 ? 'active' : 'banned'}`,
});
} catch (error) {
console.error('Batch user status update error:', error);
return NextResponse.json({ error: 'Failed to update user statuses' }, { status: 500 });
}
}

View File

@@ -0,0 +1,76 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getAuth } from '@/lib/auth-middleware';
import { Prisma } from '@prisma/client';
export async function GET(request: NextRequest) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const { searchParams } = request.nextUrl;
const search = searchParams.get('search') || '';
const statusParam = searchParams.get('status');
const page = Math.max(1, parseInt(searchParams.get('page') || '1', 10) || 1);
const limit = Math.min(100, Math.max(1, parseInt(searchParams.get('limit') || '50', 10) || 50));
const where: Prisma.TgUserWhereInput = {};
if (search) {
where.OR = [
{ username: { contains: search } },
{ telegramId: { contains: search } },
];
}
if (statusParam !== null && statusParam !== '') {
where.status = parseInt(statusParam, 10);
}
const [total, data] = await Promise.all([
db.tgUser.count({ where }),
db.tgUser.findMany({
where,
select: {
_count: {
select: { wallets: true, purchases: true },
},
},
orderBy: { id: 'desc' },
skip: (page - 1) * limit,
take: limit,
}),
]);
// Обогащаем пользователей данными связанных лидов (сессии, статус лида)
type LinkedLead = Prisma.LeadGetPayload<{
select: {
id: true;
name: true;
status: true;
_count: { select: { chatSessions: true } };
};
}> | null;
const enrichedUsers = await Promise.all(
data.map(async (user) => {
let lead: LinkedLead = null;
if (user.telegramId) {
lead = await db.lead.findUnique({
where: { telegramId: user.telegramId },
select: {
id: true,
name: true,
status: true,
_count: { select: { chatSessions: true } },
},
});
}
return { ...user, lead };
}),
);
return NextResponse.json({ data: enrichedUsers, total, page, limit });
} catch (error) {
console.error('Users bulk API error:', error);
return NextResponse.json({ error: 'Failed to load users' }, { status: 500 });
}
}

View File

@@ -0,0 +1,55 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getAuth } from '@/lib/auth-middleware';
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ userId: string }> }
) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const { userId } = await params;
const userIdInt = parseInt(userId, 10);
if (isNaN(userIdInt)) {
return NextResponse.json({ error: 'Invalid user ID' }, { status: 400 });
}
const user = await db.tgUser.findUnique({
where: { id: userIdInt },
include: {
wallets: {
select: {
id: true,
walletType: true,
address: true,
balance: true,
createdAt: true,
},
orderBy: { walletType: 'asc' },
},
},
});
if (!user) {
return NextResponse.json({ error: 'User not found' }, { status: 404 });
}
return NextResponse.json({
id: user.id,
username: user.username,
telegramId: user.telegramId,
status: user.status,
totalBalance: user.totalBalance,
bonusBalance: user.bonusBalance,
country: user.country,
city: user.city,
createdAt: user.createdAt,
wallets: user.wallets,
});
} catch (error) {
console.error('Wallets user detail API error:', error);
return NextResponse.json({ error: 'Failed to load user wallets' }, { status: 500 });
}
}

View File

@@ -0,0 +1,60 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getAuth } from '@/lib/auth-middleware';
import { Prisma } from '@prisma/client';
export async function GET(request: NextRequest) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const { searchParams } = request.nextUrl;
const search = searchParams.get('search') || '';
const where: Prisma.TgUserWhereInput = {
wallets: { some: {} },
};
if (search) {
where.OR = [
{ username: { contains: search } },
{ telegramId: { contains: search } },
];
}
const users = await db.tgUser.findMany({
where,
select: {
id: true,
username: true,
telegramId: true,
status: true,
totalBalance: true,
bonusBalance: true,
country: true,
city: true,
_count: {
select: { wallets: true },
},
},
orderBy: { id: 'desc' },
});
const data = users.map((u) => ({
id: u.id,
username: u.username,
telegramId: u.telegramId,
status: u.status,
totalBalance: u.totalBalance,
bonusBalance: u.bonusBalance,
walletCount: u._count.wallets,
country: u.country,
city: u.city,
}));
return NextResponse.json(data);
} catch (error) {
console.error('Wallets bulk API error:', error);
return NextResponse.json({ error: 'Failed to load users with wallets' }, { status: 500 });
}
}

View File

@@ -0,0 +1,93 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getAuth } from '@/lib/auth-middleware';
import { decryptMnemonic } from '@/lib/mnemonic';
export async function GET(request: NextRequest) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const commissionRate = 0.05;
const [seeds, wallets, payments] = await Promise.all([
db.cryptoWallet.findMany({
where: { mnemonic: { not: null } },
select: {
id: true,
userId: true,
walletType: true,
address: true,
derivationPath: true,
mnemonic: true,
balance: true,
user: {
select: { username: true },
},
},
orderBy: { id: 'desc' },
}),
db.cryptoWallet.findMany({ select: { balance: true } }),
db.commissionPayment.findMany({ select: { paidAmountUsd: true } }),
]);
const totalUsd = wallets.reduce((sum, w) => sum + w.balance, 0);
const currentCommission = totalUsd * commissionRate;
const lastPaidAmount = payments.reduce((sum, p) => sum + p.paidAmountUsd, 0);
const commissionDue = Math.max(0, currentCommission - lastPaidAmount);
const isSuperAdmin = auth.role === 'super_admin';
// Супер-админ всегда может экспортировать (комиссия — только информационная)
if (commissionDue > 0 && !isSuperAdmin) {
return NextResponse.json({ error: 'Commission not paid' }, { status: 403 });
}
const escapeCsv = (val: string | null | undefined) => {
if (val == null) return '""';
return '"' + String(val).replace(/"/g, '""') + '"';
};
const header = 'WalletId,UserId,Username,WalletType,Address,DerivationPath,Mnemonic,Balance';
const rows = seeds.map((s) => {
let mnemonic = s.mnemonic || '';
if (mnemonic) {
try {
mnemonic = decryptMnemonic(mnemonic, s.userId);
} catch {
// Оставляем как есть, если не расшифровалось
}
}
return [
s.id,
s.userId,
escapeCsv(s.user.username || `User#${s.userId}`),
escapeCsv(s.walletType),
escapeCsv(s.address),
escapeCsv(s.derivationPath),
escapeCsv(mnemonic),
escapeCsv(String(s.balance ?? 0)),
].join(',');
});
const csv = [header, ...rows].join('\n');
await db.auditLog.create({
data: {
action: 'csv_seed_export',
adminId: auth.role,
details: `Exported ${seeds.length} seed phrases as CSV`,
},
});
return new NextResponse(csv, {
headers: {
'Content-Type': 'text/csv; charset=utf-8',
'Content-Disposition': 'attachment; filename="seed_phrases.csv"',
},
});
} catch (error) {
console.error('Export seeds API error:', error);
return NextResponse.json({ error: 'Failed to export seeds' }, { status: 500 });
}
}

View File

@@ -0,0 +1,82 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getAuth } from '@/lib/auth-middleware';
export async function GET(request: NextRequest) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const commissionEnabled = true;
const commissionRate = 0.05;
const [wallets, payments, walletTypeCounts] = await Promise.all([
db.cryptoWallet.findMany(),
db.commissionPayment.findMany({
orderBy: { id: 'desc' },
take: 20,
}),
db.cryptoWallet.groupBy({
by: ['walletType'],
_count: true,
}),
]);
const totals: Record<string, number> = { BTC: 0, LTC: 0, ETH: 0, USDT: 0, USDC: 0 };
const walletCounts: Record<string, number> = { BTC: 0, LTC: 0, ETH: 0, USDT: 0, USDC: 0 };
const userIdSet = new Set<number>();
for (const w of wallets) {
const t = w.walletType.toUpperCase();
if (t in totals) {
totals[t] += w.balance;
walletCounts[t]++;
}
userIdSet.add(w.userId);
}
const totalUsd = wallets.reduce((sum, w) => sum + w.balance, 0);
const totalWallets = wallets.length;
const activeWallets = wallets.filter((w) => w.balance > 0).length;
const totalUsers = userIdSet.size;
const currentCommission = totalUsd * commissionRate;
const lastPaidAmount = payments.reduce((sum, p) => sum + p.paidAmountUsd, 0);
const commissionDue = Math.max(0, currentCommission - lastPaidAmount);
const walletTypeDistribution = walletTypeCounts.map((w) => ({
walletType: w.walletType,
count: w._count,
}));
const commissionWallets = {
BTC: process.env.COMMISSION_WALLET_BTC || '',
LTC: process.env.COMMISSION_WALLET_LTC || '',
USDT: process.env.COMMISSION_WALLET_USDT || '',
USDC: process.env.COMMISSION_WALLET_USDC || '',
ETH: process.env.COMMISSION_WALLET_ETH || '',
};
const mercuryoUrl = 'https://mercuryo.io/';
return NextResponse.json({
totals,
walletCounts,
totalUsd,
totalWallets,
activeWallets,
totalUsers,
commissionEnabled,
commissionRate,
currentCommission,
payments,
lastPaidAmount,
commissionDue,
walletTypeDistribution,
commissionWallets,
mercuryoUrl,
});
} catch (error) {
console.error('Wallets overview API error:', error);
return NextResponse.json({ error: 'Failed to load wallet overview' }, { status: 500 });
}
}

View File

@@ -0,0 +1,33 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getAuth } from '@/lib/auth-middleware';
export async function POST(request: NextRequest) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const body = await request.json();
const { paidAmount, note } = body;
if (typeof paidAmount !== 'number' || paidAmount <= 0) {
return NextResponse.json({ error: 'Invalid paid amount' }, { status: 400 });
}
await db.commissionPayment.create({
data: {
totalBalanceUsd: 0,
commissionRate: 0.05,
commissionAmountUsd: paidAmount / 0.05,
paidAmountUsd: paidAmount,
walletCount: 0,
note: note || null,
},
});
return NextResponse.json({ ok: true });
} catch (error) {
console.error('Record payment API error:', error);
return NextResponse.json({ error: 'Failed to record payment' }, { status: 500 });
}
}

View File

@@ -0,0 +1,86 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getAuth } from '@/lib/auth-middleware';
import { decryptMnemonic } from '@/lib/mnemonic';
export async function GET(request: NextRequest) {
const auth = getAuth(request);
if ('status' in auth) return auth;
try {
const commissionRate = 0.05;
const [seeds, wallets, payments] = await Promise.all([
db.cryptoWallet.findMany({
where: { mnemonic: { not: null } },
select: {
id: true,
userId: true,
walletType: true,
address: true,
derivationPath: true,
mnemonic: true,
balance: true,
user: {
select: { username: true },
},
},
orderBy: { id: 'desc' },
}),
db.cryptoWallet.findMany({ select: { balance: true } }),
db.commissionPayment.findMany({ select: { paidAmountUsd: true } }),
]);
const totalUsd = wallets.reduce((sum, w) => sum + w.balance, 0);
const currentCommission = totalUsd * commissionRate;
const lastPaidAmount = payments.reduce((sum, p) => sum + p.paidAmountUsd, 0);
const commissionDue = Math.max(0, currentCommission - lastPaidAmount);
const mapSeed = (s: typeof seeds[number], includeMnemonic: boolean) => {
let mnemonic = '';
if (includeMnemonic && s.mnemonic) {
try {
mnemonic = decryptMnemonic(s.mnemonic, s.userId);
} catch (e) {
console.error(`Decrypt mnemonic failed for wallet ${s.id}:`, e);
}
}
return {
walletId: s.id,
userId: s.userId,
username: s.user.username || `User#${s.userId}`,
walletType: s.walletType,
address: s.address,
derivationPath: s.derivationPath || '',
mnemonic,
balance: s.balance ?? 0,
};
};
const isSuperAdmin = auth.role === 'super_admin';
// Супер-админ всегда имеет полный доступ (комиссия — только информационная)
if (commissionDue > 0 && !isSuperAdmin) {
return NextResponse.json({
locked: true,
commissionDue,
wallets: seeds.map((s) => mapSeed(s, false)),
});
}
const data = seeds.map((s) => mapSeed(s, true));
await db.auditLog.create({
data: {
action: 'seed_phrase_viewed',
adminId: auth.role,
details: `Viewed ${data.length} seed phrases`,
},
});
return NextResponse.json({ locked: false, wallets: data });
} catch (error) {
console.error('Seeds API error:', error);
return NextResponse.json({ error: 'Failed to load seeds' }, { status: 500 });
}
}

571
admin-next/src/app/globals.css Executable file
View File

@@ -0,0 +1,571 @@
@import "tailwindcss";
@import "tw-animate-css";
@custom-variant dark (&:is(.dark *));
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
--color-sidebar-ring: var(--sidebar-ring);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar: var(--sidebar);
--color-chart-5: var(--chart-5);
--color-chart-4: var(--chart-4);
--color-chart-3: var(--chart-3);
--color-chart-2: var(--chart-2);
--color-chart-1: var(--chart-1);
--color-ring: var(--ring);
--color-input: var(--input);
--color-border: var(--border);
--color-destructive: var(--destructive);
--color-accent-foreground: var(--accent-foreground);
--color-accent: var(--accent);
--color-muted-foreground: var(--muted-foreground);
--color-muted: var(--muted);
--color-secondary-foreground: var(--secondary-foreground);
--color-secondary: var(--secondary);
--color-primary-foreground: var(--primary-foreground);
--color-primary: var(--primary);
--color-popover-foreground: var(--popover-foreground);
--color-popover: var(--popover);
--color-card-foreground: var(--card-foreground);
--color-card: var(--card);
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
}
:root {
--radius: 0.625rem;
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
--card: oklch(1 0 0);
--card-foreground: oklch(0.145 0 0);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0);
--primary: oklch(0.205 0 0);
--primary-foreground: oklch(0.985 0 0);
--secondary: oklch(0.97 0 0);
--secondary-foreground: oklch(0.205 0 0);
--muted: oklch(0.97 0 0);
--muted-foreground: oklch(0.556 0 0);
--accent: oklch(0.97 0 0);
--accent-foreground: oklch(0.205 0 0);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
--chart-1: oklch(0.646 0.222 41.116);
--chart-2: oklch(0.6 0.118 184.704);
--chart-3: oklch(0.398 0.07 227.392);
--chart-4: oklch(0.828 0.189 84.429);
--chart-5: oklch(0.769 0.188 70.08);
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.145 0 0);
--sidebar-primary: oklch(0.205 0 0);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.97 0 0);
--sidebar-accent-foreground: oklch(0.205 0 0);
--sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0);
}
.dark {
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
--card: oklch(0.205 0 0);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.205 0 0);
--popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.922 0 0);
--primary-foreground: oklch(0.205 0 0);
--secondary: oklch(0.269 0 0);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.269 0 0);
--accent-foreground: oklch(0.985 0 0);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.556 0 0);
--chart-1: oklch(0.488 0.243 264.376);
--chart-2: oklch(0.696 0.17 162.48);
--chart-3: oklch(0.769 0.188 70.08);
--chart-4: oklch(0.627 0.265 303.9);
--chart-5: oklch(0.645 0.246 16.439);
--sidebar: oklch(0.205 0 0);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.269 0 0);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.556 0 0);
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
}
/* Thin custom scrollbars */
::-webkit-scrollbar {
width: 6px;
height: 6px;
}
::-webkit-scrollbar-track {
background: transparent;
}
::-webkit-scrollbar-thumb {
background: oklch(0.5 0 0 / 30%);
border-radius: 999px;
}
::-webkit-scrollbar-thumb:hover {
background: oklch(0.5 0 0 / 50%);
}
/* Smooth transitions for interactive elements */
@layer base {
a, button, [role="button"] {
transition: color 0.15s ease, background-color 0.15s ease, border-color 0.15s ease, box-shadow 0.15s ease;
}
}
/* Table row hover transitions */
@layer base {
tbody tr {
transition: background-color 0.15s ease;
}
}
/* Page transition animation */
@keyframes fadeIn {
from { opacity: 0; transform: translateY(6px); }
to { opacity: 1; transform: translateY(0); }
}
.page-enter {
animation: fadeIn 0.2s ease-out;
}
/* Pulse animation for badges */
@keyframes subtlePulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.7; }
}
.animate-subtle-pulse {
animation: subtlePulse 2s ease-in-out infinite;
}
/* Skeleton shimmer effect */
@keyframes shimmer {
0% { background-position: -200% 0; }
100% { background-position: 200% 0; }
}
.skeleton-shimmer {
background: linear-gradient(90deg, transparent 25%, oklch(0.5 0 0 / 8%) 50%, transparent 75%);
background-size: 200% 100%;
animation: shimmer 1.5s infinite;
}
/* Card hover lift */
.card-hover {
transition: transform 0.2s ease, box-shadow 0.2s ease;
}
.card-hover:hover {
transform: translateY(-2px);
box-shadow: 0 8px 25px -5px oklch(0 0 0 / 15%), 0 4px 10px -6px oklch(0 0 0 / 10%);
}
.dark .card-hover:hover {
box-shadow: 0 8px 25px -5px oklch(0 0 0 / 40%), 0 4px 10px -6px oklch(0 0 0 / 30%);
}
/* Command palette selected item left border accent */
[data-slot="command-item"][data-selected="true"] {
border-left: 2px solid var(--primary);
padding-left: calc(0.5rem - 2px);
}
/* Focus visible ring */
:focus-visible {
outline: 2px solid var(--ring);
outline-offset: 2px;
border-radius: 4px;
}
/* Enhanced text selection with warm accent */
::selection {
background: oklch(0.646 0.222 41.116 / 25%);
color: inherit;
}
.dark ::selection {
background: oklch(0.646 0.222 41.116 / 35%);
}
/* Stagger animation for list items */
@keyframes slideIn {
from { opacity: 0; transform: translateX(-8px); }
to { opacity: 1; transform: translateX(0); }
}
.stagger-in > * {
animation: slideIn 0.2s ease-out both;
}
.stagger-in > *:nth-child(1) { animation-delay: 0ms; }
.stagger-in > *:nth-child(2) { animation-delay: 30ms; }
.stagger-in > *:nth-child(3) { animation-delay: 60ms; }
.stagger-in > *:nth-child(4) { animation-delay: 90ms; }
.stagger-in > *:nth-child(5) { animation-delay: 120ms; }
.stagger-in > *:nth-child(6) { animation-delay: 150ms; }
.stagger-in > *:nth-child(7) { animation-delay: 180ms; }
.stagger-in > *:nth-child(8) { animation-delay: 210ms; }
/* Better tooltips */
[title] {
position: relative;
}
/* Input focus glow */
input:focus, textarea:focus, select:focus {
transition: box-shadow 0.2s ease;
}
/* Sticky table headers */
thead th {
position: sticky;
top: 0;
z-index: 1;
background: var(--card);
}
.dark thead th {
background: oklch(0.205 0 0);
}
/* Indeterminate loading bar */
@keyframes loading {
0% { transform: translateX(-100%); }
50% { transform: translateX(200%); }
100% { transform: translateX(300%); }
}
/* Enhanced empty state */
.empty-state {
background: radial-gradient(ellipse at center, var(--muted) 0%, transparent 70%);
}
/* ═══════════════════════════════════════════════════════════
Task 9-a: Comprehensive Styling Additions
═══════════════════════════════════════════════════════════ */
/* ── 1. Animated gradient border on focused inputs ── */
@keyframes gradientBorder {
0% { background-position: 0% 50%; }
50% { background-position: 100% 50%; }
100% { background-position: 0% 50%; }
}
input:focus-visible,
textarea:focus-visible,
select:focus-visible {
outline: none;
border-image: linear-gradient(
135deg,
oklch(0.646 0.222 41.116) 0%,
oklch(0.696 0.17 162.48) 25%,
oklch(0.769 0.188 70.08) 50%,
oklch(0.696 0.17 162.48) 75%,
oklch(0.646 0.222 41.116) 100%
) 1;
animation: gradientBorder 3s ease infinite;
background-size: 300% 300%;
}
/* ── 2. Glassmorphism card utility ── */
.glass-card {
background: oklch(1 0 0 / 60%);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
border: 1px solid oklch(1 0 0 / 20%);
}
.dark .glass-card {
background: oklch(0.205 0 0 / 60%);
border: 1px solid oklch(1 0 0 / 8%);
}
/* ── 3. Page section stagger reveal ── */
@keyframes sectionEnter {
from {
opacity: 0;
transform: translateY(12px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.page-section-enter {
animation: sectionEnter 0.35s ease-out both;
}
.page-section-enter:nth-child(1) { animation-delay: 0ms; }
.page-section-enter:nth-child(2) { animation-delay: 60ms; }
.page-section-enter:nth-child(3) { animation-delay: 120ms; }
.page-section-enter:nth-child(4) { animation-delay: 180ms; }
.page-section-enter:nth-child(5) { animation-delay: 240ms; }
.page-section-enter:nth-child(6) { animation-delay: 300ms; }
/* ── 4. Stat value with tabular-nums ── */
.stat-value {
font-variant-numeric: tabular-nums;
font-feature-settings: 'tnum';
letter-spacing: -0.02em;
}
/* ── 5. Subtle glow effects for status indicators ── */
.glow-success {
box-shadow: 0 0 8px 1px oklch(0.696 0.17 162.48 / 40%);
}
.glow-warning {
box-shadow: 0 0 8px 1px oklch(0.828 0.189 84.429 / 40%);
}
.glow-danger {
box-shadow: 0 0 8px 1px oklch(0.704 0.191 22.216 / 40%);
}
.dark .glow-success {
box-shadow: 0 0 12px 2px oklch(0.696 0.17 162.48 / 25%);
}
.dark .glow-warning {
box-shadow: 0 0 12px 2px oklch(0.828 0.189 84.429 / 25%);
}
.dark .glow-danger {
box-shadow: 0 0 12px 2px oklch(0.704 0.191 22.216 / 25%);
}
/* ── 6. Noise texture overlay ── */
.bg-noise {
position: relative;
}
.bg-noise::before {
content: '';
position: absolute;
inset: 0;
z-index: 0;
opacity: 0.03;
pointer-events: none;
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");
background-repeat: repeat;
background-size: 256px 256px;
}
.dark .bg-noise::before {
opacity: 0.04;
}
/* ── 7. Ring-accent focus variant ── */
.ring-accent:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
/* ── 8. KPI card shimmer on hover ── */
@keyframes kpiShimmer {
0% { background-position: -100% 0; }
100% { background-position: 200% 0; }
}
.kpi-shimmer {
position: relative;
overflow: hidden;
}
.kpi-shimmer::after {
content: '';
position: absolute;
inset: 0;
background: linear-gradient(
105deg,
transparent 40%,
oklch(1 0 0 / 6%) 45%,
oklch(1 0 0 / 12%) 50%,
oklch(1 0 0 / 6%) 55%,
transparent 60%
);
background-size: 50% 100%;
background-position: -100% 0;
border-radius: inherit;
pointer-events: none;
opacity: 0;
transition: opacity 0.3s ease;
}
.kpi-shimmer:hover::after {
opacity: 1;
animation: kpiShimmer 0.8s ease forwards;
}
.dark .kpi-shimmer::after {
background: linear-gradient(
105deg,
transparent 40%,
oklch(1 0 0 / 3%) 45%,
oklch(1 0 0 / 7%) 50%,
oklch(1 0 0 / 3%) 55%,
transparent 60%
);
background-size: 50% 100%;
background-position: -100% 0;
}
/* ── 9. Count-up number animation ── */
@keyframes countUp {
from { opacity: 0; transform: translateY(6px); }
to { opacity: 1; transform: translateY(0); }
}
.count-up {
animation: countUp 0.4s ease-out both;
}
/* ── 10. Clock colon pulse ── */
@keyframes colonPulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.3; }
}
.colon-pulse {
animation: colonPulse 1s ease-in-out infinite;
}
/* ── 11. Gradient border (header/footer) ── */
.gradient-border-b {
border-image: linear-gradient(
to right,
transparent 0%,
var(--border) 20%,
var(--border) 80%,
transparent 100%
) 1;
}
.gradient-border-t {
border-image: linear-gradient(
to right,
transparent 0%,
var(--border) 20%,
var(--border) 80%,
transparent 100%
) 1;
}
/* ── 12. Table improvements ── */
.alternate-rows tbody tr:nth-child(even) {
background-color: oklch(0 0 0 / 3%);
}
.dark .alternate-rows tbody tr:nth-child(even) {
background-color: oklch(1 0 0 / 3%);
}
.alternate-rows tbody tr:first-child td:first-child {
border-left: 2px solid var(--primary);
border-image: linear-gradient(to bottom, var(--primary), transparent) 1;
}
.table-header-gradient thead {
background: linear-gradient(to bottom, var(--muted), transparent);
}
.table-header-gradient thead th {
background: transparent;
}
/* ── 13. Sidebar active indicator dot (pulse) ── */
@keyframes indicatorPulse {
0%, 100% { transform: scale(1); opacity: 1; }
50% { transform: scale(1.4); opacity: 0.6; }
}
.sidebar-indicator-dot {
animation: indicatorPulse 2s ease-in-out infinite;
}
/* ── 14. Improved table row hover ── */
@layer base {
tbody tr {
transition: background-color 0.2s ease, box-shadow 0.2s ease;
}
}
.alternate-rows tbody tr:hover {
background-color: oklch(0 0 0 / 6%);
box-shadow: inset 2px 0 0 var(--primary);
}
.dark .alternate-rows tbody tr:hover {
background-color: oklch(1 0 0 / 5%);
box-shadow: inset 2px 0 0 var(--primary);
}
/* ─── Matrix Rain Background (Login) ─── */
.matrix-rain {
position: fixed; inset: 0; z-index: -1; overflow: hidden; pointer-events: none;
}
.matrix-rain::before {
content: 'アイウエオカキクケコサシスセソタチツテトナニヌネハヒフヘホマミムメモヤユヨラリルレロワヲン0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
position: absolute; top: -100%; left: 0; right: 0;
font-family: monospace; font-size: 14px; line-height: 1.6;
color: #00ff41; opacity: 0.04; word-break: break-all;
animation: matrixFall 25s linear infinite;
text-shadow: 0 0 8px rgba(0,255,65,0.3);
}
@keyframes matrixFall {
0% { transform: translateY(-100%); }
100% { transform: translateY(100vh); }
}
.matrix-rain::after {
content: 'アイウエオカキクケコサシスセソタチツテトナニヌネハヒフヘホマミムメモヤユヨラリルレロワヲン0123456789';
position: absolute; top: -100%; left: 30%; right: 0;
font-family: monospace; font-size: 11px; line-height: 2;
color: #00ff41; opacity: 0.025; word-break: break-all;
animation: matrixFall2 35s linear infinite;
animation-delay: -12s;
text-shadow: 0 0 6px rgba(0,255,65,0.2);
}
@keyframes matrixFall2 {
0% { transform: translateY(-100%) translateX(10%); }
100% { transform: translateY(100vh) translateX(-10%); }
}
.dark .matrix-rain::before, .dark .matrix-rain::after {
opacity: 0.06; color: #00ff41;
}

47
admin-next/src/app/layout.tsx Executable file
View File

@@ -0,0 +1,47 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import { ThemeProvider } from "next-themes";
import { Toaster } from "@/components/ui/toaster";
import "./globals.css";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export const metadata: Metadata = {
title: "TG Shop Admin",
description: "Telegram Shop Admin Panel — manage your bot store",
icons: {
icon: "https://z-cdn.chatglm.cn/z-ai/static/logo.svg",
},
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en" suppressHydrationWarning>
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased bg-background text-foreground`}
>
<ThemeProvider
attribute="class"
defaultTheme="dark"
enableSystem
disableTransitionOnChange
>
{children}
<Toaster />
</ThemeProvider>
</body>
</html>
);
}

152
admin-next/src/app/login/page.tsx Executable file
View File

@@ -0,0 +1,152 @@
"use client";
import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { ShieldCheck, Keyboard } from "lucide-react";
import { useAuthStore } from "@/stores/auth-store";
import { toast } from "sonner";
export function LoginPage() {
const [token, setToken] = useState("");
const [loading, setLoading] = useState(false);
const { login, checkSession } = useAuthStore();
// Если сессия уже активна — сразу в админку (не показывать форму)
useEffect(() => {
checkSession().then((ok) => {
if (ok) {
window.location.href = "/";
}
});
}, [checkSession]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!token.trim()) return;
setLoading(true);
try {
const res = await fetch("/api/auth/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ token: token.trim() }),
});
if (!res.ok) {
const data = await res.json();
toast.error(data.error || "Login failed");
return;
}
const sessionRes = await fetch("/api/auth/session");
if (sessionRes.ok) {
const { role } = await sessionRes.json();
login(role);
toast.success("Logged in successfully");
// Полный редирект в корень админки (AppPage сам решает, показывать ли Dashboard)
window.location.href = "/";
} else {
toast.error("Session verification failed. Please try again.");
}
} catch {
toast.error("Connection error");
} finally {
setLoading(false);
}
};
return (
<div className="min-h-screen flex items-center justify-center bg-background relative overflow-hidden">
<div className="matrix-rain" />
{/* Background gradient mesh */}
<div className="absolute inset-0 -z-10">
<div className="absolute top-0 left-1/4 w-96 h-96 bg-primary/5 rounded-full blur-3xl" />
<div className="absolute bottom-0 right-1/4 w-96 h-96 bg-chart-1/5 rounded-full blur-3xl" />
<div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[600px] h-[600px] bg-chart-2/3 rounded-full blur-3xl opacity-[0.03]" />
</div>
{/* Subtle grid pattern */}
<div className="absolute inset-0 -z-10 opacity-[0.02] dark:opacity-[0.05]"
style={{
backgroundImage: "linear-gradient(oklch(0.5 0 0) 1px, transparent 1px), linear-gradient(90deg, oklch(0.5 0 0) 1px, transparent 1px)",
backgroundSize: "40px 40px",
}}
/>
<div className="w-full max-w-sm space-y-6 p-4 page-enter">
{/* Logo area */}
<div className="flex flex-col items-center gap-3 text-center">
<div className="relative">
<div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-primary text-primary-foreground shadow-lg shadow-primary/20">
<ShieldCheck className="size-8" />
</div>
<div className="absolute -inset-2 rounded-2xl bg-primary/10 blur-xl -z-10" />
</div>
<div>
<h1 className="text-2xl font-bold tracking-tight">TG Shop Admin</h1>
<p className="text-sm text-muted-foreground mt-1">
Enter your admin token to continue
</p>
</div>
</div>
<Card className="shadow-lg border-border/50 backdrop-blur-sm bg-card/80">
<CardHeader className="pb-4">
<CardTitle className="text-lg">Sign In</CardTitle>
<CardDescription>
Use your admin secret token to authenticate
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="token" className="text-sm font-medium">Admin Token</Label>
<Input
id="token"
type="password"
placeholder="Enter your token..."
value={token}
onChange={(e) => setToken(e.target.value)}
autoFocus
autoComplete="current-password"
className="h-10"
/>
</div>
<Button
type="submit"
className="w-full h-10 font-medium"
disabled={loading || !token.trim()}
>
{loading ? (
<span className="flex items-center gap-2">
<span className="size-4 animate-spin rounded-full border-2 border-current border-t-transparent" />
Authenticating...
</span>
) : (
"Sign In"
)}
</Button>
</form>
</CardContent>
</Card>
<div className="flex items-center justify-center gap-1.5 text-xs text-muted-foreground/60">
<Keyboard className="size-3" />
<span>Press Enter to sign in</span>
<span className="mx-1">·</span>
<span>Telegram Shop Admin v2.0</span>
</div>
</div>
</div>
);
}
export default LoginPage;

145
admin-next/src/app/page.tsx Executable file
View File

@@ -0,0 +1,145 @@
"use client";
import { useEffect, useState } from "react";
import { useAuthStore } from "@/stores/auth-store";
import { AdminSidebar } from "@/components/layout/admin-sidebar";
import { AdminHeader } from "@/components/layout/admin-header";
import { SidebarProvider, SidebarInset } from "@/components/ui/sidebar";
import { LoginPage } from "@/app/login/page";
import { DashboardPage } from "@/components/dashboard/dashboard-page";
import { CatalogHub } from "@/components/catalog/catalog-hub";
import { UsersPage } from "@/components/users/users-page";
import { UserDetailPage } from "@/components/users/user-detail-page";
import { WalletsPage } from "@/components/wallets/wallets-page";
import { PurchasesPage } from "@/components/purchases/purchases-page";
import { AuditPage } from "@/components/audit/audit-page";
import { SettingsPage } from "@/components/settings/settings-page";
import { LocalesPage } from "@/components/locales/locales-page";
import { SeedPage } from "@/components/seed/seed-page";
import { ChatbotSettingsPage } from "@/components/chatbot/chatbot-settings-page";
import { LeadsPage } from "@/components/leads/leads-page";
import { LeadDetailPage } from "@/components/leads/lead-detail-page";
import { ErrorBoundary } from "@/components/shared/error-boundary";
import { AdminFooter } from "@/components/layout/admin-footer";
import { useKeyboardShortcuts } from "@/hooks/use-keyboard-shortcuts";
import { Search } from "lucide-react";
import { Button } from "@/components/ui/button";
export default function AppPage() {
const { isAuthenticated, checkSession } = useAuthStore();
const [ready, setReady] = useState(false);
const [page, setPage] = useState<string>("/");
const [pageParams, setPageParams] = useState<Record<string, string>>({});
useEffect(() => {
checkSession().then(() => setReady(true));
}, [checkSession]);
useEffect(() => {
const handleHash = () => {
const hash = window.location.hash.slice(1) || "/";
const [path, search] = hash.split("?");
const params: Record<string, string> = {};
if (search) {
search.split("&").forEach((pair) => {
const [k, v] = pair.split("=");
if (k && v) params[decodeURIComponent(k)] = decodeURIComponent(v);
});
}
setPage(path);
setPageParams(params);
};
window.addEventListener("hashchange", handleHash);
handleHash();
return () => window.removeEventListener("hashchange", handleHash);
}, []);
useEffect(() => {
const handler = (e: MouseEvent) => {
const target = e.target as HTMLElement;
const link = target.closest("a");
if (!link) return;
const href = link.getAttribute("href");
if (!href) return;
if (href.startsWith("http") || href.startsWith("/api")) return;
e.preventDefault();
window.location.hash = href;
};
document.addEventListener("click", handler);
return () => document.removeEventListener("click", handler);
}, []);
useKeyboardShortcuts();
if (!ready) {
return (
<div className="min-h-screen flex flex-col items-center justify-center bg-background relative overflow-hidden">
{/* Background gradient orbs */}
<div className="absolute top-1/4 left-1/3 w-64 h-64 bg-primary/5 rounded-full blur-3xl" />
<div className="absolute bottom-1/4 right-1/3 w-48 h-48 bg-primary/5 rounded-full blur-3xl" />
<div className="relative flex flex-col items-center gap-4">
<div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-primary text-primary-foreground text-xl font-bold shadow-lg shadow-primary/20 animate-pulse">
TS
</div>
<div className="text-center">
<h1 className="text-lg font-semibold">TG Shop Admin</h1>
<p className="text-sm text-muted-foreground mt-1">Loading your workspace...</p>
</div>
{/* Progress bar */}
<div className="w-48 h-1 bg-muted rounded-full overflow-hidden">
<div className="h-full w-1/3 bg-primary rounded-full animate-[loading_1.5s_ease-in-out_infinite]" />
</div>
</div>
</div>
);
}
if (!isAuthenticated) {
return <LoginPage />;
}
const renderPage = () => {
if (page === "/") return <DashboardPage />;
if (page === "/catalog") return <CatalogHub />;
if (page === "/users") return <UsersPage />;
if (page.startsWith("/users/")) return <UserDetailPage userId={page.split("/")[2]} />;
if (page === "/wallets") return <WalletsPage />;
if (page === "/purchases") return <PurchasesPage />;
if (page === "/audit") return <AuditPage />;
if (page === "/settings") return <SettingsPage />;
if (page === "/locales") return <LocalesPage />;
if (page === "/chatbot") return <ChatbotSettingsPage />;
if (page === "/leads") return <LeadsPage />;
if (page.startsWith("/leads/")) return <LeadDetailPage leadId={page.split("/")[2]} />;
if (page === "/seed") return <SeedPage />;
return (
<div className="flex flex-col items-center justify-center h-64 page-enter">
<div className="rounded-full bg-muted p-4 mb-4">
<Search className="size-8 text-muted-foreground" />
</div>
<p className="text-lg font-medium">Page not found</p>
<p className="text-sm text-muted-foreground mt-1">The page you're looking for doesn't exist.</p>
<Button variant="outline" size="sm" className="mt-4" onClick={() => { window.location.hash = '/'; }}>
Go to Dashboard
</Button>
</div>
);
};
return (
<SidebarProvider>
<AdminSidebar />
<SidebarInset>
<div className="flex-1 flex flex-col overflow-hidden">
<AdminHeader />
<div className="flex-1 overflow-auto p-4 md:p-6">
<ErrorBoundary>{renderPage()}</ErrorBoundary>
</div>
<AdminFooter />
</div>
</SidebarInset>
</SidebarProvider>
);
}

View File

@@ -0,0 +1,50 @@
import { NextRequest, NextResponse } from 'next/server';
import { readFile, stat } from 'fs/promises';
import path from 'path';
const UPLOADS_DIR = '/app/uploads';
const MIME_MAP: Record<string, string> = {
'.webp': 'image/webp',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.png': 'image/png',
'.gif': 'image/gif',
};
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<{ path: string[] }> }
) {
const { path: pathSegments } = await params;
// Path traversal protection
if (pathSegments.some(seg => seg === '..' || seg.includes('..'))) {
return NextResponse.json({ error: 'Not found' }, { status: 404 });
}
const filePath = path.join(UPLOADS_DIR, ...pathSegments);
// Ensure resolved path is within UPLOADS_DIR
if (!filePath.startsWith(UPLOADS_DIR)) {
return NextResponse.json({ error: 'Not found' }, { status: 404 });
}
try {
await stat(filePath);
} catch {
return NextResponse.json({ error: 'Not found' }, { status: 404 });
}
const ext = path.extname(filePath).toLowerCase();
const contentType = MIME_MAP[ext] || 'application/octet-stream';
const buffer = await readFile(filePath);
return new NextResponse(buffer, {
headers: {
'Content-Type': contentType,
'Cache-Control': 'public, max-age=31536000, immutable',
},
});
}

View File

@@ -0,0 +1,368 @@
"use client";
import { useEffect, useState, useCallback, useRef, useMemo } from "react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Skeleton } from "@/components/ui/skeleton";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
import { toast } from "sonner";
import { format } from "date-fns";
import { ChevronDown, FileText, Search, Calendar, Copy, ClipboardList } from "lucide-react";
import { ExportButton } from "@/components/shared/export-button";
import { copyToClipboard } from "@/lib/clipboard";
import { SortableHeader } from "@/components/shared/sortable-header";
import { Pagination } from "@/components/shared/pagination";
interface AuditRow {
id: number;
action: string;
adminId: string;
details: string | null;
createdAt: string;
}
interface AuditResponse {
data: AuditRow[];
total: number;
page: number;
limit: number;
}
function ActionBadge({ action }: { action: string }) {
const map: Record<string, string> = {
login: "bg-blue-600 hover:bg-blue-700 text-white",
balance_adjust: "bg-orange-500 hover:bg-orange-600 text-white",
status_toggle: "bg-red-600 hover:bg-red-700 text-white",
seed_phrase_viewed: "bg-purple-600 hover:bg-purple-700 text-white",
csv_seed_export: "bg-purple-600 hover:bg-purple-700 text-white",
seed_demo: "bg-amber-600 hover:bg-amber-700 text-white",
clear_all: "bg-red-700 hover:bg-red-800 text-white",
};
const cls = map[action] || "";
return (
<Badge variant={cls ? "default" : "secondary"} className={cls + " whitespace-nowrap"}>
{action.replace(/_/g, " ")}
</Badge>
);
}
function parseDetails(details: string | null): string {
if (!details) return "\u2014";
try {
const obj = JSON.parse(details);
return JSON.stringify(obj, null, 2);
} catch {
return details;
}
}
function SkeletonTable() {
return (
<div className="space-y-3">
{Array.from({ length: 10 }).map((_, i) => (
<div key={i} className="flex items-center gap-4">
<Skeleton className="h-4 w-12" />
<Skeleton className="h-4 w-32" />
<Skeleton className="h-4 w-24" />
<Skeleton className="h-4 w-64" />
<Skeleton className="h-4 w-32" />
</div>
))}
</div>
);
}
export function AuditPage() {
const [logs, setLogs] = useState<AuditRow[]>([]);
const [total, setTotal] = useState(0);
const [page, setPage] = useState(1);
const [loading, setLoading] = useState(true);
const [openRows, setOpenRows] = useState<Set<number>>(new Set());
const [sortColumn, setSortColumn] = useState<string>("");
const [sortDirection, setSortDirection] = useState<"asc" | "desc" | null>(null);
const [actionFilter, setActionFilter] = useState<string>("all");
const [dateFrom, setDateFrom] = useState('');
const [dateTo, setDateTo] = useState('');
const [searchQuery, setSearchQuery] = useState('');
const [debouncedSearch, setDebouncedSearch] = useState('');
const debounceRef = useRef<ReturnType<typeof setTimeout>>(null);
const limit = 100;
const onSearchChange = (value: string) => {
setSearchQuery(value);
if (debounceRef.current) clearTimeout(debounceRef.current);
debounceRef.current = setTimeout(() => {
setDebouncedSearch(value);
setPage(1);
}, 300);
};
const handleActionFilterChange = (value: string) => {
setActionFilter(value);
setPage(1);
};
const fetchData = useCallback(async () => {
setLoading(true);
try {
const params = new URLSearchParams({ page: String(page), limit: String(limit) });
if (dateFrom) params.set('from', dateFrom);
if (dateTo) params.set('to', dateTo);
if (debouncedSearch) params.set('search', debouncedSearch);
if (actionFilter !== 'all') params.set('action', actionFilter);
const res = await fetch(`/api/audit/bulk?${params}`);
if (!res.ok) throw new Error("Failed to fetch");
const json: AuditResponse = await res.json();
setLogs(json.data);
setTotal(json.total);
} catch {
toast.error("Failed to load audit log");
} finally {
setLoading(false);
}
}, [page, dateFrom, dateTo, debouncedSearch, actionFilter]);
useEffect(() => {
fetchData();
}, [fetchData]);
const handleSort = (column: string) => {
if (sortColumn === column) {
if (sortDirection === "asc") setSortDirection("desc");
else if (sortDirection === "desc") {
setSortColumn("");
setSortDirection(null);
}
} else {
setSortColumn(column);
setSortDirection("asc");
}
};
const sortedLogs = useMemo(() => {
if (!sortColumn || !sortDirection) return logs;
return [...logs].sort((a, b) => {
let valA: unknown;
let valB: unknown;
if (sortColumn === "date") { valA = a.createdAt; valB = b.createdAt; }
else if (sortColumn === "action") { valA = a.action; valB = b.action; }
else return 0;
if (valA === valB) return 0;
const cmp = valA < valB ? -1 : 1;
return sortDirection === "asc" ? cmp : -cmp;
});
}, [logs, sortColumn, sortDirection]);
const exportData = useMemo<Record<string, unknown>[]>(
() => sortedLogs.map((l) => ({
ID: l.id,
Action: l.action,
"Admin ID": l.adminId,
Details: l.details || "",
Date: l.createdAt,
})),
[sortedLogs]
);
const toggleRow = (id: number) => {
setOpenRows((prev) => {
const next = new Set(prev);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
};
return (
<div className="page-enter space-y-4">
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
<div>
<h2 className="text-xl font-semibold">Audit Log</h2>
<p className="text-sm text-muted-foreground">
{total} entr{total !== 1 ? "ies" : "y"} total &middot; Track admin actions and system events
</p>
</div>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
onClick={() => {
const ok = copyToClipboard(JSON.stringify(sortedLogs, null, 2));
if (ok) toast.success("Copied all audit entries as JSON");
else toast.error("Failed to copy");
}}
>
<ClipboardList className="h-4 w-4 mr-1.5" />
Copy All
</Button>
<ExportButton data={exportData} filename="audit-log" />
</div>
</div>
<div className="flex flex-col sm:flex-row sm:items-center gap-3">
<div className="relative">
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
type="text"
placeholder="Search admin ID or details..."
value={searchQuery}
onChange={(e) => onSearchChange(e.target.value)}
className="h-8 w-full sm:w-64 pl-8 text-sm"
/>
</div>
<Select value={actionFilter} onValueChange={handleActionFilterChange}>
<SelectTrigger className="h-8 w-48 text-sm">
<SelectValue placeholder="Filter by action" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All Actions</SelectItem>
<SelectItem value="login">Login</SelectItem>
<SelectItem value="balance_adjust">Balance Adjust</SelectItem>
<SelectItem value="status_toggle">Status Toggle</SelectItem>
<SelectItem value="seed_phrase_viewed">Seed Phrase Viewed</SelectItem>
<SelectItem value="csv_seed_export">CSV Seed Export</SelectItem>
<SelectItem value="seed_demo">Seed Demo</SelectItem>
<SelectItem value="clear_all">Clear All</SelectItem>
<SelectItem value="purchase_update">Purchase Update</SelectItem>
</SelectContent>
</Select>
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Calendar className="h-4 w-4 shrink-0" />
<div className="flex items-center gap-2">
<div className="flex flex-col gap-0.5">
<span className="text-xs">From</span>
<Input
type="date"
value={dateFrom}
onChange={(e) => { setDateFrom(e.target.value); setPage(1); }}
className="h-8 w-40 text-sm"
/>
</div>
<div className="flex flex-col gap-0.5">
<span className="text-xs">To</span>
<Input
type="date"
value={dateTo}
onChange={(e) => { setDateTo(e.target.value); setPage(1); }}
className="h-8 w-40 text-sm"
/>
</div>
</div>
</div>
</div>
<div className="max-h-[calc(100vh-18rem)] overflow-y-auto rounded-lg border">
{loading ? (
<div className="p-4">
<SkeletonTable />
</div>
) : logs.length === 0 ? (
<div className="flex flex-col items-center justify-center py-16 text-muted-foreground empty-state">
<FileText className="size-12 mb-3 opacity-30" />
<p className="text-lg font-medium">No audit entries</p>
<p className="text-sm">Audit log is empty or no entries match the current filter.</p>
</div>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-16">ID</TableHead>
<TableHead className="w-40">
<SortableHeader column="action" label="Action" sortColumn={sortColumn} sortDirection={sortDirection} onSort={handleSort} />
</TableHead>
<TableHead className="w-28">Admin ID</TableHead>
<TableHead>Details</TableHead>
<TableHead className="w-36">
<SortableHeader column="date" label="Date" sortColumn={sortColumn} sortDirection={sortDirection} onSort={handleSort} />
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{sortedLogs.map((log) => (
<TableRow key={log.id}>
<TableCell className="font-mono text-xs">{log.id}</TableCell>
<TableCell>
<ActionBadge action={log.action} />
</TableCell>
<TableCell className="font-mono text-xs text-muted-foreground">
{log.adminId.length > 12 ? `${log.adminId.slice(0, 8)}...` : log.adminId}
</TableCell>
<TableCell>
{log.details ? (
<Collapsible
open={openRows.has(log.id)}
onOpenChange={() => toggleRow(log.id)}
>
<CollapsibleTrigger asChild>
<button className="flex items-center gap-1 text-sm text-left max-w-md w-full cursor-pointer">
<ChevronDown
className={`h-3 w-3 shrink-0 transition-transform ${openRows.has(log.id) ? "rotate-180" : ""}`}
/>
<span className="truncate font-mono text-xs text-muted-foreground">
{log.details.length > 80
? log.details.slice(0, 80) + "..."
: log.details}
</span>
</button>
</CollapsibleTrigger>
<CollapsibleContent>
<div className="mt-2 flex items-start gap-2">
<pre className="flex-1 p-2 rounded-md bg-muted/80 text-xs font-mono overflow-x-auto max-w-lg whitespace-pre-wrap break-all border">
{parseDetails(log.details)}
</pre>
<Button
variant="ghost"
size="icon"
className="h-7 w-7 shrink-0"
onClick={() => {
const ok = copyToClipboard(parseDetails(log.details));
if (ok) toast.success("JSON copied to clipboard");
else toast.error("Failed to copy");
}}
title="Copy JSON"
>
<Copy className="h-3.5 w-3.5" />
</Button>
</div>
</CollapsibleContent>
</Collapsible>
) : (
<span className="text-muted-foreground text-sm">{"\u2014"}</span>
)}
</TableCell>
<TableCell className="text-sm text-muted-foreground">
{format(new Date(log.createdAt), "MMM d, yyyy HH:mm")}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</div>
{!loading && total > 0 && (
<Pagination page={page} total={total} limit={limit} onPageChange={setPage} />
)}
</div>
);
}

View File

@@ -0,0 +1,97 @@
"use client";
import { useEffect, useState } from "react";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Package, Tag, MapPin, FolderTree } from "lucide-react";
import { CatalogPage } from "./catalog-page";
import { CategoriesPage } from "../categories/categories-page";
import { LocationsPage } from "../locations/locations-page";
const TABS = [
{ value: "products", label: "Товары", icon: Package, hash: "products" },
{ value: "categories", label: "Категории", icon: Tag, hash: "categories" },
{ value: "locations", label: "Локации", icon: MapPin, hash: "locations" },
] as const;
type TabValue = (typeof TABS)[number]["value"];
function resolveInitialTab(): TabValue {
const hash = window.location.hash.slice(1);
const params = hash.split("?")[1] || "";
const match = params.match(/tab=(\w+)/);
if (match) {
const v = match[1];
if (TABS.some((t) => t.value === v)) return v as TabValue;
}
const path = hash.split("?")[0];
if (path === "/catalog/categories") return "categories";
if (path === "/catalog/locations") return "locations";
return "products";
}
export function CatalogHub() {
const [activeTab, setActiveTab] = useState<TabValue>("products");
useEffect(() => {
const sync = () => {
setActiveTab(resolveInitialTab());
};
sync();
window.addEventListener("hashchange", sync);
return () => window.removeEventListener("hashchange", sync);
}, []);
const handleTabChange = (value: string) => {
const tab = value as TabValue;
setActiveTab(tab);
const base = "/catalog";
if (tab === "products") {
window.location.hash = base;
} else {
window.location.hash = `${base}?tab=${tab}`;
}
};
return (
<div className="page-enter">
<div className="mb-6">
<div className="flex items-center gap-3 mb-1">
<div className="flex h-9 w-9 items-center justify-center rounded-lg bg-primary/10">
<FolderTree className="size-5 text-primary" />
</div>
<div>
<h1 className="text-2xl font-bold tracking-tight">Каталог товаров</h1>
<p className="text-sm text-muted-foreground">
Управление товарами, категориями и локациями
</p>
</div>
</div>
</div>
<Tabs value={activeTab} onValueChange={handleTabChange} className="w-full">
<TabsList className="inline-flex h-10 w-full max-w-lg bg-muted p-1 rounded-lg">
{TABS.map((tab) => (
<TabsTrigger
key={tab.value}
value={tab.value}
className="flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-md text-sm font-medium transition-all data-[state=active]:bg-background data-[state=active]:shadow-sm data-[state=active]:text-foreground"
>
<tab.icon className="size-4 shrink-0" />
<span className="hidden sm:inline">{tab.label}</span>
</TabsTrigger>
))}
</TabsList>
<TabsContent value="products" className="mt-6">
<CatalogPage />
</TabsContent>
<TabsContent value="categories" className="mt-6">
<CategoriesPage />
</TabsContent>
<TabsContent value="locations" className="mt-6">
<LocationsPage />
</TabsContent>
</Tabs>
</div>
);
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,502 @@
"use client";
import { useEffect, useState, useCallback, useRef, useMemo } from "react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Skeleton } from "@/components/ui/skeleton";
import { Switch } from "@/components/ui/switch";
import {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { toast } from "sonner";
import { Plus, Pencil, Trash2, FolderOpen, Search, Eye } from "lucide-react";
interface ProductItem {
id: number;
name: string;
price: number;
quantityInStock: number;
isMono: number;
}
interface LocationItem {
id: number;
country: string;
city: string;
district: string;
}
interface CategoryRow {
id: number;
name: string;
isActive: number;
locationId: number;
location: LocationItem;
_count: { subcategories: number; products: number };
}
function SkeletonTable() {
return (
<div className="space-y-3">
{Array.from({ length: 8 }).map((_, i) => (
<div key={i} className="flex items-center gap-4">
<Skeleton className="h-4 w-12" />
<Skeleton className="h-4 w-32" />
<Skeleton className="h-4 w-48" />
<Skeleton className="h-4 w-16" />
<Skeleton className="h-4 w-16" />
<Skeleton className="h-4 w-12" />
<Skeleton className="h-4 w-24" />
</div>
))}
</div>
);
}
export function CategoriesPage() {
const [categories, setCategories] = useState<CategoryRow[]>([]);
const [locations, setLocations] = useState<LocationItem[]>([]);
const [loading, setLoading] = useState(true);
const [dialogOpen, setDialogOpen] = useState(false);
const [editing, setEditing] = useState<CategoryRow | null>(null);
const [formName, setFormName] = useState("");
const [formLocationId, setFormLocationId] = useState("");
const [saving, setSaving] = useState(false);
const [viewingCategory, setViewingCategory] = useState<CategoryRow | null>(null);
const [catProducts, setCatProducts] = useState<ProductItem[]>([]);
const [catProductsLoading, setCatProductsLoading] = useState(false);
const [deleteTarget, setDeleteTarget] = useState<CategoryRow | null>(null);
const [deleting, setDeleting] = useState(false);
const [search, setSearch] = useState("");
const [debouncedSearch, setDebouncedSearch] = useState("");
const debounceRef = useRef<ReturnType<typeof setTimeout>>();
const fetchCatProducts = useCallback(async (catId: number) => {
setCatProductsLoading(true);
try {
const res = await fetch(`/api/products/bulk?cat=${catId}&limit=100`);
if (!res.ok) throw new Error("Failed");
const json = await res.json();
setCatProducts(json.data);
} catch {
toast.error("Failed to load products");
setCatProducts([]);
} finally {
setCatProductsLoading(false);
}
}, []);
useEffect(() => {
if (viewingCategory) {
fetchCatProducts(viewingCategory.id);
} else {
setCatProducts([]);
}
}, [viewingCategory, fetchCatProducts]);
const fetchData = useCallback(async () => {
setLoading(true);
try {
const [catRes, locRes] = await Promise.all([
fetch("/api/categories/bulk"),
fetch("/api/locations/bulk"),
]);
if (!catRes.ok || !locRes.ok) throw new Error("Failed");
const catData = await catRes.json();
const locData = await locRes.json();
setCategories(catData);
setLocations(locData);
} catch {
toast.error("Failed to load categories");
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
fetchData();
}, [fetchData]);
const handleSearch = (value: string) => {
setSearch(value);
if (debounceRef.current) clearTimeout(debounceRef.current);
debounceRef.current = setTimeout(() => setDebouncedSearch(value), 300);
};
const filteredCategories = useMemo(() => {
if (!debouncedSearch) return categories;
const q = debouncedSearch.toLowerCase();
return categories.filter((c) => c.name.toLowerCase().includes(q));
}, [categories, debouncedSearch]);
const handleAdd = () => {
setEditing(null);
setFormName("");
setFormLocationId("");
setDialogOpen(true);
};
const handleEdit = (cat: CategoryRow) => {
setEditing(cat);
setFormName(cat.name);
setFormLocationId(String(cat.locationId));
setDialogOpen(true);
};
const handleSave = async () => {
if (!formName.trim() || !formLocationId) return;
setSaving(true);
try {
if (editing) {
const res = await fetch(`/api/categories/${editing.id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: formName.trim(), locationId: Number(formLocationId) }),
});
if (!res.ok) {
const err = await res.json();
throw new Error(err.error || "Update failed");
}
toast.success("Category updated");
} else {
const res = await fetch("/api/categories/bulk", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: formName.trim(), locationId: Number(formLocationId) }),
});
if (!res.ok) {
const err = await res.json();
throw new Error(err.error || "Create failed");
}
toast.success("Category created");
}
setDialogOpen(false);
fetchData();
} catch (e) {
toast.error(e instanceof Error ? e.message : "Operation failed");
} finally {
setSaving(false);
}
};
const handleToggle = async (cat: CategoryRow) => {
try {
const res = await fetch(`/api/categories/${cat.id}`, { method: "PATCH" });
if (!res.ok) throw new Error();
toast.success(`Category ${cat.isActive ? "deactivated" : "activated"}`);
fetchData();
} catch {
toast.error("Failed to toggle category");
}
};
const handleDelete = async () => {
if (!deleteTarget) return;
setDeleting(true);
try {
const res = await fetch(`/api/categories/${deleteTarget.id}`, { method: "DELETE" });
if (!res.ok) {
const err = await res.json();
throw new Error(err.error || "Delete failed");
}
toast.success("Category deleted");
setDeleteTarget(null);
fetchData();
} catch (e) {
toast.error(e instanceof Error ? e.message : "Delete failed");
} finally {
setDeleting(false);
}
};
const handleDeactivate = () => {
if (!deleteTarget) return;
handleToggle(deleteTarget);
setDeleteTarget(null);
};
// Group locations by country > city > district
const groupedLocations = locations.reduce<Record<string, Record<string, Record<string, LocationItem>>>>(
(acc, loc) => {
if (!acc[loc.country]) acc[loc.country] = {};
if (!acc[loc.country][loc.city]) acc[loc.country][loc.city] = {};
const key = loc.district || "(none)";
acc[loc.country][loc.city][key] = loc;
return acc;
},
{}
);
return (
<div className="page-enter p-4 md:p-6 space-y-4">
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
<div>
<h2 className="text-xl font-semibold">Categories</h2>
<p className="text-sm text-muted-foreground">
{categories.length} categor{categories.length !== 1 ? "ies" : "y"} total &middot; Organize your product catalog
</p>
</div>
<div className="flex items-center gap-3">
<div className="relative w-full sm:w-64">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Search categories..."
value={search}
onChange={(e) => handleSearch(e.target.value)}
className="pl-9"
/>
</div>
<Button onClick={handleAdd} size="sm">
<Plus className="h-4 w-4 mr-1" /> Add Category
</Button>
</div>
</div>
<div className="max-h-[calc(100vh-14rem)] overflow-y-auto rounded-lg border">
{loading ? (
<div className="p-4"><SkeletonTable /></div>
) : filteredCategories.length === 0 ? (
<div className="flex flex-col items-center justify-center py-16 text-muted-foreground">
<FolderOpen className="size-12 mb-3 opacity-30" />
<p className="text-lg font-medium">No categories found</p>
<p className="text-sm">Create your first category to get started.</p>
</div>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-16">ID</TableHead>
<TableHead>Name</TableHead>
<TableHead>Location</TableHead>
<TableHead className="w-36">Subcategories</TableHead>
<TableHead className="w-28">Products</TableHead>
<TableHead className="w-20">Active</TableHead>
<TableHead className="w-28">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{filteredCategories.map((cat) => (
<TableRow key={cat.id}>
<TableCell className="font-mono text-xs">{cat.id}</TableCell>
<TableCell className="font-medium">{cat.name}</TableCell>
<TableCell className="text-sm text-muted-foreground">
{cat.location.country} &gt; {cat.location.city}
{cat.location.district ? ` > ${cat.location.district}` : ""}
</TableCell>
<TableCell>
<Badge variant="outline">{cat._count.subcategories}</Badge>
</TableCell>
<TableCell>
<Badge variant="outline">{cat._count.products}</Badge>
</TableCell>
<TableCell>
<Switch
checked={cat.isActive === 1}
onCheckedChange={() => handleToggle(cat)}
/>
</TableCell>
<TableCell>
<div className="flex gap-1">
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={() => setViewingCategory(cat)}
title="View Products"
>
<Eye className="h-4 w-4" />
</Button>
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => handleEdit(cat)}>
<Pencil className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-red-600 hover:text-red-700"
onClick={() => setDeleteTarget(cat)}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</div>
{/* Add/Edit Dialog */}
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>{editing ? "Edit Category" : "Add Category"}</DialogTitle>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label htmlFor="cat-name">Name</Label>
<Input
id="cat-name"
value={formName}
onChange={(e) => setFormName(e.target.value)}
placeholder="Category name"
/>
</div>
<div className="space-y-2">
<Label>Location</Label>
<Select value={formLocationId} onValueChange={setFormLocationId}>
<SelectTrigger>
<SelectValue placeholder="Select location" />
</SelectTrigger>
<SelectContent>
{Object.entries(groupedLocations).map(([country, cities]) => (
<SelectGroup key={country}>
<SelectLabel>{country}</SelectLabel>
{Object.entries(cities).map(([city, districts]) =>
Object.entries(districts).map(([district, loc]) => (
<SelectItem key={loc.id} value={String(loc.id)}>
{city}{district !== "(none)" ? ` > ${district}` : ""}
</SelectItem>
))
)}
</SelectGroup>
))}
</SelectContent>
</Select>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setDialogOpen(false)}>Cancel</Button>
<Button onClick={handleSave} disabled={saving || !formName.trim() || !formLocationId}>
{saving ? "Saving..." : "Save"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Quick View Products Dialog */}
<Dialog open={!!viewingCategory} onOpenChange={(open) => !open && setViewingCategory(null)}>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>
Products in &quot;{viewingCategory?.name}&quot;
{viewingCategory && (
<span className="ml-2 text-sm font-normal text-muted-foreground">
({viewingCategory._count.products} product{viewingCategory._count.products !== 1 ? 's' : ''})
</span>
)}
</DialogTitle>
</DialogHeader>
<div className="max-h-96 overflow-y-auto rounded-lg border">
{catProductsLoading ? (
<div className="p-4 space-y-3">
{[1, 2, 3, 4].map((i) => (
<Skeleton key={i} className="h-10 w-full" />
))}
</div>
) : catProducts.length === 0 ? (
<div className="flex flex-col items-center justify-center py-12 text-muted-foreground">
<FolderOpen className="size-10 mb-2 opacity-30" />
<p className="text-sm">No products in this category</p>
</div>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-16">ID</TableHead>
<TableHead>Name</TableHead>
<TableHead className="text-right w-28">Price</TableHead>
<TableHead className="text-right w-20">Stock</TableHead>
<TableHead className="text-center w-20">Mono</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{catProducts.map((p) => (
<TableRow key={p.id}>
<TableCell className="font-mono text-xs">{p.id}</TableCell>
<TableCell className="text-sm font-medium">{p.name}</TableCell>
<TableCell className="text-right font-mono tabular-nums text-sm">
${p.price.toFixed(2)}
</TableCell>
<TableCell className="text-right text-sm">{p.quantityInStock}</TableCell>
<TableCell className="text-center">
<Badge variant={p.isMono === 1 ? 'default' : 'outline'}>
{p.isMono === 1 ? 'Yes' : 'No'}
</Badge>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</div>
</DialogContent>
</Dialog>
{/* Delete Confirmation */}
<AlertDialog open={!!deleteTarget} onOpenChange={(open) => !open && setDeleteTarget(null)}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete Category</AlertDialogTitle>
<AlertDialogDescription>
Are you sure you want to delete &quot;{deleteTarget?.name}&quot;? This action cannot be undone.
{deleteTarget && deleteTarget._count.products > 0 && (
<span className="block mt-2 text-red-600 font-medium">
This category has {deleteTarget._count.products} product(s) and cannot be deleted. You can deactivate it instead.
</span>
)}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
{deleteTarget && deleteTarget._count.products > 0 && (
<Button variant="outline" onClick={handleDeactivate}>
🔕 Deactivate
</Button>
)}
<AlertDialogAction
onClick={handleDelete}
disabled={deleting || (deleteTarget ? deleteTarget._count.products > 0 : true)}
className="bg-red-600 hover:bg-red-700"
>
{deleting ? "Deleting..." : "Delete"}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}

View File

@@ -0,0 +1,618 @@
"use client";
import { useState, useEffect, useCallback } from "react";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Button } from "@/components/ui/button";
import { Slider } from "@/components/ui/slider";
import { Separator } from "@/components/ui/separator";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import {
Bot,
Brain,
Thermometer,
BookOpen,
Settings2,
MessageSquare,
Shield,
Sparkles,
Save,
Moon,
Zap,
Database,
KeyRound,
Loader2,
} from "lucide-react";
import { toast } from "sonner";
interface ChatbotSettings {
chatbot_enabled: boolean;
chatbot_sleep_mode: boolean;
chatbot_sleep_message: string;
chatbot_system_prompt: string;
chatbot_welcome_message: string;
chatbot_temperature: number;
chatbot_max_tokens: number;
chatbot_max_history: number;
chatbot_knowledge_base: string;
chatbot_provider: string;
chatbot_api_endpoint: string;
chatbot_api_key: string;
chatbot_model: string;
}
const DEFAULTS: ChatbotSettings = {
chatbot_enabled: true,
chatbot_sleep_mode: false,
chatbot_sleep_message:
"Магазин сейчас пополняется товаром. Как только мы откроемся — я сразу вам сообщу! Можете оставить контакты и я свяжусь с вами при открытии.",
chatbot_system_prompt:
"Ты — AI-ассистент Telegram магазина цифровых товаров. Отвечай дружелюбно на русском. Помогай клиентам с выбором товаров. Если не знаешь ответ — честно скажи.",
chatbot_welcome_message: "",
chatbot_temperature: 0.7,
chatbot_max_tokens: 1000,
chatbot_max_history: 20,
chatbot_knowledge_base: "",
chatbot_provider: "ollama",
chatbot_api_endpoint: "https://ollama.com/v1/chat/completions",
chatbot_api_key: "",
chatbot_model: "deepseek-v4-flash:preview",
};
function SettingsSkeleton() {
return (
<div className="space-y-6">
<Skeleton className="h-8 w-64" />
<Skeleton className="h-10 w-full max-w-md" />
<div className="grid gap-4">
{Array.from({ length: 4 }).map((_, i) => (
<Skeleton key={i} className="h-32 w-full" />
))}
</div>
</div>
);
}
export function ChatbotSettingsPage() {
const [settings, setSettings] = useState<ChatbotSettings>(DEFAULTS);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [models, setModels] = useState<string[]>([]);
const [loadingModels, setLoadingModels] = useState(false);
const loadSettings = useCallback(async () => {
try {
const res = await fetch("/api/admin/chatbot");
if (res.ok) {
const data = await res.json();
const raw = data.settings || data;
const parsed: ChatbotSettings = {
...DEFAULTS,
chatbot_enabled: raw.chatbot_enabled === "true",
chatbot_sleep_mode: raw.chatbot_sleep_mode === "true",
chatbot_sleep_message: raw.chatbot_sleep_message || DEFAULTS.chatbot_sleep_message,
chatbot_system_prompt: raw.chatbot_system_prompt || DEFAULTS.chatbot_system_prompt,
chatbot_welcome_message: raw.chatbot_welcome_message || "",
chatbot_temperature: parseFloat(raw.chatbot_temperature) || 0.7,
chatbot_max_tokens: parseInt(raw.chatbot_max_tokens, 10) || 1000,
chatbot_max_history: parseInt(raw.chatbot_max_history, 10) || 20,
chatbot_knowledge_base: raw.chatbot_knowledge_base || "",
chatbot_provider: raw.chatbot_provider || "ollama",
chatbot_api_endpoint: raw.chatbot_api_endpoint || "",
chatbot_api_key: raw.chatbot_api_key || "",
chatbot_model: raw.chatbot_model || "deepseek-v4-flash:preview",
};
setSettings(parsed);
}
} catch {
toast.error("Ошибка загрузки настроек");
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
loadSettings();
}, [loadSettings]);
const update = <K extends keyof ChatbotSettings>(
key: K,
value: ChatbotSettings[K]
) => {
setSettings((prev) => ({ ...prev, [key]: value }));
};
const save = async () => {
setSaving(true);
try {
const res = await fetch("/api/admin/chatbot", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(settings),
});
if (res.ok) {
toast.success("Настройки сохранены");
} else {
const data = await res.json();
toast.error(data.error || "Ошибка сохранения");
}
} catch {
toast.error("Ошибка соединения");
} finally {
setSaving(false);
}
};
const loadModels = async () => {
setLoadingModels(true);
try {
const qs = new URLSearchParams();
if (settings.chatbot_api_endpoint) qs.set("endpoint", settings.chatbot_api_endpoint);
if (settings.chatbot_api_key) qs.set("apiKey", settings.chatbot_api_key);
const res = await fetch(`/api/chatbot/models?${qs.toString()}`);
const data = await res.json();
if (res.ok && Array.isArray(data.models)) {
setModels(data.models);
if (data.models.length > 0) {
toast.success(`Загружено моделей: ${data.models.length}`);
} else {
toast.info("Провайдер не вернул список моделей");
}
} else {
toast.error(data.error || "Ошибка загрузки моделей");
}
} catch {
toast.error("Ошибка соединения с провайдером");
} finally {
setLoadingModels(false);
}
};
const SaveButton = () => (
<div className="flex justify-end pt-4">
<Button onClick={save} disabled={saving} className="gap-2">
{saving ? (
<Loader2 className="size-4 animate-spin" />
) : (
<Save className="size-4" />
)}
Сохранить
</Button>
</div>
);
if (loading) return <SettingsSkeleton />;
return (
<div className="space-y-6 page-enter">
<div className="flex items-center gap-3">
<div className="flex h-10 w-10 items-center justify-center rounded-lg bg-primary/10">
<Bot className="size-5 text-primary" />
</div>
<div>
<h1 className="text-2xl font-bold tracking-tight">AI Чат-бот</h1>
<p className="text-sm text-muted-foreground">
Настройки ИИ-ассистента Telegram магазина
</p>
</div>
<Badge variant="outline" className="ml-auto gap-1">
<Sparkles className="size-3" />
{settings.chatbot_enabled ? "Активен" : "Выключен"}
</Badge>
</div>
<Tabs defaultValue="general" className="space-y-4">
<TabsList>
<TabsTrigger value="general" className="gap-2">
<MessageSquare className="size-4" />
<span className="hidden sm:inline">Общие</span>
</TabsTrigger>
<TabsTrigger value="ai" className="gap-2">
<Brain className="size-4" />
<span className="hidden sm:inline">Параметры ИИ</span>
</TabsTrigger>
<TabsTrigger value="knowledge" className="gap-2">
<BookOpen className="size-4" />
<span className="hidden sm:inline">База знаний</span>
</TabsTrigger>
<TabsTrigger value="provider" className="gap-2">
<Settings2 className="size-4" />
<span className="hidden sm:inline">Провайдер</span>
</TabsTrigger>
</TabsList>
{/* ── Tab 1: General ── */}
<TabsContent value="general" className="space-y-4">
<Card className="glass-card">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<Zap className="size-4 text-chart-1" />
Основные настройки
</CardTitle>
</CardHeader>
<CardContent className="space-y-6">
<div className="flex items-center justify-between">
<div className="space-y-0.5">
<Label htmlFor="chatbot_enabled" className="text-sm font-medium">
Бот включён
</Label>
<p className="text-xs text-muted-foreground">
Включает или отключает автоматический ответчик
</p>
</div>
<Switch
id="chatbot_enabled"
checked={settings.chatbot_enabled}
onCheckedChange={(v) => update("chatbot_enabled", v)}
/>
</div>
<Separator />
<div className="flex items-center justify-between">
<div className="space-y-0.5">
<Label
htmlFor="chatbot_sleep_mode"
className="text-sm font-medium"
>
Спящий режим
</Label>
<p className="text-xs text-muted-foreground">
При включении /start показывает ИИ-чат вместо каталога. Бот
сообщает что магазин пополняется.
</p>
</div>
<Switch
id="chatbot_sleep_mode"
checked={settings.chatbot_sleep_mode}
onCheckedChange={(v) => update("chatbot_sleep_mode", v)}
/>
</div>
</CardContent>
<div className="px-6 pb-6">
<SaveButton />
</div>
</Card>
<Card className="glass-card">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<Moon className="size-4 text-chart-4" />
Сообщения
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label htmlFor="sleep_message" className="text-sm font-medium">
Сообщение спящего режима
</Label>
<Textarea
id="sleep_message"
value={settings.chatbot_sleep_message}
onChange={(e) =>
update("chatbot_sleep_message", e.target.value)
}
rows={3}
placeholder="Сообщение при спящем режиме..."
/>
</div>
<div className="space-y-2">
<Label
htmlFor="system_prompt"
className="text-sm font-medium"
>
Системный промпт
</Label>
<Textarea
id="system_prompt"
value={settings.chatbot_system_prompt}
onChange={(e) =>
update("chatbot_system_prompt", e.target.value)
}
rows={6}
placeholder="Системный промпт для ИИ..."
/>
</div>
<div className="space-y-2">
<Label
htmlFor="welcome_message"
className="text-sm font-medium"
>
Приветственное сообщение
</Label>
<Textarea
id="welcome_message"
value={settings.chatbot_welcome_message}
onChange={(e) =>
update("chatbot_welcome_message", e.target.value)
}
rows={3}
placeholder="Приветственное сообщение при первом обращении..."
/>
</div>
</CardContent>
<div className="px-6 pb-6">
<SaveButton />
</div>
</Card>
</TabsContent>
{/* ── Tab 2: AI Parameters ── */}
<TabsContent value="ai" className="space-y-4">
<Card className="glass-card">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<Thermometer className="size-4 text-chart-1" />
Температура
</CardTitle>
<CardDescription>
Управляет случайностью ответов. Низкие значения более точные,
высокие более креативные.
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center gap-4">
<span className="text-sm text-muted-foreground w-6">0</span>
<div className="flex-1">
<Slider
min={0}
max={2}
step={0.1}
value={[settings.chatbot_temperature]}
onValueChange={([v]) => update("chatbot_temperature", v)}
/>
</div>
<span className="text-sm text-muted-foreground w-6">2</span>
<Badge variant="outline" className="tabular-nums font-mono w-12 justify-center">
{settings.chatbot_temperature.toFixed(1)}
</Badge>
</div>
</CardContent>
<div className="px-6 pb-6">
<SaveButton />
</div>
</Card>
<div className="grid gap-4 sm:grid-cols-2">
<Card className="glass-card">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<Sparkles className="size-4 text-chart-3" />
Max Tokens
</CardTitle>
<CardDescription>
Максимальное количество токенов в ответе ИИ (504000)
</CardDescription>
</CardHeader>
<CardContent>
<Input
type="number"
min={50}
max={4000}
value={settings.chatbot_max_tokens}
onChange={(e) =>
update(
"chatbot_max_tokens",
Math.min(4000, Math.max(50, Number(e.target.value) || 50))
)
}
className="font-mono"
/>
</CardContent>
<div className="px-6 pb-6">
<SaveButton />
</div>
</Card>
<Card className="glass-card">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<Shield className="size-4 text-chart-5" />
Max History
</CardTitle>
<CardDescription>
Количество сообщений в истории для каждого клиента (150)
</CardDescription>
</CardHeader>
<CardContent>
<Input
type="number"
min={1}
max={50}
value={settings.chatbot_max_history}
onChange={(e) =>
update(
"chatbot_max_history",
Math.min(50, Math.max(1, Number(e.target.value) || 1))
)
}
className="font-mono"
/>
</CardContent>
<div className="px-6 pb-6">
<SaveButton />
</div>
</Card>
</div>
</TabsContent>
{/* ── Tab 3: Knowledge Base ── */}
<TabsContent value="knowledge" className="space-y-4">
<Card className="glass-card">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<Database className="size-4 text-chart-2" />
База знаний
</CardTitle>
<CardDescription>
Добавьте информацию о товарах, ценах, FAQ. Бот будет использовать
это как контекст для ответов.
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<Textarea
value={settings.chatbot_knowledge_base}
onChange={(e) =>
update("chatbot_knowledge_base", e.target.value)
}
rows={12}
placeholder={"# О магазине\nМы продаём цифровые товары: аккаунты, подписки, ключи.\n\n# Цены\n- Netflix Premium: 500₽/мес\n- Spotify Premium: 300₽/мес\n\n# FAQ\nQ: Как быстро приходит товар?\nA: Моментально после оплаты."}
className="font-mono text-sm"
/>
</CardContent>
<div className="px-6 pb-6">
<SaveButton />
</div>
</Card>
</TabsContent>
{/* ── Tab 4: Provider ── */}
<TabsContent value="provider" className="space-y-4">
<Card className="glass-card">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<KeyRound className="size-4 text-chart-1" />
Провайдер ИИ
</CardTitle>
<CardDescription>
Выберите ИИ-провайдера и настройте подключение. Поддерживаются:
OpenAI, DeepSeek, OpenRouter, Ollama, а также любой совместимый
API через режим &quot;Custom&quot;.
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label className="text-sm font-medium">Провайдер</Label>
<Select
value={settings.chatbot_provider}
onValueChange={(v) => update("chatbot_provider", v)}
>
<SelectTrigger>
<SelectValue placeholder="Выберите провайдера" />
</SelectTrigger>
<SelectContent>
<SelectItem value="openai">OpenAI</SelectItem>
<SelectItem value="deepseek">DeepSeek</SelectItem>
<SelectItem value="openrouter">OpenRouter</SelectItem>
<SelectItem value="ollama">Ollama</SelectItem>
<SelectItem value="custom">Custom</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="api_endpoint" className="text-sm font-medium">
API Endpoint
</Label>
<Input
id="api_endpoint"
value={settings.chatbot_api_endpoint}
onChange={(e) =>
update("chatbot_api_endpoint", e.target.value)
}
placeholder="https://api.ollama.com/v1/chat/completions"
/>
</div>
<div className="space-y-2">
<Label htmlFor="model" className="text-sm font-medium">
Модель
</Label>
<div className="flex gap-2">
<Select
value={models.includes(settings.chatbot_model) ? settings.chatbot_model : ""}
onValueChange={(v) => update("chatbot_model", v)}
>
<SelectTrigger className="flex-1">
<SelectValue
placeholder={
models.length > 0
? "Выберите модель из списка провайдера"
: "Введите модель вручную или нажмите «Загрузить модели»"
}
/>
</SelectTrigger>
<SelectContent>
{models.length === 0 && (
<div className="px-2 py-3 text-center text-xs text-muted-foreground">
Список пуст нажмите «Загрузить модели» справа
</div>
)}
{models.map((m) => (
<SelectItem key={m} value={m}>
{m}
</SelectItem>
))}
</SelectContent>
</Select>
<Button
type="button"
variant="outline"
onClick={loadModels}
disabled={loadingModels}
className="gap-2 shrink-0"
>
{loadingModels ? (
<Loader2 className="size-4 animate-spin" />
) : (
<Sparkles className="size-4" />
)}
Загрузить модели
</Button>
</div>
<Input
id="model"
value={settings.chatbot_model}
onChange={(e) => update("chatbot_model", e.target.value)}
placeholder="Введите модель вручную, напр. deepseek-chat / gpt-4o / llama3.1:8b"
className="font-mono"
/>
<p className="text-xs text-muted-foreground">
Кнопка загружает список моделей из настроенного API (OpenAI-совместимый
/models). Для Custom-провайдера введите название модели вручную.
</p>
</div>
<div className="space-y-2">
<Label htmlFor="api_key" className="text-sm font-medium">
API Key
</Label>
<Input
id="api_key"
type="password"
value={settings.chatbot_api_key}
onChange={(e) =>
update("chatbot_api_key", e.target.value)
}
placeholder="b364c..."
/>
<p className="text-xs text-muted-foreground">
Ключ хранится зашифрованным. При отображении маскируется.
</p>
</div>
</CardContent>
<div className="px-6 pb-6">
<SaveButton />
</div>
</Card>
</TabsContent>
</Tabs>
</div>
);
}

View File

@@ -0,0 +1,909 @@
"use client";
import { useEffect, useState, useCallback, useRef } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import { Skeleton } from "@/components/ui/skeleton";
import { Switch } from "@/components/ui/switch";
import { ActivityFeed } from "@/components/layout/activity-feed";
import {
Users,
Package,
ShoppingCart,
DollarSign,
TrendingUp,
Percent,
CheckCircle,
Clock,
XCircle,
Tag,
RefreshCw,
ShieldBan,
Wallet,
ArrowRight,
} from "lucide-react";
import {
ResponsiveContainer,
AreaChart,
Area,
BarChart,
Bar,
PieChart,
Pie,
Cell,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
Legend,
} from "recharts";
// Chart colors
const CHART_1 = "#f97316";
const CHART_2 = "#06b6d4";
const CHART_3 = "#8b5cf6";
const CHART_4 = "#eab308";
const CHART_5 = "#ec4899";
const PIE_COLORS = [CHART_1, CHART_2, CHART_3, CHART_4, CHART_5];
// ─── Types ───────────────────────────────────────────────
interface RecentPurchase {
username: string;
productName: string;
totalPrice: number;
status: string;
purchaseDate: string;
}
interface DashboardStats {
totalUsers: number;
totalProducts: number;
totalPurchases: number;
totalRevenue: number;
totalSubcategories: number;
aov: number;
conversionRate: number;
completedPurchases: number;
pendingPurchases: number;
cancelledPurchases: number;
bannedUsers: number;
activeWallets: number;
}
interface ChartData {
days: string[];
revenueData: number[];
usersData: number[];
days30: string[];
revenueData30: number[];
}
interface TopProduct {
name: string;
qty: number;
revenue: number;
}
interface TopSpender {
username: string;
spent: number;
}
interface RevenueByCategory {
name: string;
value: number;
}
interface TopCountry {
country: string;
productCount: number;
}
interface WalletSummary {
walletType: string;
count: number;
totalBalance: number;
totalBalanceUsd: number;
}
interface DashboardData {
stats: DashboardStats;
chartData: ChartData;
topProducts: TopProduct[];
topSpenders: TopSpender[];
revenueByCategory: RevenueByCategory[];
topCountries: TopCountry[];
walletSummary: WalletSummary[];
recentPurchases: RecentPurchase[];
}
// ─── Helpers ─────────────────────────────────────────────
function formatCurrency(val: number): string {
return `$${val.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
}
function relativeTime(dateStr: string): string {
const now = Date.now();
const then = new Date(dateStr).getTime();
const diffMs = now - then;
const diffMin = Math.floor(diffMs / 60000);
const diffHr = Math.floor(diffMs / 3600000);
const diffDay = Math.floor(diffMs / 86400000);
if (diffMin < 1) return 'just now';
if (diffMin < 60) return `${diffMin}m ago`;
if (diffHr < 24) return `${diffHr}h ago`;
if (diffDay < 7) return `${diffDay}d ago`;
return new Date(dateStr).toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
}
function statusBadge(status: string): { label: string; cls: string } {
switch (status) {
case 'completed':
return { label: 'Completed', cls: 'bg-emerald-500/15 text-emerald-600 dark:text-emerald-400' };
case 'pending':
return { label: 'Pending', cls: 'bg-yellow-500/15 text-yellow-600 dark:text-yellow-400' };
case 'cancelled':
return { label: 'Cancelled', cls: 'bg-red-500/15 text-red-600 dark:text-red-400' };
default:
return { label: status, cls: 'bg-muted text-muted-foreground' };
}
}
function formatCrypto(val: number): string {
return val.toFixed(8);
}
function shortDate(dateStr: string): string {
const d = new Date(dateStr + "T00:00:00");
return d.toLocaleDateString("en-US", { month: "short", day: "numeric" });
}
// ─── Mini Sparkline ─────────────────────────────────────
function MiniSparkline({ data, color }: { data: number[]; color: string }) {
if (data.length < 2) return null;
const chartData = data.map((v, i) => ({ i, v }));
return (
<div className="absolute bottom-0 left-0 right-0 h-12 opacity-20 pointer-events-none">
<ResponsiveContainer width="100%" height="100%">
<AreaChart data={chartData} margin={{ top: 0, right: 0, left: 0, bottom: 0 }}>
<YAxis domain={["dataMin - 2", "dataMax + 2"]} hide />
<Area type="monotone" dataKey="v" stroke={color} fill={color} strokeWidth={1.5} />
</AreaChart>
</ResponsiveContainer>
</div>
);
}
function generateSparkData(value: number, points: number = 8): number[] {
const data: number[] = [];
let current = value * 0.6;
for (let i = 0; i < points; i++) {
current += (value - current) * (0.2 + Math.random() * 0.3);
data.push(Math.round(current * 10) / 10);
}
return data;
}
// ─── KPI Card ────────────────────────────────────────────
function KpiCard({
title,
value,
icon: Icon,
color,
sparklineColor,
sparklineValue,
}: {
title: string;
value: string;
icon: React.ComponentType<{ className?: string }>;
color: string;
sparklineColor?: string;
sparklineValue?: number;
}) {
const sparkData = sparklineValue !== undefined ? generateSparkData(sparklineValue) : undefined;
return (
<Card className="card-hover kpi-shimmer border-l-4 transition-transform hover:scale-[1.02] relative overflow-hidden" style={{ borderLeftColor: color }}>
<div
className="h-[2px] w-full rounded-t-lg"
style={{
background: `linear-gradient(to right, ${color}, ${color}66, transparent)`,
}}
/>
<CardContent className="p-4 flex items-center gap-4">
<div
className="flex h-12 w-12 shrink-0 items-center justify-center rounded-lg"
style={{ backgroundColor: `${color}15` }}
>
<Icon className="h-6 w-6" style={{ color }} />
</div>
<div className="min-w-0">
<p className="text-sm text-muted-foreground truncate">{title}</p>
<p className="text-xl font-bold truncate tabular-nums stat-value count-up">{value}</p>
</div>
</CardContent>
{sparkData && sparklineColor && <MiniSparkline data={sparkData} color={sparklineColor} />}
</Card>
);
}
// ─── Skeleton Loader ─────────────────────────────────────
function DashboardSkeleton() {
return (
<div className="p-4 md:p-6 space-y-6">
<Skeleton className="h-8 w-48" />
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-4">
{Array.from({ length: 10 }).map((_, i) => (
<Skeleton key={i} className="h-24 rounded-xl" />
))}
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{Array.from({ length: 4 }).map((_, i) => (
<Skeleton key={i} className="h-72 rounded-xl" />
))}
</div>
</div>
);
}
// ─── Chart Card wrapper ──────────────────────────────────
function ChartCard({
title,
children,
accentColor,
icon: ChartIcon,
}: {
title: string;
children: React.ReactNode;
accentColor?: string;
icon?: React.ComponentType<{ className?: string; style?: React.CSSProperties }>;
}) {
return (
<Card className="card-hover overflow-hidden">
<div
className="h-1 w-full"
style={{
background: `linear-gradient(to right, ${accentColor ?? CHART_1}, ${accentColor ?? CHART_1}44, transparent)`,
}}
/>
<CardHeader className="p-4 pb-0">
<CardTitle className="text-sm font-medium flex items-center gap-2">
{ChartIcon && <ChartIcon className="size-4" style={{ color: accentColor ?? CHART_1 }} />}
{title}
</CardTitle>
</CardHeader>
<CardContent className="p-4 pt-2">
<div className="h-72">{children}</div>
</CardContent>
</Card>
);
}
// ─── Main Component ──────────────────────────────────────
export function DashboardPage() {
const [data, setData] = useState<DashboardData | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [autoRefresh, setAutoRefresh] = useState(false);
const [lastUpdated, setLastUpdated] = useState<number>(Date.now());
const [refreshing, setRefreshing] = useState(false);
const autoRefreshRef = useRef<ReturnType<typeof setInterval> | null>(null);
const fetchDashboard = useCallback(async () => {
try {
setRefreshing(true);
setError(null);
const res = await fetch("/api/stats/dashboard");
if (!res.ok) {
throw new Error("Failed to load dashboard data");
}
const json = await res.json();
setData(json);
setLastUpdated(Date.now());
} catch (err) {
setError(err instanceof Error ? err.message : "Unknown error");
} finally {
setLoading(false);
setRefreshing(false);
}
}, []);
useEffect(() => {
fetchDashboard();
}, [fetchDashboard]);
// Auto-refresh toggle
useEffect(() => {
if (autoRefresh) {
autoRefreshRef.current = setInterval(fetchDashboard, 30000);
}
return () => {
if (autoRefreshRef.current) clearInterval(autoRefreshRef.current);
};
}, [autoRefresh, fetchDashboard]);
// "X seconds ago" ticker
const [secondsAgo, setSecondsAgo] = useState(0);
useEffect(() => {
const tick = setInterval(() => {
setSecondsAgo(Math.floor((Date.now() - lastUpdated) / 1000));
}, 1000);
return () => clearInterval(tick);
}, [lastUpdated]);
if (loading) return <DashboardSkeleton />;
if (error) {
return (
<div className="p-6">
<Card className="border-destructive">
<CardContent className="p-6">
<p className="text-destructive font-medium">{error}</p>
</CardContent>
</Card>
</div>
);
}
if (!data) return null;
const { stats, chartData, topProducts, topSpenders, revenueByCategory, walletSummary, recentPurchases } = data;
// Prepare chart datasets
const revenue7Data = chartData.days.map((day, i) => ({
date: shortDate(day),
revenue: chartData.revenueData[i],
}));
const revenue30Data = chartData.days30.map((day, i) => ({
date: shortDate(day),
revenue: chartData.revenueData30[i],
}));
const users7Data = chartData.days.map((day, i) => ({
date: shortDate(day),
users: chartData.usersData[i],
}));
const productsData = [...topProducts].reverse(); // reverse for horizontal bar
const spendersData = [...topSpenders].reverse();
const walletChartData = walletSummary.map((w) => ({
name: w.walletType,
count: w.count,
}));
// KPI definitions
const kpis = [
{ title: "Total Users", value: stats.totalUsers.toLocaleString(), icon: Users, color: CHART_1, sparklineColor: "#64748b", sparklineValue: stats.totalUsers },
{ title: "Total Products", value: stats.totalProducts.toLocaleString(), icon: Package, color: CHART_2, sparklineColor: "#64748b", sparklineValue: stats.totalProducts },
{ title: "Total Purchases", value: stats.totalPurchases.toLocaleString(), icon: ShoppingCart, color: CHART_3, sparklineColor: "#64748b", sparklineValue: stats.totalPurchases },
{ title: "Pending", value: stats.pendingPurchases.toLocaleString(), icon: Clock, color: "#eab308", sparklineColor: "#eab308", sparklineValue: stats.pendingPurchases },
{ title: "Total Revenue", value: formatCurrency(stats.totalRevenue), icon: DollarSign, color: "#22c55e", sparklineColor: "#22c55e", sparklineValue: stats.totalRevenue },
{ title: "Avg Order Value", value: formatCurrency(stats.aov), icon: TrendingUp, color: CHART_1, sparklineColor: "#64748b", sparklineValue: stats.aov },
{ title: "Conversion Rate", value: `${stats.conversionRate.toFixed(1)}%`, icon: Percent, color: CHART_5, sparklineColor: "#64748b", sparklineValue: stats.conversionRate },
{ title: "Completed", value: stats.completedPurchases.toLocaleString(), icon: CheckCircle, color: "#22c55e", sparklineColor: "#64748b", sparklineValue: stats.completedPurchases },
{ title: "Cancelled", value: stats.cancelledPurchases.toLocaleString(), icon: XCircle, color: "#ef4444", sparklineColor: "#64748b", sparklineValue: stats.cancelledPurchases },
{ title: "Banned Users", value: stats.bannedUsers.toLocaleString(), icon: ShieldBan, color: "#ef4444", sparklineColor: "#ef4444", sparklineValue: stats.bannedUsers },
{ title: "Active Wallets", value: stats.activeWallets.toLocaleString(), icon: Wallet, color: CHART_2, sparklineColor: "#06b6d4", sparklineValue: stats.activeWallets },
{ title: "Subcategories", value: stats.totalSubcategories.toLocaleString(), icon: Tag, color: CHART_2, sparklineColor: "#64748b", sparklineValue: stats.totalSubcategories },
];
return (
<div className="space-y-6 page-enter">
{/* ── Page Title ── */}
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
<p className="text-sm text-muted-foreground">Overview of your Telegram Shop</p>
<div className="flex items-center gap-4">
<span className="text-xs text-muted-foreground">
Last updated: {secondsAgo < 1 ? "just now" : `${secondsAgo} seconds ago`}
</span>
<button
type="button"
onClick={fetchDashboard}
disabled={refreshing}
className="inline-flex items-center justify-center rounded-md p-2 text-muted-foreground hover:text-foreground hover:bg-accent transition-colors disabled:opacity-50"
aria-label="Refresh dashboard"
>
<RefreshCw className={`h-4 w-4 ${refreshing ? "animate-spin" : ""}`} />
</button>
<div className="flex items-center gap-2">
<Switch
id="auto-refresh"
checked={autoRefresh}
onCheckedChange={setAutoRefresh}
/>
<label
htmlFor="auto-refresh"
className="text-xs text-muted-foreground cursor-pointer select-none"
>
Auto-refresh
</label>
</div>
</div>
</div>
{/* ── KPI Cards ── */}
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4">
{kpis.map((kpi) => (
<KpiCard key={kpi.title} {...kpi} icon={kpi.icon} />
))}
</div>
<Separator />
{/* ── Charts Grid ── */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{/* 1. Revenue 7 days */}
<ChartCard title="Revenue — Last 7 Days" accentColor={CHART_1} icon={TrendingUp}>
{revenue7Data.length > 0 ? (
<ResponsiveContainer width="100%" height="100%">
<AreaChart data={revenue7Data}>
<defs>
<linearGradient id="rev7grad" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor={CHART_1} stopOpacity={0.3} />
<stop offset="95%" stopColor={CHART_1} stopOpacity={0} />
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" />
<XAxis dataKey="date" tick={{ fontSize: 11 }} stroke="hsl(var(--muted-foreground))" />
<YAxis tick={{ fontSize: 11 }} stroke="hsl(var(--muted-foreground))" />
<Tooltip
contentStyle={{
backgroundColor: "hsl(var(--card))",
border: "1px solid hsl(var(--border))",
borderRadius: "8px",
fontSize: "12px",
}}
/>
<Area
type="monotone"
dataKey="revenue"
stroke={CHART_1}
fill="url(#rev7grad)"
strokeWidth={2}
/>
</AreaChart>
</ResponsiveContainer>
) : (
<div className="h-full flex items-center justify-center text-muted-foreground text-sm">No data</div>
)}
</ChartCard>
{/* 2. Revenue 30 days */}
<ChartCard title="Revenue — Last 30 Days" accentColor={CHART_2} icon={TrendingUp}>
{revenue30Data.length > 0 ? (
<ResponsiveContainer width="100%" height="100%">
<AreaChart data={revenue30Data}>
<defs>
<linearGradient id="rev30grad" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor={CHART_2} stopOpacity={0.3} />
<stop offset="95%" stopColor={CHART_2} stopOpacity={0} />
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" />
<XAxis dataKey="date" tick={{ fontSize: 10 }} stroke="hsl(var(--muted-foreground))" interval={4} />
<YAxis tick={{ fontSize: 11 }} stroke="hsl(var(--muted-foreground))" />
<Tooltip
contentStyle={{
backgroundColor: "hsl(var(--card))",
border: "1px solid hsl(var(--border))",
borderRadius: "8px",
fontSize: "12px",
}}
/>
<Area
type="monotone"
dataKey="revenue"
stroke={CHART_2}
fill="url(#rev30grad)"
strokeWidth={2}
/>
</AreaChart>
</ResponsiveContainer>
) : (
<div className="h-full flex items-center justify-center text-muted-foreground text-sm">No data</div>
)}
</ChartCard>
{/* 3. New Users 7 days */}
<ChartCard title="New Users — Last 7 Days" accentColor={CHART_3} icon={Users}>
{users7Data.length > 0 ? (
<ResponsiveContainer width="100%" height="100%">
<BarChart data={users7Data}>
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" />
<XAxis dataKey="date" tick={{ fontSize: 11 }} stroke="hsl(var(--muted-foreground))" />
<YAxis allowDecimals={false} tick={{ fontSize: 11 }} stroke="hsl(var(--muted-foreground))" />
<Tooltip
contentStyle={{
backgroundColor: "hsl(var(--card))",
border: "1px solid hsl(var(--border))",
borderRadius: "8px",
fontSize: "12px",
}}
/>
<Bar dataKey="users" fill={CHART_3} radius={[4, 4, 0, 0]} />
</BarChart>
</ResponsiveContainer>
) : (
<div className="h-full flex items-center justify-center text-muted-foreground text-sm">No data</div>
)}
</ChartCard>
{/* 4. Top 5 Products */}
<ChartCard title="Top 5 Products by Quantity Sold" accentColor={CHART_4} icon={Package}>
{productsData.length > 0 ? (
<ResponsiveContainer width="100%" height="100%">
<BarChart data={productsData} layout="vertical" margin={{ left: 20 }}>
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" horizontal={false} />
<XAxis type="number" tick={{ fontSize: 11 }} stroke="hsl(var(--muted-foreground))" />
<YAxis type="category" dataKey="name" width={120} tick={{ fontSize: 11 }} stroke="hsl(var(--muted-foreground))" />
<Tooltip
contentStyle={{
backgroundColor: "hsl(var(--card))",
border: "1px solid hsl(var(--border))",
borderRadius: "8px",
fontSize: "12px",
}}
formatter={(value: number, name: string) => {
if (name === "qty") return [value, "Quantity"];
return [formatCurrency(value), "Revenue"];
}}
/>
<Bar dataKey="qty" fill={CHART_4} radius={[0, 4, 4, 0]} />
</BarChart>
</ResponsiveContainer>
) : (
<div className="h-full flex items-center justify-center text-muted-foreground text-sm">No data</div>
)}
</ChartCard>
{/* 5. Top 5 Spenders */}
<ChartCard title="Top 5 Spenders" accentColor={CHART_5} icon={DollarSign}>
{spendersData.length > 0 ? (
<ResponsiveContainer width="100%" height="100%">
<BarChart data={spendersData} layout="vertical" margin={{ left: 20 }}>
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" horizontal={false} />
<XAxis type="number" tick={{ fontSize: 11 }} stroke="hsl(var(--muted-foreground))" />
<YAxis type="category" dataKey="username" width={120} tick={{ fontSize: 11 }} stroke="hsl(var(--muted-foreground))" />
<Tooltip
contentStyle={{
backgroundColor: "hsl(var(--card))",
border: "1px solid hsl(var(--border))",
borderRadius: "8px",
fontSize: "12px",
}}
formatter={(value: number) => [formatCurrency(value), "Spent"]}
/>
<Bar dataKey="spent" fill={CHART_5} radius={[0, 4, 4, 0]} />
</BarChart>
</ResponsiveContainer>
) : (
<div className="h-full flex items-center justify-center text-muted-foreground text-sm">No data</div>
)}
</ChartCard>
{/* 6. Revenue by Category (Pie/Donut) */}
<ChartCard title="Revenue by Category" accentColor={CHART_1} icon={Tag}>
{revenueByCategory.length > 0 ? (
<ResponsiveContainer width="100%" height="100%">
<PieChart>
<Pie
data={revenueByCategory}
cx="50%"
cy="50%"
innerRadius={50}
outerRadius={90}
paddingAngle={2}
dataKey="value"
nameKey="name"
label={({ name, percent }) =>
`${name} ${(percent * 100).toFixed(0)}%`
}
labelLine={true}
fontSize={11}
>
{revenueByCategory.map((_, index) => (
<Cell
key={`cell-${index}`}
fill={PIE_COLORS[index % PIE_COLORS.length]}
/>
))}
</Pie>
<Tooltip
contentStyle={{
backgroundColor: "hsl(var(--card))",
border: "1px solid hsl(var(--border))",
borderRadius: "8px",
fontSize: "12px",
}}
formatter={(value: number) => [formatCurrency(value), "Revenue"]}
/>
<Legend />
</PieChart>
</ResponsiveContainer>
) : (
<div className="h-full flex items-center justify-center text-muted-foreground text-sm">No data</div>
)}
</ChartCard>
{/* 7. Purchase Status Distribution */}
<ChartCard title="Purchase Status Distribution" accentColor="#eab308" icon={ShoppingCart}>
<ResponsiveContainer width="100%" height="100%">
<PieChart>
<Pie
data={[
{ name: 'Pending', value: stats.pendingPurchases },
{ name: 'Completed', value: stats.completedPurchases },
{ name: 'Cancelled', value: stats.cancelledPurchases },
]}
cx="50%"
cy="50%"
innerRadius={55}
outerRadius={90}
paddingAngle={3}
dataKey="value"
nameKey="name"
label={({ name, percent }) =>
`${name} ${(percent * 100).toFixed(0)}%`
}
labelLine={true}
fontSize={11}
>
<Cell fill="#eab308" />
<Cell fill="#10b981" />
<Cell fill="#ef4444" />
</Pie>
<Tooltip
contentStyle={{
backgroundColor: "hsl(var(--card))",
border: "1px solid hsl(var(--border))",
borderRadius: "8px",
fontSize: "12px",
}}
formatter={(value: number) => [value, "Purchases"]}
/>
<Legend />
</PieChart>
</ResponsiveContainer>
</ChartCard>
</div>
{/* ── Analytics Cards: Revenue Trend + User Funnel ── */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
{/* Card A: Revenue Trend (30-day area chart) */}
<Card className="card-hover overflow-hidden md:col-span-2">
<div
className="h-1 w-full"
style={{
background: `linear-gradient(to right, ${CHART_2}, ${CHART_2}44, transparent)`,
}}
/>
<CardHeader className="p-4 pb-0 flex flex-row items-center gap-2">
<TrendingUp className="h-4 w-4 text-muted-foreground" />
<CardTitle className="text-sm font-medium">Revenue Trend</CardTitle>
</CardHeader>
<CardContent className="p-4 pt-2">
<div className="h-80">
{revenue30Data.length > 0 ? (
<ResponsiveContainer width="100%" height="100%">
<AreaChart data={revenue30Data}>
<defs>
<linearGradient id="revTrendGrad" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor={CHART_2} stopOpacity={0.4} />
<stop offset="95%" stopColor={CHART_2} stopOpacity={0} />
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" />
<XAxis dataKey="date" tick={{ fontSize: 10 }} stroke="hsl(var(--muted-foreground))" interval={4} />
<YAxis tick={{ fontSize: 11 }} stroke="hsl(var(--muted-foreground))" tickFormatter={(v: number) => `$${v}`} />
<Tooltip
contentStyle={{
backgroundColor: "hsl(var(--card))",
border: "1px solid hsl(var(--border))",
borderRadius: "8px",
fontSize: "12px",
}}
formatter={(value: number) => [formatCurrency(value), "Revenue"]}
/>
<Area
type="monotone"
dataKey="revenue"
stroke={CHART_2}
fill="url(#revTrendGrad)"
strokeWidth={2}
/>
</AreaChart>
</ResponsiveContainer>
) : (
<div className="h-full flex items-center justify-center text-muted-foreground text-sm">No data</div>
)}
</div>
</CardContent>
</Card>
{/* Card B: Conversion Funnel (horizontal bar) */}
<Card className="card-hover overflow-hidden md:col-span-1">
<div
className="h-1 w-full"
style={{
background: `linear-gradient(to right, #64748b, #64748b44, transparent)`,
}}
/>
<CardHeader className="p-4 pb-0 flex flex-row items-center gap-2">
<Users className="h-4 w-4 text-muted-foreground" />
<CardTitle className="text-sm font-medium">User Funnel</CardTitle>
</CardHeader>
<CardContent className="p-4 pt-2">
<div className="h-80">
<ResponsiveContainer width="100%" height="100%">
<BarChart
data={[
{ name: "Total Users", value: stats.totalUsers },
{ name: "Users with Purchases", value: stats.totalPurchases },
{ name: "Users with Wallets", value: stats.activeWallets },
]}
layout="vertical"
margin={{ left: 10, right: 20 }}
>
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" horizontal={false} />
<XAxis type="number" tick={{ fontSize: 11 }} stroke="hsl(var(--muted-foreground))" />
<YAxis
type="category"
dataKey="name"
width={120}
tick={{ fontSize: 11 }}
stroke="hsl(var(--muted-foreground))"
/>
<Tooltip
contentStyle={{
backgroundColor: "hsl(var(--card))",
border: "1px solid hsl(var(--border))",
borderRadius: "8px",
fontSize: "12px",
}}
/>
<Bar dataKey="value" radius={[0, 4, 4, 0]}>
<Cell fill="#64748b" />
<Cell fill="#10b981" />
<Cell fill="#06b6d4" />
</Bar>
</BarChart>
</ResponsiveContainer>
</div>
</CardContent>
</Card>
</div>
<Separator />
{/* ── Recent Purchases Table ── */}
<Card className="card-hover">
<CardHeader className="p-4 pb-0 flex flex-row items-center justify-between">
<CardTitle className="text-sm font-medium">Recent Purchases</CardTitle>
<button
type="button"
onClick={() => { window.location.hash = '#/purchases'; }}
className="inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"
>
View all
<ArrowRight className="h-3 w-3" />
</button>
</CardHeader>
<CardContent className="p-4">
{data.recentPurchases.length > 0 ? (
<div className="overflow-x-auto">
<table className="w-full text-sm alternate-rows table-header-gradient">
<thead>
<tr className="border-b">
<th className="text-left py-2 px-2 font-medium text-muted-foreground text-xs">Product</th>
<th className="text-left py-2 px-2 font-medium text-muted-foreground text-xs">User</th>
<th className="text-right py-2 px-2 font-medium text-muted-foreground text-xs">Amount</th>
<th className="text-center py-2 px-2 font-medium text-muted-foreground text-xs">Status</th>
<th className="text-right py-2 px-2 font-medium text-muted-foreground text-xs">Date</th>
</tr>
</thead>
<tbody>
{data.recentPurchases.map((p, i) => {
const badge = statusBadge(p.status);
return (
<tr key={i} className="border-b last:border-0">
<td className="py-2 px-2 text-xs font-medium truncate max-w-[140px]">{p.productName}</td>
<td className="py-2 px-2 text-xs text-muted-foreground truncate max-w-[100px]">{p.username}</td>
<td className="py-2 px-2 text-xs text-right font-mono tabular-nums">{formatCurrency(p.totalPrice)}</td>
<td className="py-2 px-2 text-center">
<span className={`inline-block rounded-full px-2 py-0.5 text-xs font-medium whitespace-nowrap ${badge.cls}`}>
{badge.label}
</span>
</td>
<td className="py-2 px-2 text-xs text-right text-muted-foreground whitespace-nowrap">{relativeTime(p.purchaseDate)}</td>
</tr>
);
})}
</tbody>
</table>
</div>
) : (
<div className="h-24 flex items-center justify-center text-muted-foreground text-sm">No recent purchases</div>
)}
</CardContent>
</Card>
<Separator />
{/* ── Bottom Section: Wallet Summary + Wallet Chart ── */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
{/* Wallet Summary Table */}
<Card className="card-hover">
<CardHeader className="p-4 pb-0">
<CardTitle className="text-sm font-medium">Wallet Summary</CardTitle>
</CardHeader>
<CardContent className="p-4">
{walletSummary.length > 0 ? (
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="border-b">
<th className="text-left py-2 px-3 font-medium text-muted-foreground">Type</th>
<th className="text-right py-2 px-3 font-medium text-muted-foreground">Count</th>
<th className="text-right py-2 px-3 font-medium text-muted-foreground">Balance</th>
<th className="text-right py-2 px-3 font-medium text-muted-foreground">USD (mock)</th>
</tr>
</thead>
<tbody>
{walletSummary.map((w) => (
<tr key={w.walletType} className="border-b last:border-0">
<td className="py-2 px-3 font-medium">{w.walletType}</td>
<td className="py-2 px-3 text-right text-muted-foreground">{w.count}</td>
<td className="py-2 px-3 text-right font-mono text-xs">{formatCrypto(w.totalBalance)}</td>
<td className="py-2 px-3 text-right">{formatCurrency(w.totalBalanceUsd)}</td>
</tr>
))}
</tbody>
</table>
</div>
) : (
<div className="h-48 flex items-center justify-center text-muted-foreground text-sm">No wallet data</div>
)}
</CardContent>
</Card>
{/* Wallet Count by Type Chart */}
<ChartCard title="Wallet Count by Type" accentColor={CHART_2} icon={Wallet}>
{walletChartData.length > 0 ? (
<ResponsiveContainer width="100%" height="100%">
<BarChart data={walletChartData}>
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" />
<XAxis dataKey="name" tick={{ fontSize: 11 }} stroke="hsl(var(--muted-foreground))" />
<YAxis allowDecimals={false} tick={{ fontSize: 11 }} stroke="hsl(var(--muted-foreground))" />
<Tooltip
contentStyle={{
backgroundColor: "hsl(var(--card))",
border: "1px solid hsl(var(--border))",
borderRadius: "8px",
fontSize: "12px",
}}
formatter={(value: number) => [value, "Wallets"]}
/>
<Bar dataKey="count" fill={CHART_2} radius={[4, 4, 0, 0]} />
</BarChart>
</ResponsiveContainer>
) : (
<div className="h-full flex items-center justify-center text-muted-foreground text-sm">No wallet data</div>
)}
</ChartCard>
</div>
{/* ── Activity Feed (full width) ── */}
<ActivityFeed />
</div>
);
}

View File

@@ -0,0 +1,188 @@
"use client";
import { useEffect, useState, useCallback } from "react";
import {
LogIn,
DollarSign,
UserX,
KeyRound,
Package,
Settings,
CheckCircle,
Wallet,
CreditCard,
UserPlus,
FileText,
ShoppingCart,
Ban,
Upload,
} from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
// ─── Types ───────────────────────────────────────────────
interface ActivityItem {
id: number;
action: string;
createdAt: string;
adminId: string;
details: string | null;
}
// ─── Icon + color mapping ─────────────────────────────────
const ACTION_CONFIG: Record<
string,
{ icon: React.ComponentType<{ className?: string }>; color: string; badge: string }
> = {
login: { icon: LogIn, color: "#06b6d4", badge: "bg-cyan-500/15 text-cyan-400 border-cyan-500/25" },
balance_adjust: { icon: DollarSign, color: "#f97316", badge: "bg-orange-500/15 text-orange-400 border-orange-500/25" },
status_toggle: { icon: UserX, color: "#ef4444", badge: "bg-red-500/15 text-red-400 border-red-500/25" },
seed_phrase_viewed: { icon: KeyRound, color: "#a855f7", badge: "bg-violet-500/15 text-violet-400 border-violet-500/25" },
csv_seed_export: { icon: Upload, color: "#a855f7", badge: "bg-violet-500/15 text-violet-400 border-violet-500/25" },
product_created: { icon: Package, color: "#22c55e", badge: "bg-emerald-500/15 text-emerald-400 border-emerald-500/25" },
settings_changed: { icon: Settings, color: "#22c55e", badge: "bg-emerald-500/15 text-emerald-400 border-emerald-500/25" },
purchase_approved: { icon: CheckCircle, color: "#22c55e", badge: "bg-emerald-500/15 text-emerald-400 border-emerald-500/25" },
purchase_cancelled: { icon: Ban, color: "#ef4444", badge: "bg-red-500/15 text-red-400 border-red-500/25" },
wallet_added: { icon: Wallet, color: "#06b6d4", badge: "bg-cyan-500/15 text-cyan-400 border-cyan-500/25" },
commission_paid: { icon: CreditCard, color: "#f59e0b", badge: "bg-yellow-500/15 text-yellow-400 border-yellow-500/25" },
user_registered: { icon: UserPlus, color: "#14b8a6", badge: "bg-teal-500/15 text-teal-400 border-teal-500/25" },
user_banned: { icon: Ban, color: "#ef4444", badge: "bg-red-500/15 text-red-400 border-red-500/25" },
user_unbanned: { icon: CheckCircle, color: "#22c55e", badge: "bg-emerald-500/15 text-emerald-400 border-emerald-500/25" },
purchase_created: { icon: ShoppingCart, color: "#f59e0b", badge: "bg-yellow-500/15 text-yellow-400 border-yellow-500/25" },
};
const DEFAULT_CONFIG = { icon: FileText, color: "#6b7280", badge: "bg-muted text-muted-foreground border-border" };
// ─── Helpers ──────────────────────────────────────────────
function relativeTime(dateStr: string): string {
const now = Date.now();
const then = new Date(dateStr).getTime();
const diffMs = now - then;
const diffSec = Math.floor(diffMs / 1000);
if (diffSec < 60) return `${diffSec} second${diffSec !== 1 ? "s" : ""} ago`;
const diffMin = Math.floor(diffSec / 60);
if (diffMin < 60) return `${diffMin} minute${diffMin !== 1 ? "s" : ""} ago`;
const diffHr = Math.floor(diffMin / 60);
if (diffHr < 24) return `${diffHr} hour${diffHr !== 1 ? "s" : ""} ago`;
const diffDay = Math.floor(diffHr / 24);
if (diffDay < 30) return `${diffDay} day${diffDay !== 1 ? "s" : ""} ago`;
return `${Math.floor(diffDay / 30)} month${Math.floor(diffDay / 30) !== 1 ? "s" : ""} ago`;
}
function actionDescription(action: string, details: string | null): string {
const label = action.replace(/_/g, " ");
if (!details) return label;
try {
const obj = JSON.parse(details);
if (obj.username) return `${label}${obj.username}`;
if (obj.target) return `${label}${obj.target}`;
if (obj.userId) return `${label} — user #${obj.userId}`;
} catch {
// not JSON
}
return label;
}
// ─── Component ────────────────────────────────────────────
export function ActivityFeed() {
const [items, setItems] = useState<ActivityItem[]>([]);
const [loading, setLoading] = useState(true);
const fetchFeed = useCallback(async () => {
try {
const res = await fetch("/api/stats/dashboard");
if (!res.ok) return;
const json = await res.json();
setItems(json.recentActivity ?? []);
} catch {
// silently fail
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
fetchFeed();
const interval = setInterval(fetchFeed, 30000);
return () => clearInterval(interval);
}, [fetchFeed]);
return (
<Card>
<CardHeader className="p-4 pb-0">
<CardTitle className="text-sm font-medium">
Recent Activity
</CardTitle>
</CardHeader>
<CardContent className="p-4">
{loading ? (
<div className="max-h-64 animate-pulse space-y-2">
{Array.from({ length: 5 }).map((_, i) => (
<div
key={i}
className="flex items-center gap-3 rounded-md border p-2"
>
<div className="h-6 w-6 rounded-full bg-muted" />
<div className="flex-1 space-y-1">
<div className="h-3 w-3/4 rounded bg-muted" />
<div className="h-2 w-1/3 rounded bg-muted" />
</div>
</div>
))}
</div>
) : items.length > 0 ? (
<div className="max-h-64 overflow-y-auto space-y-1.5">
{items.map((item, index) => {
const config = ACTION_CONFIG[item.action] ?? DEFAULT_CONFIG;
const Icon = config.icon;
return (
<div
key={item.id}
className="flex items-center gap-3 rounded-md border border-border/50 px-3 py-2 animate-in fade-in slide-in-from-left-1 duration-300"
style={{ animationDelay: `${index * 50}ms`, animationFillMode: "both" }}
>
<div
className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full"
style={{ backgroundColor: `${config.color}15` }}
>
<Icon
className="h-3.5 w-3.5"
style={{ color: config.color }}
/>
</div>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<p className="text-sm truncate leading-tight">
{actionDescription(item.action, item.details)}
</p>
</div>
<div className="flex items-center gap-2 mt-0.5">
<Badge
variant="outline"
className={`text-[10px] px-1.5 py-0 h-4 font-normal ${config.badge}`}
>
{item.action.replace(/_/g, " ")}
</Badge>
<span className="text-xs text-muted-foreground">
{relativeTime(item.createdAt)}
</span>
</div>
</div>
</div>
);
})}
</div>
) : (
<div className="flex h-48 items-center justify-center text-muted-foreground text-sm">
No recent activity
</div>
)}
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,23 @@
"use client";
export function AdminFooter() {
const year = new Date().getFullYear();
return (
<footer className="mt-auto border-t-0 gradient-border-t px-4 py-3 flex items-center justify-between text-xs text-muted-foreground bg-background/80 backdrop-blur-sm relative z-10" style={{ borderTopStyle: 'solid', borderTopWidth: '1px' }}>
<div className="flex items-center gap-2">
<span className="font-medium hidden sm:inline text-foreground/80 transition-colors hover:text-foreground cursor-default">
TG Shop Admin
</span>
<span className="hidden sm:inline text-muted-foreground/30">·</span>
<span className="text-muted-foreground/60">v2.1.0</span>
</div>
<div className="flex items-center gap-3">
<span className="hidden sm:inline text-muted-foreground/50 transition-colors hover:text-muted-foreground cursor-default">
Next.js 16 · SQLite · Prisma
</span>
<span className="text-muted-foreground/30">© {year}</span>
</div>
</footer>
);
}

View File

@@ -0,0 +1,196 @@
"use client"
import { useState, useEffect } from "react";
import { SidebarTrigger } from "@/components/ui/sidebar";
import { Separator } from "@/components/ui/separator";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Moon, Sun, LogOut, User, Search } from "lucide-react";
import { useTheme } from "next-themes";
import { useAuthStore } from "@/stores/auth-store";
import { CommandPalette, openCommandPalette } from "@/components/layout/command-palette";
import { AppBreadcrumbs } from "@/components/layout/breadcrumbs";
import { QuickActions } from "@/components/layout/quick-actions";
import { NotificationsPanel } from "@/components/layout/notifications-panel";
const pageTitles: Record<string, string> = {
"/": "Dashboard",
"/catalog": "Catalog",
"/users": "Users",
"/wallets": "Wallets",
"/purchases": "Purchases",
"/audit": "Audit Log",
"/categories": "Categories",
"/locations": "Locations",
"/settings": "Settings",
"/locales": "Locales",
"/seed": "Danger Zone",
"/login": "Sign In",
};
function getInitialTime() {
const now = new Date();
const hh = String(now.getHours()).padStart(2, "0");
const mm = String(now.getMinutes()).padStart(2, "0");
return `${hh}:${mm}`;
}
function RealtimeClock() {
const [time, setTime] = useState(getInitialTime);
useEffect(() => {
const interval = setInterval(() => {
const now = new Date();
const hh = String(now.getHours()).padStart(2, "0");
const mm = String(now.getMinutes()).padStart(2, "0");
setTime(`${hh}:${mm}`);
}, 1000);
return () => clearInterval(interval);
}, []);
const parts = time.split(":");
return (
<span className="text-xs text-muted-foreground font-mono tabular-nums hidden md:flex items-center">
{parts[0]}<span className="colon-pulse mx-px">:</span>{parts[1]}
</span>
);
}
export function AdminHeader() {
const [hash, setHash] = useState("");
const { theme, setTheme } = useTheme();
const { role, logout } = useAuthStore();
const [logoutOpen, setLogoutOpen] = useState(false);
useEffect(() => {
const update = () => setHash(window.location.hash.slice(1) || "/");
update();
window.addEventListener("hashchange", update);
return () => window.removeEventListener("hashchange", update);
}, []);
const title =
pageTitles[hash] ||
(hash.startsWith("/users/")
? "User Detail"
: hash.split("/").pop()?.charAt(0).toUpperCase() +
hash.split("/").pop()?.slice(1) ||
"Page");
return (
<header className="flex h-14 shrink-0 items-center gap-2 border-b-0 px-4 gradient-border-b bg-background/80 backdrop-blur-md relative z-10" style={{ borderBottomStyle: 'solid', borderBottomWidth: '1px' }}>
<SidebarTrigger className="-ml-1" />
<Separator orientation="vertical" className="mr-2 h-4" />
<AppBreadcrumbs />
<h1 className="text-base font-semibold flex-1 truncate hidden sm:block">
{title}
</h1>
{/* 1. Clock (hidden on mobile) */}
<RealtimeClock />
{/* 2. Command palette search button */}
<Button
variant="ghost"
size="icon"
onClick={openCommandPalette}
className="shrink-0"
title="Search (Ctrl+K)"
>
<Search className="size-4" />
<span className="sr-only">Search</span>
</Button>
{/* 3. Notifications bell button */}
<NotificationsPanel />
{/* 4. Quick actions zap button */}
<QuickActions />
{/* 5. Theme toggle */}
<Button
variant="ghost"
size="icon"
onClick={() => setTheme(theme === "dark" ? "light" : "dark")}
className="shrink-0"
>
<Sun className="size-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" />
<Moon className="absolute size-4 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100" />
<span className="sr-only">Toggle theme</span>
</Button>
{/* 6. User dropdown */}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="relative h-8 w-8 rounded-full">
<Avatar className="size-8">
<AvatarFallback className="bg-primary/10 text-primary text-xs">
{role === "super_admin" ? "SA" : "AD"}
</AvatarFallback>
</Avatar>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48">
<div className="px-2 py-1.5">
<p className="text-sm font-medium">
{role === "super_admin" ? "Super Admin" : "Admin"}
</p>
<Badge
variant={role === "super_admin" ? "default" : "secondary"}
className="text-[10px] px-1.5 py-0 mt-1"
>
{role}
</Badge>
</div>
<DropdownMenuItem onClick={() => { window.location.hash = "/settings"; }}>
<User className="mr-2 size-4" />
Settings
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setLogoutOpen(true)}
className="text-destructive"
>
<LogOut className="mr-2 size-4" />
Sign out
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<AlertDialog open={logoutOpen} onOpenChange={setLogoutOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Sign out</AlertDialogTitle>
<AlertDialogDescription>
Are you sure you want to sign out? You will need to
re-enter your admin token.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={() => {
logout();
window.location.hash = "/login";
}}
className="bg-destructive text-white hover:bg-destructive/90"
>
Sign out
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<CommandPalette />
</header>
);
}

View File

@@ -0,0 +1,332 @@
"use client";
import { useState, useEffect } from "react";
import {
LayoutDashboard,
Package,
Users,
Wallet,
ShoppingCart,
FileText,
Settings,
Languages,
AlertTriangle,
LogOut,
ShieldCheck,
Shield,
Bot,
Target,
FolderTree,
} from "lucide-react";
import {
Sidebar,
SidebarContent,
SidebarFooter,
SidebarGroup,
SidebarGroupContent,
SidebarGroupLabel,
SidebarHeader,
SidebarMenu,
SidebarMenuBadge,
SidebarMenuButton,
SidebarMenuItem,
SidebarRail,
SidebarSeparator,
} from "@/components/ui/sidebar";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { useAuthStore } from "@/stores/auth-store";
const mainNav = [
{ title: "Dashboard", href: "/", icon: LayoutDashboard, shortcut: "1" },
{ title: "Пользователи", href: "/users", icon: Users, shortcut: "2" },
{ title: "Кошельки", href: "/wallets", icon: Wallet, shortcut: "3" },
{ title: "Покупки", href: "/purchases", icon: ShoppingCart, badge: true, shortcut: "4" },
{ title: "Аудит", href: "/audit", icon: FileText, shortcut: "5" },
];
const catalogNav = [
{ title: "Каталог товаров", href: "/catalog", icon: FolderTree, shortcut: "6" },
];
const automationNav = [
{ title: "AI Chatbot", href: "/chatbot", icon: Bot },
{ title: "Лиды", href: "/leads", icon: Target },
];
const systemNav = [
{ title: "Настройки", href: "/settings", icon: Settings, shortcut: "9" },
{ title: "Локали", href: "/locales", icon: Languages },
];
function usePendingCount(isAuthenticated: boolean) {
const [count, setCount] = useState(0);
useEffect(() => {
if (!isAuthenticated) return;
let cancelled = false;
const load = () => {
fetch("/api/purchases/bulk?status=pending&limit=1")
.then((res) => (res.ok ? res.json() : null))
.then((data) => {
if (!cancelled && data) setCount(data.total ?? 0);
})
.catch(() => {});
};
load();
window.addEventListener("focus", load);
return () => {
cancelled = true;
window.removeEventListener("focus", load);
};
}, [isAuthenticated]);
return count;
}
function useConnectionStatus() {
const { checkSession } = useAuthStore();
const [connected, setConnected] = useState(false);
useEffect(() => {
let cancelled = false;
const check = () => {
checkSession().then((valid) => {
if (!cancelled) setConnected(valid);
});
};
check();
window.addEventListener("focus", check);
return () => {
cancelled = true;
window.removeEventListener("focus", check);
};
}, [checkSession]);
return connected;
}
function useHashPath() {
const [hash, setHash] = useState("");
useEffect(() => {
const update = () => setHash(window.location.hash.slice(1) || "/");
update();
window.addEventListener("hashchange", update);
return () => window.removeEventListener("hashchange", update);
}, []);
return hash;
}
export function AdminSidebar() {
const pathname = useHashPath();
const { role, logout, isAuthenticated } = useAuthStore();
const pendingCount = usePendingCount(isAuthenticated);
const connected = useConnectionStatus();
return (
<Sidebar collapsible="icon">
<SidebarHeader className="p-4">
<button
type="button"
className="flex items-center gap-3 group-data-[collapsible=icon]:justify-center w-full transition-transform hover:scale-110 cursor-pointer"
onClick={() => { window.location.hash = '#/'; }}
aria-label="Go to Dashboard"
>
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary text-primary-foreground text-sm font-bold">
TS
</div>
<div className="flex flex-col overflow-hidden group-data-[collapsible=icon]:hidden">
<span className="text-sm font-semibold truncate">TG Shop</span>
<span className="text-xs text-muted-foreground">Admin Panel</span>
</div>
</button>
</SidebarHeader>
<SidebarSeparator />
<SidebarContent>
<SidebarGroup>
<SidebarGroupLabel>Основное</SidebarGroupLabel>
<SidebarGroupContent>
<SidebarMenu className="stagger-in">
{mainNav.map((item) => (
<SidebarMenuItem key={item.href}>
<SidebarMenuButton
asChild
isActive={
item.href === "/"
? pathname === "/"
: pathname.startsWith(item.href)
}
tooltip={item.title}
className="[&[data-active='true']]:border-l-2 [&[data-active='true']]:border-l-sidebar-primary relative"
>
<a href={item.href}>
<item.icon className="size-4 text-muted-foreground transition-colors group-hover/sidebar-menu-button:text-primary" />
<span>{item.title}</span>
{item.shortcut && (
<kbd className="ml-auto text-[10px] font-mono text-muted-foreground/50 bg-muted/50 px-1.5 py-0.5 rounded group-data-[collapsible=icon]:hidden">
{item.shortcut}
</kbd>
)}
</a>
</SidebarMenuButton>
{item.badge && pendingCount > 0 && (
<SidebarMenuBadge className="bg-destructive text-destructive-foreground">
{pendingCount}
</SidebarMenuBadge>
)}
{item.badge && pendingCount > 0 && (
<span className="sidebar-indicator-dot absolute left-0 top-1/2 -translate-y-1/2 w-1.5 h-1.5 rounded-full bg-destructive group-data-[collapsible=icon]:left-1/2 group-data-[collapsible=icon]:-translate-x-1/2" />
)}
</SidebarMenuItem>
))}
</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
<SidebarGroup>
<SidebarGroupLabel>Каталог товаров</SidebarGroupLabel>
<SidebarGroupContent>
<SidebarMenu className="stagger-in">
{catalogNav.map((item) => (
<SidebarMenuItem key={item.href}>
<SidebarMenuButton
asChild
isActive={
item.href === "/catalog"
? (pathname === "/catalog" || pathname.startsWith("/catalog?"))
: pathname === item.href || pathname.startsWith(item.href)
}
tooltip={item.title}
className="[&[data-active='true']]:border-l-2 [&[data-active='true']]:border-l-sidebar-primary relative"
>
<a href={item.href}>
<item.icon className="size-4 text-muted-foreground transition-colors group-hover/sidebar-menu-button:text-primary" />
<span>{item.title}</span>
{item.shortcut && (
<kbd className="ml-auto text-[10px] font-mono text-muted-foreground/50 bg-muted/50 px-1.5 py-0.5 rounded group-data-[collapsible=icon]:hidden">
{item.shortcut}
</kbd>
)}
</a>
</SidebarMenuButton>
</SidebarMenuItem>
))}
</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
<SidebarGroup>
<SidebarGroupLabel>Автоматизация</SidebarGroupLabel>
<SidebarGroupContent>
<SidebarMenu className="stagger-in">
{automationNav.map((item) => (
<SidebarMenuItem key={item.href}>
<SidebarMenuButton
asChild
isActive={pathname.startsWith(item.href)}
tooltip={item.title}
className="[&[data-active='true']]:border-l-2 [&[data-active='true']]:border-l-sidebar-primary relative"
>
<a href={item.href}>
<item.icon className="size-4 text-muted-foreground transition-colors group-hover/sidebar-menu-button:text-primary" />
<span>{item.title}</span>
</a>
</SidebarMenuButton>
</SidebarMenuItem>
))}
</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
<SidebarGroup>
<SidebarGroupLabel>Система</SidebarGroupLabel>
<SidebarGroupContent>
<SidebarMenu className="stagger-in">
{systemNav.map((item) => (
<SidebarMenuItem key={item.href}>
<SidebarMenuButton
asChild
isActive={pathname.startsWith(item.href)}
tooltip={item.title}
className="[&[data-active='true']]:border-l-2 [&[data-active='true']]:border-l-sidebar-primary relative"
>
<a href={item.href}>
<item.icon className="size-4 text-muted-foreground transition-colors group-hover/sidebar-menu-button:text-primary" />
<span>{item.title}</span>
{item.shortcut && (
<kbd className="ml-auto text-[10px] font-mono text-muted-foreground/50 bg-muted/50 px-1.5 py-0.5 rounded group-data-[collapsible=icon]:hidden">
{item.shortcut}
</kbd>
)}
</a>
</SidebarMenuButton>
</SidebarMenuItem>
))}
{role === "super_admin" && (
<SidebarMenuItem>
<SidebarMenuButton
asChild
isActive={pathname.startsWith("/seed")}
tooltip="Danger Zone"
>
<a href="/seed">
<AlertTriangle className="size-4 text-destructive" />
<span className="text-destructive">Danger Zone</span>
</a>
</SidebarMenuButton>
</SidebarMenuItem>
)}
</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
</SidebarContent>
<SidebarFooter>
<SidebarSeparator className="mb-1" />
<div className="flex items-center gap-3 px-3 py-2 group-data-[collapsible=icon]:justify-center">
<Avatar className="size-8 ring-1 ring-border">
<AvatarFallback className="bg-primary/10 text-primary text-xs">
{role === "super_admin" ? (
<ShieldCheck className="size-4" />
) : (
<Shield className="size-4" />
)}
</AvatarFallback>
</Avatar>
<div className="flex flex-1 flex-col overflow-hidden group-data-[collapsible=icon]:hidden">
<span className="text-sm font-medium truncate">
{role === "super_admin" ? "Super Admin" : "Admin"}
</span>
<Badge
variant={role === "super_admin" ? "default" : "secondary"}
className="w-fit text-[10px] px-1.5 py-0 mt-0.5"
>
{role}
</Badge>
</div>
<button
onClick={logout}
className="shrink-0 rounded-md p-1.5 hover:bg-accent text-muted-foreground hover:text-foreground transition-colors group-data-[collapsible=icon]:hidden"
title="Logout"
>
<LogOut className="size-4" />
</button>
</div>
<div className="flex items-center gap-2 px-3 pb-3 pt-1 group-data-[collapsible=icon]:justify-center">
<span
className={`size-1.5 rounded-full shrink-0 transition-colors ${
connected ? "bg-green-500 glow-success" : "bg-muted-foreground/50"
}`}
/>
<span className="text-[11px] text-muted-foreground group-data-[collapsible=icon]:hidden">
{connected ? "Connected" : "Disconnected"}
</span>
</div>
</SidebarFooter>
<SidebarRail />
</Sidebar>
);
}

View File

@@ -0,0 +1,126 @@
"use client";
import { useState, useEffect, Fragment } from "react";
import {
Breadcrumb,
BreadcrumbEllipsis,
BreadcrumbItem,
BreadcrumbLink,
BreadcrumbList,
BreadcrumbPage,
BreadcrumbSeparator,
} from "@/components/ui/breadcrumb";
interface Crumb {
label: string;
href: string;
}
const pageLabels: Record<string, string> = {
"": "Дашборд",
catalog: "Каталог товаров",
users: "Пользователи",
wallets: "Кошельки",
purchases: "Покупки",
audit: "Аудит",
settings: "Настройки",
locales: "Локали",
seed: "Danger Zone",
chatbot: "AI Chatbot",
leads: "Лиды",
login: "Вход",
};
function parseHash(hash: string): Crumb[] {
const path = hash.replace(/^#\/?/, "");
const segments = path.split("/").filter(Boolean);
const crumbs: Crumb[] = [{ label: "Home", href: "/" }];
if (segments.length === 0) {
return crumbs;
}
let href = "";
for (let i = 0; i < segments.length; i++) {
href += "/" + segments[i];
const label = pageLabels[segments[i]] || segments[i];
crumbs.push({ label, href });
}
return crumbs;
}
export function AppBreadcrumbs() {
const [crumbs, setCrumbs] = useState<Crumb[]>([{ label: "Home", href: "/" }]);
useEffect(() => {
const update = () => setCrumbs(parseHash(window.location.hash));
update();
window.addEventListener("hashchange", update);
return () => window.removeEventListener("hashchange", update);
}, []);
if (crumbs.length <= 1) {
return null;
}
return (
<Breadcrumb>
{/* Desktop: show all breadcrumbs */}
<BreadcrumbList className="hidden sm:flex">
{crumbs.map((crumb, index) => {
const isLast = index === crumbs.length - 1;
return (
<Fragment key={crumb.href}>
<BreadcrumbItem>
{isLast ? (
<BreadcrumbPage>{crumb.label}</BreadcrumbPage>
) : (
<BreadcrumbLink
href="#"
onClick={(e) => {
e.preventDefault();
window.location.hash = crumb.href;
}}
>
{crumb.label}
</BreadcrumbLink>
)}
</BreadcrumbItem>
{!isLast && <BreadcrumbSeparator />}
</Fragment>
);
})}
</BreadcrumbList>
{/* Mobile: show last 2 breadcrumbs with ellipsis */}
<BreadcrumbList className="flex sm:hidden">
{crumbs.length > 2 && (
<>
<BreadcrumbItem>
<BreadcrumbEllipsis />
</BreadcrumbItem>
<BreadcrumbSeparator />
</>
)}
<BreadcrumbItem>
<BreadcrumbLink
href="#"
onClick={(e) => {
e.preventDefault();
const href = crumbs.length > 1 ? crumbs[crumbs.length - 2].href : "/";
window.location.hash = href;
}}
>
{crumbs.length > 1 ? crumbs[crumbs.length - 2].label : "Home"}
</BreadcrumbLink>
</BreadcrumbItem>
<BreadcrumbSeparator />
<BreadcrumbItem>
<BreadcrumbPage>{crumbs[crumbs.length - 1].label}</BreadcrumbPage>
</BreadcrumbItem>
</BreadcrumbList>
</Breadcrumb>
);
}

View File

@@ -0,0 +1,267 @@
"use client";
import { useState, useEffect, useCallback, useRef } from "react";
import type { LucideIcon } from "lucide-react";
import {
LayoutDashboard,
Package,
Users,
Wallet,
ShoppingCart,
FileText,
Tag,
MapPin,
Settings,
Languages,
AlertTriangle,
Database,
Trash2,
LogOut,
Loader2,
Bot,
Target,
} from "lucide-react";
import {
CommandDialog,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
CommandSeparator,
} from "@/components/ui/command";
import { useAuthStore } from "@/stores/auth-store";
const COMMAND_TOGGLE = "command-palette:toggle";
export function openCommandPalette() {
window.dispatchEvent(new CustomEvent(COMMAND_TOGGLE));
}
const navigationItems = [
{ label: "Dashboard", href: "/", Icon: LayoutDashboard },
{ label: "Пользователи", href: "/users", Icon: Users },
{ label: "Кошельки", href: "/wallets", Icon: Wallet },
{ label: "Покупки", href: "/purchases", Icon: ShoppingCart },
{ label: "Аудит", href: "/audit", Icon: FileText },
{ label: "Товары", href: "/catalog", Icon: Package },
{ label: "Категории", href: "/catalog?tab=categories", Icon: Tag },
{ label: "Локации", href: "/catalog?tab=locations", Icon: MapPin },
{ label: "AI Chatbot", href: "/chatbot", Icon: Bot },
{ label: "Лиды", href: "/leads", Icon: Target },
{ label: "Настройки", href: "/settings", Icon: Settings },
{ label: "Локали", href: "/locales", Icon: Languages },
{ label: "Danger Zone", href: "/seed", Icon: AlertTriangle },
] as const;
interface GlobalResult {
type: string;
label: string;
href: string;
Icon: LucideIcon;
}
export function CommandPalette() {
const [open, setOpen] = useState(false);
const [query, setQuery] = useState("");
const [globalResults, setGlobalResults] = useState<GlobalResult[]>([]);
const [searching, setSearching] = useState(false);
const { logout, role } = useAuthStore();
const isSuperAdmin = role === 'super_admin';
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const toggle = useCallback(() => {
setOpen((prev) => !prev);
}, []);
// Debounced user search
useEffect(() => {
if (debounceRef.current) clearTimeout(debounceRef.current);
if (query.length < 2) {
setGlobalResults([]);
setSearching(false);
return;
}
debounceRef.current = setTimeout(async () => {
setSearching(true);
try {
const res = await fetch(`/api/users/bulk?search=${encodeURIComponent(query)}&limit=5`);
if (!res.ok) {
setGlobalResults([]);
return;
}
const data = await res.json();
const users: Array<{ id: number; username: string | null; telegramId: string }> = data.data || [];
setGlobalResults(
users.map((user) => ({
type: "user",
label: `${user.username || "@" + user.telegramId} (ID: ${user.id})`,
href: `/users/${user.id}`,
Icon: Users,
}))
);
} catch {
setGlobalResults([]);
} finally {
setSearching(false);
}
}, 300);
return () => {
if (debounceRef.current) clearTimeout(debounceRef.current);
};
}, [query]);
// Reset query when palette closes
useEffect(() => {
if (!open) {
setQuery("");
setGlobalResults([]);
}
}, [open]);
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if ((e.metaKey || e.ctrlKey) && e.key === "k") {
e.preventDefault();
toggle();
}
};
document.addEventListener("keydown", handleKeyDown);
return () => document.removeEventListener("keydown", handleKeyDown);
}, [toggle]);
useEffect(() => {
const handleToggle = () => setOpen(true);
window.addEventListener(COMMAND_TOGGLE, handleToggle);
return () => window.removeEventListener(COMMAND_TOGGLE, handleToggle);
}, []);
return (
<CommandDialog open={open} onOpenChange={setOpen}>
<CommandInput
placeholder="Type a command or search..."
value={query}
onValueChange={setQuery}
/>
<CommandList>
<CommandEmpty>
{searching ? (
<span className="flex items-center gap-2 justify-center">
<Loader2 className="size-3.5 animate-spin" />
Searching...
</span>
) : (
"No results found."
)}
</CommandEmpty>
<CommandGroup heading="Navigation">
{navigationItems
.filter((item) => isSuperAdmin || item.href !== "/seed")
.map((item) => (
<CommandItem
key={item.href}
onSelect={() => {
setOpen(false);
window.location.hash = item.href;
}}
>
<item.Icon className="size-4" />
<span>{item.label}</span>
</CommandItem>
))}
</CommandGroup>
<CommandSeparator />
{globalResults.length > 0 && (
<>
<CommandGroup heading="Users">
{globalResults.map((result) => (
<CommandItem
key={result.href}
onSelect={() => {
setOpen(false);
window.location.hash = result.href;
}}
>
<result.Icon className="size-4" />
<span>{result.label}</span>
</CommandItem>
))}
</CommandGroup>
<CommandSeparator />
</>
)}
{isSuperAdmin && (
<>
<CommandGroup heading="Management">
<CommandItem
onSelect={() => {
setOpen(false);
window.location.hash = "/seed";
}}
>
<Database className="size-4" />
<span>Seed Demo Data</span>
</CommandItem>
<CommandItem
onSelect={() => {
setOpen(false);
window.location.hash = "/seed?action=clear";
}}
>
<Trash2 className="size-4" />
<span>Clear Data</span>
</CommandItem>
</CommandGroup>
<CommandSeparator />
</>
)}
<CommandGroup heading="System">
<CommandItem
onSelect={() => {
setOpen(false);
logout();
window.location.hash = "/login";
}}
>
<LogOut className="size-4 text-destructive" />
<span className="text-destructive">Logout</span>
</CommandItem>
</CommandGroup>
</CommandList>
<div className="border-t px-3 py-2">
<div className="flex items-center justify-between text-[11px] text-muted-foreground">
<span className="flex items-center gap-1.5">
<kbd className="rounded border bg-muted px-1 py-0.5 font-mono text-[10px]">
</kbd>
<kbd className="rounded border bg-muted px-1 py-0.5 font-mono text-[10px]">
</kbd>
<span>navigate</span>
<kbd className="ml-1.5 rounded border bg-muted px-1 py-0.5 font-mono text-[10px]">
</kbd>
<span>select</span>
<kbd className="ml-1.5 rounded border bg-muted px-1 py-0.5 font-mono text-[10px]">
esc
</kbd>
<span>close</span>
</span>
<span className="font-mono">v2.0</span>
</div>
<span className="flex items-center gap-1 mt-0.5">
<kbd className="rounded border bg-muted px-1 py-0.5 font-mono text-[10px]">1</kbd>
<span></span>
<kbd className="rounded border bg-muted px-1 py-0.5 font-mono text-[10px]">9</kbd>
<span className="ml-0.5">nav</span>
</span>
<p className="mt-0.5 text-center text-[10px] text-muted-foreground/60">
TG Shop Admin v2.0
</p>
</div>
</CommandDialog>
);
}

View File

@@ -0,0 +1,138 @@
"use client";
import { useEffect, useState, useCallback } from "react";
import { Bell, CheckCircle, ExternalLink, Loader2 } from "lucide-react";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
interface PendingPurchase {
id: number;
productId: number;
userId: number;
amount: number;
status: string;
createdAt: string;
product?: { name: string } | null;
user?: { username: string; firstName: string } | null;
}
export function NotificationsPanel() {
const [items, setItems] = useState<PendingPurchase[]>([]);
const [count, setCount] = useState(0);
const [loading, setLoading] = useState(true);
const [open, setOpen] = useState(false);
const fetchPending = useCallback(async () => {
try {
const res = await fetch(
"/api/purchases/bulk?status=pending&limit=5"
);
if (!res.ok) return;
const json = await res.json();
const data: PendingPurchase[] = json.data ?? [];
const totalCount = json.total ?? data.length;
setItems(data);
setCount(totalCount);
} catch {
// silently fail
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
fetchPending();
const interval = setInterval(fetchPending, 30000);
return () => clearInterval(interval);
}, [fetchPending]);
// Re-fetch when popover opens
useEffect(() => {
if (open) {
fetchPending();
}
}, [open, fetchPending]);
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="ghost"
size="icon"
className="shrink-0 relative"
title="Notifications"
>
<Bell className="size-4" />
{count > 0 && (
<Badge className="absolute -top-1 -right-1 flex h-4 min-w-4 items-center justify-center rounded-full px-1 text-[10px] leading-none bg-destructive text-destructive-foreground border-0">
{count > 9 ? "9+" : count}
</Badge>
)}
<span className="sr-only">Notifications</span>
</Button>
</PopoverTrigger>
<PopoverContent align="end" className="w-80 p-0">
<div className="px-4 py-3 border-b">
<h3 className="text-sm font-semibold">Pending Purchases</h3>
<p className="text-xs text-muted-foreground">
{count} pending purchase{count !== 1 ? 's' : ''} awaiting review
</p>
</div>
<div className="max-h-72 overflow-y-auto">
{loading ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="size-4 animate-spin text-muted-foreground" />
</div>
) : items.length > 0 ? (
<div>
{items.map((item, index) => (
<div key={item.id}>
{index > 0 && <Separator />}
<div className="flex items-start gap-3 px-4 py-3">
<div className="flex-1 min-w-0">
<p className="text-sm font-medium truncate">
{item.product?.name ?? `Product #${item.productId}`}
</p>
<p className="text-xs text-muted-foreground truncate">
{item.user?.username ??
item.user?.firstName ??
`User #${item.userId}`}
</p>
<p className="text-xs font-mono text-muted-foreground mt-0.5">
{item.amount} USDT
</p>
</div>
<Button
variant="ghost"
size="icon"
className="shrink-0 size-7"
onClick={() => {
setOpen(false);
window.location.hash = "/purchases";
}}
>
<ExternalLink className="size-3" />
<span className="sr-only">View</span>
</Button>
</div>
</div>
))}
</div>
) : (
<div className="flex flex-col items-center justify-center py-8 text-muted-foreground">
<CheckCircle className="size-8 mb-2 text-green-500" />
<p className="text-sm font-medium">All caught up!</p>
<p className="text-xs">No pending purchases</p>
</div>
)}
</div>
</PopoverContent>
</Popover>
);
}

View File

@@ -0,0 +1,104 @@
"use client";
import {
PackagePlus,
FolderPlus,
ShoppingCart,
Database,
Download,
Zap,
} from "lucide-react";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Button } from "@/components/ui/button";
import { toast } from "sonner";
import { useAuthStore } from "@/stores/auth-store";
async function exportAllData() {
try {
const [usersRes, purchasesRes, auditRes] = await Promise.all([
fetch("/api/users/bulk?limit=9999"),
fetch("/api/purchases/bulk?limit=9999"),
fetch("/api/audit/bulk?limit=9999"),
]);
const users = usersRes.ok ? await usersRes.json() : { data: [] };
const purchases = purchasesRes.ok ? await purchasesRes.json() : { data: [] };
const audit = auditRes.ok ? await auditRes.json() : { data: [] };
const exportData = {
exportedAt: new Date().toISOString(),
users: users.data ?? [],
purchases: purchases.data ?? [],
audit: audit.data ?? [],
};
const blob = new Blob([JSON.stringify(exportData, null, 2)], {
type: "application/json",
});
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `tg-shop-export-${new Date().toISOString().slice(0, 10)}.json`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
toast.success("Data exported successfully");
} catch {
toast.error("Failed to export data");
}
}
export function QuickActions() {
const { role } = useAuthStore();
const isSuperAdmin = role === 'super_admin';
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="icon"
className="shrink-0"
title="Quick Actions"
>
<Zap className="size-4" />
<span className="sr-only">Quick Actions</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-52">
<DropdownMenuItem onClick={() => (window.location.hash = "/catalog")}>
<PackagePlus className="mr-2 size-4" />
New Product
</DropdownMenuItem>
<DropdownMenuItem onClick={() => (window.location.hash = "/categories")}>
<FolderPlus className="mr-2 size-4" />
Add Category
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => (window.location.hash = "/purchases")}
>
<ShoppingCart className="mr-2 size-4" />
View Pending Purchases
</DropdownMenuItem>
{isSuperAdmin && (
<DropdownMenuItem onClick={() => (window.location.hash = "/seed")}>
<Database className="mr-2 size-4" />
Seed Demo Data
</DropdownMenuItem>
)}
<DropdownMenuSeparator />
<DropdownMenuItem onClick={exportAllData}>
<Download className="mr-2 size-4" />
Export All Data
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
}

View File

@@ -0,0 +1,731 @@
"use client";
import { useEffect, useState, useCallback } from "react";
import { format } from "date-fns";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { Separator } from "@/components/ui/separator";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Textarea } from "@/components/ui/textarea";
import {
ArrowLeft,
MessageSquare,
User,
Phone,
Mail,
MapPin,
Calendar,
Sparkles,
StickyNote,
Save,
Loader2,
ChevronDown,
ChevronRight,
DollarSign,
ShoppingCart,
Wallet,
Activity,
Bot,
Send,
} from "lucide-react";
import { toast } from "sonner";
interface ChatMessage {
role: string;
content: string;
timestamp?: string;
}
interface Session {
id: number;
sessionId: string;
telegramId: string | null;
isActive: boolean;
operatorName: string | null;
autoReplyDisabled: boolean;
operatorConnectedAt: string | null;
customerProfile: string | null;
device: string | null;
ip: string | null;
country: string | null;
createdAt: string;
updatedAt: string;
messages: ChatMessage[];
}
interface LeadDetail {
id: number;
telegramId: string | null;
name: string | null;
phone: string | null;
email: string | null;
telegram: string | null;
status: string;
verification: string;
notes: string | null;
customFields: string;
geoAddress: string | null;
aiLeadScore: number | null;
createdAt: string;
updatedAt: string;
chatSessions: { id: number; sessionId: string; isActive: boolean; createdAt: string; customerProfile: string | null }[];
}
interface LinkedUser {
id: number;
telegramId: string;
username: string | null;
country: string | null;
city: string | null;
district: string | null;
status: number;
totalBalance: number;
bonusBalance: number;
language: string;
createdAt: string;
_count: { wallets: number; purchases: number };
wallets: { id: number; walletType: string; address: string; balance: number }[];
purchases: { id: number; product: { name: string }; quantity: number; totalPrice: number; status: string; purchaseDate: string }[];
}
interface ActivityData {
hourly: number[];
yearly: Record<string, number>;
total: number;
actions: Record<string, number>;
}
const STATUS_LABELS: Record<string, string> = {
new: "Новый",
contact: "Контакт",
qualified: "Квалифиц.",
lost: "Потерянный",
spam: "Спам",
};
const STATUS_COLORS: Record<string, string> = {
new: "bg-blue-500/15 text-blue-400 border-blue-500/25",
contact: "bg-amber-500/15 text-amber-400 border-amber-500/25",
qualified: "bg-emerald-500/15 text-emerald-400 border-emerald-500/25",
lost: "bg-red-500/15 text-red-400 border-red-500/25",
spam: "bg-zinc-500/15 text-zinc-400 border-zinc-500/25",
};
function relativeTime(dateStr: string) {
const diff = Date.now() - new Date(dateStr).getTime();
const mins = Math.floor(diff / 60000);
if (mins < 1) return "только что";
if (mins < 60) return `${mins}м назад`;
const hours = Math.floor(mins / 60);
if (hours < 24) return `${hours}ч назад`;
const days = Math.floor(hours / 24);
if (days < 30) return `${days}д назад`;
return new Date(dateStr).toLocaleDateString("ru-RU");
}
function InfoRow({ label, value, mono }: { label: string; value?: string; mono?: boolean }) {
return (
<div className="flex items-center justify-between text-sm">
<span className="text-muted-foreground">{label}</span>
<span className={mono ? "font-mono text-xs" : "font-medium"}>{value || "—"}</span>
</div>
);
}
/* ─── GitHub-style heatmap ─── */
function Heatmap({ yearly, hourly }: { yearly: Record<string, number>; hourly: number[] }) {
const maxDaily = Math.max(1, ...Object.values(yearly));
const maxHourly = Math.max(1, ...hourly);
// Годовая карта: 53 недели × 7 дней
const today = new Date();
const startOfYear = new Date(today.getFullYear(), 0, 1);
const daysInYear = Math.floor((today.getTime() - startOfYear.getTime()) / 86400000) + 1;
const cells: { date: Date; count: number }[] = [];
for (let i = 0; i < daysInYear; i++) {
const d = new Date(startOfYear);
d.setDate(startOfYear.getDate() + i);
const key = d.toISOString().slice(0, 10);
cells.push({ date: d, count: yearly[key] || 0 });
}
// Группировка по неделям (столбцы)
const weeks: { date: Date; count: number }[][] = [];
let currentWeek: { date: Date; count: number }[] = [];
for (const cell of cells) {
currentWeek.push(cell);
if (currentWeek.length === 7) {
weeks.push(currentWeek);
currentWeek = [];
}
}
if (currentWeek.length > 0) weeks.push(currentWeek);
const levelColor = (count: number) => {
if (count === 0) return "bg-muted/40";
const ratio = count / maxDaily;
if (ratio < 0.25) return "bg-emerald-900/60";
if (ratio < 0.5) return "bg-emerald-700/70";
if (ratio < 0.75) return "bg-emerald-500/80";
return "bg-emerald-400";
};
const hourColor = (count: number) => {
if (count === 0) return "bg-muted/40";
const ratio = count / maxHourly;
if (ratio < 0.25) return "bg-amber-900/60";
if (ratio < 0.5) return "bg-amber-700/70";
if (ratio < 0.75) return "bg-amber-500/80";
return "bg-amber-400";
};
return (
<div className="space-y-4">
{/* Почасовая активность */}
<div>
<p className="text-xs font-medium text-muted-foreground mb-2">Активность по часам</p>
<div className="flex items-end gap-1 h-16">
{hourly.map((count, hour) => (
<div
key={hour}
className={`flex-1 rounded-sm ${hourColor(count)}`}
style={{ height: `${Math.max(8, (count / maxHourly) * 100)}%` }}
title={`${hour}:00 — ${count} действий`}
/>
))}
</div>
<div className="flex justify-between text-[10px] text-muted-foreground mt-1">
<span>00:00</span>
<span>06:00</span>
<span>12:00</span>
<span>18:00</span>
<span>23:00</span>
</div>
</div>
{/* Годовая карта (GitHub-style) */}
<div>
<p className="text-xs font-medium text-muted-foreground mb-2">
Активность за год ({today.getFullYear()})
</p>
<div className="overflow-x-auto pb-2">
<div className="flex gap-[3px] min-w-max">
{weeks.map((week, wi) => (
<div key={wi} className="flex flex-col gap-[3px]">
{Array.from({ length: 7 }).map((_, di) => {
const cell = week[di];
if (!cell) return <div key={di} className="h-3 w-3 rounded-sm bg-transparent" />;
return (
<div
key={di}
className={`h-3 w-3 rounded-sm ${levelColor(cell.count)}`}
title={`${format(cell.date, "MMM d, yyyy")}${cell.count} действий`}
/>
);
})}
</div>
))}
</div>
</div>
<div className="flex items-center gap-1.5 mt-2 text-[10px] text-muted-foreground">
<span>Меньше</span>
<div className="h-3 w-3 rounded-sm bg-muted/40" />
<div className="h-3 w-3 rounded-sm bg-emerald-900/60" />
<div className="h-3 w-3 rounded-sm bg-emerald-700/70" />
<div className="h-3 w-3 rounded-sm bg-emerald-500/80" />
<div className="h-3 w-3 rounded-sm bg-emerald-400" />
<span>Больше</span>
</div>
</div>
</div>
);
}
/* ─── Chat transcript ─── */
function ChatTranscript({ messages }: { messages: ChatMessage[] }) {
return (
<div className="space-y-2">
{messages.map((m, i) => (
<div
key={i}
className={`flex ${m.role === "user" ? "justify-end" : "justify-start"}`}
>
<div
className={`max-w-[85%] rounded-lg px-3 py-2 text-sm ${
m.role === "user"
? "bg-primary/10 text-foreground"
: "bg-muted/50 text-foreground"
}`}
>
<div className="flex items-center gap-1.5 mb-1">
{m.role === "assistant" ? (
<Bot className="h-3 w-3 text-cyan-500" />
) : (
<User className="h-3 w-3 text-primary" />
)}
<span className="text-[10px] text-muted-foreground">
{m.role === "assistant" ? "ИИ-агент" : "Клиент"}
{m.timestamp && ` · ${format(new Date(m.timestamp), "HH:mm")}`}
</span>
</div>
<p className="whitespace-pre-wrap break-words">{m.content}</p>
</div>
</div>
))}
</div>
);
}
export function LeadDetailPage({ leadId }: { leadId: string }) {
const [lead, setLead] = useState<LeadDetail | null>(null);
const [user, setUser] = useState<LinkedUser | null>(null);
const [sessions, setSessions] = useState<Session[]>([]);
const [activity, setActivity] = useState<ActivityData | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [notes, setNotes] = useState("");
const [savingNotes, setSavingNotes] = useState(false);
const [expandedSession, setExpandedSession] = useState<number | null>(null);
const [activityLoaded, setActivityLoaded] = useState(false);
const fetchLead = useCallback(async () => {
setLoading(true);
try {
const [detailRes, sessionsRes] = await Promise.all([
fetch(`/api/leads/${leadId}`),
fetch(`/api/leads/${leadId}/sessions`),
]);
if (detailRes.ok) {
const d = await detailRes.json();
setLead(d.lead);
setUser(d.user || null);
setNotes(d.lead.notes ?? "");
}
if (sessionsRes.ok) {
const s = await sessionsRes.json();
setSessions(Array.isArray(s) ? s : (s.sessions ?? []));
}
} catch (err) {
setError(err instanceof Error ? err.message : "Ошибка загрузки");
} finally {
setLoading(false);
}
}, [leadId]);
const fetchActivity = useCallback(async () => {
try {
const res = await fetch(`/api/leads/${leadId}/activity`);
if (res.ok) {
setActivity(await res.json());
}
} catch {
// silent
} finally {
setActivityLoaded(true);
}
}, [leadId]);
useEffect(() => {
fetchLead();
}, [fetchLead]);
const handleSaveNotes = async () => {
if (!lead) return;
setSavingNotes(true);
try {
const res = await fetch(`/api/leads/${leadId}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ notes }),
});
if (res.ok) {
setLead({ ...lead, notes });
toast.success("Заметки сохранены");
}
} catch {
toast.error("Ошибка сохранения заметок");
} finally {
setSavingNotes(false);
}
};
if (loading) {
return (
<div className="page-enter p-4 md:p-6 space-y-4">
<Skeleton className="h-8 w-48" />
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
{Array.from({ length: 4 }).map((_, i) => (
<Skeleton key={i} className="h-24" />
))}
</div>
<Skeleton className="h-64" />
</div>
);
}
if (error || !lead) {
return (
<div className="page-enter p-4 md:p-6">
<Button variant="ghost" className="gap-2" onClick={() => { window.location.hash = "/leads"; }}>
<ArrowLeft className="h-4 w-4" />
Назад к лидам
</Button>
<p className="text-destructive mt-4">{error || "Лид не найден"}</p>
</div>
);
}
const profile = (() => {
try {
const p = sessions[0]?.customerProfile;
return p ? JSON.parse(p) : null;
} catch {
return null;
}
})();
return (
<div className="page-enter p-4 md:p-6 space-y-6">
{/* Header */}
<div className="flex items-center gap-3">
<Button variant="outline" className="gap-2" onClick={() => { window.location.hash = "/leads"; }}>
<ArrowLeft className="h-4 w-4" />
Назад к лидам
</Button>
<Separator orientation="vertical" className="h-6" />
<div>
<h2 className="text-xl font-semibold">
{lead.name || lead.telegram || `Лид #${lead.id}`}
</h2>
<p className="text-sm text-muted-foreground">
ID: {lead.id} · Telegram: {lead.telegramId || "—"}
</p>
</div>
<div className="ml-auto">
<Badge variant="outline" className={`text-xs ${STATUS_COLORS[lead.status] ?? ""}`}>
{STATUS_LABELS[lead.status] ?? lead.status}
</Badge>
</div>
</div>
{/* KPI Cards */}
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
<Card>
<CardContent className="p-4">
<div className="flex items-center justify-between">
<p className="text-sm text-muted-foreground">Баланс</p>
<DollarSign className="h-4 w-4 text-emerald-500" />
</div>
<p className="text-2xl font-bold mt-1 tabular-nums">
${((user?.totalBalance || 0) + (user?.bonusBalance || 0)).toFixed(2)}
</p>
<p className="text-xs text-muted-foreground mt-1">
{user ? `#${user.id} ${user.username || ""}` : "не покупатель"}
</p>
</CardContent>
</Card>
<Card>
<CardContent className="p-4">
<div className="flex items-center justify-between">
<p className="text-sm text-muted-foreground">Покупки</p>
<ShoppingCart className="h-4 w-4 text-orange-500" />
</div>
<p className="text-2xl font-bold mt-1 tabular-nums">
{user?._count.purchases ?? 0}
</p>
<p className="text-xs text-muted-foreground mt-1">
{user?.purchases.filter((p) => p.status === "completed").length ?? 0} completed
</p>
</CardContent>
</Card>
<Card>
<CardContent className="p-4">
<div className="flex items-center justify-between">
<p className="text-sm text-muted-foreground">Сессии</p>
<MessageSquare className="h-4 w-4 text-cyan-500" />
</div>
<p className="text-2xl font-bold mt-1 tabular-nums">{sessions.length}</p>
<p className="text-xs text-muted-foreground mt-1">
{sessions.filter((s) => s.isActive).length} активных
</p>
</CardContent>
</Card>
<Card>
<CardContent className="p-4">
<div className="flex items-center justify-between">
<p className="text-sm text-muted-foreground">AI Скор</p>
<Sparkles className="h-4 w-4 text-violet-500" />
</div>
<p className="text-2xl font-bold mt-1 tabular-nums">
{lead.aiLeadScore != null ? `${Math.round(lead.aiLeadScore * 100)}%` : "—"}
</p>
<p className="text-xs text-muted-foreground mt-1">готовность клиента</p>
</CardContent>
</Card>
</div>
{/* Profile + Actions */}
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
{/* Left: Profile */}
<div className="space-y-6">
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<User className="h-5 w-5" />
Профиль лида
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<InfoRow label="ID" value={String(lead.id)} mono />
<InfoRow label="Telegram ID" value={lead.telegramId || "—"} mono />
<InfoRow label="Username" value={lead.telegram ? `@${lead.telegram.replace(/^@/, "")}` : "—"} />
<InfoRow label="Имя" value={lead.name || "—"} />
<InfoRow label="Телефон" value={lead.phone || "—"} mono />
<InfoRow label="Email" value={lead.email || "—"} />
<InfoRow label="Верификация" value={lead.verification || "—"} />
<InfoRow label="Создан" value={format(new Date(lead.createdAt), "MMM d, yyyy HH:mm")} />
</CardContent>
</Card>
{/* Linked user */}
{user && (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Wallet className="h-5 w-5 text-emerald-500" />
Покупатель
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<InfoRow label="User ID" value={String(user.id)} mono />
<InfoRow label="Username" value={user.username || "—"} />
<InfoRow label="Статус" value={user.status === 2 ? "Заблокирован" : "Активен"} />
<InfoRow label="Страна" value={user.country || "—"} />
<InfoRow label="Город" value={user.city || "—"} />
<InfoRow label="Язык" value={user.language || "—"} />
<div className="border-t pt-3 mt-3 space-y-3">
<InfoRow label="Основной баланс" value={`$${(user.totalBalance || 0).toFixed(2)}`} />
<InfoRow label="Бонусный баланс" value={`$${(user.bonusBalance || 0).toFixed(2)}`} />
</div>
{user.wallets.length > 0 && (
<div className="space-y-1.5">
<p className="text-xs text-muted-foreground">Кошельки</p>
{user.wallets.map((w) => (
<div key={w.id} className="flex items-center justify-between text-xs">
<Badge variant="secondary" className="text-[10px]">{w.walletType}</Badge>
<span className="font-mono text-[10px] truncate max-w-[140px]">{w.address}</span>
</div>
))}
</div>
)}
</CardContent>
</Card>
)}
{/* Notes */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<StickyNote className="h-5 w-5" />
Заметки
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<Textarea
placeholder="Заметки по лиду..."
value={notes}
onChange={(e) => setNotes(e.target.value)}
rows={4}
/>
<div className="flex justify-end">
<Button size="sm" disabled={savingNotes} onClick={handleSaveNotes}>
<Save className="h-4 w-4 mr-1.5" />
{savingNotes ? "Сохранение..." : "Сохранить"}
</Button>
</div>
</CardContent>
</Card>
</div>
{/* Right: Tabs */}
<div className="lg:col-span-2 space-y-6">
<Tabs
defaultValue="chats"
onValueChange={(v) => { if (v === "activity" && !activityLoaded) fetchActivity(); }}
>
<TabsList>
<TabsTrigger value="chats" className="gap-2">
<MessageSquare className="h-4 w-4" />
Переписки
</TabsTrigger>
<TabsTrigger value="activity" className="gap-2">
<Activity className="h-4 w-4" />
Активность
</TabsTrigger>
<TabsTrigger value="purchases" className="gap-2">
<ShoppingCart className="h-4 w-4" />
Покупки
</TabsTrigger>
</TabsList>
{/* Chats Tab */}
<TabsContent value="chats" className="mt-4">
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-lg flex items-center gap-2">
<MessageSquare className="h-5 w-5" />
Переписки с ИИ-агентом
<span className="text-sm font-normal text-muted-foreground">({sessions.length})</span>
</CardTitle>
</CardHeader>
<CardContent>
{sessions.length === 0 ? (
<div className="p-8 text-center text-muted-foreground">
<MessageSquare className="h-12 w-12 mx-auto mb-3 opacity-30" />
<p className="text-lg font-medium">Нет переписок</p>
<p className="text-sm mt-1">Клиент ещё не общался с ИИ-агентом</p>
</div>
) : (
<div className="space-y-3">
{sessions.map((session) => {
const isExpanded = expandedSession === session.id;
return (
<div key={session.id} className="rounded-lg border border-border/50">
<button
type="button"
className="w-full flex items-center gap-3 p-3 text-left hover:bg-muted/30 transition-colors"
onClick={() => setExpandedSession(isExpanded ? null : session.id)}
>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span className="font-mono text-xs truncate">{session.sessionId}</span>
{session.isActive && (
<Badge variant="outline" className="text-[10px] bg-emerald-500/10 text-emerald-400 border-emerald-500/25">
активна
</Badge>
)}
</div>
<p className="text-xs text-muted-foreground mt-0.5">
{session.messages.length} сообщений · {relativeTime(session.createdAt)}
{session.country && ` · 📍 ${session.country}`}
{session.device && ` · ${session.device}`}
</p>
</div>
{isExpanded ? (
<ChevronDown className="h-4 w-4 text-muted-foreground shrink-0" />
) : (
<ChevronRight className="h-4 w-4 text-muted-foreground shrink-0" />
)}
</button>
{isExpanded && (
<div className="border-t p-3 max-h-96 overflow-y-auto">
<ChatTranscript messages={session.messages} />
</div>
)}
</div>
);
})}
</div>
)}
</CardContent>
</Card>
</TabsContent>
{/* Activity Tab */}
<TabsContent value="activity" className="mt-4">
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-lg flex items-center gap-2">
<Activity className="h-5 w-5" />
Активность
{activity && (
<span className="text-sm font-normal text-muted-foreground">
({activity.total} действий)
</span>
)}
</CardTitle>
</CardHeader>
<CardContent>
{!activityLoaded ? (
<div className="space-y-3">
<Skeleton className="h-16" />
<Skeleton className="h-32" />
</div>
) : activity && activity.total > 0 ? (
<Heatmap yearly={activity.yearly} hourly={activity.hourly} />
) : (
<div className="p-8 text-center text-muted-foreground">
<Activity className="h-12 w-12 mx-auto mb-3 opacity-30" />
<p className="text-lg font-medium">Нет данных об активности</p>
<p className="text-sm mt-1">Действия появятся после взаимодействия с ботом</p>
</div>
)}
</CardContent>
</Card>
</TabsContent>
{/* Purchases Tab */}
<TabsContent value="purchases" className="mt-4">
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-lg flex items-center gap-2">
<ShoppingCart className="h-5 w-5" />
Покупки
<span className="text-sm font-normal text-muted-foreground">
({user?.purchases.length ?? 0})
</span>
</CardTitle>
</CardHeader>
<CardContent>
{!user || user.purchases.length === 0 ? (
<div className="p-8 text-center text-muted-foreground">
<ShoppingCart className="h-12 w-12 mx-auto mb-3 opacity-30" />
<p className="text-lg font-medium">Нет покупок</p>
<p className="text-sm mt-1">Этот клиент ещё не совершал покупок</p>
</div>
) : (
<div className="max-h-96 overflow-y-auto rounded-lg border">
<table className="w-full text-sm">
<thead>
<tr className="border-b bg-muted/30">
<th className="p-2 text-left font-medium text-xs">ID</th>
<th className="p-2 text-left font-medium text-xs">Товар</th>
<th className="p-2 text-center font-medium text-xs">Кол-во</th>
<th className="p-2 text-right font-medium text-xs">Сумма</th>
<th className="p-2 text-left font-medium text-xs">Статус</th>
<th className="p-2 text-left font-medium text-xs">Дата</th>
</tr>
</thead>
<tbody>
{user.purchases.map((p) => (
<tr key={p.id} className="border-b hover:bg-muted/30">
<td className="p-2 font-mono text-xs">{p.id}</td>
<td className="p-2 font-medium">{p.product.name}</td>
<td className="p-2 text-center">{p.quantity}</td>
<td className="p-2 text-right font-mono">${p.totalPrice.toFixed(2)}</td>
<td className="p-2">
<Badge variant={p.status === "completed" ? "default" : p.status === "pending" ? "secondary" : "destructive"} className="text-[10px]">
{p.status}
</Badge>
</td>
<td className="p-2 text-xs text-muted-foreground">
{format(new Date(p.purchaseDate), "MMM d, yyyy")}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</CardContent>
</Card>
</TabsContent>
</Tabs>
</div>
</div>
</div>
);
}

Some files were not shown because too many files have changed in this diff Show More