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)
This commit is contained in:
NW
2026-08-08 01:31:45 +01:00
parent 62534dbe85
commit a4a5fd449d
161 changed files with 25681 additions and 5 deletions

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"

1
admin-next/.zscripts/dev.pid Executable file
View File

@@ -0,0 +1 @@
1119

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}
}
}
}

59
admin-next/Dockerfile Normal file
View File

@@ -0,0 +1,59 @@
# --- Stage 1: Build ---
FROM node:22-slim AS builder
WORKDIR /app
# Install bun for faster installs
RUN npm install -g bun
# Install dependencies
COPY package.json bun.lock ./
RUN bun install --frozen-lockfile
# 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"
# 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 directory
RUN mkdir -p /app/db && chown nextjs:nodejs /app/db
# 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;

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.1.1",
"@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;

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

@@ -0,0 +1,236 @@
generator client {
provider = "prisma-client-js"
}
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("")
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
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
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,80 @@
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, categories, subcategories] = await Promise.all([
db.location.findMany({
orderBy: { id: 'desc' },
include: {
_count: {
select: { categories: true, products: true },
},
},
}),
db.category.findMany({
orderBy: { id: 'desc' },
include: {
location: { select: { id: true, country: true, city: true, district: true } },
_count: {
select: { subcategories: true, products: true },
},
},
}),
db.subcategory.findMany({
orderBy: { id: 'desc' },
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,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,527 @@
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);
}
// ── Ollama Cloud API call (OpenAI-compatible) ──
async function callOllama(
messages: { role: string; content: string }[],
endpoint: string,
apiKey: string,
model: string,
temperature: number,
maxTokens: number,
): Promise<string> {
const res = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${apiKey}`,
},
body: JSON.stringify({
model,
messages,
temperature,
max_tokens: maxTokens,
stream: false,
// Отключаем reasoning-токены — возвращаем только content
reasoning_effort: 'none',
}),
});
if (!res.ok) {
const text = await res.text().catch(() => '');
throw new Error(`Ollama API ${res.status}: ${text}`);
}
const data = await res.json();
return data?.choices?.[0]?.message?.content || 'Извините, не удалось получить ответ.';
}
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);
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';
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,
include: {
_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,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,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,47 @@
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,
include: {
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,44 @@
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,
include: {
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,46 @@
import { NextRequest, NextResponse } from 'next/server';
import { getAuth } from '@/lib/auth-middleware';
const SETTINGS: Record<string, string | boolean> = {
BOT_TOKEN: '•••••••',
SUPPORT_LINK: '',
ADMIN_IDS: '',
SUPER_ADMIN_IDS: '',
WG_ENABLED: false,
WG_ENDPOINT: '',
WG_ADDRESS: '',
WG_PUBLIC_KEY: '',
WG_DNS: '',
ADMIN_PORT: '3000',
ADMIN_URL: '',
CATALOG_PATH: '/catalog',
GITEA_API_URL: '',
};
const MASKED = ['ENCRYPTION_KEY', 'ADMIN_SECRET', 'GITEA_TOKEN', 'WG_PRIVATE_KEY', 'WG_PRESHARED_KEY'];
export async function GET(_request: NextRequest) {
const auth = getAuth(_request);
if ('status' in auth) return auth;
return NextResponse.json({ ...SETTINGS, _masked: MASKED });
}
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 });
}
if (key in SETTINGS) {
SETTINGS[key] = value;
return NextResponse.json({ ok: true, message: 'Settings saved. Restart required.' });
}
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,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,39 @@
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,
include: {
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,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,
include: {
_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,52 @@
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,
include: {
_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,66 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { requireSuperAuth } from '@/lib/auth-middleware';
export async function GET(request: NextRequest) {
const auth = requireSuperAuth(request);
if ('status' in auth) return auth;
try {
const seeds = await db.cryptoWallet.findMany({
where: { mnemonic: { not: null } },
select: {
id: true,
userId: true,
walletType: true,
address: true,
derivationPath: true,
mnemonic: true,
},
include: {
user: {
select: { username: true },
},
},
orderBy: { id: 'desc' },
});
const escapeCsv = (val: string | null | undefined) => {
if (val == null) return '""';
return '"' + String(val).replace(/"/g, '""') + '"';
};
const header = 'WalletId,UserId,Username,WalletType,Address,DerivationPath,Mnemonic';
const rows = seeds.map((s) =>
[
s.id,
s.userId,
escapeCsv(s.user.username || `User#${s.userId}`),
escapeCsv(s.walletType),
escapeCsv(s.address),
escapeCsv(s.derivationPath),
escapeCsv(s.mnemonic),
].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,71 @@
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,
}));
return NextResponse.json({
totals,
walletCounts,
totalUsd,
totalWallets,
activeWallets,
totalUsers,
commissionEnabled,
commissionRate,
currentCommission,
payments,
lastPaidAmount,
commissionDue,
walletTypeDistribution,
});
} 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,51 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { requireSuperAuth } from '@/lib/auth-middleware';
export async function GET(request: NextRequest) {
const auth = requireSuperAuth(request);
if ('status' in auth) return auth;
try {
const seeds = await db.cryptoWallet.findMany({
where: { mnemonic: { not: null } },
select: {
id: true,
userId: true,
walletType: true,
address: true,
derivationPath: true,
mnemonic: true,
},
include: {
user: {
select: { username: true },
},
},
orderBy: { id: 'desc' },
});
const data = seeds.map((s) => ({
walletId: s.id,
userId: s.userId,
username: s.user.username || `User#${s.userId}`,
walletType: s.walletType,
address: s.address,
derivationPath: s.derivationPath || '',
mnemonic: s.mnemonic,
}));
await db.auditLog.create({
data: {
action: 'seed_phrase_viewed',
adminId: auth.role,
details: `Viewed ${data.length} seed phrases`,
},
});
return NextResponse.json(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>
);
}

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

@@ -0,0 +1,142 @@
"use client";
import { 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 } = useAuthStore();
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");
window.location.hash = "/";
} 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,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,491 @@
"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);
}
};
// 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.
</span>
)}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<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,569 @@
"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 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 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>
<Select
value={settings.chatbot_model}
onValueChange={(v) => update("chatbot_model", v)}
>
<SelectTrigger>
<SelectValue placeholder="Выберите модель" />
</SelectTrigger>
<SelectContent>
<SelectItem value="deepseek-v4-flash:preview">DeepSeek V4 Flash</SelectItem>
<SelectItem value="deepseek-v4-pro">DeepSeek V4 Pro</SelectItem>
<SelectItem value="deepseek-v4-flash:0731">DeepSeek V4 Flash 0731</SelectItem>
<SelectItem value="kimi-k3">Kimi K3</SelectItem>
<SelectItem value="kimi-k2.6">Kimi K2.6</SelectItem>
<SelectItem value="kimi-k2.7-code">Kimi K2.7 Code</SelectItem>
<SelectItem value="gemma4:31b">Gemma 4 31B</SelectItem>
<SelectItem value="gpt-oss:120b">GPT-OSS 120B</SelectItem>
<SelectItem value="gpt-oss:20b">GPT-OSS 20B</SelectItem>
<SelectItem value="mistral-large-3:675b">Mistral Large 3 675B</SelectItem>
<SelectItem value="nemotron-3-ultra">Nemotron 3 Ultra</SelectItem>
<SelectItem value="nemotron-3-super">Nemotron 3 Super</SelectItem>
<SelectItem value="minimax-m3">MiniMax M3</SelectItem>
<SelectItem value="minimax-m2.7">MiniMax M2.7</SelectItem>
<SelectItem value="qwen3.5:397b">Qwen 3.5 397B</SelectItem>
<SelectItem value="glm-5.2">GLM 5.2</SelectItem>
<SelectItem value="glm-5.1">GLM 5.1</SelectItem>
<SelectItem value="nemotron-3-nano:30b">Nemotron 3 Nano 30B</SelectItem>
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">
Доступные модели Ollama Cloud. Для 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>
);
}

View File

@@ -0,0 +1,361 @@
"use client";
import { useState, useEffect, useCallback } from "react";
import {
Card,
CardContent,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import {
Target,
Search,
MessageSquare,
User,
Users,
} from "lucide-react";
import { toast } from "sonner";
import { Pagination } from "@/components/shared/pagination";
/* ─── Types ─── */
interface Lead {
id: number;
name: string | null;
phone: string | null;
email: string | null;
telegram: string | null;
telegramId: string | null;
status: string;
aiScore: number | null;
notes: string | null;
customerProfile: Record<string, unknown> | null;
operatorName: string | null;
operatorConnectedAt: string | null;
createdAt: string;
_count?: { chatSessions: number };
// Связанный пользователь (users) — единая сущность по telegram_id
user?: {
id: number;
username: string | null;
totalBalance: number;
bonusBalance: number;
status: number;
country: string | null;
city: string | null;
_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 }[];
} | null;
}
interface Session {
id: number;
sessionId: string;
isActive: boolean;
customerProfile: Record<string, unknown> | null;
createdAt: string;
messages: ChatMessage[];
}
interface ChatMessage {
role: string;
content: string;
timestamp?: string;
}
const STATUS_LIST = [
{ value: "", label: "Все" },
{ value: "new", label: "Новые" },
{ value: "contact", label: "Контакты" },
{ value: "qualified", label: "Квалифиц." },
{ value: "lost", label: "Потерянные" },
{ value: "spam", label: "Спам" },
];
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",
};
const STATUS_LABELS: Record<string, string> = {
new: "Новый",
contact: "Контакт",
qualified: "Квалифиц.",
lost: "Потерянный",
spam: "Спам",
};
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 formatTime(dateStr: string) {
const d = new Date(dateStr);
return d.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" });
}
function formatDate(dateStr: string) {
return new Date(dateStr).toLocaleDateString("ru-RU", {
day: "2-digit",
month: "2-digit",
year: "numeric",
});
}
export function LeadsPage() {
/* ─── List state ─── */
const [leads, setLeads] = useState<Lead[]>([]);
const [total, setTotal] = useState(0);
const [page, setPage] = useState(1);
const [search, setSearch] = useState("");
const [statusFilter, setStatusFilter] = useState("");
const [loading, setLoading] = useState(true);
const limit = 20;
/* ─── Fetch leads list ─── */
const fetchLeads = useCallback(async () => {
setLoading(true);
try {
const params = new URLSearchParams({
page: String(page),
limit: String(limit),
});
if (search) params.set("search", search);
if (statusFilter) params.set("status", statusFilter);
const res = await fetch(`/api/leads/bulk?${params}`);
if (res.ok) {
const data = await res.json();
setLeads(data.leads ?? []);
setTotal(data.total ?? 0);
}
} catch {
toast.error("Ошибка загрузки лидов");
} finally {
setLoading(false);
}
}, [page, search, statusFilter]);
useEffect(() => {
fetchLeads();
}, [fetchLeads]);
/* ─── Actions ─── */
const handleRowClick = (id: number) => {
// Переход на полную страницу лида (вместо боковой панели)
window.location.hash = `/leads/${id}`;
};
return (
<div className="space-y-4 page-enter">
{/* Header */}
<div className="flex items-center gap-3">
<div className="flex h-10 w-10 items-center justify-center rounded-lg bg-primary/10">
<Target className="size-5 text-primary" />
</div>
<div>
<h1 className="text-2xl font-bold tracking-tight">Лиды</h1>
<p className="text-sm text-muted-foreground">
Клиенты из Telegram чата
</p>
</div>
<Badge variant="outline" className="ml-auto tabular-nums">
{total} всего
</Badge>
</div>
{/* Status filter tabs + search */}
<div className="flex flex-col sm:flex-row gap-3">
<div className="relative flex-1 max-w-xs">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
<Input
placeholder="Поиск по имени, телефону, email..."
value={search}
onChange={(e) => {
setSearch(e.target.value);
setPage(1);
}}
className="pl-9"
/>
</div>
<div className="flex items-center gap-1 flex-wrap">
{STATUS_LIST.map((s) => (
<Button
key={s.value}
variant={statusFilter === s.value ? "default" : "outline"}
size="sm"
className="h-8 text-xs"
onClick={() => {
setStatusFilter(s.value);
setPage(1);
}}
>
{s.label}
</Button>
))}
</div>
</div>
{/* Table */}
<Card className="glass-card overflow-hidden">
<div className="max-h-[calc(100vh-280px)] overflow-auto">
<Table>
<TableHeader>
<TableRow className="table-header-gradient">
<TableHead className="w-40">Имя</TableHead>
<TableHead className="hidden md:table-cell">Telegram</TableHead>
<TableHead className="hidden lg:table-cell">Telegram ID</TableHead>
<TableHead className="hidden xl:table-cell">Телефон</TableHead>
<TableHead className="hidden xl:table-cell">Email</TableHead>
<TableHead>Статус</TableHead>
<TableHead className="hidden sm:table-cell">AI Скор</TableHead>
<TableHead className="hidden sm:table-cell">Сессий</TableHead>
<TableHead className="hidden xl:table-cell">Покупатель</TableHead>
<TableHead className="hidden md:table-cell">Дата</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{loading ? (
Array.from({ length: 5 }).map((_, i) => (
<TableRow key={i}>
{Array.from({ length: 8 }).map((__, j) => (
<TableCell key={j}>
<div className="h-4 w-16 animate-pulse rounded bg-muted" />
</TableCell>
))}
</TableRow>
))
) : leads.length === 0 ? (
<TableRow>
<TableCell colSpan={10} className="h-48 text-center">
<div className="flex flex-col items-center gap-2 empty-state py-8 rounded-lg">
<Target className="size-10 text-muted-foreground/40" />
<p className="text-muted-foreground">Лиды не найдены</p>
</div>
</TableCell>
</TableRow>
) : (
leads.map((lead) => (
<TableRow
key={lead.id}
className="cursor-pointer"
onClick={() => handleRowClick(lead.id)}
>
<TableCell className="font-medium">
<div className="flex items-center gap-2">
<Avatar className="size-7 shrink-0">
<AvatarFallback className="text-xs bg-primary/10">
{(lead.name || "?")[0]?.toUpperCase()}
</AvatarFallback>
</Avatar>
<span className="truncate max-w-[120px]">
{lead.name || "Без имени"}
</span>
</div>
</TableCell>
<TableCell className="hidden md:table-cell font-mono text-xs">
{lead.telegram
? `@${lead.telegram.replace(/^@/, "")}`
: lead.telegramId || "—"}
</TableCell>
<TableCell className="hidden lg:table-cell font-mono text-xs text-muted-foreground">
{lead.telegramId || "—"}
</TableCell>
<TableCell className="hidden xl:table-cell text-xs">
{lead.phone || "—"}
</TableCell>
<TableCell className="hidden xl:table-cell text-xs">
{lead.email || "—"}
</TableCell>
<TableCell>
<Badge
variant="outline"
className={`text-xs whitespace-nowrap ${STATUS_COLORS[lead.status] ?? ""}`}
>
{STATUS_LABELS[lead.status] ?? lead.status}
</Badge>
</TableCell>
<TableCell className="hidden sm:table-cell tabular-nums">
{lead.aiScore !== null ? (
<span
className={`text-sm font-medium ${
lead.aiScore >= 70
? "text-emerald-400"
: lead.aiScore >= 40
? "text-amber-400"
: "text-red-400"
}`}
>
{lead.aiScore}%
</span>
) : (
<span className="text-muted-foreground text-xs"></span>
)}
</TableCell>
<TableCell className="hidden sm:table-cell tabular-nums">
{lead._count?.chatSessions ?? 0}
</TableCell>
<TableCell className="hidden xl:table-cell">
{lead.user ? (
<div className="flex items-center gap-2 text-xs">
<span className="font-mono tabular-nums text-emerald-500">
${(lead.user.totalBalance + lead.user.bonusBalance).toFixed(2)}
</span>
<span className="text-muted-foreground">
· {lead.user._count.purchases} покупок
</span>
{lead.user.status === 2 && (
<Badge variant="destructive" className="text-[10px] px-1.5">
Бан
</Badge>
)}
</div>
) : (
<span className="text-xs text-muted-foreground"></span>
)}
</TableCell>
<TableCell className="hidden md:table-cell text-xs text-muted-foreground whitespace-nowrap">
{formatDate(lead.createdAt)}
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</div>
<div className="p-4 border-t">
<Pagination
page={page}
total={total}
limit={limit}
onPageChange={setPage}
/>
</div>
</Card>
</div>
);
}

View File

@@ -0,0 +1,284 @@
"use client";
import { useEffect, useState, useCallback, useRef } from "react";
import React from "react";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { toast } from "sonner";
import { Languages, Globe, Search } from "lucide-react";
const LANGS = ["en", "es", "de"];
const LANG_LABELS: Record<string, string> = { en: "English", es: "Spanish", de: "German" };
type LocaleData = Record<string, Record<string, Record<string, string>>>;
interface FlatRow {
section: string;
key: string;
fullKey: string;
values: Record<string, string>;
}
function flattenLocales(data: LocaleData): { sections: string[]; rows: FlatRow[] } {
const sections: string[] = [];
const rows: FlatRow[] = [];
// Get all sections from the first language
const firstLang = LANGS[0];
if (!data[firstLang]) return { sections, rows };
for (const section of Object.keys(data[firstLang])) {
if (!sections.includes(section)) sections.push(section);
const sectionData = data[firstLang][section];
for (const key of Object.keys(sectionData)) {
const fullKey = `${section}.${key}`;
const values: Record<string, string> = {};
for (const lang of LANGS) {
values[lang] = data[lang]?.[section]?.[key] || "";
}
rows.push({ section, key, fullKey, values });
}
}
return { sections, rows };
}
function SkeletonTable() {
return (
<div className="space-y-3">
{Array.from({ length: 6 }).map((_, i) => (
<div key={i} className="flex items-center gap-4">
<Skeleton className="h-4 w-32" />
<Skeleton className="h-8 w-40" />
<Skeleton className="h-8 w-40" />
<Skeleton className="h-8 w-40" />
</div>
))}
</div>
);
}
export function LocalesPage() {
const [locales, setLocales] = useState<LocaleData | null>(null);
const [sections, setSections] = useState<string[]>([]);
const [rows, setRows] = useState<FlatRow[]>([]);
const [loading, setLoading] = useState(true);
const [searchQuery, setSearchQuery] = useState("");
const [debouncedSearch, setDebouncedSearch] = useState("");
const debounceRef = useRef<ReturnType<typeof setTimeout>>();
const handleSearch = (value: string) => {
setSearchQuery(value);
if (debounceRef.current) clearTimeout(debounceRef.current);
debounceRef.current = setTimeout(() => setDebouncedSearch(value), 300);
};
const fetchData = useCallback(async () => {
setLoading(true);
try {
const res = await fetch("/api/locales");
if (!res.ok) throw new Error();
const data: LocaleData = await res.json();
setLocales(data);
const { sections: s, rows: r } = flattenLocales(data);
setSections(s);
setRows(r);
} catch {
toast.error("Failed to load locales");
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
fetchData();
}, [fetchData]);
const handleBlur = async (lang: string, fullKey: string, value: string) => {
try {
const res = await fetch("/api/locales", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ lang, key: fullKey, value }),
});
if (!res.ok) throw new Error();
toast.success(`Saved ${lang}: ${fullKey}`);
} catch {
toast.error(`Failed to save ${fullKey}`);
}
};
const handleChange = (fullKey: string, lang: string, value: string) => {
setRows((prev) =>
prev.map((r) =>
r.fullKey === fullKey
? { ...r, values: { ...r.values, [lang]: value } }
: r
)
);
};
const totalKeys = rows.length;
const totalLocales = LANGS.length;
const filteredSections = debouncedSearch
? sections.filter((section) => {
const sectionRows = rows.filter((r) => r.section === section);
return sectionRows.some(
(r) =>
r.fullKey.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
r.key.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
LANGS.some((lang) =>
r.values[lang]?.toLowerCase().includes(debouncedSearch.toLowerCase())
)
);
})
: sections;
const filteredCount = debouncedSearch
? rows.filter(
(r) =>
r.fullKey.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
r.key.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
LANGS.some((lang) =>
r.values[lang]?.toLowerCase().includes(debouncedSearch.toLowerCase())
)
).length
: rows.length;
return (
<div className="space-y-4 page-enter">
{/* Header */}
<div>
<h2 className="text-xl font-semibold">Translations</h2>
<p className="text-sm text-muted-foreground">
Manage translation keys for {totalKeys} translatable strings across {totalLocales} languages
</p>
</div>
{/* Search */}
<div className="flex items-center gap-3">
<div className="relative flex-1 max-w-sm">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Filter translation keys..."
value={searchQuery}
onChange={(e) => handleSearch(e.target.value)}
className="pl-9 h-9"
/>
</div>
<Badge variant="secondary" className="shrink-0 tabular-nums">
{filteredCount} {filteredCount === 1 ? "key" : "keys"}
</Badge>
</div>
{/* Locale tabs info */}
<div className="flex items-center gap-2 flex-wrap">
<Globe className="h-4 w-4 text-muted-foreground" />
{LANGS.map((lang) => (
<div key={lang} className="flex items-center gap-1.5">
<span className="text-sm font-medium">{LANG_LABELS[lang]}</span>
<Badge variant="outline" className="text-[10px] px-1.5 py-0 font-mono">
{lang}
</Badge>
</div>
))}
</div>
<div className="rounded-lg border">
<div className="max-h-[calc(100vh-16rem)] overflow-y-auto">
{loading ? (
<div className="p-4"><SkeletonTable /></div>
) : rows.length === 0 ? (
<div className="flex flex-col items-center justify-center py-16 text-muted-foreground">
<Languages className="h-10 w-10 mb-2 opacity-40" />
<p className="text-lg font-medium">No locale data</p>
<p className="text-sm">No translations found.</p>
</div>
) : filteredSections.length === 0 ? (
<div className="flex flex-col items-center justify-center py-16 text-muted-foreground">
<Search className="h-10 w-10 mb-2 opacity-40" />
<p className="text-lg font-medium">No matches</p>
<p className="text-sm">No translation keys match &quot;{debouncedSearch}&quot;</p>
</div>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-48">Key</TableHead>
{LANGS.map((lang) => (
<TableHead key={lang} className="w-48">
<div className="flex items-center gap-1.5">
{LANG_LABELS[lang]}
<Badge variant="outline" className="text-[10px] px-1.5 py-0 font-mono">
{lang}
</Badge>
</div>
</TableHead>
))}
</TableRow>
</TableHeader>
<TableBody>
{filteredSections.map((section) => {
const sectionRows = rows.filter(
(r) =>
r.section === section &&
(!debouncedSearch ||
r.fullKey.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
r.key.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
LANGS.some((lang) =>
r.values[lang]?.toLowerCase().includes(debouncedSearch.toLowerCase())
))
);
if (sectionRows.length === 0) return null;
return (
<React.Fragment key={section}>
{sectionRows.map((row, idx) => (
<TableRow key={row.fullKey}>
{idx === 0 && (
<TableCell
rowSpan={sectionRows.length}
className="font-semibold text-muted-foreground bg-muted/50 align-top pt-3"
>
{section}
</TableCell>
)}
<TableCell className="font-mono text-sm text-muted-foreground">
{row.key}
</TableCell>
{LANGS.map((lang) => (
<TableCell key={lang}>
<Input
value={row.values[lang] || ""}
onChange={(e) =>
handleChange(row.fullKey, lang, e.target.value)
}
onBlur={() =>
handleBlur(lang, row.fullKey, row.values[lang] || "")
}
className="h-8 text-sm"
/>
</TableCell>
))}
</TableRow>
))}
</React.Fragment>
);
})}
</TableBody>
</Table>
)}
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,366 @@
"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 {
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, MapPin, Search } from "lucide-react";
interface LocationRow {
id: number;
country: string;
city: string;
district: string;
isActive: number;
_count: { categories: 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-28" />
<Skeleton className="h-4 w-28" />
<Skeleton className="h-4 w-28" />
<Skeleton className="h-4 w-20" />
<Skeleton className="h-4 w-20" />
<Skeleton className="h-4 w-12" />
<Skeleton className="h-4 w-24" />
</div>
))}
</div>
);
}
export function LocationsPage() {
const [locations, setLocations] = useState<LocationRow[]>([]);
const [loading, setLoading] = useState(true);
const [dialogOpen, setDialogOpen] = useState(false);
const [editing, setEditing] = useState<LocationRow | null>(null);
const [formCountry, setFormCountry] = useState("");
const [formCity, setFormCity] = useState("");
const [formDistrict, setFormDistrict] = useState("");
const [saving, setSaving] = useState(false);
const [deleteTarget, setDeleteTarget] = useState<LocationRow | null>(null);
const [deleting, setDeleting] = useState(false);
const [search, setSearch] = useState("");
const [debouncedSearch, setDebouncedSearch] = useState("");
const debounceRef = useRef<ReturnType<typeof setTimeout>>();
const fetchData = useCallback(async () => {
setLoading(true);
try {
const res = await fetch("/api/locations/bulk");
if (!res.ok) throw new Error("Failed");
setLocations(await res.json());
} catch {
toast.error("Failed to load locations");
} 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 filteredLocations = useMemo(() => {
if (!debouncedSearch) return locations;
const q = debouncedSearch.toLowerCase();
return locations.filter(
(loc) =>
loc.country.toLowerCase().includes(q) ||
loc.city.toLowerCase().includes(q)
);
}, [locations, debouncedSearch]);
const handleAdd = () => {
setEditing(null);
setFormCountry("");
setFormCity("");
setFormDistrict("");
setDialogOpen(true);
};
const handleEdit = (loc: LocationRow) => {
setEditing(loc);
setFormCountry(loc.country);
setFormCity(loc.city);
setFormDistrict(loc.district);
setDialogOpen(true);
};
const handleSave = async () => {
if (!formCountry.trim() || !formCity.trim()) return;
setSaving(true);
try {
if (editing) {
const res = await fetch(`/api/locations/${editing.id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
country: formCountry.trim(),
city: formCity.trim(),
district: formDistrict.trim(),
}),
});
if (!res.ok) {
const err = await res.json();
throw new Error(err.error || "Update failed");
}
toast.success("Location updated");
} else {
const res = await fetch("/api/locations/bulk", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
country: formCountry.trim(),
city: formCity.trim(),
district: formDistrict.trim(),
}),
});
if (!res.ok) {
const err = await res.json();
throw new Error(err.error || "Create failed");
}
toast.success("Location created");
}
setDialogOpen(false);
fetchData();
} catch (e) {
toast.error(e instanceof Error ? e.message : "Operation failed");
} finally {
setSaving(false);
}
};
const handleToggle = async (loc: LocationRow) => {
try {
const res = await fetch(`/api/locations/${loc.id}`, { method: "PATCH" });
if (!res.ok) throw new Error();
toast.success(`Location ${loc.isActive ? "deactivated" : "activated"}`);
fetchData();
} catch {
toast.error("Failed to toggle location");
}
};
const handleDelete = async () => {
if (!deleteTarget) return;
setDeleting(true);
try {
const res = await fetch(`/api/locations/${deleteTarget.id}`, { method: "DELETE" });
if (!res.ok) {
const err = await res.json();
throw new Error(err.error || "Delete failed");
}
toast.success("Location deleted");
setDeleteTarget(null);
fetchData();
} catch (e) {
toast.error(e instanceof Error ? e.message : "Delete failed");
} finally {
setDeleting(false);
}
};
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">Locations</h2>
<p className="text-sm text-muted-foreground">
{locations.length} location{locations.length !== 1 ? "s" : ""} total &middot; Manage delivery regions and zones
</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 country or city..."
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 Location
</Button>
</div>
</div>
<div className="max-h-[calc(100vh-14rem)] overflow-y-auto rounded-lg border">
{loading ? (
<div className="p-4"><SkeletonTable /></div>
) : filteredLocations.length === 0 ? (
<div className="flex flex-col items-center justify-center py-16 text-muted-foreground">
<MapPin className="size-12 mb-3 opacity-30" />
<p className="text-lg font-medium">No locations found</p>
<p className="text-sm">Create your first location to get started.</p>
</div>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-16">ID</TableHead>
<TableHead>Country</TableHead>
<TableHead>City</TableHead>
<TableHead>District</TableHead>
<TableHead className="w-36">Categories</TableHead>
<TableHead className="w-28">Products</TableHead>
<TableHead className="w-20">Active</TableHead>
<TableHead className="w-28">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{filteredLocations.map((loc) => (
<TableRow key={loc.id}>
<TableCell className="font-mono text-xs">{loc.id}</TableCell>
<TableCell className="font-medium">{loc.country}</TableCell>
<TableCell>{loc.city}</TableCell>
<TableCell>{loc.district || "\u2014"}</TableCell>
<TableCell>
<Badge variant="outline">{loc._count.categories}</Badge>
</TableCell>
<TableCell>
<Badge variant="outline">{loc._count.products}</Badge>
</TableCell>
<TableCell>
<Switch
checked={loc.isActive === 1}
onCheckedChange={() => handleToggle(loc)}
/>
</TableCell>
<TableCell>
<div className="flex gap-1">
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => handleEdit(loc)}>
<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(loc)}
>
<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 Location" : "Add Location"}</DialogTitle>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label htmlFor="loc-country">Country</Label>
<Input
id="loc-country"
value={formCountry}
onChange={(e) => setFormCountry(e.target.value)}
placeholder="e.g. USA"
/>
</div>
<div className="space-y-2">
<Label htmlFor="loc-city">City</Label>
<Input
id="loc-city"
value={formCity}
onChange={(e) => setFormCity(e.target.value)}
placeholder="e.g. New York"
/>
</div>
<div className="space-y-2">
<Label htmlFor="loc-district">District</Label>
<Input
id="loc-district"
value={formDistrict}
onChange={(e) => setFormDistrict(e.target.value)}
placeholder="Optional"
/>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setDialogOpen(false)}>Cancel</Button>
<Button onClick={handleSave} disabled={saving || !formCountry.trim() || !formCity.trim()}>
{saving ? "Saving..." : "Save"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Delete Confirmation */}
<AlertDialog open={!!deleteTarget} onOpenChange={(open) => !open && setDeleteTarget(null)}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete Location</AlertDialogTitle>
<AlertDialogDescription>
Are you sure you want to delete &quot;{deleteTarget?.country} &gt; {deleteTarget?.city}&quot;? This action cannot be undone.
{deleteTarget && (deleteTarget._count.categories > 0 || deleteTarget._count.products > 0) && (
<span className="block mt-2 text-red-600 font-medium">
This location has {deleteTarget._count.categories} categor{deleteTarget._count.categories === 1 ? "y" : "ies"}
and {deleteTarget._count.products} product(s) and cannot be deleted.
</span>
)}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={handleDelete}
disabled={deleting || (deleteTarget ? (deleteTarget._count.categories > 0 || 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,519 @@
"use client";
import { useEffect, useState, useCallback, useMemo } from "react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Skeleton } from "@/components/ui/skeleton";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { toast } from "sonner";
import { format } from "date-fns";
import { Copy, ShoppingCart, CheckCircle, XCircle, Calendar, CheckCircle2, Ban } from "lucide-react";
import { ExportButton } from "@/components/shared/export-button";
import { SortableHeader } from "@/components/shared/sortable-header";
import { Pagination } from "@/components/shared/pagination";
import { Input } from "@/components/ui/input";
import { copyToClipboard } from "@/lib/clipboard";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
interface PurchaseRow {
id: number;
userId: number;
productId: number;
walletType: string | null;
txHash: string | null;
quantity: number;
totalPrice: number;
purchaseDate: string;
status: string;
user: { username: string | null; telegramId: string };
product: { name: string };
}
interface PurchasesResponse {
data: PurchaseRow[];
total: number;
page: number;
limit: number;
}
const STATUS_TABS = ["", "pending", "completed", "cancelled"] as const;
const STATUS_LABELS: Record<string, string> = { "": "All", pending: "Pending", completed: "Completed", cancelled: "Cancelled" };
function StatusBadge({ status }: { status: string }) {
if (status === "completed")
return <Badge className="bg-emerald-600 hover:bg-emerald-700 text-white whitespace-nowrap">Completed</Badge>;
if (status === "pending")
return <Badge className="bg-yellow-500 hover:bg-yellow-600 text-white whitespace-nowrap">Pending</Badge>;
if (status === "cancelled")
return <Badge className="bg-red-600 hover:bg-red-700 text-white whitespace-nowrap">Cancelled</Badge>;
return <Badge variant="secondary" className="whitespace-nowrap">{status}</Badge>;
}
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-28" />
<Skeleton className="h-4 w-28" />
<Skeleton className="h-4 w-12" />
<Skeleton className="h-4 w-20" />
<Skeleton className="h-4 w-16" />
<Skeleton className="h-4 w-24" />
<Skeleton className="h-4 w-20" />
<Skeleton className="h-4 w-20" />
</div>
))}
</div>
);
}
function truncateHash(hash: string | null): string {
if (!hash) return "\u2014";
if (hash.length <= 16) return hash;
return `${hash.slice(0, 10)}...${hash.slice(-6)}`;
}
export function PurchasesPage() {
const [purchases, setPurchases] = useState<PurchaseRow[]>([]);
const [total, setTotal] = useState(0);
const [page, setPage] = useState(1);
const [status, setStatus] = useState<string>("");
const [loading, setLoading] = useState(true);
const [sortColumn, setSortColumn] = useState<string>("");
const [sortDirection, setSortDirection] = useState<"asc" | "desc" | null>(null);
const [tabCounts, setTabCounts] = useState<Record<string, number>>({ "": 0, pending: 0, completed: 0, cancelled: 0 });
const [confirmDialog, setConfirmDialog] = useState<{ purchaseId: number; newStatus: string; productName: string } | null>(null);
const [updatingId, setUpdatingId] = useState<number | null>(null);
const [dateFrom, setDateFrom] = useState('');
const [dateTo, setDateTo] = useState('');
const [selectedIds, setSelectedIds] = useState<Set<number>>(new Set());
const [batchLoading, setBatchLoading] = useState(false);
const limit = 50;
const fetchData = useCallback(async () => {
setLoading(true);
try {
const params = new URLSearchParams({ page: String(page), limit: String(limit) });
if (status) params.set("status", status);
if (dateFrom) params.set('from', dateFrom);
if (dateTo) params.set('to', dateTo);
const res = await fetch(`/api/purchases/bulk?${params}`);
if (!res.ok) throw new Error("Failed to fetch");
const json: PurchasesResponse = await res.json();
setPurchases(json.data);
setTotal(json.total);
} catch {
toast.error("Failed to load purchases");
} finally {
setLoading(false);
}
}, [page, status, dateFrom, dateTo]);
const fetchCounts = useCallback(async () => {
try {
const statuses = ["", "pending", "completed", "cancelled"];
const results = await Promise.all(
statuses.map(async (s) => {
const params = new URLSearchParams({ page: "1", limit: "1" });
if (s) params.set("status", s);
const res = await fetch(`/api/purchases/bulk?${params}`);
if (!res.ok) return { key: s, count: 0 };
const json: PurchasesResponse = await res.json();
return { key: s, count: json.total };
})
);
const counts: Record<string, number> = {};
for (const r of results) counts[r.key] = r.count;
setTabCounts(counts);
} catch {
// silent fail for counts
}
}, []);
useEffect(() => {
fetchData();
fetchCounts();
}, [fetchData, fetchCounts]);
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 sortedPurchases = useMemo(() => {
if (!sortColumn || !sortDirection) return purchases;
return [...purchases].sort((a, b) => {
let valA: unknown;
let valB: unknown;
if (sortColumn === "date") { valA = a.purchaseDate; valB = b.purchaseDate; }
else if (sortColumn === "amount") { valA = a.totalPrice; valB = b.totalPrice; }
else if (sortColumn === "status") { valA = a.status; valB = b.status; }
else return 0;
if (valA === valB) return 0;
const cmp = valA < valB ? -1 : 1;
return sortDirection === "asc" ? cmp : -cmp;
});
}, [purchases, sortColumn, sortDirection]);
const exportData = useMemo<Record<string, unknown>[]>(
() => sortedPurchases.map((p) => ({
ID: p.id,
User: p.user.username || `@${p.user.telegramId}`,
Product: p.product.name,
Qty: p.quantity,
"Total Price": p.totalPrice,
Currency: p.walletType || "",
"TX Hash": p.txHash || "",
Date: p.purchaseDate,
Status: p.status,
})),
[sortedPurchases]
);
const handleStatusChange = (s: string) => {
setStatus(s);
setPage(1);
};
const handleStatusUpdate = async (purchaseId: number, newStatus: string) => {
setUpdatingId(purchaseId);
try {
const res = await fetch(`/api/purchases/${purchaseId}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ status: newStatus }),
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err.error || 'Failed to update status');
}
toast.success(newStatus === 'completed' ? 'Purchase approved' : 'Purchase cancelled');
fetchData();
fetchCounts();
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Failed to update purchase status');
} finally {
setUpdatingId(null);
setConfirmDialog(null);
}
};
const copyHash = async (hash: string) => {
const ok = await copyToClipboard(hash);
if (ok) toast.success("Copied!");
};
const toggleSelect = (id: number) => {
setSelectedIds((prev) => {
const next = new Set(prev);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
};
const toggleSelectAll = () => {
if (selectedIds.size === sortedPurchases.length) {
setSelectedIds(new Set());
} else {
setSelectedIds(new Set(sortedPurchases.map((p) => p.id)));
}
};
const handleBatchStatus = async (newStatus: 'completed' | 'cancelled') => {
if (selectedIds.size === 0) return;
setBatchLoading(true);
try {
const res = await fetch('/api/purchases/batch-status', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ purchaseIds: Array.from(selectedIds), status: newStatus }),
});
if (!res.ok) {
const data = await res.json();
throw new Error(data.error || 'Batch update failed');
}
const data = await res.json();
toast.success(data.message);
setSelectedIds(new Set());
fetchData();
fetchCounts();
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Batch update failed');
} finally {
setBatchLoading(false);
}
};
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">Purchases</h2>
<p className="text-sm text-muted-foreground">
{total} purchase{total !== 1 ? "s" : ""} total &middot; Track and manage all transactions{status ? ` · Filtered by status: ${STATUS_LABELS[status] || status}` : ""}
</p>
</div>
</div>
<Tabs value={status} onValueChange={handleStatusChange}>
<TabsList>
{STATUS_TABS.map((s) => (
<TabsTrigger key={s} value={s}>
{STATUS_LABELS[s]} ({tabCounts[s] ?? 0})
</TabsTrigger>
))}
</TabsList>
</Tabs>
<div className="flex flex-col sm:flex-row sm:items-center gap-3">
<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 className="sm:ml-auto">
<ExportButton data={exportData} filename="purchases" />
</div>
</div>
<div className="max-h-[calc(100vh-14rem)] overflow-y-auto rounded-lg border">
{loading ? (
<div className="p-4">
<SkeletonTable />
</div>
) : purchases.length === 0 ? (
<div className="flex flex-col items-center justify-center py-16 text-muted-foreground empty-state">
<ShoppingCart className="size-12 mb-3 opacity-30" />
<p className="text-lg font-medium">No purchases found</p>
<p className="text-sm">There are no purchases matching the current filter.</p>
</div>
) : (
<Table className="alternate-rows table-header-gradient">
<TableHeader>
<TableRow>
<TableHead className="w-10">
<Checkbox
checked={sortedPurchases.length > 0 && selectedIds.size === sortedPurchases.length}
onCheckedChange={toggleSelectAll}
aria-label="Select all purchases"
/>
</TableHead>
<TableHead className="w-16">ID</TableHead>
<TableHead>User</TableHead>
<TableHead>Product</TableHead>
<TableHead className="w-16">Qty</TableHead>
<TableHead className="w-28">
<SortableHeader column="amount" label="Total Price" sortColumn={sortColumn} sortDirection={sortDirection} onSort={handleSort} />
</TableHead>
<TableHead className="w-20">Currency</TableHead>
<TableHead className="w-36">TX Hash</TableHead>
<TableHead className="w-32">
<SortableHeader column="date" label="Date" sortColumn={sortColumn} sortDirection={sortDirection} onSort={handleSort} />
</TableHead>
<TableHead className="w-28">
<SortableHeader column="status" label="Status" sortColumn={sortColumn} sortDirection={sortDirection} onSort={handleSort} />
</TableHead>
<TableHead className="w-28">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{sortedPurchases.map((p) => (
<TableRow key={p.id} data-selected={selectedIds.has(p.id) ? true : undefined}>
<TableCell>
<Checkbox
checked={selectedIds.has(p.id)}
onCheckedChange={() => toggleSelect(p.id)}
aria-label={`Select purchase ${p.id}`}
/>
</TableCell>
<TableCell className="font-mono text-xs border-l-2 border-l-primary/10">{p.id}</TableCell>
<TableCell>
<a
href={`#/users/${p.userId}`}
className="text-orange-500 hover:text-orange-400 hover:underline font-medium"
>
{p.user.username || `@${p.user.telegramId}`}
</a>
</TableCell>
<TableCell className="max-w-48 truncate" title={p.product.name}>
{p.product.name}
</TableCell>
<TableCell>{p.quantity}</TableCell>
<TableCell className="font-mono">
${p.totalPrice.toFixed(2)}
</TableCell>
<TableCell>
<Badge variant="outline" className="text-xs whitespace-nowrap">
{p.walletType || "\u2014"}
</Badge>
</TableCell>
<TableCell>
{p.txHash ? (
<button
onClick={() => copyHash(p.txHash!)}
className="flex items-center gap-1 text-xs font-mono text-muted-foreground hover:text-foreground cursor-pointer"
title={p.txHash}
>
<Copy className="h-3 w-3" />
{truncateHash(p.txHash)}
</button>
) : (
<span className="text-muted-foreground text-sm">{"\u2014"}</span>
)}
</TableCell>
<TableCell className="text-sm text-muted-foreground">
{format(new Date(p.purchaseDate), "MMM d, yyyy HH:mm")}
</TableCell>
<TableCell>
<StatusBadge status={p.status} />
</TableCell>
<TableCell>
{p.status === 'pending' ? (
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0 text-emerald-500 hover:text-emerald-400 hover:bg-emerald-500/10"
title="Approve purchase"
disabled={updatingId === p.id}
onClick={() => setConfirmDialog({ purchaseId: p.id, newStatus: 'completed', productName: p.product.name })}
>
<CheckCircle className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0 text-red-500 hover:text-red-400 hover:bg-red-500/10"
title="Cancel purchase"
disabled={updatingId === p.id}
onClick={() => setConfirmDialog({ purchaseId: p.id, newStatus: 'cancelled', productName: p.product.name })}
>
<XCircle className="h-4 w-4" />
</Button>
</div>
) : (
<span className="text-sm text-muted-foreground"></span>
)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</div>
<AlertDialog open={confirmDialog !== null} onOpenChange={(open) => { if (!open) setConfirmDialog(null); }}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
{confirmDialog?.newStatus === 'completed' ? 'Approve Purchase' : 'Cancel Purchase'}
</AlertDialogTitle>
<AlertDialogDescription>
Are you sure you want to {confirmDialog?.newStatus === 'completed' ? 'approve' : 'cancel'} the purchase for <strong>{confirmDialog?.productName}</strong>? This action cannot be undone.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Back</AlertDialogCancel>
<AlertDialogAction
onClick={() => {
if (confirmDialog) handleStatusUpdate(confirmDialog.purchaseId, confirmDialog.newStatus);
}}
className={confirmDialog?.newStatus === 'completed' ? 'bg-emerald-600 hover:bg-emerald-700' : 'bg-red-600 hover:bg-red-700'}
>
{confirmDialog?.newStatus === 'completed' ? 'Approve' : 'Cancel'}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
{!loading && total > 0 && (
<Pagination page={page} total={total} limit={limit} onPageChange={setPage} />
)}
{/* Floating batch action bar */}
{selectedIds.size > 0 && (
<div className="fixed bottom-6 left-1/2 -translate-x-1/2 z-50 flex items-center gap-3 rounded-xl border border-border/50 bg-background/90 backdrop-blur-lg px-5 py-3 shadow-lg animate-in slide-in-from-bottom-4 fade-in duration-200">
<span className="text-sm font-medium">
{selectedIds.size} selected
</span>
<div className="w-px h-6 bg-border" />
<Button
size="sm"
variant="outline"
className="gap-1.5 text-emerald-500 hover:text-emerald-400 hover:bg-emerald-500/10 hover:border-emerald-500/30"
disabled={batchLoading}
onClick={() => handleBatchStatus('completed')}
>
<CheckCircle2 className="h-4 w-4" />
{batchLoading ? 'Updating...' : 'Approve Selected'}
</Button>
<Button
size="sm"
variant="outline"
className="gap-1.5 text-red-500 hover:text-red-400 hover:bg-red-500/10 hover:border-red-500/30"
disabled={batchLoading}
onClick={() => handleBatchStatus('cancelled')}
>
<Ban className="h-4 w-4" />
{batchLoading ? 'Updating...' : 'Cancel Selected'}
</Button>
<Button
size="sm"
variant="ghost"
className="text-muted-foreground"
onClick={() => setSelectedIds(new Set())}
>
Clear
</Button>
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,294 @@
"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 { Skeleton } from "@/components/ui/skeleton";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Badge } from "@/components/ui/badge";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { toast } from "sonner";
import { useAuthStore } from "@/stores/auth-store";
import { Database, Trash2, AlertTriangle, Loader2, CheckCircle, Sprout } from "lucide-react";
export function SeedPage() {
const { role } = useAuthStore();
const [seeded, setSeeded] = useState<boolean | null>(null);
const [checking, setChecking] = useState(true);
const [seedDialogOpen, setSeedDialogOpen] = useState(false);
const [clearDialogOpen, setClearDialogOpen] = useState(false);
const [reauthToken, setReauthToken] = useState("");
const [actionLoading, setActionLoading] = useState(false);
const [activeAction, setActiveAction] = useState<"seed" | "clear" | null>(null);
const checkData = async () => {
setChecking(true);
try {
const res = await fetch("/api/seed/data");
if (res.ok) {
const data = await res.json();
setSeeded(data.seeded);
}
} catch {
// ignore
} finally {
setChecking(false);
}
};
useEffect(() => {
if (role === "super_admin") checkData();
}, [role]);
const handleAction = async (type: "seed" | "clear") => {
if (!reauthToken.trim()) return;
setActionLoading(true);
setActiveAction(type);
try {
const url = type === "seed" ? "/api/seed/demo" : "/api/seed/clear";
const res = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ reauthToken }),
});
if (!res.ok) {
const err = await res.json();
throw new Error(err.error || "Operation failed");
}
toast.success(type === "seed" ? "Demo data seeded successfully" : "All data cleared successfully");
setSeedDialogOpen(false);
setClearDialogOpen(false);
setReauthToken("");
checkData();
} catch (e) {
toast.error(e instanceof Error ? e.message : "Operation failed");
} finally {
setActionLoading(false);
setActiveAction(null);
}
};
if (role !== "super_admin") {
return (
<div className="flex flex-col items-center justify-center py-20 text-muted-foreground">
<AlertTriangle className="h-12 w-12 mb-4 text-red-500" />
<p className="text-lg font-semibold">Access Denied</p>
<p className="text-sm">Only super admins can access this page.</p>
</div>
);
}
return (
<div className="space-y-6 page-enter">
<div className="max-w-2xl mx-auto space-y-6">
<div>
<h2 className="text-xl font-semibold">Database Seed</h2>
<p className="text-sm text-muted-foreground">Manage demo data and database state. Requires re-authentication for destructive actions.</p>
</div>
<Alert className="border-orange-500/50 bg-orange-500/5">
<AlertTriangle className="h-4 w-4 text-orange-500" />
<AlertDescription className="text-orange-400">
This section is restricted to super administrators only.
</AlertDescription>
</Alert>
{/* Status Card */}
{checking ? (
<Card>
<CardContent className="p-4 flex items-center gap-4">
<Skeleton className="h-10 w-10 rounded-lg" />
<div className="space-y-2">
<Skeleton className="h-4 w-32" />
<Skeleton className="h-3 w-48" />
</div>
</CardContent>
</Card>
) : seeded ? (
<Card className="border-l-4 border-l-emerald-500 bg-emerald-500/5">
<CardContent className="p-4 flex items-center gap-4">
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-emerald-500/15">
<CheckCircle className="h-5 w-5 text-emerald-500" />
</div>
<div>
<p className="font-medium">Database Contains Data</p>
<p className="text-sm text-muted-foreground">The database is currently populated with demo data.</p>
</div>
<Badge variant="default" className="ml-auto bg-emerald-600 text-white">
Seeded
</Badge>
</CardContent>
</Card>
) : (
<Card className="border-l-4 border-l-muted">
<CardContent className="p-4 flex items-center gap-4">
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-muted">
<Database className="h-5 w-5 text-muted-foreground" />
</div>
<div>
<p className="font-medium">Database is Empty</p>
<p className="text-sm text-muted-foreground">No demo data has been seeded yet.</p>
</div>
<Badge variant="secondary" className="ml-auto">
Empty
</Badge>
</CardContent>
</Card>
)}
<div className="grid gap-4 md:grid-cols-2">
{/* Seed Demo Data Card */}
<Card className="border-l-4 border-l-emerald-500/50 card-hover">
<CardHeader>
<div className="flex items-center gap-2">
<div className="flex h-8 w-8 items-center justify-center rounded-lg bg-emerald-500/15">
<Sprout className="h-4 w-4 text-emerald-500" />
</div>
<CardTitle className="text-base">Seed Demo Data</CardTitle>
</div>
<CardDescription>
Populate the database with sample data including locations, categories, products, users, and purchases. This will replace any existing data.
</CardDescription>
</CardHeader>
<CardContent>
<Button
variant="outline"
className="border-emerald-500/50 text-emerald-400 hover:bg-emerald-500/10"
onClick={() => setSeedDialogOpen(true)}
>
<Sprout className="h-4 w-4 mr-1" />
Seed Demo Data
</Button>
</CardContent>
</Card>
{/* Clear All Data Card */}
<Card className="border-l-4 border-l-red-500/50 card-hover">
<CardHeader>
<div className="flex items-center gap-2">
<div className="flex h-8 w-8 items-center justify-center rounded-lg bg-red-500/15">
<Trash2 className="h-4 w-4 text-red-500" />
</div>
<CardTitle className="text-base text-red-400">Clear All Data</CardTitle>
</div>
<CardDescription>
Permanently delete all records from every table in the database. This action is irreversible and cannot be undone.
</CardDescription>
</CardHeader>
<CardContent>
<Button
variant="outline"
className="border-red-500/50 text-red-400 hover:bg-red-500/10"
onClick={() => setClearDialogOpen(true)}
>
<Trash2 className="h-4 w-4 mr-1" />
Clear All Data
</Button>
</CardContent>
</Card>
</div>
</div>
{/* Seed Demo Dialog */}
<AlertDialog open={seedDialogOpen} onOpenChange={setSeedDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle className="text-red-600">Seed Demo Data</AlertDialogTitle>
<AlertDialogDescription asChild>
<div className="space-y-3">
<p>
This will <strong>delete all existing data</strong> and populate the database
with sample demo data. This action is irreversible.
</p>
<p className="font-medium text-red-600">
Type your admin password to confirm.
</p>
</div>
</AlertDialogDescription>
</AlertDialogHeader>
<div className="py-2">
<Label htmlFor="seed-reauth">Reauth Token</Label>
<Input
id="seed-reauth"
type="password"
value={reauthToken}
onChange={(e) => setReauthToken(e.target.value)}
placeholder="Enter admin password"
className="mt-1.5"
/>
</div>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={() => handleAction("seed")}
disabled={!reauthToken.trim() || actionLoading}
className="bg-red-600 hover:bg-red-700"
>
{actionLoading && activeAction === "seed" ? (
<><Loader2 className="h-4 w-4 mr-1 animate-spin" /> Seeding...</>
) : (
"Confirm Seed"
)}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
{/* Clear All Dialog */}
<AlertDialog open={clearDialogOpen} onOpenChange={setClearDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle className="text-red-600">Clear All Data</AlertDialogTitle>
<AlertDialogDescription asChild>
<div className="space-y-3">
<p>
This will <strong>permanently delete all records</strong> from every table
in the database. This action cannot be undone.
</p>
<p className="font-medium text-red-600">
Type your admin password to confirm.
</p>
</div>
</AlertDialogDescription>
</AlertDialogHeader>
<div className="py-2">
<Label htmlFor="clear-reauth">Reauth Token</Label>
<Input
id="clear-reauth"
type="password"
value={reauthToken}
onChange={(e) => setReauthToken(e.target.value)}
placeholder="Enter admin password"
className="mt-1.5"
/>
</div>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={() => handleAction("clear")}
disabled={!reauthToken.trim() || actionLoading}
className="bg-red-600 hover:bg-red-700"
>
{actionLoading && activeAction === "clear" ? (
<><Loader2 className="h-4 w-4 mr-1 animate-spin" /> Clearing...</>
) : (
<><Trash2 className="h-4 w-4 mr-1" /> Confirm Clear</>
)}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}

View File

@@ -0,0 +1,386 @@
"use client";
import { useEffect, useState, useRef } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Skeleton } from "@/components/ui/skeleton";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { toast } from "sonner";
import { useAuthStore } from "@/stores/auth-store";
import { Bot, Shield, Wrench, Save, AlertTriangle, Download, Upload, Database, Info } from "lucide-react";
const MASKED_PLACEHOLDER = "\u25CF\u25CF\u25CF\u25CF\u25CF\u25CF\u25CF";
const KEY_META: Record<string, { label: string; description: string }> = {
BOT_TOKEN: { label: "Bot Token", description: "Telegram Bot API token from @BotFather" },
SUPPORT_LINK: { label: "Support Link", description: "URL shown to users for support" },
ADMIN_IDS: { label: "Admin Telegram IDs", description: "Comma-separated list of admin user IDs" },
SUPER_ADMIN_IDS: { label: "Super Admin IDs", description: "Comma-separated list of super admin IDs" },
WG_ENABLED: { label: "WireGuard VPN", description: "Enable WireGuard VPN for product delivery" },
WG_ENDPOINT: { label: "VPN Endpoint", description: "WireGuard server endpoint address" },
WG_ADDRESS: { label: "VPN Address", description: "WireGuard client address" },
WG_PUBLIC_KEY: { label: "VPN Public Key", description: "WireGuard server public key" },
WG_DNS: { label: "VPN DNS", description: "DNS server for VPN connection" },
ADMIN_PORT: { label: "Admin Port", description: "Port for the admin panel HTTP server" },
ADMIN_URL: { label: "Admin URL", description: "Public URL for the admin panel" },
CATALOG_PATH: { label: "Catalog Path", description: "File system path to the product catalog" },
GITEA_API_URL: { label: "Gitea API URL", description: "Gitea instance API endpoint URL" },
};
const SECTIONS = [
{
title: "Bot Configuration",
keys: ["BOT_TOKEN", "SUPPORT_LINK", "ADMIN_IDS", "SUPER_ADMIN_IDS"],
icon: Bot,
description: "Telegram bot and user management settings",
},
{
title: "WireGuard VPN",
keys: ["WG_ENABLED", "WG_ENDPOINT", "WG_ADDRESS", "WG_PUBLIC_KEY", "WG_DNS"],
icon: Shield,
description: "VPN configuration for secure product delivery",
},
{
title: "Admin Panel",
keys: ["ADMIN_PORT", "ADMIN_URL", "CATALOG_PATH", "GITEA_API_URL"],
icon: Wrench,
description: "Admin panel server and integration settings",
},
];
function SkeletonForm() {
return (
<div className="space-y-4">
{Array.from({ length: 4 }).map((_, i) => (
<div key={i} className="space-y-2">
<Skeleton className="h-4 w-24" />
<Skeleton className="h-9 w-full" />
</div>
))}
</div>
);
}
export function SettingsPage() {
const { role } = useAuthStore();
const isSuperAdmin = role === "super_admin";
const [settings, setSettings] = useState<Record<string, string | boolean> | null>(null);
const [masked, setMasked] = useState<string[]>([]);
const [saving, setSaving] = useState<string | null>(null);
const [exporting, setExporting] = useState(false);
const [importing, setImporting] = useState(false);
const [importDialogOpen, setImportDialogOpen] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
fetch("/api/settings")
.then((res) => res.json())
.then((data) => {
const m: string[] = data._masked || [];
setMasked(m);
delete data._masked;
setSettings(data);
})
.catch(() => toast.error("Failed to load settings"));
}, []);
const handleSave = async (key: string) => {
if (!settings) return;
setSaving(key);
try {
const res = await fetch("/api/settings", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key, value: settings[key] }),
});
if (!res.ok) throw new Error();
toast.success(`${KEY_META[key]?.label || key} saved. Restart required.`);
} catch {
toast.error(`Failed to save ${KEY_META[key]?.label || key}`);
} finally {
setSaving(null);
}
};
const handleChange = (key: string, value: string) => {
setSettings((prev) => (prev ? { ...prev, [key]: value } : prev));
};
const handleSwitchChange = (key: string, checked: boolean) => {
setSettings((prev) => (prev ? { ...prev, [key]: checked } : prev));
};
const handleExport = async () => {
setExporting(true);
try {
const res = await fetch("/api/settings/export");
if (!res.ok) throw new Error();
const data = await res.json();
const blob = new Blob([JSON.stringify(data, null, 2)], { type: "application/json" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `telegram-shop-backup-${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");
} finally {
setExporting(false);
}
};
const handleImport = async () => {
const file = fileInputRef.current?.files?.[0];
if (!file) return;
setImporting(true);
try {
const text = await file.text();
const data = JSON.parse(text);
const res = await fetch("/api/settings/import", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
});
if (!res.ok) throw new Error();
const result = await res.json();
if (result.ok) {
toast.info(result.message || "Import not yet implemented");
} else {
toast.error(result.error || "Import failed");
}
} catch {
toast.error("Failed to import data. Ensure the file is valid JSON.");
} finally {
setImporting(false);
setImportDialogOpen(false);
if (fileInputRef.current) fileInputRef.current.value = "";
}
};
return (
<div className="page-enter space-y-6">
<Alert className="border-yellow-500 bg-yellow-50 dark:bg-yellow-950/20">
<AlertTriangle className="h-4 w-4 text-yellow-600" />
<AlertDescription className="text-yellow-700 dark:text-yellow-400">
Restart the application to apply changes.
</AlertDescription>
</Alert>
<p className="text-sm text-muted-foreground">Configure bot settings, WireGuard VPN, and admin panel options. Changes require a restart.</p>
{!settings ? (
<div className="space-y-6">
{SECTIONS.map((s) => (
<Card key={s.title}>
<CardHeader className="pb-4">
<CardTitle className="flex items-center gap-2 text-base">
<s.icon className="h-4 w-4" />
{s.title}
</CardTitle>
<CardDescription>{s.description}</CardDescription>
</CardHeader>
<CardContent>
<SkeletonForm />
</CardContent>
</Card>
))}
</div>
) : (
<div className="space-y-6">
{SECTIONS.map((section) => {
const SectionIcon = section.icon;
return (
<Card key={section.title}>
<CardHeader className="pb-4">
<CardTitle className="flex items-center gap-2 text-base">
<SectionIcon className="h-4 w-4" />
{section.title}
</CardTitle>
<CardDescription>{section.description}</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-4">
{section.keys.map((key) => {
const isMasked = masked.includes(key);
const isBool = key === "WG_ENABLED";
const value = String(settings[key] ?? "");
const meta = KEY_META[key];
return (
<div key={key} className="flex items-end gap-3">
<div className="flex-1 space-y-1.5">
<div className="flex items-center gap-1.5">
<Label htmlFor={key} className="text-sm">
{meta?.label || key}
</Label>
{meta && (
<Tooltip>
<TooltipTrigger asChild>
<Info className="h-3.5 w-3.5 text-muted-foreground/50 cursor-help" />
</TooltipTrigger>
<TooltipContent side="top" sideOffset={4}>
{meta.description}
</TooltipContent>
</Tooltip>
)}
</div>
{meta && (
<p className="text-xs text-muted-foreground/60 mt-0.5">{meta.description}</p>
)}
{isBool ? (
<div className="flex items-center gap-2">
<Switch
id={key}
checked={settings[key] === true}
onCheckedChange={(checked) => handleSwitchChange(key, checked)}
/>
<span className="text-sm text-muted-foreground">
{settings[key] ? "Enabled" : "Disabled"}
</span>
</div>
) : isMasked ? (
<Input
id={key}
value={MASKED_PLACEHOLDER}
disabled
className="max-w-md"
/>
) : (
<Input
id={key}
value={value}
onChange={(e) => handleChange(key, e.target.value)}
className="max-w-md"
/>
)}
</div>
{!isMasked && (
<Button
size="sm"
variant="outline"
onClick={() => handleSave(key)}
disabled={saving === key}
>
{saving === key ? (
"Saving..."
) : (
<>
<Save className="h-4 w-4 mr-1" />
Save
</>
)}
</Button>
)}
</div>
);
})}
</div>
</CardContent>
</Card>
);
})}
</div>
)}
{/* Data Management Section */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<Database className="h-4 w-4 text-orange-500" />
Data Management
</CardTitle>
<CardDescription>
Export all database records as JSON for backup, or import from a previous backup file.
</CardDescription>
</CardHeader>
<CardContent>
<div className="flex flex-wrap gap-3">
<div className="flex items-center gap-2">
<Button
variant="outline"
onClick={handleExport}
disabled={exporting}
className="gap-2"
>
<Download className="h-4 w-4" />
{exporting ? "Exporting..." : "Export All Data"}
</Button>
<Tooltip>
<TooltipTrigger asChild>
<Info className="h-4 w-4 text-muted-foreground/50 cursor-help" />
</TooltipTrigger>
<TooltipContent side="top" sideOffset={4}>
Exports all 10 database tables including users, wallets, purchases, and settings.
</TooltipContent>
</Tooltip>
</div>
{isSuperAdmin && (
<AlertDialog open={importDialogOpen} onOpenChange={setImportDialogOpen}>
<AlertDialogTrigger asChild>
<Button variant="destructive" className="gap-2">
<Upload className="h-4 w-4" />
Import Data
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>\u26A0\uFE0F Confirm Data Import</AlertDialogTitle>
<AlertDialogDescription>
Importing data will overwrite existing records. This is a dangerous operation
that cannot be undone. Make sure you have a recent backup before proceeding.
Only super admins can perform this action.
</AlertDialogDescription>
</AlertDialogHeader>
<div className="py-2">
<input
ref={fileInputRef}
type="file"
accept=".json"
className="block w-full text-sm text-muted-foreground
file:mr-4 file:py-2 file:px-4
file:rounded-md file:border-0
file:text-sm file:font-semibold
file:bg-orange-50 file:text-orange-700
hover:file:bg-orange-100
dark:file:bg-orange-950 dark:file:text-orange-300"
/>
</div>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={handleImport}
disabled={importing}
>
{importing ? "Importing..." : "Proceed with Import"}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
)}
</div>
</CardContent>
</Card>
</div>
);
}

View File

@@ -0,0 +1,58 @@
'use client';
import React from 'react';
import { AlertTriangle, RotateCcw } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
interface Props {
children: React.ReactNode;
fallback?: React.ReactNode;
}
interface State {
hasError: boolean;
error: Error | null;
}
export class ErrorBoundary extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = { hasError: false, error: null };
}
static getDerivedStateFromError(error: Error): State {
return { hasError: true, error };
}
resetErrorBoundary = () => {
this.setState({ hasError: false, error: null });
};
render() {
if (this.state.hasError) {
if (this.props.fallback) return this.props.fallback;
return (
<div className="flex items-center justify-center min-h-[400px]">
<Card className="max-w-md w-full mx-4">
<CardContent className="flex flex-col items-center gap-4 pt-6">
<div className="rounded-full bg-destructive/10 p-4">
<AlertTriangle className="size-8 text-destructive" />
</div>
<div className="text-center">
<h3 className="text-lg font-semibold">Something went wrong</h3>
<p className="text-sm text-muted-foreground mt-1">
{this.state.error?.message || 'An unexpected error occurred.'}
</p>
</div>
<Button variant="outline" onClick={this.resetErrorBoundary}>
<RotateCcw className="size-4 mr-2" />
Try Again
</Button>
</CardContent>
</Card>
</div>
);
}
return this.props.children;
}
}

View File

@@ -0,0 +1,86 @@
"use client";
import { Download, FileDown, FileJson } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { toast } from "sonner";
interface ExportButtonProps {
data: Record<string, unknown>[];
filename: string;
label?: string;
}
function toCsv(data: Record<string, unknown>[]): string {
if (data.length === 0) return "";
const headers = Object.keys(data[0]);
const escape = (val: unknown): string => {
const s = String(val ?? "");
if (s.includes(",") || s.includes('"') || s.includes("\n")) {
return `"${s.replace(/"/g, '""')}"`;
}
return s;
};
const rows = data.map((row) => headers.map((h) => escape(row[h])).join(","));
return [headers.join(","), ...rows].join("\n");
}
function downloadFile(content: string, filename: string, mimeType: string) {
const blob = new Blob([content], { type: mimeType });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
export function ExportButton({ data, filename, label }: ExportButtonProps) {
const handleExportCsv = () => {
if (data.length === 0) {
toast.info("No data to export");
return;
}
const csv = toCsv(data);
downloadFile(csv, `${filename}.csv`, "text/csv;charset=utf-8;");
toast.success(`Exported ${data.length} rows as CSV`);
};
const handleExportJson = () => {
if (data.length === 0) {
toast.info("No data to export");
return;
}
const json = JSON.stringify(data, null, 2);
downloadFile(json, `${filename}.json`, "application/json");
toast.success(`Exported ${data.length} rows as JSON`);
};
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="sm">
<Download className="h-4 w-4 mr-1.5" />
{label ?? "Export"}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={handleExportCsv}>
<FileDown className="h-4 w-4 mr-2" />
CSV
</DropdownMenuItem>
<DropdownMenuItem onClick={handleExportJson}>
<FileJson className="h-4 w-4 mr-2" />
JSON
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
}

View File

@@ -0,0 +1,83 @@
"use client";
import { useMemo } from "react";
import { Button } from "@/components/ui/button";
import { ChevronLeft, ChevronRight } from "lucide-react";
interface PaginationProps {
page: number;
total: number;
limit: number;
onPageChange: (page: number) => void;
}
function getPageNumbers(currentPage: number, totalPages: number): (number | "...")[] {
if (totalPages <= 7) {
return Array.from({ length: totalPages }, (_, i) => i + 1);
}
const pages: (number | "...")[] = [1];
if (currentPage > 3) pages.push("...");
const start = Math.max(2, currentPage - 1);
const end = Math.min(totalPages - 1, currentPage + 1);
for (let i = start; i <= end; i++) pages.push(i);
if (currentPage < totalPages - 2) pages.push("...");
pages.push(totalPages);
return pages;
}
export function Pagination({ page, total, limit, onPageChange }: PaginationProps) {
const totalPages = useMemo(() => Math.max(1, Math.ceil(total / limit)), [total, limit]);
const rangeStart = total === 0 ? 0 : (page - 1) * limit + 1;
const rangeEnd = Math.min(page * limit, total);
const pageNumbers = useMemo(() => getPageNumbers(page, totalPages), [page, totalPages]);
if (total <= 0) return null;
return (
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
<p className="text-sm text-muted-foreground">
Showing {rangeStart}\u2013{rangeEnd} of {total}
</p>
<div className="flex items-center gap-1">
<Button
variant="outline"
size="icon"
className="h-8 w-8"
disabled={page <= 1}
onClick={() => onPageChange(page - 1)}
aria-label="Previous page"
>
<ChevronLeft className="h-4 w-4" />
</Button>
{pageNumbers.map((p, i) =>
p === "..." ? (
<span key={`ellipsis-${i}`} className="px-1.5 text-sm text-muted-foreground">
</span>
) : (
<Button
key={p}
variant={page === p ? "default" : "outline"}
size="icon"
className="h-8 w-8"
onClick={() => onPageChange(p)}
aria-label={`Page ${p}`}
>
{p}
</Button>
)
)}
<Button
variant="outline"
size="icon"
className="h-8 w-8"
disabled={page >= totalPages}
onClick={() => onPageChange(page + 1)}
aria-label="Next page"
>
<ChevronRight className="h-4 w-4" />
</Button>
</div>
</div>
);
}

View File

@@ -0,0 +1,40 @@
"use client";
import { ArrowUpDown, ArrowUp, ArrowDown } from "lucide-react";
interface SortableHeaderProps {
column: string;
label: string;
sortColumn: string;
sortDirection: "asc" | "desc" | null;
onSort: (column: string) => void;
}
export function SortableHeader({
column,
label,
sortColumn,
sortDirection,
onSort,
}: SortableHeaderProps) {
const isActive = sortColumn === column;
return (
<button
type="button"
onClick={() => onSort(column)}
className={`flex items-center gap-1 hover:text-foreground transition-colors cursor-pointer ${
isActive ? "text-primary" : "text-muted-foreground"
}`}
>
{label}
{isActive && sortDirection === "asc" ? (
<ArrowUp className="h-3.5 w-3.5" />
) : isActive && sortDirection === "desc" ? (
<ArrowDown className="h-3.5 w-3.5" />
) : (
<ArrowUpDown className="h-3.5 w-3.5 opacity-50" />
)}
</button>
);
}

View File

@@ -0,0 +1,66 @@
"use client"
import * as React from "react"
import * as AccordionPrimitive from "@radix-ui/react-accordion"
import { ChevronDownIcon } from "lucide-react"
import { cn } from "@/lib/utils"
function Accordion({
...props
}: React.ComponentProps<typeof AccordionPrimitive.Root>) {
return <AccordionPrimitive.Root data-slot="accordion" {...props} />
}
function AccordionItem({
className,
...props
}: React.ComponentProps<typeof AccordionPrimitive.Item>) {
return (
<AccordionPrimitive.Item
data-slot="accordion-item"
className={cn("border-b last:border-b-0", className)}
{...props}
/>
)
}
function AccordionTrigger({
className,
children,
...props
}: React.ComponentProps<typeof AccordionPrimitive.Trigger>) {
return (
<AccordionPrimitive.Header className="flex">
<AccordionPrimitive.Trigger
data-slot="accordion-trigger"
className={cn(
"focus-visible:border-ring focus-visible:ring-ring/50 flex flex-1 items-start justify-between gap-4 rounded-md py-4 text-left text-sm font-medium transition-all outline-none hover:underline focus-visible:ring-[3px] disabled:pointer-events-none disabled:opacity-50 [&[data-state=open]>svg]:rotate-180",
className
)}
{...props}
>
{children}
<ChevronDownIcon className="text-muted-foreground pointer-events-none size-4 shrink-0 translate-y-0.5 transition-transform duration-200" />
</AccordionPrimitive.Trigger>
</AccordionPrimitive.Header>
)
}
function AccordionContent({
className,
children,
...props
}: React.ComponentProps<typeof AccordionPrimitive.Content>) {
return (
<AccordionPrimitive.Content
data-slot="accordion-content"
className="data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down overflow-hidden text-sm"
{...props}
>
<div className={cn("pt-0 pb-4", className)}>{children}</div>
</AccordionPrimitive.Content>
)
}
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent }

View File

@@ -0,0 +1,157 @@
"use client"
import * as React from "react"
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"
import { cn } from "@/lib/utils"
import { buttonVariants } from "@/components/ui/button"
function AlertDialog({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />
}
function AlertDialogTrigger({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
return (
<AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
)
}
function AlertDialogPortal({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
return (
<AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />
)
}
function AlertDialogOverlay({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
return (
<AlertDialogPrimitive.Overlay
data-slot="alert-dialog-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className
)}
{...props}
/>
)
}
function AlertDialogContent({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Content>) {
return (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
data-slot="alert-dialog-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
className
)}
{...props}
/>
</AlertDialogPortal>
)
}
function AlertDialogHeader({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
)
}
function AlertDialogFooter({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className
)}
{...props}
/>
)
}
function AlertDialogTitle({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
return (
<AlertDialogPrimitive.Title
data-slot="alert-dialog-title"
className={cn("text-lg font-semibold", className)}
{...props}
/>
)
}
function AlertDialogDescription({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
return (
<AlertDialogPrimitive.Description
data-slot="alert-dialog-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
function AlertDialogAction({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Action>) {
return (
<AlertDialogPrimitive.Action
className={cn(buttonVariants(), className)}
{...props}
/>
)
}
function AlertDialogCancel({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel>) {
return (
<AlertDialogPrimitive.Cancel
className={cn(buttonVariants({ variant: "outline" }), className)}
{...props}
/>
)
}
export {
AlertDialog,
AlertDialogPortal,
AlertDialogOverlay,
AlertDialogTrigger,
AlertDialogContent,
AlertDialogHeader,
AlertDialogFooter,
AlertDialogTitle,
AlertDialogDescription,
AlertDialogAction,
AlertDialogCancel,
}

View File

@@ -0,0 +1,66 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const alertVariants = cva(
"relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",
{
variants: {
variant: {
default: "bg-card text-card-foreground",
destructive:
"text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90",
},
},
defaultVariants: {
variant: "default",
},
}
)
function Alert({
className,
variant,
...props
}: React.ComponentProps<"div"> & VariantProps<typeof alertVariants>) {
return (
<div
data-slot="alert"
role="alert"
className={cn(alertVariants({ variant }), className)}
{...props}
/>
)
}
function AlertTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-title"
className={cn(
"col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",
className
)}
{...props}
/>
)
}
function AlertDescription({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-description"
className={cn(
"text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",
className
)}
{...props}
/>
)
}
export { Alert, AlertTitle, AlertDescription }

View File

@@ -0,0 +1,11 @@
"use client"
import * as AspectRatioPrimitive from "@radix-ui/react-aspect-ratio"
function AspectRatio({
...props
}: React.ComponentProps<typeof AspectRatioPrimitive.Root>) {
return <AspectRatioPrimitive.Root data-slot="aspect-ratio" {...props} />
}
export { AspectRatio }

View File

@@ -0,0 +1,53 @@
"use client"
import * as React from "react"
import * as AvatarPrimitive from "@radix-ui/react-avatar"
import { cn } from "@/lib/utils"
function Avatar({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Root>) {
return (
<AvatarPrimitive.Root
data-slot="avatar"
className={cn(
"relative flex size-8 shrink-0 overflow-hidden rounded-full",
className
)}
{...props}
/>
)
}
function AvatarImage({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Image>) {
return (
<AvatarPrimitive.Image
data-slot="avatar-image"
className={cn("aspect-square size-full", className)}
{...props}
/>
)
}
function AvatarFallback({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
return (
<AvatarPrimitive.Fallback
data-slot="avatar-fallback"
className={cn(
"bg-muted flex size-full items-center justify-center rounded-full",
className
)}
{...props}
/>
)
}
export { Avatar, AvatarImage, AvatarFallback }

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