Compare commits
137 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
45542289f5 | ||
|
|
0d4d0fdb0e | ||
|
|
cbdccaa60e | ||
|
|
87009bfd05 | ||
|
|
94a79dd26b | ||
|
|
5ef68eec63 | ||
|
|
e01886e505 | ||
|
|
67672624e3 | ||
|
|
d937858ce3 | ||
|
|
468a6f5645 | ||
|
|
1640f263b1 | ||
|
|
cc4515cc6d | ||
|
|
6a79ab40b1 | ||
|
|
a11373a90b | ||
|
|
26020cf572 | ||
|
|
b7221d31c1 | ||
|
|
5ffa4bda8f | ||
|
|
7dcf93f759 | ||
|
|
e63e9b9922 | ||
|
|
8d9bccfae8 | ||
|
|
e55e6378e1 | ||
|
|
bbf15a0551 | ||
|
|
6c0be291e0 | ||
|
|
351dd9b559 | ||
|
|
8e4530236c | ||
|
|
c51a0443a8 | ||
|
|
657cd32aaa | ||
|
|
7d629e9cd4 | ||
|
|
ca35d96925 | ||
|
|
dc60a00103 | ||
|
|
d1d1044bbc | ||
|
|
f68dda63af | ||
|
|
ab8e0619c4 | ||
|
|
99ad3f6f8e | ||
|
|
217166d3aa | ||
|
|
cdee1a227a | ||
|
|
e6582f26c8 | ||
|
|
80a873d56a | ||
|
|
9dc3d3d697 | ||
|
|
0d1ea92965 | ||
|
|
bba4c6bae7 | ||
|
|
61ff34464f | ||
|
|
f4c9bad648 | ||
|
|
80796cdcca | ||
|
|
970dc5bbe8 | ||
|
|
6cade53ec5 | ||
|
|
34981f821d | ||
|
|
22f1686ff7 | ||
|
|
5d34f3707a | ||
|
|
d8ec5683d1 | ||
|
|
06a70b6680 | ||
|
|
938fcd4422 | ||
|
|
d86467674e | ||
|
|
a21ce6e8d6 | ||
|
|
0a4507bbd0 | ||
|
|
2f27c330a1 | ||
|
|
cff4579ff1 | ||
|
|
f2de129ba8 | ||
|
|
2a9a242f50 | ||
|
|
4e74053017 | ||
|
|
bb1fcd8c37 | ||
|
|
fb694cc749 | ||
|
|
778b18dd35 | ||
|
|
c80de8800f | ||
|
|
54c0ba67c8 | ||
|
|
2f19553dec | ||
|
|
d7c213c110 | ||
|
|
b832de9194 | ||
|
|
a781e84537 | ||
|
|
17881b5b0e | ||
|
|
40ece4e764 | ||
|
|
a983da20e5 | ||
|
|
43555a9985 | ||
|
|
adb0ce31c0 | ||
|
|
c619931386 | ||
|
|
026dfb2ffe | ||
|
|
5396a4e628 | ||
|
|
3e801fe85a | ||
|
|
ec3372a3c0 | ||
|
|
157c07c747 | ||
|
|
6505d1876a | ||
|
|
2a3ff9db9b | ||
|
|
434e326991 | ||
|
|
16b66f83da | ||
|
|
cc4c6c5e96 | ||
|
|
3301570213 | ||
|
|
c65176e607 | ||
|
|
55aa93d117 | ||
|
|
7c61b7fc44 | ||
|
|
bc7f86119c | ||
|
|
bc1490f0fd | ||
|
|
7bf2aa8b3c | ||
|
|
ba086b602f | ||
|
|
0d793ee31c | ||
|
|
7579be007f | ||
|
|
515e7d2719 | ||
|
|
c9cfdfc07a | ||
|
|
c589afd859 | ||
|
|
f10f8af0f6 | ||
|
|
cbeba449ef | ||
|
|
fa02ca000b | ||
|
|
af01d60d9b | ||
|
|
06f06a8a52 | ||
|
|
fc54d9e176 | ||
|
|
8fab48f849 | ||
|
|
69878126f6 | ||
|
|
0185520445 | ||
|
|
00cb224e84 | ||
|
|
c5a932b9f1 | ||
|
|
becc328811 | ||
|
|
c2ae4c78f7 | ||
|
|
40f2483332 | ||
|
|
a27eb84d61 | ||
|
|
01b80eaf9e | ||
|
|
1e713ea613 | ||
|
|
1eb7c71ff9 | ||
|
|
b9bf2733f9 | ||
|
|
1e48c209f7 | ||
|
|
fff455312e | ||
|
|
a5626ebefe | ||
|
|
400b1aac8d | ||
|
|
872baa7933 | ||
|
|
04b47b62ad | ||
|
|
8894d2daae | ||
|
|
3145ef884d | ||
|
|
7b1c21e972 | ||
|
|
5421285a29 | ||
|
|
59727b6be9 | ||
|
|
142cdf8b41 | ||
|
|
24ae1bc45e | ||
|
|
a1cd74e90f | ||
|
|
6e8b1ccefd | ||
|
|
4d9c20d90d | ||
|
|
91d3f06f38 | ||
|
|
a5f5312476 | ||
|
|
36254e048e | ||
|
|
72f76b8bca |
7
.dockerignore
Normal file
7
.dockerignore
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
# .dockerignore
|
||||||
|
# node_modules
|
||||||
|
# npm-debug.log
|
||||||
|
# README.md
|
||||||
|
# .env*
|
||||||
|
# .next
|
||||||
|
# .git
|
||||||
25
.env.example
25
.env.example
@@ -4,9 +4,15 @@
|
|||||||
NEXT_PUBLIC_APP_URL=http://localhost:3000
|
NEXT_PUBLIC_APP_URL=http://localhost:3000
|
||||||
|
|
||||||
# -----------------------------------------------------------------------------
|
# -----------------------------------------------------------------------------
|
||||||
# Authentication (NextAuth.js)
|
# Database
|
||||||
# -----------------------------------------------------------------------------
|
# -----------------------------------------------------------------------------
|
||||||
AUTH_SECRET=
|
DATABASE_URL='postgres://[user]:[password]@[hostname]:5432/[dbname]'
|
||||||
|
|
||||||
|
# -----------------------------------------------------------------------------
|
||||||
|
# Authentication (NextAuth.js 5.0.x)
|
||||||
|
# -----------------------------------------------------------------------------
|
||||||
|
AUTH_SECRET=abc123
|
||||||
|
AUTH_URL=http://localhost:3000
|
||||||
|
|
||||||
GOOGLE_CLIENT_ID=
|
GOOGLE_CLIENT_ID=
|
||||||
GOOGLE_CLIENT_SECRET=
|
GOOGLE_CLIENT_SECRET=
|
||||||
@@ -16,17 +22,10 @@ LinuxDo_CLIENT_ID=
|
|||||||
LinuxDo_CLIENT_SECRET=
|
LinuxDo_CLIENT_SECRET=
|
||||||
|
|
||||||
# -----------------------------------------------------------------------------
|
# -----------------------------------------------------------------------------
|
||||||
# Database, example: DATABASE_URL='postgres://[user]:[password]@[hostname]:5432/[dbname]'
|
# Email api (https://resend.com) for Auth login (NextAuth) and send email
|
||||||
# -----------------------------------------------------------------------------
|
|
||||||
DATABASE_URL='postgres://[user]:[password]@[neon_hostname]/[dbname]?sslmode=require'
|
|
||||||
|
|
||||||
# -----------------------------------------------------------------------------
|
|
||||||
# Email api (https://resend.com) for login and send email
|
|
||||||
# -----------------------------------------------------------------------------
|
# -----------------------------------------------------------------------------
|
||||||
RESEND_API_KEY=
|
RESEND_API_KEY=
|
||||||
|
RESEND_FROM_EMAIL="wrdo <support@wr.do>"
|
||||||
# Open Signup
|
|
||||||
NEXT_PUBLIC_OPEN_SIGNUP=1
|
|
||||||
|
|
||||||
# Google Analytics
|
# Google Analytics
|
||||||
NEXT_PUBLIC_GOOGLE_ID=
|
NEXT_PUBLIC_GOOGLE_ID=
|
||||||
@@ -37,5 +36,7 @@ SCREENSHOTONE_BASE_URL=https://shot.wr.do
|
|||||||
# GitHub api token for getting gitHub stars count
|
# GitHub api token for getting gitHub stars count
|
||||||
GITHUB_TOKEN=
|
GITHUB_TOKEN=
|
||||||
|
|
||||||
|
# Skip DB check and migration. if false, will check and migrate database each time start docker compose.
|
||||||
|
SKIP_DB_CHECK=false
|
||||||
|
SKIP_DB_MIGRATION=false
|
||||||
|
|
||||||
|
|||||||
64
.github/workflows/docker-build-push.yml
vendored
Normal file
64
.github/workflows/docker-build-push.yml
vendored
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
name: Build and Push Docker Image to GHCR
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
|
tags:
|
||||||
|
- "v*.*.*"
|
||||||
|
pull_request:
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
|
|
||||||
|
env:
|
||||||
|
REGISTRY: ghcr.io
|
||||||
|
IMAGE_NAME: ${{ github.repository }}/wrdo
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build-and-push:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
packages: write
|
||||||
|
|
||||||
|
steps:
|
||||||
|
# 检出代码
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
# 设置 Docker Buildx(支持多平台构建)
|
||||||
|
- name: Set up Docker Buildx
|
||||||
|
uses: docker/setup-buildx-action@v3
|
||||||
|
|
||||||
|
# 登录到 GitHub Container Registry
|
||||||
|
- name: Log in to GitHub Container Registry
|
||||||
|
uses: docker/login-action@v3
|
||||||
|
with:
|
||||||
|
registry: ${{ env.REGISTRY }}
|
||||||
|
username: ${{ github.actor }}
|
||||||
|
password: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
# 提取 Docker 镜像元数据(标签、版本等)
|
||||||
|
- name: Extract Docker metadata
|
||||||
|
id: meta
|
||||||
|
uses: docker/metadata-action@v5
|
||||||
|
with:
|
||||||
|
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
||||||
|
tags: |
|
||||||
|
type=sha,format=short
|
||||||
|
type=ref,event=branch,prefix=
|
||||||
|
type=ref,event=tag
|
||||||
|
|
||||||
|
# 构建并推送 Docker 镜像
|
||||||
|
- name: Build and push Docker image
|
||||||
|
uses: docker/build-push-action@v6
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
file: ./Dockerfile
|
||||||
|
push: true # ${{ github.event_name != 'pull_request' }}
|
||||||
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
|
labels: ${{ steps.meta.outputs.labels }}
|
||||||
|
build-args: |
|
||||||
|
ENVIRONMENT=${{ github.event.inputs.environment || 'production' }}
|
||||||
|
cache-from: type=gha
|
||||||
|
cache-to: type=gha,mode=max
|
||||||
60
Dockerfile
Normal file
60
Dockerfile
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
FROM node:20-alpine AS base
|
||||||
|
|
||||||
|
FROM base AS deps
|
||||||
|
|
||||||
|
RUN apk add --no-cache openssl
|
||||||
|
RUN apk add --no-cache libc6-compat
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
RUN npm install -g pnpm
|
||||||
|
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
RUN pnpm config set registry https://registry.npmmirror.com
|
||||||
|
|
||||||
|
RUN pnpm i --frozen-lockfile
|
||||||
|
|
||||||
|
FROM base AS builder
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
RUN apk add --no-cache openssl
|
||||||
|
|
||||||
|
RUN npm install -g pnpm
|
||||||
|
|
||||||
|
COPY --from=deps /app/node_modules ./node_modules
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
RUN pnpm run build
|
||||||
|
|
||||||
|
FROM base AS runner
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
RUN apk add --no-cache openssl
|
||||||
|
|
||||||
|
RUN npm install -g pnpm
|
||||||
|
|
||||||
|
ENV NODE_ENV=production
|
||||||
|
ENV IS_DOCKER=true
|
||||||
|
|
||||||
|
RUN pnpm add npm-run-all dotenv prisma@5.17.0 @prisma/client@5.17.0
|
||||||
|
|
||||||
|
COPY --from=builder /app/public ./public
|
||||||
|
COPY --from=builder /app/prisma ./prisma
|
||||||
|
|
||||||
|
# Automatically leverage output traces to reduce image size
|
||||||
|
# https://nextjs.org/docs/advanced-features/output-file-tracing
|
||||||
|
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
|
||||||
|
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
|
||||||
|
|
||||||
|
# Check db
|
||||||
|
COPY scripts/check-db.js /app/scripts/check-db.js
|
||||||
|
|
||||||
|
EXPOSE 3000
|
||||||
|
|
||||||
|
ENV HOSTNAME=0.0.0.0
|
||||||
|
ENV PORT=3000
|
||||||
|
|
||||||
|
# CMD ["node", "server.js"]
|
||||||
|
CMD ["pnpm", "start-docker"]
|
||||||
100
README-zh.md
100
README-zh.md
@@ -1,47 +1,89 @@
|
|||||||
<div align="center">
|
<div align="center">
|
||||||
<h1>WR.DO</h1>
|
<h1>WR.DO</h1>
|
||||||
<p><a href="https://discord.gg/AHPQYuZu3m">Discord</a> · English | <a href="/README-zh.md">简体中文</a></p>
|
<p><a href="https://wr.do/docs/developer">开发文档</a> · <a href="https://discord.gg/AHPQYuZu3m">Discord</a> · English | <a href="/README-zh.md">简体中文</a></p>
|
||||||
<p>生成短链接, 创建 DNS 记录, 管理临时邮箱</p>
|
<p>生成短链接, 创建 DNS 记录, 管理临时邮箱</p>
|
||||||
<!-- <img src="https://wr.do/_static/images/light-preview.png"/> -->
|
<!-- <img src="https://wr.do/_static/images/light-preview.png"/> -->
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
## 功能
|
## 简介
|
||||||
|
|
||||||
- 🔗 **短链生成**:生成附有访问者统计信息的短链接 (支持密码保护, 支持调用 API)
|
WR.DO 是一个一站式网络工具平台,集成短链服务、临时邮箱、子域名管理和开放API接口。支持自定义链接、密码保护、访问统计;提供无限制临时邮箱收发;管理多域名DNS记录;内置网站截图、元数据提取等实用API。完整的管理后台,支持用户权限控制和服务配置。
|
||||||
- 📮 **临时邮箱**:创建多个临时邮箱接收和发送邮件(支持调用 API)
|
|
||||||
- 🌐 **多租户支持**:无缝管理多个 DNS 记录
|
|
||||||
- 📸 **截图 API**:访问截图 API、网站元数据抓取 API
|
|
||||||
- <20>😀 **权限管理**:方便审核的管理员面板
|
|
||||||
- 🔒 **安全可靠**:基于 Cloudflare 强大的 DNS API
|
|
||||||
|
|
||||||
## Screenshots
|
## 功能列表
|
||||||
|
|
||||||

|
- 🔗 **短链服务**:
|
||||||
|
- 支持自定义短链
|
||||||
|
- 支持生成自定义二维码
|
||||||
|
- 支持密码保护链接
|
||||||
|
- 支持设置过期时间
|
||||||
|
- 支持访问统计(实时日志、地图等多维度数据分析)
|
||||||
|
- 支持调用 API 创建短链
|
||||||
|
|
||||||

|
- 📮 **临时邮箱服务**:
|
||||||
|
- 支持创建自定义前缀邮箱
|
||||||
|
- 支持过滤未读邮件列表
|
||||||
|
- 可创建无限数量邮箱
|
||||||
|
- 支持接收无限制邮件 (依赖 Cloudflare Email Worker)
|
||||||
|
- 支持发送邮件(依赖 Resend)
|
||||||
|
- 支持调用 API 创建邮箱
|
||||||
|
- 支持调用 API 获取收件箱邮件
|
||||||
|
-
|
||||||
|
- 🌐 **子域名管理服务**:
|
||||||
|
- 支持管理多 Cloudflare 账户下的多个域名的 DNS 记录
|
||||||
|
- 支持创建多种 DNS 记录类型(CNAME、A、TXT 等)
|
||||||
|
|
||||||

|
- 📡 **开放接口模块**:
|
||||||
|
- 获取网站元数据 API
|
||||||
|
- 获取网站截图 API
|
||||||
|
- 生成网站二维码 API
|
||||||
|
- 将网站转换为 Markdown、Text
|
||||||
|
- 支持所有类型 API 调用统计日志
|
||||||
|
- 支持生成用户 API Key,用于第三方调用开放接口
|
||||||
|
|
||||||

|
- 🔒 **管理员模块**:
|
||||||
|
- 多维度图表展示网站状态
|
||||||
|
- 域名服务配置(动态配置各项服务是否启用,包括短链、临时邮箱(收发邮件)、子域名管理)
|
||||||
|
- 用户列表管理(设置权限、分配使用额度、禁用用户等)
|
||||||
|
- 短链管理(管理所有用户创建的短链)
|
||||||
|
- 邮箱管理(管理所有用户创建的临时邮箱)
|
||||||
|
- 子域名管理(管理所有用户创建的子域名)
|
||||||
|
|
||||||
|
## 截图预览
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr>
|
||||||
|
<td><img src="https://wr.do/_static/images/light-preview.png" /></td>
|
||||||
|
<td><img src="https://wr.do/_static/images/example_02.png" /></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td><img src="https://wr.do/_static/images/example_01.png" /></td>
|
||||||
|
<td><img src="https://wr.do/_static/images/realtime-globe.png" /></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td><img src="https://wr.do/_static/images/example_03.png" /></td>
|
||||||
|
<td><img src="https://wr.do/_static/images/domains.png" /></td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
## 快速开始
|
## 快速开始
|
||||||
|
|
||||||
查看开发者[快速开始](https://wr.do/docs/developer/quick-start)的详细文档。
|
查看开发者[快速开始](https://wr.do/docs/developer/quick-start)详细文档。
|
||||||
|
|
||||||
查看有关[快速开始](https://wr.do/docs/quick-start)的文档。
|
## 自部署教程
|
||||||
|
|
||||||
## 自托管教程
|
### 使用 Vercel 部署
|
||||||
|
|
||||||
### 要求
|
[](https://vercel.com/new/clone?repository-url=https://github.com/oiov/wr.do.git&project-name=wrdo&env=DATABASE_URL&env=AUTH_SECRET&env=RESEND_API_KEY&env=NEXT_PUBLIC_EMAIL_R2_DOMAIN&env=GITHUB_TOKEN)
|
||||||
|
|
||||||
- [Vercel](https://vercel.com) 账户用于部署应用
|
记得填写必要的环境变量。
|
||||||
- 至少一个在 [Cloudflare](https://dash.cloudflare.com/) 托管的 **域名**
|
|
||||||
|
|
||||||
查看[开发文档](https://wr.do/docs/developer/installation)。
|
### 使用 Docker Compose 部署
|
||||||
|
|
||||||
### Email worker
|
在服务器中创建一个文件夹,进入该文件夹并新建`docker-compose.yml`文件,填写必要的环境变量,然后执行:
|
||||||
|
|
||||||
查看 [email worker](https://wr.do/docs/developer/cloudflare-email-worker) 文档用于邮件接收。
|
```bash
|
||||||
|
docker compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
## 本地开发
|
## 本地开发
|
||||||
|
|
||||||
@@ -63,10 +105,22 @@ pnpm postinstall
|
|||||||
pnpm db:push
|
pnpm db:push
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 激活管理员面板
|
#### 管理员初始化
|
||||||
|
|
||||||
Follow https://localhost:3000/setup
|
Follow https://localhost:3000/setup
|
||||||
|
|
||||||
|
## 环境变量
|
||||||
|
|
||||||
|
查看 [开发者文档](https://wr.do/docs/developer).
|
||||||
|
|
||||||
|
## 技术栈
|
||||||
|
|
||||||
|
- Next.js + React + TypeScript
|
||||||
|
- Tailwind CSS 用于样式设计
|
||||||
|
- Prisma ORM 作为数据库工具
|
||||||
|
- Cloudflare 作为主要的云基础设施
|
||||||
|
- Vercel 作为推荐的部署平台
|
||||||
|
|
||||||
## 社区群组
|
## 社区群组
|
||||||
|
|
||||||
- Discord: https://discord.gg/AHPQYuZu3m
|
- Discord: https://discord.gg/AHPQYuZu3m
|
||||||
|
|||||||
126
README.md
126
README.md
@@ -1,58 +1,109 @@
|
|||||||
<div align="center">
|
<div align="center">
|
||||||
<h1>WR.DO</h1>
|
<h1>WR.DO</h1>
|
||||||
<p><a href="https://discord.gg/AHPQYuZu3m">Discord</a> · English | <a href="/README-zh.md">简体中文</a></p>
|
<p><a href="https://wr.do/docs/developer">Docs</a> · <a href="https://discord.gg/AHPQYuZu3m">Discord</a> · English | <a href="/README-zh.md">简体中文</a></p>
|
||||||
<p>Make Short Links, Manage DNS Records, Email Support.</p>
|
<p>Make Short Links, Manage DNS Records, Receive Emails.</p>
|
||||||
<!-- <img src="https://wr.do/_static/images/light-preview.png"/> -->
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
## Introduction
|
||||||
|
|
||||||
|
WR.DO is a all-in-one web utility platform featuring short links with analytics, temporary email service, subdomain management, open APIs for screenshots and metadata extraction, plus comprehensive admin dashboard.
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- 🔗 **URL Shortening:** Generate short links with visitor analytic and password(support api)
|
- 🔗 **Short Link Service**:
|
||||||
- 📮 **Email Support:** Receive emails and send emails(support api)
|
- Custom short links
|
||||||
- 💬 **P2P Chat:** Start chat in seconds
|
- Generate custom QR codes
|
||||||
- 🌐 **Multi-Tenant Support:** Manage multiple DNS records seamlessly
|
- Password-protected links
|
||||||
- 📸 **Screenshot API:** Access to screenshot api、website meta-info scraping api.
|
- Expiration time control
|
||||||
- 😀 **Permission Management:** A convenient admin panel for auditing
|
- Access analytics (real-time logs, maps, and multi-dimensional data analysis)
|
||||||
- 🔒 **Secure & Reliable:** Built on Cloudflare's robust DNS API
|
- API integration for link creation
|
||||||
|
|
||||||
|
- 📮 **Email Service**:
|
||||||
|
- Create custom prefix emails
|
||||||
|
- Filter unread email lists
|
||||||
|
- Unlimited mailbox creation
|
||||||
|
- Receive unlimited emails (powered by Cloudflare Email Worker)
|
||||||
|
- Send emails (powered by Resend)
|
||||||
|
- API endpoints for mailbox creation
|
||||||
|
- API endpoints for inbox retrieval
|
||||||
|
|
||||||
|
- 🌐 **Subdomain Management Service**:
|
||||||
|
- Manage DNS records across multiple Cloudflare accounts and domains
|
||||||
|
- Create various DNS record types (CNAME, A, TXT, etc.)
|
||||||
|
|
||||||
|
- 📡 **Open API Module**:
|
||||||
|
- Website metadata extraction API
|
||||||
|
- Website screenshot capture API
|
||||||
|
- Website QR code generation API
|
||||||
|
- Convert websites to Markdown/Text format
|
||||||
|
- Comprehensive API call logging and statistics
|
||||||
|
- User API key generation for third-party integrations
|
||||||
|
|
||||||
|
- 🔒 **Administrator Module**:
|
||||||
|
- Multi-dimensional dashboard with website analytics
|
||||||
|
- Dynamic service configuration (toggle short links, email, subdomain management)
|
||||||
|
- User management (permissions, quotas, account control)
|
||||||
|
- Centralized short link administration
|
||||||
|
- Centralized email management
|
||||||
|
- Centralized subdomain administration
|
||||||
|
|
||||||
## Screenshots
|
## Screenshots
|
||||||
|
|
||||||

|
<table>
|
||||||
|
<tr>
|
||||||
|
<td><img src="https://wr.do/_static/images/light-preview.png" /></td>
|
||||||
|
<td><img src="https://wr.do/_static/images/example_02.png" /></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td><img src="https://wr.do/_static/images/example_01.png" /></td>
|
||||||
|
<td><img src="https://wr.do/_static/images/realtime-globe.png" /></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td><img src="https://wr.do/_static/images/example_03.png" /></td>
|
||||||
|
<td><img src="https://wr.do/_static/images/domains.png" /></td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
## Quick Start
|
## Quick Start
|
||||||
|
|
||||||
See usage docs about [guide](https://wr.do/docs/quick-start) for quick start.
|
|
||||||
|
|
||||||
## Self-hosted Tutorial
|
|
||||||
|
|
||||||
See step by step installation tutorial at [Quick Start for Developer](https://wr.do/docs/developer/quick-start).
|
See step by step installation tutorial at [Quick Start for Developer](https://wr.do/docs/developer/quick-start).
|
||||||
|
|
||||||
### Requirements
|
## Self-hosted
|
||||||
|
|
||||||
- [Vercel](https://vercel.com) to deploy app
|
### Deploy with Vercel
|
||||||
- A **domain** name hosted on [Cloudflare](https://dash.cloudflare.com/)
|
|
||||||
|
|
||||||
See more docs about [developer](https://wr.do/docs/developer/installation).
|
[](https://vercel.com/new/clone?repository-url=https://github.com/oiov/wr.do.git&project-name=wrdo&env=DATABASE_URL&env=AUTH_SECRET&env=RESEND_API_KEY&env=NEXT_PUBLIC_EMAIL_R2_DOMAIN&env=GITHUB_TOKEN)
|
||||||
|
|
||||||
### Email worker
|
Remember to fill in the necessary environment variables.
|
||||||
|
|
||||||
See docs about [email worker](https://wr.do/docs/developer/cloudflare-email-worker).
|
### Deploy with Docker Compose
|
||||||
|
|
||||||
|
Create a new folder and copy the [`docker-compose.yml`](https://github.com/oiov/wr.do/blob/main/docker-compose.yml)、[`.env`](https://github.com/oiov/wr.do/blob/main/.env.example) file to the folder.
|
||||||
|
|
||||||
|
```yml
|
||||||
|
- wrdo
|
||||||
|
| - docker-compose.yml
|
||||||
|
| - .env
|
||||||
|
```
|
||||||
|
|
||||||
|
Fill in the environment variables in the `.env` file, then:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
## Local development
|
## Local development
|
||||||
|
|
||||||
copy `.env.example` to `.env` and fill in the necessary environment variables.
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone https://github.com/oiov/wr.do
|
git clone https://github.com/oiov/wr.do
|
||||||
cd wr.do
|
cd wr.do
|
||||||
pnpm install
|
pnpm install
|
||||||
|
```
|
||||||
|
|
||||||
|
copy `.env.example` to `.env` and fill in the necessary environment variables.
|
||||||
|
|
||||||
|
```bash
|
||||||
# run on localhost:3000
|
# run on localhost:3000
|
||||||
pnpm dev
|
pnpm dev
|
||||||
```
|
```
|
||||||
@@ -68,21 +119,24 @@ pnpm db:push
|
|||||||
|
|
||||||
Follow https://localhost:3000/setup
|
Follow https://localhost:3000/setup
|
||||||
|
|
||||||
## Legitimacy review
|
## Environment Variables
|
||||||
|
|
||||||
- To avoid abuse, applications without website content will be rejected
|
Via [Installation For Developer](https://wr.do/docs/developer).
|
||||||
- To avoid domain name conflicts, please check before applying
|
|
||||||
- Completed website construction or released open source project (ready to build website for open source project)
|
|
||||||
- Political sensitivity, violence, pornography, link jumping, VPN, reverse proxy services, and other illegal or sensitive content must not appear on the website
|
|
||||||
|
|
||||||
**Administrators will conduct domain name checks periodically to clean up domain names that violate the above rules, have no content, and are not open source related**
|
## Technology Stack
|
||||||
|
|
||||||
|
- Next.js + React + TypeScript
|
||||||
|
- Tailwind CSS for styling and design
|
||||||
|
- Prisma ORM as the database toolkit
|
||||||
|
- Cloudflare as the primary cloud infrastructure
|
||||||
|
- Vercel as the recommended deployment platform
|
||||||
|
|
||||||
## Community Group
|
## Community Group
|
||||||
|
|
||||||
- Discord: https://discord.gg/AHPQYuZu3m
|
- Discord: https://discord.gg/AHPQYuZu3m
|
||||||
- 微信群:
|
- 微信群:
|
||||||
|
|
||||||

|
<img width="300" src="https://wr.do/s/group" />
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
@@ -97,3 +151,5 @@ Follow https://localhost:3000/setup
|
|||||||
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=oiov/wr.do&type=Date" />
|
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=oiov/wr.do&type=Date" />
|
||||||
</picture>
|
</picture>
|
||||||
</a>
|
</a>
|
||||||
|
|
||||||
|
[](https://dartnode.com "Powered by DartNode - Free VPS for Open Source")
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { Suspense } from "react";
|
import { Suspense } from "react";
|
||||||
import { Metadata } from "next";
|
import { Metadata } from "next";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
|
|
||||||
import { siteConfig } from "@/config/site";
|
import { siteConfig } from "@/config/site";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
@@ -14,6 +15,7 @@ export const metadata: Metadata = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export default function LoginPage() {
|
export default function LoginPage() {
|
||||||
|
const t = useTranslations("Auth");
|
||||||
return (
|
return (
|
||||||
<div className="container flex h-screen w-screen flex-col items-center justify-center">
|
<div className="container flex h-screen w-screen flex-col items-center justify-center">
|
||||||
<Link
|
<Link
|
||||||
@@ -25,44 +27,44 @@ export default function LoginPage() {
|
|||||||
>
|
>
|
||||||
<>
|
<>
|
||||||
<Icons.chevronLeft className="mr-2 size-4" />
|
<Icons.chevronLeft className="mr-2 size-4" />
|
||||||
Back
|
{t("Back")}
|
||||||
</>
|
</>
|
||||||
</Link>
|
</Link>
|
||||||
<div className="mx-auto flex w-full flex-col justify-center space-y-6 sm:w-[350px]">
|
<div className="mx-auto flex w-full flex-col justify-center space-y-6 sm:w-[350px]">
|
||||||
<div className="flex flex-col space-y-2 text-center">
|
<div className="flex flex-col space-y-2 text-center">
|
||||||
<Icons.logo className="mx-auto size-12" />
|
<Icons.logo className="mx-auto size-12" />
|
||||||
<div className="text-2xl font-semibold tracking-tight">
|
<div className="text-2xl font-semibold tracking-tight">
|
||||||
<span>Welcome to</span>{" "}
|
<span>{t("Welcome to")}</span>{" "}
|
||||||
<span style={{ fontFamily: "Bahamas Bold" }}>
|
<span style={{ fontFamily: "Bahamas Bold" }}>
|
||||||
{siteConfig.name}
|
{siteConfig.name}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<p className="text-sm text-muted-foreground">
|
<p className="text-sm text-muted-foreground">
|
||||||
Choose your login method to continue
|
{t("Choose your login method to continue")}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<Suspense>
|
<Suspense>
|
||||||
<UserAuthForm />
|
<UserAuthForm />
|
||||||
</Suspense>
|
</Suspense>
|
||||||
<p className="mt-4 break-all rounded-md border border-dashed bg-neutral-50 p-2 text-left text-sm text-gray-600 dark:border-neutral-600 dark:bg-neutral-800 dark:text-zinc-400">
|
{/* <p className="mt-4 break-all rounded-md border border-dashed bg-neutral-50 p-2 text-left text-sm text-gray-600 dark:border-neutral-600 dark:bg-neutral-800 dark:text-zinc-400">
|
||||||
📢 To keep our free resources accessible to all, we're allowing only
|
📢 To keep our free resources accessible to all, we're allowing only
|
||||||
200 new account sign-ups each day.
|
200 new account sign-ups each day.
|
||||||
</p>
|
</p> */}
|
||||||
|
|
||||||
<p className="px-8 text-center text-sm text-muted-foreground">
|
<p className="px-8 text-center text-sm text-muted-foreground">
|
||||||
By clicking continue, you agree to our{" "}
|
{t("By clicking continue, you agree to our")}{" "}
|
||||||
<Link
|
<Link
|
||||||
href="/terms"
|
href="/terms"
|
||||||
className="hover:text-brand underline underline-offset-4"
|
className="hover:text-brand underline underline-offset-4"
|
||||||
>
|
>
|
||||||
Terms of Service
|
{t("Terms of Service")}
|
||||||
</Link>{" "}
|
</Link>{" "}
|
||||||
and{" "}
|
{t("and")}{" "}
|
||||||
<Link
|
<Link
|
||||||
href="/privacy"
|
href="/privacy"
|
||||||
className="hover:text-brand underline underline-offset-4"
|
className="hover:text-brand underline underline-offset-4"
|
||||||
>
|
>
|
||||||
Privacy Policy
|
{t("Privacy Policy")}
|
||||||
</Link>
|
</Link>
|
||||||
.
|
.
|
||||||
</p>
|
</p>
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { NavMobile } from "@/components/layout/mobile-nav";
|
import { NavMobile } from "@/components/layout/mobile-nav";
|
||||||
import { NavBar } from "@/components/layout/navbar";
|
import { NavBar } from "@/components/layout/navbar";
|
||||||
|
import { Notification } from "@/components/layout/notification";
|
||||||
import { SiteFooter } from "@/components/layout/site-footer";
|
import { SiteFooter } from "@/components/layout/site-footer";
|
||||||
|
|
||||||
interface MarketingLayoutProps {
|
interface MarketingLayoutProps {
|
||||||
@@ -11,6 +12,7 @@ export default function MarketingLayout({ children }: MarketingLayoutProps) {
|
|||||||
<div className="flex min-h-screen flex-col dark:bg-black">
|
<div className="flex min-h-screen flex-col dark:bg-black">
|
||||||
<NavMobile />
|
<NavMobile />
|
||||||
<NavBar scroll={true} />
|
<NavBar scroll={true} />
|
||||||
|
<Notification />
|
||||||
<main className="flex-1 bg-[radial-gradient(circle_500px_at_50%_300px,#a1fffc36,#ffffff)] dark:bg-[radial-gradient(circle_500px_at_50%_300px,#a1fffc36,#000)]">
|
<main className="flex-1 bg-[radial-gradient(circle_500px_at_50%_300px,#a1fffc36,#ffffff)] dark:bg-[radial-gradient(circle_500px_at_50%_300px,#a1fffc36,#000)]">
|
||||||
{children}
|
{children}
|
||||||
</main>
|
</main>
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
|
import { getCurrentUser } from "@/lib/session";
|
||||||
import HeroLanding, { LandingImages } from "@/components/sections/hero-landing";
|
import HeroLanding, { LandingImages } from "@/components/sections/hero-landing";
|
||||||
import { PricingSection } from "@/components/sections/pricing";
|
import { PricingSection } from "@/components/sections/pricing";
|
||||||
|
|
||||||
export default function IndexPage() {
|
export default async function IndexPage() {
|
||||||
|
const user = await getCurrentUser();
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<HeroLanding />
|
<HeroLanding userId={user?.id} />
|
||||||
<LandingImages />
|
<LandingImages />
|
||||||
<PricingSection />
|
<PricingSection />
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { TrendingUp } from "lucide-react";
|
import { TrendingUp } from "lucide-react";
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
import {
|
import {
|
||||||
Label,
|
Label,
|
||||||
PolarGrid,
|
PolarGrid,
|
||||||
@@ -29,6 +30,7 @@ export function RadialShapeChart({
|
|||||||
total: number;
|
total: number;
|
||||||
totalUser: number;
|
totalUser: number;
|
||||||
}) {
|
}) {
|
||||||
|
const t = useTranslations("Components");
|
||||||
const chartData = [
|
const chartData = [
|
||||||
{ browser: "safari", actived: total, fill: "var(--color-safari)" },
|
{ browser: "safari", actived: total, fill: "var(--color-safari)" },
|
||||||
];
|
];
|
||||||
@@ -94,7 +96,7 @@ export function RadialShapeChart({
|
|||||||
<TrendingUp className="size-4" />
|
<TrendingUp className="size-4" />
|
||||||
</div>
|
</div>
|
||||||
<div className="leading-none text-muted-foreground">
|
<div className="leading-none text-muted-foreground">
|
||||||
Cumulative proportion of activated <strong>Api Key</strong> users
|
{t("Activated Api Key users")}
|
||||||
</div>
|
</div>
|
||||||
</CardFooter>
|
</CardFooter>
|
||||||
</Card>
|
</Card>
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { ScrapeMeta } from "@prisma/client";
|
import { ScrapeMeta } from "@prisma/client";
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
import { Area, AreaChart, CartesianGrid, XAxis, YAxis } from "recharts";
|
import { Area, AreaChart, CartesianGrid, XAxis, YAxis } from "recharts";
|
||||||
|
|
||||||
|
import { useElementSize } from "@/hooks/use-element-size";
|
||||||
import {
|
import {
|
||||||
Card,
|
Card,
|
||||||
CardContent,
|
CardContent,
|
||||||
@@ -54,8 +56,11 @@ export function LineChartMultiple({
|
|||||||
type1,
|
type1,
|
||||||
type2,
|
type2,
|
||||||
}: LineChartMultipleProps) {
|
}: LineChartMultipleProps) {
|
||||||
|
const { ref: wrapperRef, width: wrapperWidth } = useElementSize();
|
||||||
const processedData = processChartData(chartData, type1, type2);
|
const processedData = processChartData(chartData, type1, type2);
|
||||||
|
|
||||||
|
const t = useTranslations("Components");
|
||||||
|
|
||||||
const chartConfig = {
|
const chartConfig = {
|
||||||
source1: {
|
source1: {
|
||||||
label: type1,
|
label: type1,
|
||||||
@@ -67,20 +72,22 @@ export function LineChartMultiple({
|
|||||||
},
|
},
|
||||||
} satisfies ChartConfig;
|
} satisfies ChartConfig;
|
||||||
|
|
||||||
|
const message = type2
|
||||||
|
? t("total-requests-two-types", { type1, type2 })
|
||||||
|
: t("total-requests-one-type", { type1 });
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardDescription>
|
<CardDescription>{message}</CardDescription>
|
||||||
Total requests of {type1}
|
|
||||||
{type2 && ` and ${type2}`}.
|
|
||||||
</CardDescription>
|
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent ref={wrapperRef}>
|
||||||
<ChartContainer config={chartConfig}>
|
<ChartContainer config={chartConfig}>
|
||||||
<AreaChart
|
<AreaChart
|
||||||
className="mt-6"
|
className="mt-6"
|
||||||
accessibilityLayer
|
accessibilityLayer
|
||||||
data={processedData}
|
data={processedData}
|
||||||
|
width={wrapperWidth}
|
||||||
margin={{
|
margin={{
|
||||||
left: 12,
|
left: 12,
|
||||||
right: 12,
|
right: 12,
|
||||||
|
|||||||
@@ -4,10 +4,7 @@ import { DashboardHeader } from "@/components/dashboard/header";
|
|||||||
export default function AdminPanelLoading() {
|
export default function AdminPanelLoading() {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<DashboardHeader
|
<DashboardHeader heading="Admin Panel" text="" />
|
||||||
heading="Admin Panel"
|
|
||||||
text="Access only for users with ADMIN role."
|
|
||||||
/>
|
|
||||||
<div className="flex flex-col gap-5">
|
<div className="flex flex-col gap-5">
|
||||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3 lg:grid-cols-3">
|
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3 lg:grid-cols-3">
|
||||||
<Skeleton className="h-32 w-full rounded-lg" />
|
<Skeleton className="h-32 w-full rounded-lg" />
|
||||||
|
|||||||
@@ -134,7 +134,6 @@ async function RequestStatsSection() {
|
|||||||
|
|
||||||
return hasStats ? (
|
return hasStats ? (
|
||||||
<>
|
<>
|
||||||
<h2 className="my-1 text-xl font-semibold">Request Statistics</h2>
|
|
||||||
<DailyPVUVChart
|
<DailyPVUVChart
|
||||||
data={screenshot_stats
|
data={screenshot_stats
|
||||||
.concat(meta_stats)
|
.concat(meta_stats)
|
||||||
@@ -200,7 +199,6 @@ async function MarkdownTextChartSection() {
|
|||||||
async function LogsSection({ userId }: { userId: string }) {
|
async function LogsSection({ userId }: { userId: string }) {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<h2 className="my-1 text-xl font-semibold">Request Logs</h2>
|
|
||||||
<LogsTable userId={userId} target={"/api/v1/scraping/admin/logs"} />
|
<LogsTable userId={userId} target={"/api/v1/scraping/admin/logs"} />
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
@@ -213,10 +211,7 @@ export default async function AdminPage() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<DashboardHeader
|
<DashboardHeader heading="Admin Panel" text="" />
|
||||||
heading="Admin Panel"
|
|
||||||
text="Access only for users with ADMIN role."
|
|
||||||
/>
|
|
||||||
<div className="flex flex-col gap-5">
|
<div className="flex flex-col gap-5">
|
||||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3 xl:grid-cols-3">
|
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3 xl:grid-cols-3">
|
||||||
<ErrorBoundary
|
<ErrorBoundary
|
||||||
|
|||||||
@@ -4,7 +4,10 @@ import { DashboardHeader } from "@/components/dashboard/header";
|
|||||||
export default function DashboardRecordsLoading() {
|
export default function DashboardRecordsLoading() {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<DashboardHeader heading="DNS Records" text="" />
|
<DashboardHeader
|
||||||
|
heading="Manage DNS Records"
|
||||||
|
text="List and manage records"
|
||||||
|
/>
|
||||||
<Skeleton className="h-32 w-full rounded-lg" />
|
<Skeleton className="h-32 w-full rounded-lg" />
|
||||||
<Skeleton className="h-[400px] w-full rounded-lg" />
|
<Skeleton className="h-[400px] w-full rounded-lg" />
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import { DashboardHeader } from "@/components/dashboard/header";
|
|||||||
import UserRecordsList from "../../dashboard/records/record-list";
|
import UserRecordsList from "../../dashboard/records/record-list";
|
||||||
|
|
||||||
export const metadata = constructMetadata({
|
export const metadata = constructMetadata({
|
||||||
title: "DNS Records - WR.DO",
|
title: "DNS Records",
|
||||||
description: "List and manage records.",
|
description: "List and manage records.",
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -19,10 +19,10 @@ export default async function DashboardPage() {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<DashboardHeader
|
<DashboardHeader
|
||||||
heading="Manage DNS Records"
|
heading="Manage DNS Records"
|
||||||
text="List and manage records."
|
text="List and manage records"
|
||||||
link="/docs/dns-records"
|
link="/docs/dns-records"
|
||||||
linkText="DNS records."
|
linkText="DNS records"
|
||||||
/>
|
/>
|
||||||
<UserRecordsList
|
<UserRecordsList
|
||||||
user={{
|
user={{
|
||||||
@@ -30,6 +30,7 @@ export default async function DashboardPage() {
|
|||||||
name: user.name || "",
|
name: user.name || "",
|
||||||
apiKey: user.apiKey || "",
|
apiKey: user.apiKey || "",
|
||||||
email: user.email || "",
|
email: user.email || "",
|
||||||
|
role: user.role,
|
||||||
}}
|
}}
|
||||||
action="/api/record/admin"
|
action="/api/record/admin"
|
||||||
/>
|
/>
|
||||||
|
|||||||
141
app/(protected)/admin/system/app-configs.tsx
Normal file
141
app/(protected)/admin/system/app-configs.tsx
Normal file
@@ -0,0 +1,141 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useState, useTransition } from "react";
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import useSWR from "swr";
|
||||||
|
|
||||||
|
import { fetcher } from "@/lib/utils";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
|
import { Switch } from "@/components/ui/switch";
|
||||||
|
import { Textarea } from "@/components/ui/textarea";
|
||||||
|
import { Icons } from "@/components/shared/icons";
|
||||||
|
import { SkeletonSection } from "@/components/shared/section-skeleton";
|
||||||
|
|
||||||
|
export default function AppConfigs({}: {}) {
|
||||||
|
const [isPending, startTransition] = useTransition();
|
||||||
|
|
||||||
|
const { data: configs, isLoading } = useSWR<Record<string, any>>(
|
||||||
|
"/api/admin/configs",
|
||||||
|
fetcher,
|
||||||
|
);
|
||||||
|
const [notification, setNotification] = useState("");
|
||||||
|
|
||||||
|
const t = useTranslations("Setting");
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isLoading && configs?.system_notification) {
|
||||||
|
setNotification(configs.system_notification);
|
||||||
|
}
|
||||||
|
}, [configs, isLoading]);
|
||||||
|
|
||||||
|
const handleChange = (value: any, key: string, type: string) => {
|
||||||
|
startTransition(async () => {
|
||||||
|
const res = await fetch("/api/admin/configs", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({ key, value, type }),
|
||||||
|
});
|
||||||
|
if (res.ok) {
|
||||||
|
toast.success("Updated!");
|
||||||
|
} else {
|
||||||
|
toast.error("Failed!", {
|
||||||
|
description: await res.text(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
if (isLoading) {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<SkeletonSection />
|
||||||
|
<SkeletonSection />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card className="bg-neutral-50 dark:bg-neutral-900">
|
||||||
|
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||||
|
<CardTitle className="text-lg font-bold">{t("App Configs")}</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<div className="mt-3 space-y-6 border-t pt-6">
|
||||||
|
<div className="flex items-center justify-between space-x-2">
|
||||||
|
<div className="space-y-1 leading-none">
|
||||||
|
<p className="font-medium">{t("User Registration")}</p>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
{t("Allow users to sign up")}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{configs && (
|
||||||
|
<Switch
|
||||||
|
defaultChecked={configs.enable_user_registration}
|
||||||
|
onCheckedChange={(v) =>
|
||||||
|
handleChange(v, "enable_user_registration", "BOOLEAN")
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center justify-between space-x-2">
|
||||||
|
<div className="space-y-1 leading-none">
|
||||||
|
<p className="font-medium">{t("Subdomain Apply Mode")}</p>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
{t(
|
||||||
|
"Enable subdomain apply mode, each submission requires administrator review",
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{configs && (
|
||||||
|
<Switch
|
||||||
|
defaultChecked={configs.enable_subdomain_apply}
|
||||||
|
onCheckedChange={(v) =>
|
||||||
|
handleChange(v, "enable_subdomain_apply", "BOOLEAN")
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col items-start justify-start gap-3">
|
||||||
|
<div className="space-y-1 leading-none">
|
||||||
|
<p className="font-medium">{t("Notification")}</p>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
{t(
|
||||||
|
"Set system notification, this will be displayed in the header",
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{configs && (
|
||||||
|
<div className="flex w-full items-start gap-2">
|
||||||
|
<Textarea
|
||||||
|
className="h-16 max-h-32 min-h-9 resize-y"
|
||||||
|
placeholder="Support HTML format, such as <div>info</div>"
|
||||||
|
rows={5}
|
||||||
|
defaultValue={configs.system_notification}
|
||||||
|
value={notification}
|
||||||
|
onChange={(e) => setNotification(e.target.value)}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
className="h-9 text-nowrap"
|
||||||
|
disabled={
|
||||||
|
isPending || notification === configs.system_notification
|
||||||
|
}
|
||||||
|
onClick={() =>
|
||||||
|
handleChange(notification, "system_notification", "STRING")
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{isPending && (
|
||||||
|
<Icons.spinner className="mr-1 size-4 animate-spin" />
|
||||||
|
)}
|
||||||
|
{t("Save")}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -4,18 +4,16 @@ import { useState } from "react";
|
|||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { User } from "@prisma/client";
|
import { User } from "@prisma/client";
|
||||||
import { PenLine, RefreshCwIcon } from "lucide-react";
|
import { PenLine, RefreshCwIcon } from "lucide-react";
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import useSWR, { useSWRConfig } from "swr";
|
import useSWR, { useSWRConfig } from "swr";
|
||||||
|
|
||||||
import { DomainFormData } from "@/lib/dto/domains";
|
import { DomainFormData } from "@/lib/dto/domains";
|
||||||
import { fetcher, timeAgo } from "@/lib/utils";
|
import { fetcher } from "@/lib/utils";
|
||||||
|
import { useMediaQuery } from "@/hooks/use-media-query";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import {
|
import { Card, CardContent, CardHeader } from "@/components/ui/card";
|
||||||
Card,
|
import { Input } from "@/components/ui/input";
|
||||||
CardContent,
|
|
||||||
CardDescription,
|
|
||||||
CardHeader,
|
|
||||||
} from "@/components/ui/card";
|
|
||||||
import { Modal } from "@/components/ui/modal";
|
import { Modal } from "@/components/ui/modal";
|
||||||
import { Skeleton } from "@/components/ui/skeleton";
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
import { Switch } from "@/components/ui/switch";
|
import { Switch } from "@/components/ui/switch";
|
||||||
@@ -32,6 +30,7 @@ import { FormType } from "@/components/forms/record-form";
|
|||||||
import { EmptyPlaceholder } from "@/components/shared/empty-placeholder";
|
import { EmptyPlaceholder } from "@/components/shared/empty-placeholder";
|
||||||
import { Icons } from "@/components/shared/icons";
|
import { Icons } from "@/components/shared/icons";
|
||||||
import { PaginationWrapper } from "@/components/shared/pagination";
|
import { PaginationWrapper } from "@/components/shared/pagination";
|
||||||
|
import { TimeAgoIntl } from "@/components/shared/time-ago";
|
||||||
|
|
||||||
export interface DomainListProps {
|
export interface DomainListProps {
|
||||||
user: Pick<User, "id" | "name" | "email" | "apiKey" | "role" | "team">;
|
user: Pick<User, "id" | "name" | "email" | "apiKey" | "role" | "team">;
|
||||||
@@ -40,25 +39,25 @@ export interface DomainListProps {
|
|||||||
|
|
||||||
function TableColumnSekleton() {
|
function TableColumnSekleton() {
|
||||||
return (
|
return (
|
||||||
<TableRow className="grid grid-cols-7 items-center">
|
<TableRow className="grid grid-cols-4 items-center sm:grid-cols-7">
|
||||||
<TableCell className="col-span-1 flex">
|
<TableCell className="col-span-1 flex">
|
||||||
<Skeleton className="h-5 w-20" />
|
<Skeleton className="h-5 w-20" />
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell className="col-span-1 flex">
|
<TableCell className="col-span-1 hidden sm:flex">
|
||||||
<Skeleton className="h-5 w-16" />
|
|
||||||
</TableCell>
|
|
||||||
<TableCell className="col-span-1 flex">
|
|
||||||
<Skeleton className="h-5 w-16" />
|
|
||||||
</TableCell>
|
|
||||||
<TableCell className="col-span-1 flex">
|
|
||||||
<Skeleton className="h-5 w-16" />
|
|
||||||
</TableCell>
|
|
||||||
<TableCell className="col-span-1 flex">
|
|
||||||
<Skeleton className="h-5 w-16" />
|
<Skeleton className="h-5 w-16" />
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell className="col-span-1 hidden sm:flex">
|
<TableCell className="col-span-1 hidden sm:flex">
|
||||||
<Skeleton className="h-5 w-16" />
|
<Skeleton className="h-5 w-16" />
|
||||||
</TableCell>
|
</TableCell>
|
||||||
|
<TableCell className="col-span-1 hidden sm:flex">
|
||||||
|
<Skeleton className="h-5 w-16" />
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="col-span-1 flex">
|
||||||
|
<Skeleton className="h-5 w-16" />
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="col-span-1 flex">
|
||||||
|
<Skeleton className="h-5 w-16" />
|
||||||
|
</TableCell>
|
||||||
<TableCell className="col-span-1 flex">
|
<TableCell className="col-span-1 flex">
|
||||||
<Skeleton className="h-5 w-32" />
|
<Skeleton className="h-5 w-32" />
|
||||||
</TableCell>
|
</TableCell>
|
||||||
@@ -67,16 +66,14 @@ function TableColumnSekleton() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function DomainList({ user, action }: DomainListProps) {
|
export default function DomainList({ user, action }: DomainListProps) {
|
||||||
|
const { isMobile } = useMediaQuery();
|
||||||
|
const t = useTranslations("List");
|
||||||
const [isShowForm, setShowForm] = useState(false);
|
const [isShowForm, setShowForm] = useState(false);
|
||||||
const [formType, setFormType] = useState<FormType>("add");
|
const [formType, setFormType] = useState<FormType>("add");
|
||||||
const [currentEditDomain, setCurrentEditDomain] =
|
const [currentEditDomain, setCurrentEditDomain] =
|
||||||
useState<DomainFormData | null>(null);
|
useState<DomainFormData | null>(null);
|
||||||
const [currentPage, setCurrentPage] = useState(1);
|
const [currentPage, setCurrentPage] = useState(1);
|
||||||
const [pageSize, setPageSize] = useState(10);
|
const [pageSize, setPageSize] = useState(10);
|
||||||
// const [isShowDomainInfo, setShowDomainInfo] = useState(false);
|
|
||||||
// const [selectedDomain, setSelectedDomain] = useState<DomainFormData | null>(
|
|
||||||
// null,
|
|
||||||
// );
|
|
||||||
const [searchParams, setSearchParams] = useState({
|
const [searchParams, setSearchParams] = useState({
|
||||||
slug: "",
|
slug: "",
|
||||||
target: "",
|
target: "",
|
||||||
@@ -88,13 +85,13 @@ export default function DomainList({ user, action }: DomainListProps) {
|
|||||||
total: number;
|
total: number;
|
||||||
list: DomainFormData[];
|
list: DomainFormData[];
|
||||||
}>(
|
}>(
|
||||||
`${action}?page=${currentPage}&size=${pageSize}&slug=${searchParams.slug}&userName=${searchParams.userName}&target=${searchParams.target}`,
|
`${action}?page=${currentPage}&size=${pageSize}&target=${searchParams.target}`,
|
||||||
fetcher,
|
fetcher,
|
||||||
);
|
);
|
||||||
|
|
||||||
const handleRefresh = () => {
|
const handleRefresh = () => {
|
||||||
mutate(
|
mutate(
|
||||||
`${action}?page=${currentPage}&size=${pageSize}&slug=${searchParams.slug}&userName=${searchParams.userName}&target=${searchParams.target}`,
|
`${action}?page=${currentPage}&size=${pageSize}&target=${searchParams.target}`,
|
||||||
undefined,
|
undefined,
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
@@ -119,6 +116,7 @@ export default function DomainList({ user, action }: DomainListProps) {
|
|||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
if (data) {
|
if (data) {
|
||||||
toast.success("Successed!");
|
toast.success("Successed!");
|
||||||
|
handleRefresh();
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
toast.error("Activation failed!");
|
toast.error("Activation failed!");
|
||||||
@@ -128,11 +126,15 @@ export default function DomainList({ user, action }: DomainListProps) {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Card className="xl:col-span-2">
|
<Card className="xl:col-span-2">
|
||||||
<CardHeader className="flex flex-row items-center">
|
<CardHeader className="flex flex-row items-center gap-2">
|
||||||
<CardDescription className="text-balance text-lg font-bold">
|
<div className="flex items-center gap-1 text-lg font-bold">
|
||||||
<span>Total Domains:</span>{" "}
|
<span className="text-nowrap">{t("Total Domains")}:</span>
|
||||||
<span className="font-bold">{data && data.total}</span>
|
{isLoading ? (
|
||||||
</CardDescription>
|
<Skeleton className="h-6 w-16" />
|
||||||
|
) : (
|
||||||
|
<span>{data && data.total}</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="ml-auto flex items-center justify-end gap-3">
|
<div className="ml-auto flex items-center justify-end gap-3">
|
||||||
<Button
|
<Button
|
||||||
@@ -147,7 +149,7 @@ export default function DomainList({ user, action }: DomainListProps) {
|
|||||||
)}
|
)}
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
className="w-[120px] shrink-0 gap-1"
|
className="flex shrink-0 gap-1"
|
||||||
variant="default"
|
variant="default"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
setCurrentEditDomain(null);
|
setCurrentEditDomain(null);
|
||||||
@@ -156,59 +158,62 @@ export default function DomainList({ user, action }: DomainListProps) {
|
|||||||
setShowForm(!isShowForm);
|
setShowForm(!isShowForm);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
Add Domain
|
<Icons.add className="size-4" />
|
||||||
|
<span className="hidden sm:inline">{t("Add Domain")}</span>
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
{/* <div className="mb-2 flex-row items-center gap-2 space-y-2 sm:flex sm:space-y-0">
|
<div className="mb-2 flex-row items-center gap-2 space-y-2 sm:flex sm:space-y-0">
|
||||||
<div className="relative w-full">
|
<div className="relative w-full">
|
||||||
<Input
|
<Input
|
||||||
className="h-8 text-xs md:text-xs"
|
className="h-8 text-xs md:text-xs"
|
||||||
placeholder="Search by slug..."
|
placeholder={t("Search by domain name") + "..."}
|
||||||
value={searchParams.slug}
|
value={searchParams.target}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
setSearchParams({
|
setSearchParams({
|
||||||
...searchParams,
|
...searchParams,
|
||||||
slug: e.target.value,
|
target: e.target.value,
|
||||||
});
|
});
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
{searchParams.slug && (
|
{searchParams.target && (
|
||||||
<Button
|
<Button
|
||||||
className="absolute right-2 top-1/2 h-6 -translate-y-1/2 rounded-full px-1 text-gray-500 hover:text-gray-700"
|
className="absolute right-2 top-1/2 h-6 -translate-y-1/2 rounded-full px-1 text-gray-500 hover:text-gray-700"
|
||||||
onClick={() => setSearchParams({ ...searchParams, slug: "" })}
|
onClick={() =>
|
||||||
|
setSearchParams({ ...searchParams, target: "" })
|
||||||
|
}
|
||||||
variant={"ghost"}
|
variant={"ghost"}
|
||||||
>
|
>
|
||||||
<Icons.close className="size-3" />
|
<Icons.close className="size-3" />
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div> */}
|
</div>
|
||||||
|
|
||||||
<Table>
|
<Table>
|
||||||
<TableHeader className="bg-gray-100/50 dark:bg-primary-foreground">
|
<TableHeader className="bg-gray-100/50 dark:bg-primary-foreground">
|
||||||
<TableRow className="grid grid-cols-7 items-center text-xs">
|
<TableRow className="grid grid-cols-4 items-center text-xs sm:grid-cols-7">
|
||||||
<TableHead className="col-span-1 flex items-center font-bold">
|
<TableHead className="col-span-1 flex items-center font-bold">
|
||||||
Domain
|
{t("Domain Name")}
|
||||||
|
</TableHead>
|
||||||
|
<TableHead className="col-span-1 hidden items-center text-nowrap font-bold sm:flex">
|
||||||
|
{t("Shorten Service")}
|
||||||
|
</TableHead>
|
||||||
|
<TableHead className="col-span-1 hidden items-center text-nowrap font-bold sm:flex">
|
||||||
|
{t("Email Service")}
|
||||||
|
</TableHead>
|
||||||
|
<TableHead className="col-span-1 hidden items-center text-nowrap font-bold sm:flex">
|
||||||
|
{t("Subdomain Service")}
|
||||||
</TableHead>
|
</TableHead>
|
||||||
<TableHead className="col-span-1 flex items-center text-nowrap font-bold">
|
<TableHead className="col-span-1 flex items-center text-nowrap font-bold">
|
||||||
Shorten Service
|
{t("Active")}
|
||||||
</TableHead>
|
|
||||||
<TableHead className="col-span-1 flex items-center text-nowrap font-bold">
|
|
||||||
Email Service
|
|
||||||
</TableHead>
|
|
||||||
<TableHead className="col-span-1 flex items-center text-nowrap font-bold">
|
|
||||||
DNS Service
|
|
||||||
</TableHead>
|
|
||||||
<TableHead className="col-span-1 flex items-center text-nowrap font-bold">
|
|
||||||
Active
|
|
||||||
</TableHead>
|
|
||||||
<TableHead className="col-span-1 hidden items-center font-bold sm:flex">
|
|
||||||
Updated
|
|
||||||
</TableHead>
|
</TableHead>
|
||||||
<TableHead className="col-span-1 flex items-center font-bold">
|
<TableHead className="col-span-1 flex items-center font-bold">
|
||||||
Actions
|
{t("Updated")}
|
||||||
|
</TableHead>
|
||||||
|
<TableHead className="col-span-1 flex items-center font-bold">
|
||||||
|
{t("Actions")}
|
||||||
</TableHead>
|
</TableHead>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
</TableHeader>
|
</TableHeader>
|
||||||
@@ -224,7 +229,7 @@ export default function DomainList({ user, action }: DomainListProps) {
|
|||||||
) : data && data.list && data.list.length ? (
|
) : data && data.list && data.list.length ? (
|
||||||
data.list.map((domain) => (
|
data.list.map((domain) => (
|
||||||
<div className="border-b" key={domain.id}>
|
<div className="border-b" key={domain.id}>
|
||||||
<TableRow className="grid grid-cols-7 items-center">
|
<TableRow className="grid grid-cols-4 items-center sm:grid-cols-7">
|
||||||
<TableCell className="col-span-1 flex items-center gap-1">
|
<TableCell className="col-span-1 flex items-center gap-1">
|
||||||
<Link
|
<Link
|
||||||
className="overflow-hidden text-ellipsis whitespace-normal text-slate-600 hover:text-blue-400 hover:underline dark:text-slate-400"
|
className="overflow-hidden text-ellipsis whitespace-normal text-slate-600 hover:text-blue-400 hover:underline dark:text-slate-400"
|
||||||
@@ -236,7 +241,7 @@ export default function DomainList({ user, action }: DomainListProps) {
|
|||||||
{domain.domain_name}
|
{domain.domain_name}
|
||||||
</Link>
|
</Link>
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell className="col-span-1 flex items-center gap-1">
|
<TableCell className="col-span-1 hidden items-center gap-1 sm:flex">
|
||||||
<Switch
|
<Switch
|
||||||
defaultChecked={domain.enable_short_link}
|
defaultChecked={domain.enable_short_link}
|
||||||
onCheckedChange={(value) =>
|
onCheckedChange={(value) =>
|
||||||
@@ -248,21 +253,29 @@ export default function DomainList({ user, action }: DomainListProps) {
|
|||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell className="col-span-1 flex items-center gap-1">
|
<TableCell className="col-span-1 hidden items-center gap-1 sm:flex">
|
||||||
<Switch
|
<Switch
|
||||||
defaultChecked={domain.enable_email}
|
defaultChecked={domain.enable_email}
|
||||||
onCheckedChange={(value) =>
|
onCheckedChange={(value) =>
|
||||||
handleChangeStatus(value, "enable_email", domain)
|
handleChangeStatus(value, "enable_email", domain)
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
{domain.resend_api_key && (
|
||||||
|
<Icons.resend className="mx-0.5 size-4" />
|
||||||
|
)}
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell className="col-span-1 flex items-center gap-1">
|
<TableCell className="col-span-1 hidden items-center gap-1 sm:flex">
|
||||||
<Switch
|
<Switch
|
||||||
defaultChecked={domain.enable_dns}
|
defaultChecked={domain.enable_dns}
|
||||||
onCheckedChange={(value) =>
|
onCheckedChange={(value) =>
|
||||||
handleChangeStatus(value, "enable_dns", domain)
|
handleChangeStatus(value, "enable_dns", domain)
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
{domain.cf_zone_id &&
|
||||||
|
domain.cf_api_key &&
|
||||||
|
domain.cf_email && (
|
||||||
|
<Icons.cloudflare className="mx-0.5 size-4" />
|
||||||
|
)}
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell className="col-span-1 flex items-center gap-1">
|
<TableCell className="col-span-1 flex items-center gap-1">
|
||||||
<Switch
|
<Switch
|
||||||
@@ -273,12 +286,12 @@ export default function DomainList({ user, action }: DomainListProps) {
|
|||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell className="col-span-1 hidden truncate sm:flex">
|
<TableCell className="col-span-1 flex items-center truncate">
|
||||||
{timeAgo(domain.updatedAt as Date)}
|
<TimeAgoIntl date={domain.updatedAt as Date} />
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell className="col-span-1 flex items-center gap-1">
|
<TableCell className="col-span-1 flex items-center gap-1">
|
||||||
<Button
|
<Button
|
||||||
className="h-7 px-1 text-xs hover:bg-slate-100 dark:hover:text-primary-foreground"
|
className="h-7 px-1 text-xs hover:bg-slate-100 dark:hover:text-primary-foreground sm:px-1.5"
|
||||||
size="sm"
|
size="sm"
|
||||||
variant={"outline"}
|
variant={"outline"}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
@@ -288,20 +301,11 @@ export default function DomainList({ user, action }: DomainListProps) {
|
|||||||
setShowForm(!isShowForm);
|
setShowForm(!isShowForm);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<p className="hidden sm:block">Edit</p>
|
<p className="hidden text-nowrap sm:block">
|
||||||
|
{t("Edit")}
|
||||||
|
</p>
|
||||||
<PenLine className="mx-0.5 size-4 sm:ml-1 sm:size-3" />
|
<PenLine className="mx-0.5 size-4 sm:ml-1 sm:size-3" />
|
||||||
</Button>
|
</Button>
|
||||||
{domain.cf_zone_id &&
|
|
||||||
domain.cf_api_key &&
|
|
||||||
domain.cf_email && (
|
|
||||||
<Button
|
|
||||||
className="h-7 px-1 text-xs hover:bg-slate-100 dark:hover:text-primary-foreground"
|
|
||||||
size="sm"
|
|
||||||
variant="ghost"
|
|
||||||
>
|
|
||||||
<Icons.cloudflare className="mx-0.5 size-4" />
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</TableCell>
|
</TableCell>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
{/* {isShowDomainInfo && selectedDomain?.id === domain.id && (
|
{/* {isShowDomainInfo && selectedDomain?.id === domain.id && (
|
||||||
@@ -310,9 +314,11 @@ export default function DomainList({ user, action }: DomainListProps) {
|
|||||||
</div>
|
</div>
|
||||||
))
|
))
|
||||||
) : (
|
) : (
|
||||||
<EmptyPlaceholder>
|
<EmptyPlaceholder className="shadow-none">
|
||||||
<EmptyPlaceholder.Icon name="globeLock" />
|
<EmptyPlaceholder.Icon name="globeLock" />
|
||||||
<EmptyPlaceholder.Title>No Domains</EmptyPlaceholder.Title>
|
<EmptyPlaceholder.Title>
|
||||||
|
{t("No Domains")}
|
||||||
|
</EmptyPlaceholder.Title>
|
||||||
<EmptyPlaceholder.Description>
|
<EmptyPlaceholder.Description>
|
||||||
You don't have any domains yet. Start creating one.
|
You don't have any domains yet. Start creating one.
|
||||||
</EmptyPlaceholder.Description>
|
</EmptyPlaceholder.Description>
|
||||||
@@ -321,6 +327,7 @@ export default function DomainList({ user, action }: DomainListProps) {
|
|||||||
</TableBody>
|
</TableBody>
|
||||||
{data && Math.ceil(data.total / pageSize) > 1 && (
|
{data && Math.ceil(data.total / pageSize) > 1 && (
|
||||||
<PaginationWrapper
|
<PaginationWrapper
|
||||||
|
layout={isMobile ? "right" : "split"}
|
||||||
total={data.total}
|
total={data.total}
|
||||||
currentPage={currentPage}
|
currentPage={currentPage}
|
||||||
setCurrentPage={setCurrentPage}
|
setCurrentPage={setCurrentPage}
|
||||||
@@ -1,10 +1,13 @@
|
|||||||
import { Skeleton } from "@/components/ui/skeleton";
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
import { DashboardHeader } from "@/components/dashboard/header";
|
import { DashboardHeader } from "@/components/dashboard/header";
|
||||||
|
import { SkeletonSection } from "@/components/shared/section-skeleton";
|
||||||
|
|
||||||
export default function DashboardRecordsLoading() {
|
export default function DashboardRecordsLoading() {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<DashboardHeader heading="Domains Management" text="" />
|
<DashboardHeader heading="System Settings" text="" />
|
||||||
|
<SkeletonSection />
|
||||||
|
<SkeletonSection />
|
||||||
<Skeleton className="h-32 w-full rounded-lg" />
|
<Skeleton className="h-32 w-full rounded-lg" />
|
||||||
<Skeleton className="h-[400px] w-full rounded-lg" />
|
<Skeleton className="h-[400px] w-full rounded-lg" />
|
||||||
</>
|
</>
|
||||||
@@ -4,12 +4,13 @@ import { getCurrentUser } from "@/lib/session";
|
|||||||
import { constructMetadata } from "@/lib/utils";
|
import { constructMetadata } from "@/lib/utils";
|
||||||
import { DashboardHeader } from "@/components/dashboard/header";
|
import { DashboardHeader } from "@/components/dashboard/header";
|
||||||
|
|
||||||
import UserRecordsList from "../../dashboard/records/record-list";
|
import AppConfigs from "./app-configs";
|
||||||
import DomainList from "./domain-list";
|
import DomainList from "./domain-list";
|
||||||
|
import PlanList from "./plan-list";
|
||||||
|
|
||||||
export const metadata = constructMetadata({
|
export const metadata = constructMetadata({
|
||||||
title: "DNS Records - WR.DO",
|
title: "System Settings",
|
||||||
description: "List and manage records.",
|
description: "",
|
||||||
});
|
});
|
||||||
|
|
||||||
export default async function DashboardPage() {
|
export default async function DashboardPage() {
|
||||||
@@ -19,12 +20,8 @@ export default async function DashboardPage() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<DashboardHeader
|
<DashboardHeader heading="System Settings" text="" />
|
||||||
heading="Manage Domains"
|
<AppConfigs />
|
||||||
text="List and manage domains."
|
|
||||||
link="/docs/domains"
|
|
||||||
linkText="domains."
|
|
||||||
/>
|
|
||||||
<DomainList
|
<DomainList
|
||||||
user={{
|
user={{
|
||||||
id: user.id,
|
id: user.id,
|
||||||
@@ -36,6 +33,17 @@ export default async function DashboardPage() {
|
|||||||
}}
|
}}
|
||||||
action="/api/admin/domain"
|
action="/api/admin/domain"
|
||||||
/>
|
/>
|
||||||
|
<PlanList
|
||||||
|
user={{
|
||||||
|
id: user.id,
|
||||||
|
name: user.name || "",
|
||||||
|
apiKey: user.apiKey || "",
|
||||||
|
email: user.email || "",
|
||||||
|
role: user.role,
|
||||||
|
team: user.team,
|
||||||
|
}}
|
||||||
|
action="/api/admin/plan"
|
||||||
|
/>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
269
app/(protected)/admin/system/plan-list.tsx
Normal file
269
app/(protected)/admin/system/plan-list.tsx
Normal file
@@ -0,0 +1,269 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { User } from "@prisma/client";
|
||||||
|
import { PenLine, RefreshCwIcon } from "lucide-react";
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
|
import useSWR, { useSWRConfig } from "swr";
|
||||||
|
|
||||||
|
import { PlanQuotaFormData } from "@/lib/dto/plan";
|
||||||
|
import { fetcher, nFormatter } from "@/lib/utils";
|
||||||
|
import { useMediaQuery } from "@/hooks/use-media-query";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Card, CardContent, CardHeader } from "@/components/ui/card";
|
||||||
|
import { Modal } from "@/components/ui/modal";
|
||||||
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
|
import { Switch } from "@/components/ui/switch";
|
||||||
|
import {
|
||||||
|
Table,
|
||||||
|
TableBody,
|
||||||
|
TableCell,
|
||||||
|
TableHead,
|
||||||
|
TableHeader,
|
||||||
|
TableRow,
|
||||||
|
} from "@/components/ui/table";
|
||||||
|
import { PlanForm } from "@/components/forms/plan-form";
|
||||||
|
import { FormType } from "@/components/forms/record-form";
|
||||||
|
import { EmptyPlaceholder } from "@/components/shared/empty-placeholder";
|
||||||
|
import { Icons } from "@/components/shared/icons";
|
||||||
|
import { PaginationWrapper } from "@/components/shared/pagination";
|
||||||
|
import { TimeAgoIntl } from "@/components/shared/time-ago";
|
||||||
|
|
||||||
|
export interface PlanListProps {
|
||||||
|
user: Pick<User, "id" | "name" | "email" | "apiKey" | "role" | "team">;
|
||||||
|
action: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
function TableColumnSekleton() {
|
||||||
|
return (
|
||||||
|
<TableRow className="grid grid-cols-4 items-center sm:grid-cols-8">
|
||||||
|
<TableCell className="col-span-1 flex">
|
||||||
|
<Skeleton className="h-5 w-20" />
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="col-span-1 hidden sm:flex">
|
||||||
|
<Skeleton className="h-5 w-16" />
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="col-span-1 hidden sm:flex">
|
||||||
|
<Skeleton className="h-5 w-16" />
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="col-span-1 hidden sm:flex">
|
||||||
|
<Skeleton className="h-5 w-16" />
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="col-span-1 hidden sm:flex">
|
||||||
|
<Skeleton className="h-5 w-16" />
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="col-span-1 flex">
|
||||||
|
<Skeleton className="h-5 w-16" />
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="col-span-1 flex">
|
||||||
|
<Skeleton className="h-5 w-16" />
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="col-span-1 flex">
|
||||||
|
<Skeleton className="h-5 w-32" />
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function PlanList({ user, action }: PlanListProps) {
|
||||||
|
const { isMobile } = useMediaQuery();
|
||||||
|
const t = useTranslations("List");
|
||||||
|
const [isShowForm, setShowForm] = useState(false);
|
||||||
|
const [formType, setFormType] = useState<FormType>("add");
|
||||||
|
const [currentEditPlan, setCurrentEditPlan] =
|
||||||
|
useState<PlanQuotaFormData | null>(null);
|
||||||
|
const [currentPage, setCurrentPage] = useState(1);
|
||||||
|
const [pageSize, setPageSize] = useState(10);
|
||||||
|
const [searchParams, setSearchParams] = useState({
|
||||||
|
slug: "",
|
||||||
|
target: "",
|
||||||
|
userName: "",
|
||||||
|
});
|
||||||
|
|
||||||
|
const { mutate } = useSWRConfig();
|
||||||
|
const { data, isLoading } = useSWR<{
|
||||||
|
total: number;
|
||||||
|
list: PlanQuotaFormData[];
|
||||||
|
}>(
|
||||||
|
`${action}?page=${currentPage}&size=${pageSize}&target=${searchParams.target}`,
|
||||||
|
fetcher,
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleRefresh = () => {
|
||||||
|
mutate(
|
||||||
|
`${action}?page=${currentPage}&size=${pageSize}&target=${searchParams.target}`,
|
||||||
|
undefined,
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Card className="xl:col-span-2">
|
||||||
|
<CardHeader className="flex flex-row items-center gap-2">
|
||||||
|
<div className="flex items-center gap-1 text-lg font-bold">
|
||||||
|
<span className="text-nowrap">{t("Quota Settings")}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="ml-auto flex items-center justify-end gap-3">
|
||||||
|
<Button
|
||||||
|
variant={"outline"}
|
||||||
|
onClick={() => handleRefresh()}
|
||||||
|
disabled={isLoading}
|
||||||
|
>
|
||||||
|
{isLoading ? (
|
||||||
|
<RefreshCwIcon className="size-4 animate-spin" />
|
||||||
|
) : (
|
||||||
|
<RefreshCwIcon className="size-4" />
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
className="flex shrink-0 gap-1"
|
||||||
|
variant="default"
|
||||||
|
onClick={() => {
|
||||||
|
setCurrentEditPlan(null);
|
||||||
|
setShowForm(false);
|
||||||
|
setFormType("add");
|
||||||
|
setShowForm(!isShowForm);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Icons.add className="size-4" />
|
||||||
|
<span className="hidden sm:inline">{t("Add Plan")}</span>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<Table>
|
||||||
|
<TableHeader className="bg-gray-100/50 dark:bg-primary-foreground">
|
||||||
|
<TableRow className="grid grid-cols-4 items-center text-xs sm:grid-cols-8">
|
||||||
|
<TableHead className="col-span-1 flex items-center font-bold">
|
||||||
|
{t("Plan Name")}
|
||||||
|
</TableHead>
|
||||||
|
<TableHead className="col-span-1 hidden items-center text-nowrap font-bold sm:flex">
|
||||||
|
{t("Short Limit")}
|
||||||
|
</TableHead>
|
||||||
|
<TableHead className="col-span-1 hidden items-center text-nowrap font-bold sm:flex">
|
||||||
|
{t("Email Limit")}
|
||||||
|
</TableHead>
|
||||||
|
<TableHead className="col-span-1 hidden items-center text-nowrap font-bold sm:flex">
|
||||||
|
{t("Send Limit")}
|
||||||
|
</TableHead>
|
||||||
|
<TableHead className="col-span-1 hidden items-center text-nowrap font-bold sm:flex">
|
||||||
|
{t("Record Limit")}
|
||||||
|
</TableHead>
|
||||||
|
<TableHead className="col-span-1 flex items-center text-nowrap font-bold">
|
||||||
|
{t("Active")}
|
||||||
|
</TableHead>
|
||||||
|
<TableHead className="col-span-1 flex items-center font-bold">
|
||||||
|
{t("Updated")}
|
||||||
|
</TableHead>
|
||||||
|
<TableHead className="col-span-1 flex items-center font-bold">
|
||||||
|
{t("Actions")}
|
||||||
|
</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{isLoading ? (
|
||||||
|
<>
|
||||||
|
<TableColumnSekleton />
|
||||||
|
<TableColumnSekleton />
|
||||||
|
<TableColumnSekleton />
|
||||||
|
<TableColumnSekleton />
|
||||||
|
<TableColumnSekleton />
|
||||||
|
</>
|
||||||
|
) : data && data.list && data.list.length ? (
|
||||||
|
data.list.map((plan) => (
|
||||||
|
<div className="border-b" key={plan.id}>
|
||||||
|
<TableRow className="grid grid-cols-4 items-center sm:grid-cols-8">
|
||||||
|
<TableCell className="col-span-1 flex items-center gap-1">
|
||||||
|
{plan.name}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="col-span-1 hidden items-center gap-1 sm:flex">
|
||||||
|
{nFormatter(plan.slNewLinks)}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="col-span-1 hidden items-center gap-1 sm:flex">
|
||||||
|
{nFormatter(plan.emEmailAddresses)}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="col-span-1 hidden items-center gap-1 sm:flex">
|
||||||
|
{nFormatter(plan.emSendEmails)}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="col-span-1 hidden items-center gap-1 sm:flex">
|
||||||
|
{nFormatter(plan.rcNewRecords)}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="col-span-1 flex items-center gap-1">
|
||||||
|
<Switch
|
||||||
|
disabled
|
||||||
|
defaultChecked={plan.isActive}
|
||||||
|
// onCheckedChange={(value) =>
|
||||||
|
// handleChangeStatus(value, "active", domain)
|
||||||
|
// }
|
||||||
|
/>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="col-span-1 flex items-center truncate">
|
||||||
|
<TimeAgoIntl date={plan.updatedAt as Date} />
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="col-span-1 flex items-center gap-1">
|
||||||
|
<Button
|
||||||
|
className="h-7 px-1 text-xs hover:bg-slate-100 dark:hover:text-primary-foreground sm:px-1.5"
|
||||||
|
size="sm"
|
||||||
|
variant={"outline"}
|
||||||
|
onClick={() => {
|
||||||
|
setCurrentEditPlan(plan);
|
||||||
|
setShowForm(false);
|
||||||
|
setFormType("edit");
|
||||||
|
setShowForm(!isShowForm);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<p className="hidden text-nowrap sm:block">
|
||||||
|
{t("Edit")}
|
||||||
|
</p>
|
||||||
|
<PenLine className="mx-0.5 size-4 sm:ml-1 sm:size-3" />
|
||||||
|
</Button>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
) : (
|
||||||
|
<EmptyPlaceholder className="shadow-none">
|
||||||
|
<EmptyPlaceholder.Icon name="settings" />
|
||||||
|
<EmptyPlaceholder.Title>
|
||||||
|
{t("No Plans")}
|
||||||
|
</EmptyPlaceholder.Title>
|
||||||
|
<EmptyPlaceholder.Description>
|
||||||
|
You don't have any plans yet. Start creating one.
|
||||||
|
</EmptyPlaceholder.Description>
|
||||||
|
</EmptyPlaceholder>
|
||||||
|
)}
|
||||||
|
</TableBody>
|
||||||
|
{data && Math.ceil(data.total / pageSize) > 1 && (
|
||||||
|
<PaginationWrapper
|
||||||
|
layout={isMobile ? "right" : "split"}
|
||||||
|
total={data.total}
|
||||||
|
currentPage={currentPage}
|
||||||
|
setCurrentPage={setCurrentPage}
|
||||||
|
pageSize={pageSize}
|
||||||
|
setPageSize={setPageSize}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</Table>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* form */}
|
||||||
|
<Modal
|
||||||
|
className="max-h-[90vh] overflow-y-auto md:max-w-2xl"
|
||||||
|
showModal={isShowForm}
|
||||||
|
setShowModal={setShowForm}
|
||||||
|
>
|
||||||
|
<PlanForm
|
||||||
|
user={{ id: user.id, name: user.name || "" }}
|
||||||
|
isShowForm={isShowForm}
|
||||||
|
setShowForm={setShowForm}
|
||||||
|
type={formType}
|
||||||
|
initData={currentEditPlan}
|
||||||
|
action={action}
|
||||||
|
onRefresh={handleRefresh}
|
||||||
|
/>
|
||||||
|
</Modal>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -4,7 +4,10 @@ import { DashboardHeader } from "@/components/dashboard/header";
|
|||||||
export default function DashboardUrlsLoading() {
|
export default function DashboardUrlsLoading() {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<DashboardHeader heading="Short Urls" text="" />
|
<DashboardHeader
|
||||||
|
heading="Manage Short URLs"
|
||||||
|
text="List and manage short urls"
|
||||||
|
/>
|
||||||
<Skeleton className="h-32 w-full rounded-lg" />
|
<Skeleton className="h-32 w-full rounded-lg" />
|
||||||
<Skeleton className="h-[400px] w-full rounded-lg" />
|
<Skeleton className="h-[400px] w-full rounded-lg" />
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -4,11 +4,10 @@ import { getCurrentUser } from "@/lib/session";
|
|||||||
import { constructMetadata } from "@/lib/utils";
|
import { constructMetadata } from "@/lib/utils";
|
||||||
import { DashboardHeader } from "@/components/dashboard/header";
|
import { DashboardHeader } from "@/components/dashboard/header";
|
||||||
|
|
||||||
import LiveLog from "../../dashboard/urls/live-logs";
|
|
||||||
import UserUrlsList from "../../dashboard/urls/url-list";
|
import UserUrlsList from "../../dashboard/urls/url-list";
|
||||||
|
|
||||||
export const metadata = constructMetadata({
|
export const metadata = constructMetadata({
|
||||||
title: "Short URLs - WR.DO",
|
title: "Short URLs",
|
||||||
description: "List and manage records.",
|
description: "List and manage records.",
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -20,11 +19,12 @@ export default async function DashboardPage() {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<DashboardHeader
|
<DashboardHeader
|
||||||
heading="Manage Short URLs"
|
heading="Manage Short URLs"
|
||||||
text="List and manage short urls."
|
text="List and manage short urls"
|
||||||
link="/docs/short-urls"
|
link="/docs/short-urls"
|
||||||
linkText="short urls."
|
linkText="short urls"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<UserUrlsList
|
<UserUrlsList
|
||||||
user={{
|
user={{
|
||||||
id: user.id,
|
id: user.id,
|
||||||
@@ -35,7 +35,6 @@ export default async function DashboardPage() {
|
|||||||
}}
|
}}
|
||||||
action="/api/url/admin"
|
action="/api/url/admin"
|
||||||
/>
|
/>
|
||||||
<LiveLog admin={true} />
|
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ export default function OrdersLoading() {
|
|||||||
<>
|
<>
|
||||||
<DashboardHeader
|
<DashboardHeader
|
||||||
heading="User Management"
|
heading="User Management"
|
||||||
text="List and manage all users."
|
text="List and manage all users"
|
||||||
/>
|
/>
|
||||||
<Skeleton className="h-32 w-full rounded-lg" />
|
<Skeleton className="h-32 w-full rounded-lg" />
|
||||||
<Skeleton className="h-[400px] w-full rounded-lg" />
|
<Skeleton className="h-[400px] w-full rounded-lg" />
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ export default async function UsersPage() {
|
|||||||
<>
|
<>
|
||||||
<DashboardHeader
|
<DashboardHeader
|
||||||
heading="User Management"
|
heading="User Management"
|
||||||
text="List and manage all users."
|
text="List and manage all users"
|
||||||
/>
|
/>
|
||||||
<UsersList user={{ id: user.id, name: user.name || "" }} />
|
<UsersList user={{ id: user.id, name: user.name || "" }} />
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { User } from "@prisma/client";
|
|||||||
import { PenLine, RefreshCwIcon } from "lucide-react";
|
import { PenLine, RefreshCwIcon } from "lucide-react";
|
||||||
import useSWR, { useSWRConfig } from "swr";
|
import useSWR, { useSWRConfig } from "swr";
|
||||||
|
|
||||||
import { fetcher, timeAgo } from "@/lib/utils";
|
import { fetcher } from "@/lib/utils";
|
||||||
import { useMediaQuery } from "@/hooks/use-media-query";
|
import { useMediaQuery } from "@/hooks/use-media-query";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
@@ -37,6 +37,7 @@ import { UserForm } from "@/components/forms/user-form";
|
|||||||
import { EmptyPlaceholder } from "@/components/shared/empty-placeholder";
|
import { EmptyPlaceholder } from "@/components/shared/empty-placeholder";
|
||||||
import { Icons } from "@/components/shared/icons";
|
import { Icons } from "@/components/shared/icons";
|
||||||
import { PaginationWrapper } from "@/components/shared/pagination";
|
import { PaginationWrapper } from "@/components/shared/pagination";
|
||||||
|
import { TimeAgoIntl } from "@/components/shared/time-ago";
|
||||||
|
|
||||||
import CountUpFn from "../../../../components/dashboard/count-up";
|
import CountUpFn from "../../../../components/dashboard/count-up";
|
||||||
|
|
||||||
@@ -73,6 +74,7 @@ function TableColumnSekleton({ className }: { className?: string }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function UsersList({ user }: UrlListProps) {
|
export default function UsersList({ user }: UrlListProps) {
|
||||||
|
const { isMobile } = useMediaQuery();
|
||||||
const [isShowForm, setShowForm] = useState(false);
|
const [isShowForm, setShowForm] = useState(false);
|
||||||
const [currentEditUser, setcurrentEditUser] = useState<User | null>(null);
|
const [currentEditUser, setcurrentEditUser] = useState<User | null>(null);
|
||||||
const [currentPage, setCurrentPage] = useState(1);
|
const [currentPage, setCurrentPage] = useState(1);
|
||||||
@@ -104,9 +106,7 @@ export default function UsersList({ user }: UrlListProps) {
|
|||||||
<CardHeader className="flex flex-row items-center">
|
<CardHeader className="flex flex-row items-center">
|
||||||
<CardDescription className="text-balance text-lg font-bold">
|
<CardDescription className="text-balance text-lg font-bold">
|
||||||
<span>Total Users:</span>{" "}
|
<span>Total Users:</span>{" "}
|
||||||
<span className="font-bold">
|
<span className="font-bold">{data && data.total}</span>
|
||||||
{data && <CountUpFn count={data.total} />}
|
|
||||||
</span>
|
|
||||||
</CardDescription>
|
</CardDescription>
|
||||||
<div className="ml-auto flex items-center justify-end gap-3">
|
<div className="ml-auto flex items-center justify-end gap-3">
|
||||||
<Button
|
<Button
|
||||||
@@ -251,7 +251,7 @@ export default function UsersList({ user }: UrlListProps) {
|
|||||||
<Switch defaultChecked={user.active === 1} />
|
<Switch defaultChecked={user.active === 1} />
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell className="col-span-1 hidden justify-center sm:flex">
|
<TableCell className="col-span-1 hidden justify-center sm:flex">
|
||||||
{timeAgo(user.createdAt || "")}
|
<TimeAgoIntl date={user.updatedAt as Date} />
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell className="col-span-1 flex justify-center">
|
<TableCell className="col-span-1 flex justify-center">
|
||||||
<Button
|
<Button
|
||||||
@@ -271,7 +271,7 @@ export default function UsersList({ user }: UrlListProps) {
|
|||||||
</TableRow>
|
</TableRow>
|
||||||
))
|
))
|
||||||
) : (
|
) : (
|
||||||
<EmptyPlaceholder>
|
<EmptyPlaceholder className="shadow-none">
|
||||||
<EmptyPlaceholder.Icon name="users" />
|
<EmptyPlaceholder.Icon name="users" />
|
||||||
<EmptyPlaceholder.Title>No users</EmptyPlaceholder.Title>
|
<EmptyPlaceholder.Title>No users</EmptyPlaceholder.Title>
|
||||||
<EmptyPlaceholder.Description>
|
<EmptyPlaceholder.Description>
|
||||||
@@ -282,6 +282,7 @@ export default function UsersList({ user }: UrlListProps) {
|
|||||||
</TableBody>
|
</TableBody>
|
||||||
{data && Math.ceil(data.total / pageSize) > 1 && (
|
{data && Math.ceil(data.total / pageSize) > 1 && (
|
||||||
<PaginationWrapper
|
<PaginationWrapper
|
||||||
|
layout={isMobile ? "right" : "split"}
|
||||||
total={data.total}
|
total={data.total}
|
||||||
currentPage={currentPage}
|
currentPage={currentPage}
|
||||||
setCurrentPage={setCurrentPage}
|
setCurrentPage={setCurrentPage}
|
||||||
|
|||||||
@@ -1,10 +1,8 @@
|
|||||||
import { Skeleton } from "@/components/ui/skeleton";
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
import { DashboardHeader } from "@/components/dashboard/header";
|
|
||||||
|
|
||||||
export default function DashboardLoading() {
|
export default function DashboardLoading() {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<DashboardHeader heading="Dashboard" text="" />
|
|
||||||
<div className="flex flex-col gap-5">
|
<div className="flex flex-col gap-5">
|
||||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3 lg:grid-cols-3">
|
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3 lg:grid-cols-3">
|
||||||
<Skeleton className="h-32 w-full rounded-lg" />
|
<Skeleton className="h-32 w-full rounded-lg" />
|
||||||
|
|||||||
@@ -2,9 +2,9 @@ import { Suspense } from "react";
|
|||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
import { UserRole } from "@prisma/client";
|
import { UserRole } from "@prisma/client";
|
||||||
|
|
||||||
import { TeamPlanQuota } from "@/config/team";
|
|
||||||
import { getUserRecordCount } from "@/lib/dto/cloudflare-dns-record";
|
import { getUserRecordCount } from "@/lib/dto/cloudflare-dns-record";
|
||||||
import { getAllUserEmailsCount } from "@/lib/dto/email";
|
import { getAllUserEmailsCount } from "@/lib/dto/email";
|
||||||
|
import { getPlanQuota, PlanQuota } from "@/lib/dto/plan";
|
||||||
import { getUserShortUrlCount } from "@/lib/dto/short-urls";
|
import { getUserShortUrlCount } from "@/lib/dto/short-urls";
|
||||||
import { getCurrentUser } from "@/lib/session";
|
import { getCurrentUser } from "@/lib/session";
|
||||||
import { constructMetadata } from "@/lib/utils";
|
import { constructMetadata } from "@/lib/utils";
|
||||||
@@ -13,24 +13,22 @@ import {
|
|||||||
DashboardInfoCard,
|
DashboardInfoCard,
|
||||||
HeroCard,
|
HeroCard,
|
||||||
} from "@/components/dashboard/dashboard-info-card";
|
} from "@/components/dashboard/dashboard-info-card";
|
||||||
import { DashboardHeader } from "@/components/dashboard/header";
|
|
||||||
import { ErrorBoundary } from "@/components/shared/error-boundary";
|
import { ErrorBoundary } from "@/components/shared/error-boundary";
|
||||||
|
|
||||||
import UserRecordsList from "./records/record-list";
|
import UserRecordsList from "./records/record-list";
|
||||||
import LiveLog from "./urls/live-logs";
|
|
||||||
import UserUrlsList from "./urls/url-list";
|
import UserUrlsList from "./urls/url-list";
|
||||||
|
|
||||||
export const metadata = constructMetadata({
|
export const metadata = constructMetadata({
|
||||||
title: "Dashboard - WR.DO",
|
title: "Dashboard",
|
||||||
description: "List and manage records.",
|
description: "List and manage records.",
|
||||||
});
|
});
|
||||||
|
|
||||||
async function EmailHeroCardSection({
|
async function EmailHeroCardSection({
|
||||||
userId,
|
userId,
|
||||||
team,
|
plan,
|
||||||
}: {
|
}: {
|
||||||
userId: string;
|
userId: string;
|
||||||
team: string;
|
plan: PlanQuota;
|
||||||
}) {
|
}) {
|
||||||
const email_count = await getAllUserEmailsCount(userId);
|
const email_count = await getAllUserEmailsCount(userId);
|
||||||
|
|
||||||
@@ -38,17 +36,17 @@ async function EmailHeroCardSection({
|
|||||||
<HeroCard
|
<HeroCard
|
||||||
total={email_count.total}
|
total={email_count.total}
|
||||||
monthTotal={email_count.month_total}
|
monthTotal={email_count.month_total}
|
||||||
limit={TeamPlanQuota[team].EM_EmailAddresses}
|
limit={plan.emEmailAddresses}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function ShortUrlsCardSection({
|
async function ShortUrlsCardSection({
|
||||||
userId,
|
userId,
|
||||||
team,
|
plan,
|
||||||
}: {
|
}: {
|
||||||
userId: string;
|
userId: string;
|
||||||
team: string;
|
plan: PlanQuota;
|
||||||
}) {
|
}) {
|
||||||
const url_count = await getUserShortUrlCount(userId);
|
const url_count = await getUserShortUrlCount(userId);
|
||||||
|
|
||||||
@@ -58,7 +56,7 @@ async function ShortUrlsCardSection({
|
|||||||
title="Short URLs"
|
title="Short URLs"
|
||||||
total={url_count.total}
|
total={url_count.total}
|
||||||
monthTotal={url_count.month_total}
|
monthTotal={url_count.month_total}
|
||||||
limit={TeamPlanQuota[team].SL_NewLinks}
|
limit={plan.slNewLinks}
|
||||||
link="/dashboard/urls"
|
link="/dashboard/urls"
|
||||||
icon="link"
|
icon="link"
|
||||||
/>
|
/>
|
||||||
@@ -67,10 +65,10 @@ async function ShortUrlsCardSection({
|
|||||||
|
|
||||||
async function DnsRecordsCardSection({
|
async function DnsRecordsCardSection({
|
||||||
userId,
|
userId,
|
||||||
team,
|
plan,
|
||||||
}: {
|
}: {
|
||||||
userId: string;
|
userId: string;
|
||||||
team: string;
|
plan: PlanQuota;
|
||||||
}) {
|
}) {
|
||||||
const record_count = await getUserRecordCount(userId);
|
const record_count = await getUserRecordCount(userId);
|
||||||
|
|
||||||
@@ -80,17 +78,13 @@ async function DnsRecordsCardSection({
|
|||||||
title="DNS Records"
|
title="DNS Records"
|
||||||
total={record_count.total}
|
total={record_count.total}
|
||||||
monthTotal={record_count.month_total}
|
monthTotal={record_count.month_total}
|
||||||
limit={TeamPlanQuota[team].RC_NewRecords}
|
limit={plan.rcNewRecords}
|
||||||
link="/dashboard/records"
|
link="/dashboard/records"
|
||||||
icon="globeLock"
|
icon="globeLock"
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function LiveLogSection() {
|
|
||||||
return <LiveLog admin={false} />;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function UserUrlsListSection({
|
async function UserUrlsListSection({
|
||||||
user,
|
user,
|
||||||
}: {
|
}: {
|
||||||
@@ -119,7 +113,13 @@ async function UserUrlsListSection({
|
|||||||
async function UserRecordsListSection({
|
async function UserRecordsListSection({
|
||||||
user,
|
user,
|
||||||
}: {
|
}: {
|
||||||
user: { id: string; name: string; apiKey: string; email: string };
|
user: {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
apiKey: string;
|
||||||
|
email: string;
|
||||||
|
role: UserRole;
|
||||||
|
};
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<UserRecordsList
|
<UserRecordsList
|
||||||
@@ -128,6 +128,7 @@ async function UserRecordsListSection({
|
|||||||
name: user.name,
|
name: user.name,
|
||||||
apiKey: user.apiKey,
|
apiKey: user.apiKey,
|
||||||
email: user.email,
|
email: user.email,
|
||||||
|
role: user.role,
|
||||||
}}
|
}}
|
||||||
action="/api/record"
|
action="/api/record"
|
||||||
/>
|
/>
|
||||||
@@ -139,9 +140,10 @@ export default async function DashboardPage() {
|
|||||||
|
|
||||||
if (!user?.id) redirect("/login");
|
if (!user?.id) redirect("/login");
|
||||||
|
|
||||||
|
const plan = await getPlanQuota(user.team);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<DashboardHeader heading="Dashboard" text="" />
|
|
||||||
<div className="flex flex-col gap-5">
|
<div className="flex flex-col gap-5">
|
||||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3 xl:grid-cols-3">
|
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3 xl:grid-cols-3">
|
||||||
<ErrorBoundary
|
<ErrorBoundary
|
||||||
@@ -150,7 +152,7 @@ export default async function DashboardPage() {
|
|||||||
<Suspense
|
<Suspense
|
||||||
fallback={<Skeleton className="h-32 w-full rounded-lg" />}
|
fallback={<Skeleton className="h-32 w-full rounded-lg" />}
|
||||||
>
|
>
|
||||||
<EmailHeroCardSection userId={user.id} team={user.team} />
|
<EmailHeroCardSection userId={user.id} plan={plan} />
|
||||||
</Suspense>
|
</Suspense>
|
||||||
</ErrorBoundary>
|
</ErrorBoundary>
|
||||||
<ErrorBoundary
|
<ErrorBoundary
|
||||||
@@ -159,7 +161,7 @@ export default async function DashboardPage() {
|
|||||||
<Suspense
|
<Suspense
|
||||||
fallback={<Skeleton className="h-32 w-full rounded-lg" />}
|
fallback={<Skeleton className="h-32 w-full rounded-lg" />}
|
||||||
>
|
>
|
||||||
<ShortUrlsCardSection userId={user.id} team={user.team} />
|
<ShortUrlsCardSection userId={user.id} plan={plan} />
|
||||||
</Suspense>
|
</Suspense>
|
||||||
</ErrorBoundary>
|
</ErrorBoundary>
|
||||||
<ErrorBoundary
|
<ErrorBoundary
|
||||||
@@ -168,17 +170,25 @@ export default async function DashboardPage() {
|
|||||||
<Suspense
|
<Suspense
|
||||||
fallback={<Skeleton className="h-32 w-full rounded-lg" />}
|
fallback={<Skeleton className="h-32 w-full rounded-lg" />}
|
||||||
>
|
>
|
||||||
<DnsRecordsCardSection userId={user.id} team={user.team} />
|
<DnsRecordsCardSection userId={user.id} plan={plan} />
|
||||||
</Suspense>
|
</Suspense>
|
||||||
</ErrorBoundary>
|
</ErrorBoundary>
|
||||||
</div>
|
</div>
|
||||||
<ErrorBoundary
|
<ErrorBoundary
|
||||||
fallback={<Skeleton className="h-[200px] w-full rounded-lg" />}
|
fallback={<Skeleton className="h-[400px] w-full rounded-lg" />}
|
||||||
>
|
>
|
||||||
<Suspense
|
<Suspense
|
||||||
fallback={<Skeleton className="h-[200px] w-full rounded-lg" />}
|
fallback={<Skeleton className="h-[400px] w-full rounded-lg" />}
|
||||||
>
|
>
|
||||||
<LiveLogSection />
|
<UserRecordsListSection
|
||||||
|
user={{
|
||||||
|
id: user.id,
|
||||||
|
name: user.name || "",
|
||||||
|
apiKey: user.apiKey || "",
|
||||||
|
email: user.email || "",
|
||||||
|
role: user.role,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
</Suspense>
|
</Suspense>
|
||||||
</ErrorBoundary>
|
</ErrorBoundary>
|
||||||
<ErrorBoundary
|
<ErrorBoundary
|
||||||
@@ -198,22 +208,6 @@ export default async function DashboardPage() {
|
|||||||
/>
|
/>
|
||||||
</Suspense>
|
</Suspense>
|
||||||
</ErrorBoundary>
|
</ErrorBoundary>
|
||||||
<ErrorBoundary
|
|
||||||
fallback={<Skeleton className="h-[400px] w-full rounded-lg" />}
|
|
||||||
>
|
|
||||||
<Suspense
|
|
||||||
fallback={<Skeleton className="h-[400px] w-full rounded-lg" />}
|
|
||||||
>
|
|
||||||
<UserRecordsListSection
|
|
||||||
user={{
|
|
||||||
id: user.id,
|
|
||||||
name: user.name || "",
|
|
||||||
apiKey: user.apiKey || "",
|
|
||||||
email: user.email || "",
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</Suspense>
|
|
||||||
</ErrorBoundary>
|
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -5,8 +5,8 @@ export default function DashboardRecordsLoading() {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<DashboardHeader
|
<DashboardHeader
|
||||||
heading="Manage DNS Records"
|
heading="Manage DNS Records"
|
||||||
text="List and manage records."
|
text="List and manage records"
|
||||||
/>
|
/>
|
||||||
<Skeleton className="h-32 w-full rounded-lg" />
|
<Skeleton className="h-32 w-full rounded-lg" />
|
||||||
<Skeleton className="h-[400px] w-full rounded-lg" />
|
<Skeleton className="h-[400px] w-full rounded-lg" />
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import { DashboardHeader } from "@/components/dashboard/header";
|
|||||||
import UserRecordsList from "./record-list";
|
import UserRecordsList from "./record-list";
|
||||||
|
|
||||||
export const metadata = constructMetadata({
|
export const metadata = constructMetadata({
|
||||||
title: "DNS Records - WR.DO",
|
title: "DNS Records",
|
||||||
description: "List and manage records.",
|
description: "List and manage records.",
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -19,10 +19,10 @@ export default async function DashboardPage() {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<DashboardHeader
|
<DashboardHeader
|
||||||
heading="Manage DNS Records"
|
heading="Manage DNS Records"
|
||||||
text="List and manage records."
|
text="List and manage records"
|
||||||
link="/docs/dns-records"
|
link="/docs/dns-records"
|
||||||
linkText="DNS records."
|
linkText="DNS records"
|
||||||
/>
|
/>
|
||||||
<UserRecordsList
|
<UserRecordsList
|
||||||
user={{
|
user={{
|
||||||
@@ -30,6 +30,7 @@ export default async function DashboardPage() {
|
|||||||
name: user.name || "",
|
name: user.name || "",
|
||||||
apiKey: user.apiKey || "",
|
apiKey: user.apiKey || "",
|
||||||
email: user.email || "",
|
email: user.email || "",
|
||||||
|
role: user.role,
|
||||||
}}
|
}}
|
||||||
action="/api/record"
|
action="/api/record"
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -4,12 +4,14 @@ import { useState } from "react";
|
|||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { User } from "@prisma/client";
|
import { User } from "@prisma/client";
|
||||||
import { PenLine, RefreshCwIcon } from "lucide-react";
|
import { PenLine, RefreshCwIcon } from "lucide-react";
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import useSWR, { useSWRConfig } from "swr";
|
import useSWR, { useSWRConfig } from "swr";
|
||||||
|
|
||||||
import { UserRecordFormData } from "@/lib/dto/cloudflare-dns-record";
|
import { UserRecordFormData } from "@/lib/dto/cloudflare-dns-record";
|
||||||
import { TTL_ENUMS } from "@/lib/enums";
|
import { TTL_ENUMS } from "@/lib/enums";
|
||||||
import { fetcher, timeAgo } from "@/lib/utils";
|
import { fetcher } from "@/lib/utils";
|
||||||
|
import { useMediaQuery } from "@/hooks/use-media-query";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import {
|
import {
|
||||||
@@ -39,20 +41,18 @@ import {
|
|||||||
import { FormType, RecordForm } from "@/components/forms/record-form";
|
import { FormType, RecordForm } from "@/components/forms/record-form";
|
||||||
import { EmptyPlaceholder } from "@/components/shared/empty-placeholder";
|
import { EmptyPlaceholder } from "@/components/shared/empty-placeholder";
|
||||||
import { Icons } from "@/components/shared/icons";
|
import { Icons } from "@/components/shared/icons";
|
||||||
import {
|
import { LinkInfoPreviewer } from "@/components/shared/link-previewer";
|
||||||
LinkInfoPreviewer,
|
|
||||||
LinkPreviewer,
|
|
||||||
} from "@/components/shared/link-previewer";
|
|
||||||
import { PaginationWrapper } from "@/components/shared/pagination";
|
import { PaginationWrapper } from "@/components/shared/pagination";
|
||||||
|
import { TimeAgoIntl } from "@/components/shared/time-ago";
|
||||||
|
|
||||||
export interface RecordListProps {
|
export interface RecordListProps {
|
||||||
user: Pick<User, "id" | "name" | "apiKey" | "email">;
|
user: Pick<User, "id" | "name" | "apiKey" | "email" | "role">;
|
||||||
action: string;
|
action: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
function TableColumnSekleton() {
|
function TableColumnSekleton() {
|
||||||
return (
|
return (
|
||||||
<TableRow className="grid grid-cols-3 items-center sm:grid-cols-8">
|
<TableRow className="grid grid-cols-3 items-center sm:grid-cols-9">
|
||||||
<TableCell className="col-span-1">
|
<TableCell className="col-span-1">
|
||||||
<Skeleton className="h-5 w-24" />
|
<Skeleton className="h-5 w-24" />
|
||||||
</TableCell>
|
</TableCell>
|
||||||
@@ -71,6 +71,9 @@ function TableColumnSekleton() {
|
|||||||
<TableCell className="col-span-1 hidden justify-center sm:flex">
|
<TableCell className="col-span-1 hidden justify-center sm:flex">
|
||||||
<Skeleton className="h-5 w-16" />
|
<Skeleton className="h-5 w-16" />
|
||||||
</TableCell>
|
</TableCell>
|
||||||
|
<TableCell className="col-span-1 hidden justify-center sm:flex">
|
||||||
|
<Skeleton className="h-5 w-16" />
|
||||||
|
</TableCell>
|
||||||
<TableCell className="col-span-1 flex justify-center">
|
<TableCell className="col-span-1 flex justify-center">
|
||||||
<Skeleton className="h-5 w-16" />
|
<Skeleton className="h-5 w-16" />
|
||||||
</TableCell>
|
</TableCell>
|
||||||
@@ -79,16 +82,20 @@ function TableColumnSekleton() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function UserRecordsList({ user, action }: RecordListProps) {
|
export default function UserRecordsList({ user, action }: RecordListProps) {
|
||||||
|
const { isMobile } = useMediaQuery();
|
||||||
const [isShowForm, setShowForm] = useState(false);
|
const [isShowForm, setShowForm] = useState(false);
|
||||||
const [formType, setFormType] = useState<FormType>("add");
|
const [formType, setFormType] = useState<FormType>("add");
|
||||||
const [currentEditRecord, setCurrentEditRecord] =
|
const [currentEditRecord, setCurrentEditRecord] =
|
||||||
useState<UserRecordFormData | null>(null);
|
useState<UserRecordFormData | null>(null);
|
||||||
const [currentPage, setCurrentPage] = useState(1);
|
const [currentPage, setCurrentPage] = useState(1);
|
||||||
const [pageSize, setPageSize] = useState(10);
|
const [pageSize, setPageSize] = useState(10);
|
||||||
|
const isAdmin = action.includes("/admin");
|
||||||
|
|
||||||
|
const t = useTranslations("List");
|
||||||
|
|
||||||
const { mutate } = useSWRConfig();
|
const { mutate } = useSWRConfig();
|
||||||
|
|
||||||
const { data, error, isLoading } = useSWR<{
|
const { data, isLoading } = useSWR<{
|
||||||
total: number;
|
total: number;
|
||||||
list: UserRecordFormData[];
|
list: UserRecordFormData[];
|
||||||
}>(`${action}?page=${currentPage}&size=${pageSize}`, fetcher, {
|
}>(`${action}?page=${currentPage}&size=${pageSize}`, fetcher, {
|
||||||
@@ -105,7 +112,7 @@ export default function UserRecordsList({ user, action }: RecordListProps) {
|
|||||||
setChecked: (value: boolean) => void,
|
setChecked: (value: boolean) => void,
|
||||||
) => {
|
) => {
|
||||||
const originalState = record.active === 1;
|
const originalState = record.active === 1;
|
||||||
setChecked(checked); // 立即更新 UI
|
setChecked(checked);
|
||||||
|
|
||||||
const res = await fetch(`/api/record/update`, {
|
const res = await fetch(`/api/record/update`, {
|
||||||
method: "PUT",
|
method: "PUT",
|
||||||
@@ -138,32 +145,32 @@ export default function UserRecordsList({ user, action }: RecordListProps) {
|
|||||||
<>
|
<>
|
||||||
<Card className="xl:col-span-2">
|
<Card className="xl:col-span-2">
|
||||||
<CardHeader className="flex flex-row items-center">
|
<CardHeader className="flex flex-row items-center">
|
||||||
{action.includes("/admin") ? (
|
{isAdmin ? (
|
||||||
<CardDescription className="text-balance text-lg font-bold">
|
<CardDescription className="text-balance text-lg font-bold">
|
||||||
<span>Total Records:</span>{" "}
|
<span>{t("Total Subdomains")}:</span>{" "}
|
||||||
<span className="font-bold">{data && data.total}</span>
|
<span className="font-bold">{data && data.total}</span>
|
||||||
</CardDescription>
|
</CardDescription>
|
||||||
) : (
|
) : (
|
||||||
<div className="grid gap-2">
|
<div className="grid gap-2">
|
||||||
<CardTitle>DNS Records</CardTitle>
|
<CardTitle>{t("Subdomain List")}</CardTitle>
|
||||||
<CardDescription className="hidden text-balance sm:block">
|
<CardDescription className="hidden text-balance sm:block">
|
||||||
Please read the{" "}
|
{t("Please read the")}{" "}
|
||||||
<Link
|
<Link
|
||||||
target="_blank"
|
target="_blank"
|
||||||
className="font-semibold text-yellow-600 after:content-['↗'] hover:underline"
|
className="font-semibold text-yellow-600 after:content-['↗'] hover:underline"
|
||||||
href="/docs/dns-records#legitimacy-review"
|
href="/docs/dns-records#legitimacy-review"
|
||||||
>
|
>
|
||||||
Legitimacy review
|
{t("legitimacy review")}
|
||||||
</Link>{" "}
|
</Link>{" "}
|
||||||
before using. See{" "}
|
{t("before using")}. {t("See")}{" "}
|
||||||
<Link
|
<Link
|
||||||
target="_blank"
|
target="_blank"
|
||||||
className="text-blue-500 hover:underline"
|
className="text-blue-500 hover:underline"
|
||||||
href="/docs/examples/vercel"
|
href="/docs/examples/vercel"
|
||||||
>
|
>
|
||||||
examples
|
{t("examples")}
|
||||||
</Link>{" "}
|
</Link>{" "}
|
||||||
for more usage.
|
{t("for more usage")}.
|
||||||
</CardDescription>
|
</CardDescription>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@@ -180,7 +187,7 @@ export default function UserRecordsList({ user, action }: RecordListProps) {
|
|||||||
)}
|
)}
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
className="w-[120px] shrink-0 gap-1"
|
className="flex shrink-0 gap-1"
|
||||||
variant="default"
|
variant="default"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
setCurrentEditRecord(null);
|
setCurrentEditRecord(null);
|
||||||
@@ -189,34 +196,38 @@ export default function UserRecordsList({ user, action }: RecordListProps) {
|
|||||||
setShowForm(!isShowForm);
|
setShowForm(!isShowForm);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
Add Record
|
<Icons.add className="size-4" />
|
||||||
|
<span className="hidden sm:inline">{t("Add Record")}</span>
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<Table>
|
<Table>
|
||||||
<TableHeader className="bg-gray-100/50 dark:bg-primary-foreground">
|
<TableHeader className="bg-gray-100/50 dark:bg-primary-foreground">
|
||||||
<TableRow className="grid grid-cols-3 items-center sm:grid-cols-8">
|
<TableRow className="grid grid-cols-3 items-center sm:grid-cols-9">
|
||||||
<TableHead className="col-span-1 flex items-center font-bold">
|
<TableHead className="col-span-1 flex items-center font-bold">
|
||||||
Type
|
{t("Type")}
|
||||||
</TableHead>
|
</TableHead>
|
||||||
<TableHead className="col-span-1 flex items-center font-bold">
|
<TableHead className="col-span-1 flex items-center font-bold">
|
||||||
Name
|
{t("Name")}
|
||||||
</TableHead>
|
</TableHead>
|
||||||
<TableHead className="col-span-2 hidden items-center font-bold sm:flex">
|
<TableHead className="col-span-2 hidden items-center font-bold sm:flex">
|
||||||
Content
|
{t("Content")}
|
||||||
</TableHead>
|
</TableHead>
|
||||||
<TableHead className="col-span-1 hidden items-center font-bold sm:flex">
|
<TableHead className="col-span-1 hidden items-center font-bold sm:flex">
|
||||||
TTL
|
{t("TTL")}
|
||||||
</TableHead>
|
</TableHead>
|
||||||
<TableHead className="col-span-1 hidden items-center justify-center font-bold sm:flex">
|
<TableHead className="col-span-1 hidden items-center justify-center font-bold sm:flex">
|
||||||
Status
|
{t("Status")}
|
||||||
|
</TableHead>
|
||||||
|
<TableHead className="col-span-1 hidden items-center font-bold sm:flex">
|
||||||
|
{t("User")}
|
||||||
</TableHead>
|
</TableHead>
|
||||||
<TableHead className="col-span-1 hidden items-center justify-center font-bold sm:flex">
|
<TableHead className="col-span-1 hidden items-center justify-center font-bold sm:flex">
|
||||||
Updated
|
{t("Updated")}
|
||||||
</TableHead>
|
</TableHead>
|
||||||
<TableHead className="col-span-1 flex items-center justify-center font-bold">
|
<TableHead className="col-span-1 flex items-center justify-center font-bold">
|
||||||
Actions
|
{t("Actions")}
|
||||||
</TableHead>
|
</TableHead>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
</TableHeader>
|
</TableHeader>
|
||||||
@@ -233,7 +244,7 @@ export default function UserRecordsList({ user, action }: RecordListProps) {
|
|||||||
data.list.map((record) => (
|
data.list.map((record) => (
|
||||||
<TableRow
|
<TableRow
|
||||||
key={record.id}
|
key={record.id}
|
||||||
className="grid animate-fade-in grid-cols-3 items-center animate-in sm:grid-cols-8"
|
className="grid animate-fade-in grid-cols-3 items-center animate-in sm:grid-cols-9"
|
||||||
>
|
>
|
||||||
<TableCell className="col-span-1">
|
<TableCell className="col-span-1">
|
||||||
<Badge className="text-xs" variant="outline">
|
<Badge className="text-xs" variant="outline">
|
||||||
@@ -264,41 +275,112 @@ export default function UserRecordsList({ user, action }: RecordListProps) {
|
|||||||
}
|
}
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell className="col-span-1 hidden items-center justify-center gap-1 sm:flex">
|
<TableCell className="col-span-1 hidden items-center justify-center gap-1 sm:flex">
|
||||||
|
{[0, 1].includes(record.active) && (
|
||||||
<SwitchWrapper
|
<SwitchWrapper
|
||||||
record={record}
|
record={record}
|
||||||
onChangeStatu={handleChangeStatu}
|
onChangeStatu={handleChangeStatu}
|
||||||
/>
|
/>
|
||||||
{!record.active && (
|
)}
|
||||||
|
{record.active === 2 && (
|
||||||
|
<Badge
|
||||||
|
className="text-nowrap rounded-md"
|
||||||
|
variant={"yellow"}
|
||||||
|
>
|
||||||
|
{t("Pending")}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
{record.active === 3 && (
|
||||||
|
<Badge
|
||||||
|
className="text-nowrap rounded-md"
|
||||||
|
variant={"outline"}
|
||||||
|
>
|
||||||
|
{t("Rejected")}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{![1, 3].includes(record.active) && (
|
||||||
<TooltipProvider>
|
<TooltipProvider>
|
||||||
<Tooltip delayDuration={200}>
|
<Tooltip delayDuration={200}>
|
||||||
<TooltipTrigger className="truncate">
|
<TooltipTrigger className="truncate">
|
||||||
<Icons.help className="size-4 cursor-pointer text-yellow-500 opacity-90" />
|
<Icons.help className="size-4 cursor-pointer text-yellow-500 opacity-90" />
|
||||||
</TooltipTrigger>
|
</TooltipTrigger>
|
||||||
<TooltipContent>
|
<TooltipContent>
|
||||||
|
{record.active === 0 && (
|
||||||
<ul className="list-disc px-3">
|
<ul className="list-disc px-3">
|
||||||
<li>The target is currently inaccessible.</li>
|
|
||||||
<li>Please check the target and try again.</li>
|
|
||||||
<li>
|
<li>
|
||||||
If the target is not activated within 3 days,{" "}
|
{t("The target is currently inaccessible")}.
|
||||||
<br />
|
</li>
|
||||||
the administrator will{" "}
|
<li>
|
||||||
|
{t("Please check the target and try again")}
|
||||||
|
.
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
{t(
|
||||||
|
"If the target is not activated within 3 days",
|
||||||
|
)}
|
||||||
|
, <br />
|
||||||
|
{t("the administrator will")}{" "}
|
||||||
<strong className="text-red-500">
|
<strong className="text-red-500">
|
||||||
delete this record
|
{t("delete this record")}
|
||||||
</strong>
|
</strong>
|
||||||
.
|
.
|
||||||
</li>
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
|
)}
|
||||||
|
{record.active === 2 && (
|
||||||
|
<ul className="list-disc px-3">
|
||||||
|
<li>
|
||||||
|
{t(
|
||||||
|
"The record is currently pending for admin approval",
|
||||||
|
)}
|
||||||
|
.
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
</TooltipContent>
|
</TooltipContent>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
</TooltipProvider>
|
</TooltipProvider>
|
||||||
)}
|
)}
|
||||||
</TableCell>
|
</TableCell>
|
||||||
|
<TableCell className="col-span-1 hidden truncate sm:flex">
|
||||||
|
<TooltipProvider>
|
||||||
|
<Tooltip delayDuration={200}>
|
||||||
|
<TooltipTrigger className="truncate">
|
||||||
|
{record.user.name}: {record.user.email}
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent>
|
||||||
|
{record.user.name ?? record.user.email}
|
||||||
|
</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
</TooltipProvider>
|
||||||
|
</TableCell>
|
||||||
<TableCell className="col-span-1 hidden justify-center sm:flex">
|
<TableCell className="col-span-1 hidden justify-center sm:flex">
|
||||||
{timeAgo(record.modified_on as unknown as Date)}
|
<TimeAgoIntl
|
||||||
|
date={record.modified_on as unknown as Date}
|
||||||
|
/>
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell className="col-span-1 flex justify-center">
|
<TableCell className="col-span-1 flex justify-center">
|
||||||
|
{record.active === 3 ? (
|
||||||
<Button
|
<Button
|
||||||
className="text-sm hover:bg-slate-100 dark:hover:text-primary-foreground"
|
className="h-7 text-nowrap px-1 text-xs sm:px-1.5"
|
||||||
|
size="sm"
|
||||||
|
variant={"outline"}
|
||||||
|
disabled
|
||||||
|
onClick={() => {
|
||||||
|
setCurrentEditRecord(record);
|
||||||
|
setShowForm(false);
|
||||||
|
setFormType("edit");
|
||||||
|
setShowForm(!isShowForm);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<p className="hidden text-nowrap sm:block">
|
||||||
|
{t("Reject")}
|
||||||
|
</p>
|
||||||
|
<Icons.close className="mx-0.5 size-4 sm:ml-1 sm:size-3" />
|
||||||
|
</Button>
|
||||||
|
) : [0, 1].includes(record.active) ? (
|
||||||
|
<Button
|
||||||
|
className="h-7 text-nowrap px-1 text-xs hover:bg-slate-100 dark:hover:text-primary-foreground sm:px-1.5"
|
||||||
size="sm"
|
size="sm"
|
||||||
variant={"outline"}
|
variant={"outline"}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
@@ -308,24 +390,52 @@ export default function UserRecordsList({ user, action }: RecordListProps) {
|
|||||||
setShowForm(!isShowForm);
|
setShowForm(!isShowForm);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<p>Edit</p>
|
<p className="hidden text-nowrap sm:block">
|
||||||
<PenLine className="ml-1 size-4" />
|
{t("Edit")}
|
||||||
|
</p>
|
||||||
|
<PenLine className="mx-0.5 size-4 sm:ml-1 sm:size-3" />
|
||||||
</Button>
|
</Button>
|
||||||
|
) : record.active === 2 &&
|
||||||
|
user.role === "ADMIN" &&
|
||||||
|
isAdmin ? (
|
||||||
|
<Button
|
||||||
|
className="h-7 text-nowrap px-1 text-xs hover:bg-blue-400 dark:hover:text-primary-foreground sm:px-1.5"
|
||||||
|
size="sm"
|
||||||
|
variant={"blue"}
|
||||||
|
onClick={() => {
|
||||||
|
setCurrentEditRecord(record);
|
||||||
|
setShowForm(false);
|
||||||
|
setFormType("edit");
|
||||||
|
setShowForm(!isShowForm);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<p className="hidden text-nowrap sm:block">
|
||||||
|
{t("Review")}
|
||||||
|
</p>
|
||||||
|
<Icons.eye className="mx-0.5 size-4 sm:ml-1 sm:size-3" />
|
||||||
|
</Button>
|
||||||
|
) : (
|
||||||
|
"--"
|
||||||
|
)}
|
||||||
</TableCell>
|
</TableCell>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
))
|
))
|
||||||
) : (
|
) : (
|
||||||
<EmptyPlaceholder>
|
<EmptyPlaceholder className="shadow-none">
|
||||||
<EmptyPlaceholder.Icon name="globeLock" />
|
<EmptyPlaceholder.Icon name="globe" />
|
||||||
<EmptyPlaceholder.Title>No records</EmptyPlaceholder.Title>
|
<EmptyPlaceholder.Title>
|
||||||
|
{t("No Subdomains")}
|
||||||
|
</EmptyPlaceholder.Title>
|
||||||
<EmptyPlaceholder.Description>
|
<EmptyPlaceholder.Description>
|
||||||
You don't have any record yet. Start creating record.
|
You don't have any subdomain yet. Start creating
|
||||||
|
record.
|
||||||
</EmptyPlaceholder.Description>
|
</EmptyPlaceholder.Description>
|
||||||
</EmptyPlaceholder>
|
</EmptyPlaceholder>
|
||||||
)}
|
)}
|
||||||
</TableBody>
|
</TableBody>
|
||||||
{data && Math.ceil(data.total / pageSize) > 1 && (
|
{data && Math.ceil(data.total / pageSize) > 1 && (
|
||||||
<PaginationWrapper
|
<PaginationWrapper
|
||||||
|
layout={isMobile ? "right" : "split"}
|
||||||
total={data.total}
|
total={data.total}
|
||||||
currentPage={currentPage}
|
currentPage={currentPage}
|
||||||
setCurrentPage={setCurrentPage}
|
setCurrentPage={setCurrentPage}
|
||||||
@@ -338,7 +448,7 @@ export default function UserRecordsList({ user, action }: RecordListProps) {
|
|||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
<Modal
|
<Modal
|
||||||
className="md:max-w-2xl"
|
className="max-h-[99vh] overflow-y-auto md:max-w-2xl"
|
||||||
showModal={isShowForm}
|
showModal={isShowForm}
|
||||||
setShowModal={setShowForm}
|
setShowModal={setShowForm}
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import {
|
import {
|
||||||
getScrapeStatsByTypeAndUserId,
|
getScrapeStatsByTypeAndUserId,
|
||||||
getScrapeStatsByUserId,
|
|
||||||
getScrapeStatsByUserId1,
|
getScrapeStatsByUserId1,
|
||||||
} from "@/lib/dto/scrape";
|
} from "@/lib/dto/scrape";
|
||||||
|
|
||||||
@@ -21,10 +20,7 @@ export default async function DashboardScrapeCharts({ id }: { id: string }) {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{all_user_logs && all_user_logs.length > 0 && (
|
{all_user_logs && all_user_logs.length > 0 && (
|
||||||
<>
|
|
||||||
<h2 className="my-1 text-xl font-semibold">Request Statistics</h2>
|
|
||||||
<DailyPVUVChart data={all_user_logs} />
|
<DailyPVUVChart data={all_user_logs} />
|
||||||
</>
|
|
||||||
)}
|
)}
|
||||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||||
{(screenshot_stats.length > 0 || meta_stats.length > 0) && (
|
{(screenshot_stats.length > 0 || meta_stats.length > 0) && (
|
||||||
@@ -43,7 +39,6 @@ export default async function DashboardScrapeCharts({ id }: { id: string }) {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<h2 className="my-1 text-xl font-semibold">Request Logs</h2>
|
|
||||||
<LogsTable userId={id} target={"/api/v1/scraping/logs"} />
|
<LogsTable userId={id} target={"/api/v1/scraping/logs"} />
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -3,9 +3,10 @@
|
|||||||
import * as React from "react";
|
import * as React from "react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { ScrapeMeta } from "@prisma/client";
|
import { ScrapeMeta } from "@prisma/client";
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
import { Area, AreaChart, CartesianGrid, XAxis, YAxis } from "recharts";
|
import { Area, AreaChart, CartesianGrid, XAxis, YAxis } from "recharts";
|
||||||
|
|
||||||
import { isLink, nFormatter, removeUrlSuffix, timeAgo } from "@/lib/utils";
|
import { isLink, nFormatter, removeUrlSuffix } from "@/lib/utils";
|
||||||
import {
|
import {
|
||||||
Card,
|
Card,
|
||||||
CardContent,
|
CardContent,
|
||||||
@@ -18,7 +19,7 @@ import {
|
|||||||
ChartTooltip,
|
ChartTooltip,
|
||||||
ChartTooltipContent,
|
ChartTooltipContent,
|
||||||
} from "@/components/ui/chart";
|
} from "@/components/ui/chart";
|
||||||
import CountUp from "@/components/dashboard/count-up";
|
import { TimeAgoIntl } from "@/components/shared/time-ago";
|
||||||
|
|
||||||
const chartConfig = {
|
const chartConfig = {
|
||||||
request: {
|
request: {
|
||||||
@@ -102,18 +103,21 @@ export function DailyPVUVChart({ data }: { data: ScrapeMeta[] }) {
|
|||||||
(a, b) => new Date(a.updatedAt).getTime() - new Date(b.updatedAt).getTime(),
|
(a, b) => new Date(a.updatedAt).getTime() - new Date(b.updatedAt).getTime(),
|
||||||
);
|
);
|
||||||
const latestEntry = sort_data[sort_data.length - 1];
|
const latestEntry = sort_data[sort_data.length - 1];
|
||||||
const latestDate = timeAgo(latestEntry.updatedAt);
|
|
||||||
const latestFrom = latestEntry.type;
|
const latestFrom = latestEntry.type;
|
||||||
|
|
||||||
|
const t = useTranslations("Components");
|
||||||
|
|
||||||
|
const lastRequestInfo = t.rich("last-request-info", {
|
||||||
|
location: latestFrom,
|
||||||
|
timeAgo: () => <TimeAgoIntl date={latestEntry.updatedAt} />,
|
||||||
|
});
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader className="flex flex-col items-stretch space-y-0 border-b p-0 sm:flex-row">
|
<CardHeader className="flex flex-col items-stretch space-y-0 border-b p-0 sm:flex-row">
|
||||||
<div className="flex flex-1 flex-col justify-center gap-1 px-5 py-4">
|
<div className="flex flex-1 flex-col justify-center gap-1 px-5 py-4">
|
||||||
<CardTitle>Total Requests of APIs in Last 30 Days</CardTitle>
|
<CardTitle>{t("Total Requests of APIs in Last 30 Days")}</CardTitle>
|
||||||
<CardDescription>
|
<CardDescription>{lastRequestInfo}</CardDescription>
|
||||||
Last request from <strong>{latestFrom}</strong> api about{" "}
|
|
||||||
{latestDate}.
|
|
||||||
</CardDescription>
|
|
||||||
</div>
|
</div>
|
||||||
<div className="flex">
|
<div className="flex">
|
||||||
{["request", "ip"].map((key) => {
|
{["request", "ip"].map((key) => {
|
||||||
@@ -125,8 +129,8 @@ export function DailyPVUVChart({ data }: { data: ScrapeMeta[] }) {
|
|||||||
className="relative z-30 flex flex-1 flex-col items-center justify-center gap-1 border-t px-6 py-2 text-left even:border-l data-[active=true]:bg-muted/50 sm:border-l sm:border-t-0 sm:px-8 sm:py-3"
|
className="relative z-30 flex flex-1 flex-col items-center justify-center gap-1 border-t px-6 py-2 text-left even:border-l data-[active=true]:bg-muted/50 sm:border-l sm:border-t-0 sm:px-8 sm:py-3"
|
||||||
onClick={() => setActiveChart(chart)}
|
onClick={() => setActiveChart(chart)}
|
||||||
>
|
>
|
||||||
<span className="text-xs text-muted-foreground">
|
<span className="text-nowrap text-xs text-muted-foreground">
|
||||||
{chartConfig[chart].label}
|
{t(chartConfig[chart].label)}
|
||||||
</span>
|
</span>
|
||||||
<span className="text-lg font-bold leading-none">
|
<span className="text-lg font-bold leading-none">
|
||||||
{nFormatter(dataTotal[key])}
|
{nFormatter(dataTotal[key])}
|
||||||
|
|||||||
@@ -5,8 +5,8 @@ export default function DashboardRecordsLoading() {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<DashboardHeader
|
<DashboardHeader
|
||||||
heading="Scraping API Overview"
|
heading="Scraping API Overview"
|
||||||
text="Quickly extract valuable structured website data. It's free and unlimited to use!"
|
text="Quickly extract valuable structured website data"
|
||||||
/>
|
/>
|
||||||
<div className="flex flex-col gap-5">
|
<div className="flex flex-col gap-5">
|
||||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3 lg:grid-cols-3">
|
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3 lg:grid-cols-3">
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { RefreshCwIcon } from "lucide-react";
|
import { RefreshCwIcon } from "lucide-react";
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
import useSWR, { useSWRConfig } from "swr";
|
import useSWR, { useSWRConfig } from "swr";
|
||||||
|
|
||||||
import { nFormatter } from "@/lib/utils";
|
import { nFormatter } from "@/lib/utils";
|
||||||
@@ -49,6 +50,8 @@ const LogsTable = ({ userId, target }) => {
|
|||||||
const [page, setPage] = useState(1);
|
const [page, setPage] = useState(1);
|
||||||
const [pageSize, setPageSize] = useState(20);
|
const [pageSize, setPageSize] = useState(20);
|
||||||
|
|
||||||
|
const t = useTranslations("Components");
|
||||||
|
|
||||||
const [filters, setFilters] = useState({
|
const [filters, setFilters] = useState({
|
||||||
type: "",
|
type: "",
|
||||||
ip: "",
|
ip: "",
|
||||||
@@ -98,12 +101,12 @@ const LogsTable = ({ userId, target }) => {
|
|||||||
onChange={(e) => handleFilterChange("type", e.target.value)}
|
onChange={(e) => handleFilterChange("type", e.target.value)}
|
||||||
className="h-8 max-w-xs placeholder:text-xs"
|
className="h-8 max-w-xs placeholder:text-xs"
|
||||||
/>
|
/>
|
||||||
<Input
|
{/* <Input
|
||||||
placeholder="Filter by IP..."
|
placeholder="Filter by IP..."
|
||||||
value={filters.ip}
|
value={filters.ip}
|
||||||
onChange={(e) => handleFilterChange("ip", e.target.value)}
|
onChange={(e) => handleFilterChange("ip", e.target.value)}
|
||||||
className="h-8 max-w-xs placeholder:text-xs"
|
className="h-8 max-w-xs placeholder:text-xs"
|
||||||
/>
|
/> */}
|
||||||
{
|
{
|
||||||
<>
|
<>
|
||||||
<Input
|
<Input
|
||||||
@@ -139,16 +142,19 @@ const LogsTable = ({ userId, target }) => {
|
|||||||
<div className="rounded-md border">
|
<div className="rounded-md border">
|
||||||
<Table>
|
<Table>
|
||||||
<TableHeader className="bg-muted">
|
<TableHeader className="bg-muted">
|
||||||
<TableRow className="">
|
<TableRow className="grid grid-cols-5 items-center sm:grid-cols-6">
|
||||||
<TableHead className="hidden items-center justify-start px-2 sm:flex">
|
<TableHead className="hidden items-center justify-start px-2 sm:flex">
|
||||||
Date
|
{t("Date")}
|
||||||
</TableHead>
|
</TableHead>
|
||||||
<TableHead className="px-2">Type</TableHead>
|
<TableHead className="flex items-center px-2">
|
||||||
<TableHead className="hidden items-center justify-start px-2 sm:flex">
|
{t("Type")}
|
||||||
IP
|
</TableHead>
|
||||||
|
<TableHead className="col-span-3 flex items-center px-2">
|
||||||
|
{t("Link")}
|
||||||
|
</TableHead>
|
||||||
|
<TableHead className="flex items-center px-2">
|
||||||
|
{t("User")}
|
||||||
</TableHead>
|
</TableHead>
|
||||||
<TableHead className="px-2">Link</TableHead>
|
|
||||||
<TableHead className="px-2">User</TableHead>
|
|
||||||
</TableRow>
|
</TableRow>
|
||||||
</TableHeader>
|
</TableHeader>
|
||||||
<TableBody>
|
<TableBody>
|
||||||
@@ -161,9 +167,6 @@ const LogsTable = ({ userId, target }) => {
|
|||||||
<TableCell>
|
<TableCell>
|
||||||
<Skeleton className="h-2 w-[80px]" />
|
<Skeleton className="h-2 w-[80px]" />
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell className="hidden sm:inline-block">
|
|
||||||
<Skeleton className="h-2 w-[120px]" />
|
|
||||||
</TableCell>
|
|
||||||
<TableCell>
|
<TableCell>
|
||||||
<Skeleton className="h-2 w-[200px]" />
|
<Skeleton className="h-2 w-[200px]" />
|
||||||
</TableCell>
|
</TableCell>
|
||||||
@@ -173,15 +176,15 @@ const LogsTable = ({ userId, target }) => {
|
|||||||
</TableRow>
|
</TableRow>
|
||||||
))
|
))
|
||||||
: logs.map((log) => (
|
: logs.map((log) => (
|
||||||
<TableRow className="text-xs hover:bg-muted" key={log.id}>
|
<TableRow
|
||||||
|
className="grid grid-cols-5 items-center text-xs hover:bg-muted sm:grid-cols-6"
|
||||||
|
key={log.id}
|
||||||
|
>
|
||||||
<TableCell className="hidden truncate p-2 sm:inline-block">
|
<TableCell className="hidden truncate p-2 sm:inline-block">
|
||||||
{new Date(log.createdAt).toLocaleString()}
|
{new Date(log.createdAt).toLocaleString()}
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell className="p-2">{log.type}</TableCell>
|
<TableCell className="p-2">{log.type}</TableCell>
|
||||||
<TableCell className="hidden p-2 sm:inline-block">
|
<TableCell className="col-span-3 max-w-full truncate p-2">
|
||||||
{log.ip}
|
|
||||||
</TableCell>
|
|
||||||
<TableCell className="max-w-md truncate p-2">
|
|
||||||
{log.link}
|
{log.link}
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell className="max-w-md truncate p-2">
|
<TableCell className="max-w-md truncate p-2">
|
||||||
@@ -193,12 +196,13 @@ const LogsTable = ({ userId, target }) => {
|
|||||||
</Table>
|
</Table>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center justify-between gap-2">
|
<div className="flex items-start justify-between gap-2 sm:items-center">
|
||||||
<p className="ml-auto text-nowrap text-sm">
|
<p className="ml-auto text-nowrap text-sm">
|
||||||
{nFormatter(data?.total || 0)} logs
|
{nFormatter(data?.total || 0)} logs
|
||||||
</p>
|
</p>
|
||||||
{data && Math.ceil(data.total / pageSize) > 1 && (
|
{data && Math.ceil(data.total / pageSize) > 1 && (
|
||||||
<PaginationWrapper
|
<PaginationWrapper
|
||||||
|
className="m-0"
|
||||||
total={data.total}
|
total={data.total}
|
||||||
currentPage={page}
|
currentPage={page}
|
||||||
setCurrentPage={setPage}
|
setCurrentPage={setPage}
|
||||||
|
|||||||
@@ -4,7 +4,10 @@ import { DashboardHeader } from "@/components/dashboard/header";
|
|||||||
export default function DashboardRecordsLoading() {
|
export default function DashboardRecordsLoading() {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<DashboardHeader heading="Scraping API" text="" />
|
<DashboardHeader
|
||||||
|
heading="Url to Markdown"
|
||||||
|
text="Quickly extract website content and convert it to Markdown format"
|
||||||
|
/>
|
||||||
<Skeleton className="h-32 w-full rounded-lg" />
|
<Skeleton className="h-32 w-full rounded-lg" />
|
||||||
<Skeleton className="h-[400px] w-full rounded-lg" />
|
<Skeleton className="h-[400px] w-full rounded-lg" />
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import ApiReference from "@/components/shared/api-reference";
|
|||||||
import { MarkdownScraping, TextScraping } from "../scrapes";
|
import { MarkdownScraping, TextScraping } from "../scrapes";
|
||||||
|
|
||||||
export const metadata = constructMetadata({
|
export const metadata = constructMetadata({
|
||||||
title: "Url to Markdown API - WR.DO",
|
title: "Url to Markdown API",
|
||||||
description:
|
description:
|
||||||
"Quickly extract website content and convert it to Markdown format",
|
"Quickly extract website content and convert it to Markdown format",
|
||||||
});
|
});
|
||||||
@@ -21,10 +21,10 @@ export default async function DashboardPage() {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<DashboardHeader
|
<DashboardHeader
|
||||||
heading="Url to Markdown"
|
heading="Url to Markdown"
|
||||||
text="Quickly extract website content and convert it to Markdown format."
|
text="Quickly extract website content and convert it to Markdown format"
|
||||||
link="/docs/open-api/markdown"
|
link="/docs/open-api/markdown"
|
||||||
linkText="Markdown API."
|
linkText="Markdown API"
|
||||||
/>
|
/>
|
||||||
<ApiReference
|
<ApiReference
|
||||||
badge="GET /api/v1/scraping/markdown"
|
badge="GET /api/v1/scraping/markdown"
|
||||||
|
|||||||
@@ -4,7 +4,10 @@ import { DashboardHeader } from "@/components/dashboard/header";
|
|||||||
export default function DashboardRecordsLoading() {
|
export default function DashboardRecordsLoading() {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<DashboardHeader heading="Scraping API" text="" />
|
<DashboardHeader
|
||||||
|
heading="Url to Meta Info"
|
||||||
|
text="Quickly extract valuable structured website data"
|
||||||
|
/>
|
||||||
<Skeleton className="h-32 w-full rounded-lg" />
|
<Skeleton className="h-32 w-full rounded-lg" />
|
||||||
<Skeleton className="h-[400px] w-full rounded-lg" />
|
<Skeleton className="h-[400px] w-full rounded-lg" />
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -5,11 +5,10 @@ import { constructMetadata } from "@/lib/utils";
|
|||||||
import { DashboardHeader } from "@/components/dashboard/header";
|
import { DashboardHeader } from "@/components/dashboard/header";
|
||||||
import ApiReference from "@/components/shared/api-reference";
|
import ApiReference from "@/components/shared/api-reference";
|
||||||
|
|
||||||
import DashboardScrapeCharts from "../charts";
|
|
||||||
import { MetaScraping } from "../scrapes";
|
import { MetaScraping } from "../scrapes";
|
||||||
|
|
||||||
export const metadata = constructMetadata({
|
export const metadata = constructMetadata({
|
||||||
title: "Url to Meta API - WR.DO",
|
title: "Url to Meta API",
|
||||||
description: "Quickly extract valuable structured website data",
|
description: "Quickly extract valuable structured website data",
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -21,10 +20,10 @@ export default async function DashboardPage() {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<DashboardHeader
|
<DashboardHeader
|
||||||
heading="Url to Meta Info"
|
heading="Url to Meta Info"
|
||||||
text="Quickly extract valuable structured website data."
|
text="Quickly extract valuable structured website data"
|
||||||
link="/docs/open-api/meta-info"
|
link="/docs/open-api/meta-info"
|
||||||
linkText="Meta Info API."
|
linkText="Meta Info API"
|
||||||
/>
|
/>
|
||||||
<ApiReference
|
<ApiReference
|
||||||
badge="GET /api/v1/scraping/meta"
|
badge="GET /api/v1/scraping/meta"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import { DashboardHeader } from "@/components/dashboard/header";
|
|||||||
import DashboardScrapeCharts from "./charts";
|
import DashboardScrapeCharts from "./charts";
|
||||||
|
|
||||||
export const metadata = constructMetadata({
|
export const metadata = constructMetadata({
|
||||||
title: "Scraping API - WR.DO",
|
title: "Scraping API",
|
||||||
description: "Quickly extract valuable structured website data",
|
description: "Quickly extract valuable structured website data",
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -20,27 +20,27 @@ export default async function DashboardPage() {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<DashboardHeader
|
<DashboardHeader
|
||||||
heading="Scraping API Overview"
|
heading="Scraping API Overview"
|
||||||
text="Quickly extract valuable structured website data. It's free and unlimited to use!"
|
text="Quickly extract valuable structured website data"
|
||||||
link="/docs/open-api"
|
link="/docs/open-api"
|
||||||
linkText="Open API."
|
linkText="Open API."
|
||||||
/>
|
/>
|
||||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
|
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
|
||||||
<StaticInfoCard
|
<StaticInfoCard
|
||||||
title="Url to Screenshot"
|
title="Url to Screenshot"
|
||||||
desc="Take a screenshot of the webpage."
|
desc="Take a screenshot of the webpage"
|
||||||
link="/dashboard/scrape/screenshot"
|
link="/dashboard/scrape/screenshot"
|
||||||
icon="camera"
|
icon="camera"
|
||||||
/>
|
/>
|
||||||
<StaticInfoCard
|
<StaticInfoCard
|
||||||
title="Url to Meta Info"
|
title="Url to Meta Info"
|
||||||
desc="Extract website metadata."
|
desc="Extract website metadata"
|
||||||
link="/dashboard/scrape/meta-info"
|
link="/dashboard/scrape/meta-info"
|
||||||
icon="globe"
|
icon="globe"
|
||||||
/>
|
/>
|
||||||
<StaticInfoCard
|
<StaticInfoCard
|
||||||
title="Url to QR Code"
|
title="Url to QR Code"
|
||||||
desc="Generate QR Code from URL."
|
desc="Generate QR Code from URL"
|
||||||
link="/dashboard/scrape/qrcode"
|
link="/dashboard/scrape/qrcode"
|
||||||
icon="qrcode"
|
icon="qrcode"
|
||||||
/>
|
/>
|
||||||
@@ -48,13 +48,13 @@ export default async function DashboardPage() {
|
|||||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||||
<StaticInfoCard
|
<StaticInfoCard
|
||||||
title="Url to Markdown"
|
title="Url to Markdown"
|
||||||
desc="Convert website content to Markdown format."
|
desc="Convert website content to Markdown format"
|
||||||
link="/dashboard/scrape/markdown"
|
link="/dashboard/scrape/markdown"
|
||||||
icon="heading1"
|
icon="heading1"
|
||||||
/>
|
/>
|
||||||
<StaticInfoCard
|
<StaticInfoCard
|
||||||
title="Url to Text"
|
title="Url to Text"
|
||||||
desc="Extract website text."
|
desc="Convert website content to text"
|
||||||
link="/dashboard/scrape/markdown"
|
link="/dashboard/scrape/markdown"
|
||||||
icon="fileText"
|
icon="fileText"
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -4,7 +4,10 @@ import { DashboardHeader } from "@/components/dashboard/header";
|
|||||||
export default function DashboardRecordsLoading() {
|
export default function DashboardRecordsLoading() {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<DashboardHeader heading="Scraping API" text="" />
|
<DashboardHeader
|
||||||
|
heading="Url to QR Code"
|
||||||
|
text="Generate QR Code from URL"
|
||||||
|
/>
|
||||||
<Skeleton className="h-32 w-full rounded-lg" />
|
<Skeleton className="h-32 w-full rounded-lg" />
|
||||||
<Skeleton className="h-[400px] w-full rounded-lg" />
|
<Skeleton className="h-[400px] w-full rounded-lg" />
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -6,10 +6,10 @@ import { DashboardHeader } from "@/components/dashboard/header";
|
|||||||
import ApiReference from "@/components/shared/api-reference";
|
import ApiReference from "@/components/shared/api-reference";
|
||||||
import QRCodeEditor from "@/components/shared/qr";
|
import QRCodeEditor from "@/components/shared/qr";
|
||||||
|
|
||||||
import { CodeLight, QrCodeScraping } from "../scrapes";
|
import { CodeLight } from "../scrapes";
|
||||||
|
|
||||||
export const metadata = constructMetadata({
|
export const metadata = constructMetadata({
|
||||||
title: "Url to QR Code API - WR.DO",
|
title: "Url to QR Code API",
|
||||||
description: "Generate QR Code from URL",
|
description: "Generate QR Code from URL",
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -21,10 +21,10 @@ export default async function DashboardPage() {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<DashboardHeader
|
<DashboardHeader
|
||||||
heading="Url to QR Code"
|
heading="Url to QR Code"
|
||||||
text="Generate QR Code from URL"
|
text="Generate QR Code from URL"
|
||||||
link="/docs/open-api/qrcode"
|
link="/docs/open-api/qrcode"
|
||||||
linkText="QR Code API."
|
linkText="QR Code API"
|
||||||
/>
|
/>
|
||||||
<ApiReference
|
<ApiReference
|
||||||
badge="GET /api/v1/scraping/qrcode"
|
badge="GET /api/v1/scraping/qrcode"
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { useState } from "react";
|
|||||||
import JsonView from "@uiw/react-json-view";
|
import JsonView from "@uiw/react-json-view";
|
||||||
import { githubLightTheme } from "@uiw/react-json-view/githubLight";
|
import { githubLightTheme } from "@uiw/react-json-view/githubLight";
|
||||||
import { vscodeTheme } from "@uiw/react-json-view/vscode";
|
import { vscodeTheme } from "@uiw/react-json-view/vscode";
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
import { useTheme } from "next-themes";
|
import { useTheme } from "next-themes";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
|
|
||||||
@@ -50,6 +51,7 @@ export function ScreenshotScraping({
|
|||||||
}: {
|
}: {
|
||||||
user: { id: string; apiKey: string };
|
user: { id: string; apiKey: string };
|
||||||
}) {
|
}) {
|
||||||
|
const t = useTranslations("Scrape");
|
||||||
const { theme } = useTheme();
|
const { theme } = useTheme();
|
||||||
const [protocol, setProtocol] = useState("https://");
|
const [protocol, setProtocol] = useState("https://");
|
||||||
|
|
||||||
@@ -87,10 +89,12 @@ export function ScreenshotScraping({
|
|||||||
<CodeLight content={`https://wr.do/api/v1/scraping/screenshot`} />
|
<CodeLight content={`https://wr.do/api/v1/scraping/screenshot`} />
|
||||||
<Card className="bg-gray-50 dark:bg-gray-900">
|
<Card className="bg-gray-50 dark:bg-gray-900">
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>Playground</CardTitle>
|
<CardTitle>{t("Playground")}</CardTitle>
|
||||||
<CardDescription>
|
<CardDescription>
|
||||||
Automate your website screenshots and turn them into stunning
|
{t(
|
||||||
visuals for your applications.
|
"Automate your website screenshots and turn them into stunning visuals for your applications",
|
||||||
|
)}
|
||||||
|
.
|
||||||
</CardDescription>
|
</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
@@ -126,9 +130,9 @@ export function ScreenshotScraping({
|
|||||||
variant="blue"
|
variant="blue"
|
||||||
onClick={handleScrapingScreenshot}
|
onClick={handleScrapingScreenshot}
|
||||||
disabled={isShoting}
|
disabled={isShoting}
|
||||||
className="rounded-l-none"
|
className="w-28 rounded-l-none"
|
||||||
>
|
>
|
||||||
{isShoting ? "Scraping..." : "Send"}
|
{isShoting ? t("Scraping") : t("Start")}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -164,6 +168,7 @@ export function MetaScraping({
|
|||||||
}: {
|
}: {
|
||||||
user: { id: string; apiKey: string };
|
user: { id: string; apiKey: string };
|
||||||
}) {
|
}) {
|
||||||
|
const t = useTranslations("Scrape");
|
||||||
const { theme } = useTheme();
|
const { theme } = useTheme();
|
||||||
const [currentLink, setCurrentLink] = useState("wr.do");
|
const [currentLink, setCurrentLink] = useState("wr.do");
|
||||||
const [protocol, setProtocol] = useState("https://");
|
const [protocol, setProtocol] = useState("https://");
|
||||||
@@ -203,8 +208,10 @@ export function MetaScraping({
|
|||||||
<CodeLight content={`https://wr.do/api/v1/scraping/meta`} />
|
<CodeLight content={`https://wr.do/api/v1/scraping/meta`} />
|
||||||
<Card className="bg-gray-50 dark:bg-gray-900">
|
<Card className="bg-gray-50 dark:bg-gray-900">
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>Playground</CardTitle>
|
<CardTitle>{t("Playground")}</CardTitle>
|
||||||
<CardDescription>Scrape the meta data of a website.</CardDescription>
|
<CardDescription>
|
||||||
|
{t("Scrape the meta data of a website")}.
|
||||||
|
</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<div className="flex items-center">
|
<div className="flex items-center">
|
||||||
@@ -239,9 +246,9 @@ export function MetaScraping({
|
|||||||
variant="blue"
|
variant="blue"
|
||||||
onClick={handleScrapingMeta}
|
onClick={handleScrapingMeta}
|
||||||
disabled={isScraping}
|
disabled={isScraping}
|
||||||
className="rounded-l-none"
|
className="w-28 rounded-l-none"
|
||||||
>
|
>
|
||||||
{isScraping ? "Scraping..." : "Send"}
|
{isScraping ? t("Scraping") : t("Start")}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -264,6 +271,7 @@ export function MarkdownScraping({
|
|||||||
}: {
|
}: {
|
||||||
user: { id: string; apiKey: string };
|
user: { id: string; apiKey: string };
|
||||||
}) {
|
}) {
|
||||||
|
const t = useTranslations("Scrape");
|
||||||
const { theme } = useTheme();
|
const { theme } = useTheme();
|
||||||
const [currentLink, setCurrentLink] = useState("wr.do");
|
const [currentLink, setCurrentLink] = useState("wr.do");
|
||||||
const [protocol, setProtocol] = useState("https://");
|
const [protocol, setProtocol] = useState("https://");
|
||||||
@@ -334,9 +342,9 @@ export function MarkdownScraping({
|
|||||||
variant="blue"
|
variant="blue"
|
||||||
onClick={handleScrapingMeta}
|
onClick={handleScrapingMeta}
|
||||||
disabled={isScraping}
|
disabled={isScraping}
|
||||||
className="rounded-l-none"
|
className="w-28 rounded-l-none"
|
||||||
>
|
>
|
||||||
{isScraping ? "Scraping..." : "Send"}
|
{isScraping ? t("Scraping") : t("Start")}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -359,6 +367,7 @@ export function TextScraping({
|
|||||||
}: {
|
}: {
|
||||||
user: { id: string; apiKey: string };
|
user: { id: string; apiKey: string };
|
||||||
}) {
|
}) {
|
||||||
|
const t = useTranslations("Scrape");
|
||||||
const { theme } = useTheme();
|
const { theme } = useTheme();
|
||||||
const [currentLink, setCurrentLink] = useState("wr.do");
|
const [currentLink, setCurrentLink] = useState("wr.do");
|
||||||
const [protocol, setProtocol] = useState("https://");
|
const [protocol, setProtocol] = useState("https://");
|
||||||
@@ -394,7 +403,7 @@ export function TextScraping({
|
|||||||
<CodeLight content={`https://wr.do/api/v1/scraping/text`} />
|
<CodeLight content={`https://wr.do/api/v1/scraping/text`} />
|
||||||
<Card className="bg-gray-50 dark:bg-gray-900">
|
<Card className="bg-gray-50 dark:bg-gray-900">
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>Text</CardTitle>
|
<CardTitle>{t("Text")}</CardTitle>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<div className="flex items-center">
|
<div className="flex items-center">
|
||||||
@@ -429,9 +438,9 @@ export function TextScraping({
|
|||||||
variant="blue"
|
variant="blue"
|
||||||
onClick={handleScrapingMeta}
|
onClick={handleScrapingMeta}
|
||||||
disabled={isScraping}
|
disabled={isScraping}
|
||||||
className="rounded-l-none"
|
className="w-28 rounded-l-none"
|
||||||
>
|
>
|
||||||
{isScraping ? "Scraping..." : "Send"}
|
{isScraping ? t("Scraping") : t("Start")}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -454,6 +463,7 @@ export function QrCodeScraping({
|
|||||||
}: {
|
}: {
|
||||||
user: { id: string; apiKey: string };
|
user: { id: string; apiKey: string };
|
||||||
}) {
|
}) {
|
||||||
|
const t = useTranslations("Scrape");
|
||||||
const { theme } = useTheme();
|
const { theme } = useTheme();
|
||||||
const [protocol, setProtocol] = useState("https://");
|
const [protocol, setProtocol] = useState("https://");
|
||||||
|
|
||||||
@@ -487,11 +497,7 @@ export function QrCodeScraping({
|
|||||||
<CodeLight content={`https://wr.do/api/v1/scraping/qrcode`} />
|
<CodeLight content={`https://wr.do/api/v1/scraping/qrcode`} />
|
||||||
<Card className="bg-gray-50 dark:bg-gray-900">
|
<Card className="bg-gray-50 dark:bg-gray-900">
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>Playground</CardTitle>
|
<CardTitle>{t("Playground")}</CardTitle>
|
||||||
<CardDescription>
|
|
||||||
Automate your website screenshots and turn them into stunning
|
|
||||||
visuals for your applications.
|
|
||||||
</CardDescription>
|
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<div className="flex items-center">
|
<div className="flex items-center">
|
||||||
|
|||||||
@@ -4,7 +4,10 @@ import { DashboardHeader } from "@/components/dashboard/header";
|
|||||||
export default function DashboardRecordsLoading() {
|
export default function DashboardRecordsLoading() {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<DashboardHeader heading="Scraping API" text="" />
|
<DashboardHeader
|
||||||
|
heading="Url to Screenshot"
|
||||||
|
text="Quickly extract website screenshots"
|
||||||
|
/>
|
||||||
<Skeleton className="h-32 w-full rounded-lg" />
|
<Skeleton className="h-32 w-full rounded-lg" />
|
||||||
<Skeleton className="h-[400px] w-full rounded-lg" />
|
<Skeleton className="h-[400px] w-full rounded-lg" />
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import DashboardScrapeCharts from "../charts";
|
|||||||
import { ScreenshotScraping } from "../scrapes";
|
import { ScreenshotScraping } from "../scrapes";
|
||||||
|
|
||||||
export const metadata = constructMetadata({
|
export const metadata = constructMetadata({
|
||||||
title: "Url to Screenshot API - WR.DO",
|
title: "Url to Screenshot API",
|
||||||
description:
|
description:
|
||||||
"Quickly extract website screenshots. It's free and unlimited to use!",
|
"Quickly extract website screenshots. It's free and unlimited to use!",
|
||||||
});
|
});
|
||||||
@@ -22,10 +22,10 @@ export default async function DashboardPage() {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<DashboardHeader
|
<DashboardHeader
|
||||||
heading="Url to Screenshot"
|
heading="Url to Screenshot"
|
||||||
text="Quickly extract website screenshots."
|
text="Quickly extract website screenshots"
|
||||||
link="/docs/open-api/screenshot"
|
link="/docs/open-api/screenshot"
|
||||||
linkText="Screenshot API."
|
linkText="Screenshot API"
|
||||||
/>
|
/>
|
||||||
<ApiReference
|
<ApiReference
|
||||||
badge="GET /api/v1/scraping/screenshot"
|
badge="GET /api/v1/scraping/screenshot"
|
||||||
|
|||||||
@@ -5,8 +5,8 @@ export default function DashboardSettingsLoading() {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<DashboardHeader
|
<DashboardHeader
|
||||||
heading="Settings"
|
heading="Account Settings"
|
||||||
text="Manage account and website settings."
|
text="Manage account and website settings"
|
||||||
/>
|
/>
|
||||||
<div className="divide-y divide-muted pb-10">
|
<div className="divide-y divide-muted pb-10">
|
||||||
<SkeletonSection />
|
<SkeletonSection />
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ export default async function SettingsPage() {
|
|||||||
<>
|
<>
|
||||||
<DashboardHeader
|
<DashboardHeader
|
||||||
heading="Account Settings"
|
heading="Account Settings"
|
||||||
text="Manage account and website settings."
|
text="Manage account and website settings"
|
||||||
/>
|
/>
|
||||||
<div className="divide-y divide-muted pb-10">
|
<div className="divide-y divide-muted pb-10">
|
||||||
<UserNameForm user={{ id: user.id, name: user.name || "" }} />
|
<UserNameForm user={{ id: user.id, name: user.name || "" }} />
|
||||||
|
|||||||
459
app/(protected)/dashboard/urls/globe/index.tsx
Normal file
459
app/(protected)/dashboard/urls/globe/index.tsx
Normal file
@@ -0,0 +1,459 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useRef, useState } from "react";
|
||||||
|
import dynamic from "next/dynamic";
|
||||||
|
import { differenceInMinutes, format } from "date-fns";
|
||||||
|
|
||||||
|
import { DAILY_DIMENSION_ENUMS } from "@/lib/enums";
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectSeparator,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from "@/components/ui/select";
|
||||||
|
|
||||||
|
import { RealtimeChart } from "./realtime-chart";
|
||||||
|
import RealtimeLogs from "./realtime-logs";
|
||||||
|
|
||||||
|
const RealtimeGlobe = dynamic(() => import("./realtime-globe"), { ssr: false });
|
||||||
|
|
||||||
|
export interface Location {
|
||||||
|
latitude: number;
|
||||||
|
longitude: number;
|
||||||
|
count: number;
|
||||||
|
city?: string;
|
||||||
|
country?: string;
|
||||||
|
lastUpdate?: Date;
|
||||||
|
createdAt?: Date;
|
||||||
|
updatedAt?: Date;
|
||||||
|
device?: string;
|
||||||
|
browser?: string;
|
||||||
|
userUrl?: {
|
||||||
|
url: string;
|
||||||
|
target: string;
|
||||||
|
prefix: string;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
interface DatabaseLocation {
|
||||||
|
latitude: number;
|
||||||
|
longitude: number;
|
||||||
|
count: number;
|
||||||
|
city: string;
|
||||||
|
country: string;
|
||||||
|
lastUpdate: Date;
|
||||||
|
updatedAt: Date;
|
||||||
|
createdAt: Date;
|
||||||
|
device?: string;
|
||||||
|
browser?: string;
|
||||||
|
userUrl?: {
|
||||||
|
url: string;
|
||||||
|
target: string;
|
||||||
|
prefix: string;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ChartData {
|
||||||
|
time: string;
|
||||||
|
count: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
function date2unix(date: Date): number {
|
||||||
|
return Math.floor(date.getTime() / 1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function Realtime({ isAdmin = false }: { isAdmin?: boolean }) {
|
||||||
|
const mountedRef = useRef(true);
|
||||||
|
const locationDataRef = useRef<Map<string, Location>>(new Map());
|
||||||
|
const lastUpdateRef = useRef<string>();
|
||||||
|
const realtimeIntervalRef = useRef<NodeJS.Timeout | null>(null);
|
||||||
|
const [timeRange, setTimeRange] = useState<string>("30min");
|
||||||
|
const [time, setTime] = useState(() => {
|
||||||
|
const now = new Date();
|
||||||
|
return {
|
||||||
|
startAt: date2unix(new Date(now.getTime() - 30 * 60 * 1000)),
|
||||||
|
endAt: date2unix(now),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
const [filters, setFilters] = useState<Record<string, any>>({});
|
||||||
|
const [locations, setLocations] = useState<Location[]>([]);
|
||||||
|
const [chartData, setChartData] = useState<ChartData[]>([]);
|
||||||
|
const [stats, setStats] = useState({
|
||||||
|
totalClicks: 0,
|
||||||
|
uniqueLocations: 0,
|
||||||
|
rawRecords: 0,
|
||||||
|
lastFetch: new Date().toISOString(),
|
||||||
|
});
|
||||||
|
|
||||||
|
const createLocationKey = (lat: number, lng: number) => {
|
||||||
|
return `${Math.round(lat * 100) / 100},${Math.round(lng * 100) / 100}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
const processChartDataOptimized = (locations: Location[]): ChartData[] => {
|
||||||
|
const validLocations = locations.filter((loc) => loc.createdAt);
|
||||||
|
if (validLocations.length === 0) return [];
|
||||||
|
|
||||||
|
// 如果数据量很少,直接按原始时间点展示
|
||||||
|
if (validLocations.length <= 10) {
|
||||||
|
return validLocations.map((loc, index) => ({
|
||||||
|
time: format(new Date(loc.createdAt!), "HH:mm:ss"),
|
||||||
|
count: loc.count,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 否则使用智能分组
|
||||||
|
const dates = validLocations.map((loc) => new Date(loc.createdAt!));
|
||||||
|
const minDate = new Date(Math.min(...dates.map((d) => d.getTime())));
|
||||||
|
const maxDate = new Date(Math.max(...dates.map((d) => d.getTime())));
|
||||||
|
const totalMinutes = differenceInMinutes(maxDate, minDate);
|
||||||
|
|
||||||
|
// 根据数据量和时间跨度动态调整分组
|
||||||
|
const targetGroups = Math.min(validLocations.length, 20); // 目标分组数量
|
||||||
|
let groupMinutes: number;
|
||||||
|
|
||||||
|
if (totalMinutes <= 60) {
|
||||||
|
groupMinutes = Math.max(1, Math.ceil(totalMinutes / targetGroups));
|
||||||
|
} else {
|
||||||
|
groupMinutes = Math.max(5, Math.ceil(totalMinutes / targetGroups));
|
||||||
|
}
|
||||||
|
|
||||||
|
const groupByFn = (date: Date) => {
|
||||||
|
const minutes =
|
||||||
|
Math.floor(date.getMinutes() / groupMinutes) * groupMinutes;
|
||||||
|
const grouped = new Date(date);
|
||||||
|
grouped.setMinutes(minutes, 0, 0);
|
||||||
|
return grouped;
|
||||||
|
};
|
||||||
|
|
||||||
|
const groupedData = new Map<string, number>();
|
||||||
|
validLocations.forEach((loc) => {
|
||||||
|
const date = new Date(loc.createdAt!);
|
||||||
|
const groupedDate = groupByFn(date);
|
||||||
|
const key = groupedDate.getTime().toString();
|
||||||
|
groupedData.set(key, (groupedData.get(key) || 0) + loc.count);
|
||||||
|
});
|
||||||
|
|
||||||
|
return Array.from(groupedData.entries())
|
||||||
|
.sort(([a], [b]) => parseInt(a) - parseInt(b))
|
||||||
|
.map(([key, count]) => ({
|
||||||
|
time: format(new Date(parseInt(key)), "MM-dd HH:mm"),
|
||||||
|
count: count,
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
|
||||||
|
const appendLocationData = (
|
||||||
|
newData: DatabaseLocation[],
|
||||||
|
isInitialLoad = false,
|
||||||
|
) => {
|
||||||
|
const locationMap = isInitialLoad
|
||||||
|
? new Map()
|
||||||
|
: new Map(locationDataRef.current);
|
||||||
|
let totalNewClicks = 0;
|
||||||
|
|
||||||
|
newData.forEach((item) => {
|
||||||
|
const lat = Math.round(item.latitude * 100) / 100;
|
||||||
|
const lng = Math.round(item.longitude * 100) / 100;
|
||||||
|
const key = createLocationKey(lat, lng);
|
||||||
|
const clickCount = item.count || 1;
|
||||||
|
|
||||||
|
if (locationMap.has(key)) {
|
||||||
|
const existing = locationMap.get(key)!;
|
||||||
|
existing.count += clickCount;
|
||||||
|
existing.lastUpdate = new Date(item.lastUpdate);
|
||||||
|
} else {
|
||||||
|
locationMap.set(key, {
|
||||||
|
lat,
|
||||||
|
lng,
|
||||||
|
count: clickCount,
|
||||||
|
city: item.city,
|
||||||
|
country: item.country,
|
||||||
|
lastUpdate: new Date(item.lastUpdate),
|
||||||
|
device: item.device,
|
||||||
|
browser: item.browser,
|
||||||
|
userUrl: item.userUrl,
|
||||||
|
updatedAt: item.updatedAt,
|
||||||
|
createdAt: item.createdAt,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
totalNewClicks += clickCount;
|
||||||
|
});
|
||||||
|
|
||||||
|
locationDataRef.current = locationMap;
|
||||||
|
const updatedLocations = Array.from(locationMap.values());
|
||||||
|
const totalCount = updatedLocations.reduce(
|
||||||
|
(sum, loc) => sum + loc.count,
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
|
||||||
|
const normalizedLocations = updatedLocations.map((loc) => ({
|
||||||
|
...loc,
|
||||||
|
count: Math.max(0.1, loc.count / Math.max(totalCount, 1)),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const chartData = processChartDataOptimized(updatedLocations);
|
||||||
|
|
||||||
|
return {
|
||||||
|
locations: normalizedLocations,
|
||||||
|
chartData,
|
||||||
|
totalNewClicks,
|
||||||
|
totalCount,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const getLiveLocations = async (isInitialLoad = true) => {
|
||||||
|
try {
|
||||||
|
const params = new URLSearchParams({
|
||||||
|
startAt: time.startAt.toString(),
|
||||||
|
endAt: time.endAt.toString(),
|
||||||
|
isAdmin: isAdmin ? "true" : "false",
|
||||||
|
...filters,
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await fetch(`/api/url/admin/locations?${params}`);
|
||||||
|
const result = await response.json();
|
||||||
|
|
||||||
|
if (result.error) {
|
||||||
|
// console.error("API Error:", result.error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const rawData: DatabaseLocation[] = result.data || [];
|
||||||
|
const {
|
||||||
|
locations: processedLocations,
|
||||||
|
chartData,
|
||||||
|
totalNewClicks,
|
||||||
|
totalCount,
|
||||||
|
} = appendLocationData(rawData, isInitialLoad);
|
||||||
|
|
||||||
|
setStats({
|
||||||
|
totalClicks: result.totalClicks || totalCount,
|
||||||
|
uniqueLocations: processedLocations.length,
|
||||||
|
rawRecords: result.rawRecords || rawData.length,
|
||||||
|
lastFetch: result.timestamp,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (mountedRef.current) {
|
||||||
|
setLocations(processedLocations);
|
||||||
|
setChartData(chartData);
|
||||||
|
lastUpdateRef.current = result.timestamp;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isInitialLoad) {
|
||||||
|
rawData.forEach((item, index) => {
|
||||||
|
setTimeout(() => {
|
||||||
|
if (mountedRef.current) {
|
||||||
|
createTrafficEvent(
|
||||||
|
item.latitude,
|
||||||
|
item.longitude,
|
||||||
|
item.city || "Unknown",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}, index * 100);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching live locations:", error);
|
||||||
|
if (mountedRef.current) {
|
||||||
|
setLocations([]);
|
||||||
|
setChartData([]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const getRealtimeUpdates = async () => {
|
||||||
|
try {
|
||||||
|
const response = await fetch("/api/url/admin/locations", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({
|
||||||
|
lastUpdate: lastUpdateRef.current,
|
||||||
|
startAt: time.startAt,
|
||||||
|
endAt: time.endAt,
|
||||||
|
isAdmin,
|
||||||
|
...filters,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await response.json();
|
||||||
|
|
||||||
|
if (result.error || !result.data || result.data.length === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const {
|
||||||
|
locations: processedLocations,
|
||||||
|
chartData,
|
||||||
|
totalNewClicks,
|
||||||
|
} = appendLocationData(result.data, false);
|
||||||
|
|
||||||
|
setStats((prev) => ({
|
||||||
|
totalClicks: prev.totalClicks + totalNewClicks,
|
||||||
|
uniqueLocations: processedLocations.length,
|
||||||
|
rawRecords: prev.rawRecords + result.data.length,
|
||||||
|
lastFetch: result.timestamp,
|
||||||
|
}));
|
||||||
|
|
||||||
|
if (mountedRef.current) {
|
||||||
|
setLocations(processedLocations);
|
||||||
|
setChartData(chartData);
|
||||||
|
lastUpdateRef.current = result.timestamp;
|
||||||
|
|
||||||
|
result.data.forEach((item: DatabaseLocation, index: number) => {
|
||||||
|
setTimeout(() => {
|
||||||
|
if (mountedRef.current) {
|
||||||
|
createTrafficEvent(
|
||||||
|
item.latitude,
|
||||||
|
item.longitude,
|
||||||
|
item.city || "Unknown",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}, index * 100);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching realtime updates:", error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const resetLocationData = () => {
|
||||||
|
locationDataRef.current.clear();
|
||||||
|
setLocations([]);
|
||||||
|
setChartData([]);
|
||||||
|
setStats({
|
||||||
|
totalClicks: 0,
|
||||||
|
uniqueLocations: 0,
|
||||||
|
rawRecords: 0,
|
||||||
|
lastFetch: new Date().toISOString(),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!mountedRef.current) return;
|
||||||
|
|
||||||
|
realtimeIntervalRef.current = setInterval(() => {
|
||||||
|
if (mountedRef.current) {
|
||||||
|
getRealtimeUpdates();
|
||||||
|
}
|
||||||
|
}, 5000);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
if (realtimeIntervalRef.current) {
|
||||||
|
clearInterval(realtimeIntervalRef.current);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (mountedRef.current) {
|
||||||
|
resetLocationData();
|
||||||
|
getLiveLocations(true);
|
||||||
|
}
|
||||||
|
}, [time, filters]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const restoreTimeRange = () => {
|
||||||
|
setTimeRange("30min");
|
||||||
|
const now = new Date();
|
||||||
|
setTime({
|
||||||
|
startAt: date2unix(new Date(now.getTime() - 30 * 60 * 1000)),
|
||||||
|
endAt: date2unix(now),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
(window as any).restoreTimeRange = restoreTimeRange;
|
||||||
|
|
||||||
|
const interval = setInterval(
|
||||||
|
() => {
|
||||||
|
if (mountedRef.current) {
|
||||||
|
restoreTimeRange();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
5 * 60 * 1000,
|
||||||
|
);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
clearInterval(interval);
|
||||||
|
delete (window as any).restoreTimeRange;
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleTrafficEventRef = useRef<
|
||||||
|
(lat: number, lng: number, city: string) => void
|
||||||
|
>(() => {});
|
||||||
|
|
||||||
|
const createTrafficEvent = (lat: number, lng: number, city: string) => {
|
||||||
|
if (handleTrafficEventRef.current) {
|
||||||
|
handleTrafficEventRef.current(lat, lng, city);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleTimeRangeChange = (value: string) => {
|
||||||
|
setTimeRange(value);
|
||||||
|
const now = new Date();
|
||||||
|
const selectedRange = DAILY_DIMENSION_ENUMS.find((e) => e.value === value);
|
||||||
|
if (!selectedRange) return;
|
||||||
|
|
||||||
|
const minutes = selectedRange.key;
|
||||||
|
const startAt = date2unix(new Date(now.getTime() - minutes * 60 * 1000));
|
||||||
|
const endAt = date2unix(now);
|
||||||
|
|
||||||
|
setTime({ startAt, endAt });
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="relative w-full">
|
||||||
|
<div className="sm:relative sm:p-4">
|
||||||
|
<RealtimeTimePicker
|
||||||
|
timeRange={timeRange}
|
||||||
|
setTimeRange={handleTimeRangeChange}
|
||||||
|
/>
|
||||||
|
<RealtimeChart
|
||||||
|
className="left-0 top-9 z-10 rounded-t-none text-left sm:absolute"
|
||||||
|
chartData={chartData}
|
||||||
|
totalClicks={stats.totalClicks}
|
||||||
|
/>
|
||||||
|
<RealtimeGlobe
|
||||||
|
time={time}
|
||||||
|
filters={filters}
|
||||||
|
locations={locations}
|
||||||
|
stats={stats}
|
||||||
|
setHandleTrafficEvent={(fn) => (handleTrafficEventRef.current = fn)}
|
||||||
|
/>
|
||||||
|
<RealtimeLogs
|
||||||
|
className="right-0 top-0 z-10 sm:absolute"
|
||||||
|
locations={locations}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function RealtimeTimePicker({
|
||||||
|
timeRange,
|
||||||
|
setTimeRange,
|
||||||
|
}: {
|
||||||
|
timeRange: string;
|
||||||
|
setTimeRange: (value: string) => void;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<Select onValueChange={setTimeRange} name="time range" value={timeRange}>
|
||||||
|
<SelectTrigger className="left-0 top-0 z-10 h-9 rounded-b-none border-b-0 bg-transparent text-left backdrop-blur-2xl sm:absolute sm:w-[326px]">
|
||||||
|
<SelectValue placeholder="Select a time range" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{DAILY_DIMENSION_ENUMS.map((e, i) => (
|
||||||
|
<div key={e.value}>
|
||||||
|
<SelectItem value={e.value}>
|
||||||
|
<span className="flex items-center gap-1">{e.label}</span>
|
||||||
|
</SelectItem>
|
||||||
|
{i % 2 === 0 && i !== DAILY_DIMENSION_ENUMS.length - 1 && (
|
||||||
|
<SelectSeparator />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
);
|
||||||
|
}
|
||||||
97
app/(protected)/dashboard/urls/globe/realtime-chart.tsx
Normal file
97
app/(protected)/dashboard/urls/globe/realtime-chart.tsx
Normal file
@@ -0,0 +1,97 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
|
import { Bar, BarChart, Tooltip, XAxis, YAxis } from "recharts";
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
import StatusDot from "@/components/dashboard/status-dot";
|
||||||
|
import { Icons } from "@/components/shared/icons";
|
||||||
|
|
||||||
|
interface ChartData {
|
||||||
|
time: string;
|
||||||
|
count: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RealtimeChartProps {
|
||||||
|
className?: string;
|
||||||
|
chartData: ChartData[];
|
||||||
|
totalClicks: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const RealtimeChart = ({
|
||||||
|
className,
|
||||||
|
chartData,
|
||||||
|
totalClicks,
|
||||||
|
}: RealtimeChartProps) => {
|
||||||
|
const t = useTranslations("Components");
|
||||||
|
const getTickInterval = (dataLength: number) => {
|
||||||
|
if (dataLength <= 6) return 0;
|
||||||
|
if (dataLength <= 12) return 1;
|
||||||
|
if (dataLength <= 24) return Math.ceil(dataLength / 8);
|
||||||
|
return Math.ceil(dataLength / 6);
|
||||||
|
};
|
||||||
|
|
||||||
|
const filteredChartData = chartData.filter((item, index) => {
|
||||||
|
return item.count !== 0 || index === chartData.length - 1;
|
||||||
|
});
|
||||||
|
const tickInterval = getTickInterval(filteredChartData.length);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={cn(`rounded-lg border p-3 backdrop-blur-2xl`, className)}>
|
||||||
|
<div className="mb-1 flex items-center text-base font-semibold">
|
||||||
|
<StatusDot status={1} />
|
||||||
|
<h3 className="ml-2">{t("Realtime Visits")}</h3>
|
||||||
|
<Icons.mousePointerClick className="ml-auto size-4 text-muted-foreground" />
|
||||||
|
</div>
|
||||||
|
<p className="mb-2 text-lg font-semibold">{totalClicks}</p>
|
||||||
|
<BarChart
|
||||||
|
width={300}
|
||||||
|
height={200}
|
||||||
|
data={filteredChartData}
|
||||||
|
margin={{ top: 10, right: 0, left: -20, bottom: 0 }}
|
||||||
|
barCategoryGap={1}
|
||||||
|
>
|
||||||
|
<XAxis
|
||||||
|
dataKey="time"
|
||||||
|
tick={{ fontSize: 12 }}
|
||||||
|
interval={tickInterval}
|
||||||
|
tickCount={Math.min(filteredChartData.length, 10)}
|
||||||
|
axisLine={false}
|
||||||
|
tickLine={false}
|
||||||
|
type="category"
|
||||||
|
scale="point"
|
||||||
|
padding={{ left: 14, right: 20 }}
|
||||||
|
tickFormatter={(value) =>
|
||||||
|
value.split(" ")[1] ? value.split(" ")[1] : value
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<YAxis
|
||||||
|
domain={[0, "dataMax"]}
|
||||||
|
tickCount={5}
|
||||||
|
tick={{ fontSize: 12 }}
|
||||||
|
axisLine={false}
|
||||||
|
tickLine={false}
|
||||||
|
/>
|
||||||
|
<Tooltip
|
||||||
|
content={({ active, payload, label }) => {
|
||||||
|
if (active && payload && payload.length) {
|
||||||
|
return (
|
||||||
|
<div className="rounded-md border border-primary-foreground bg-primary py-2 text-primary-foreground backdrop-blur">
|
||||||
|
<p className="label px-2 text-base font-medium">{`${label}`}</p>
|
||||||
|
<p className="label px-2 text-sm">{`Visits: ${payload[0].value}`}</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<Bar
|
||||||
|
dataKey="count"
|
||||||
|
fill="#2d9af9"
|
||||||
|
radius={[1, 1, 0, 0]}
|
||||||
|
maxBarSize={40}
|
||||||
|
/>
|
||||||
|
</BarChart>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
314
app/(protected)/dashboard/urls/globe/realtime-globe.tsx
Normal file
314
app/(protected)/dashboard/urls/globe/realtime-globe.tsx
Normal file
@@ -0,0 +1,314 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useCallback, useEffect, useRef, useState } from "react";
|
||||||
|
import { useElementSize } from "@mantine/hooks";
|
||||||
|
import { scaleSequentialSqrt } from "d3-scale";
|
||||||
|
import { interpolateTurbo } from "d3-scale-chromatic";
|
||||||
|
import { GlobeInstance } from "globe.gl";
|
||||||
|
import { debounce } from "lodash-es";
|
||||||
|
import { useTheme } from "next-themes";
|
||||||
|
|
||||||
|
import { Location } from "./index";
|
||||||
|
|
||||||
|
interface GlobeProps {
|
||||||
|
time: {
|
||||||
|
startAt: number;
|
||||||
|
endAt: number;
|
||||||
|
};
|
||||||
|
filters: Record<string, any>;
|
||||||
|
locations: Location[];
|
||||||
|
stats: {
|
||||||
|
totalClicks: number;
|
||||||
|
uniqueLocations: number;
|
||||||
|
rawRecords: number;
|
||||||
|
lastFetch: string;
|
||||||
|
};
|
||||||
|
setHandleTrafficEvent: (
|
||||||
|
fn: (lat: number, lng: number, city: string) => void,
|
||||||
|
) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function RealtimeGlobe({
|
||||||
|
time,
|
||||||
|
filters,
|
||||||
|
locations,
|
||||||
|
stats,
|
||||||
|
}: GlobeProps) {
|
||||||
|
const { theme } = useTheme();
|
||||||
|
const globeRef = useRef<HTMLDivElement>(null);
|
||||||
|
const globeInstanceRef = useRef<any>(null);
|
||||||
|
const mountedRef = useRef(true);
|
||||||
|
let globe: GlobeInstance;
|
||||||
|
const [countries, setCountries] = useState<any>({});
|
||||||
|
const [currentLocation, setCurrentLocation] = useState<any>({});
|
||||||
|
const [hexAltitude, setHexAltitude] = useState(0.001);
|
||||||
|
const { ref: wrapperRef, width: wrapperWidth } = useElementSize();
|
||||||
|
const [isLoaded, setIsLoaded] = useState(false);
|
||||||
|
|
||||||
|
const highest =
|
||||||
|
locations.reduce((acc, curr) => Math.max(acc, curr.count), 0) || 1;
|
||||||
|
const weightColor = scaleSequentialSqrt(interpolateTurbo).domain([
|
||||||
|
0,
|
||||||
|
highest * 15,
|
||||||
|
]);
|
||||||
|
|
||||||
|
const loadGlobe = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
const GlobeModule = await import("globe.gl");
|
||||||
|
const Globe = GlobeModule.default;
|
||||||
|
const { MeshPhongMaterial } = await import("three");
|
||||||
|
return { Globe, MeshPhongMaterial };
|
||||||
|
} catch (err) {
|
||||||
|
// console.error("Failed to load Globe.gl:", err);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const getGlobeJSON = async () => {
|
||||||
|
try {
|
||||||
|
const response = await fetch("/countries.geojson");
|
||||||
|
const data = await response.json();
|
||||||
|
if (mountedRef.current) {
|
||||||
|
setCountries(data);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching globe JSON:", error);
|
||||||
|
if (mountedRef.current) {
|
||||||
|
setCountries({ type: "FeatureCollection", features: [] });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const getCurrentLocation = async () => {
|
||||||
|
try {
|
||||||
|
const response = await fetch("/api/location");
|
||||||
|
const data = await response.json();
|
||||||
|
if (mountedRef.current) {
|
||||||
|
setCurrentLocation(data);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching current location:", error);
|
||||||
|
if (mountedRef.current) {
|
||||||
|
setCurrentLocation({ latitude: 0, longitude: 0 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const initGlobe = useCallback(async () => {
|
||||||
|
if (
|
||||||
|
!globeRef.current ||
|
||||||
|
!countries.features ||
|
||||||
|
globeInstanceRef.current ||
|
||||||
|
!mountedRef.current
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const modules = await loadGlobe();
|
||||||
|
if (!modules || !mountedRef.current) return;
|
||||||
|
|
||||||
|
const { Globe, MeshPhongMaterial } = modules;
|
||||||
|
|
||||||
|
const container = globeRef.current;
|
||||||
|
if (!container) return;
|
||||||
|
|
||||||
|
container.innerHTML = "";
|
||||||
|
|
||||||
|
const rect = container.getBoundingClientRect();
|
||||||
|
|
||||||
|
if (rect.width === 0 || rect.height === 0) {
|
||||||
|
setTimeout(initGlobe, 200);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
globe = new Globe(container)
|
||||||
|
.width(wrapperWidth)
|
||||||
|
.height(wrapperWidth > 728 ? wrapperWidth * 0.9 : wrapperWidth)
|
||||||
|
.globeOffset([0, -80])
|
||||||
|
.atmosphereColor("rgba(170, 170, 200, 0.7)")
|
||||||
|
.backgroundColor("rgba(0,0,0,0)")
|
||||||
|
.globeMaterial(
|
||||||
|
new MeshPhongMaterial({
|
||||||
|
color: theme === "dark" ? "rgb(65, 65, 65)" : "rgb(228, 228, 231)",
|
||||||
|
transparent: false,
|
||||||
|
opacity: 1,
|
||||||
|
}) as any,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (countries.features && countries.features.length > 0) {
|
||||||
|
globe
|
||||||
|
.hexPolygonsData(countries.features)
|
||||||
|
.hexPolygonResolution(3)
|
||||||
|
.hexPolygonMargin(0.2)
|
||||||
|
.hexPolygonAltitude(() => hexAltitude)
|
||||||
|
.hexPolygonColor(
|
||||||
|
() => `rgba(45, 154, 249, ${Math.random() / 1.5 + 0.5})`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
globe
|
||||||
|
.hexBinResolution(4)
|
||||||
|
.hexBinPointsData(locations)
|
||||||
|
.hexBinMerge(true)
|
||||||
|
.hexBinPointWeight("count")
|
||||||
|
.hexTopColor((d: any) => {
|
||||||
|
const intensity = d.sumWeight || 0;
|
||||||
|
return weightColor(intensity);
|
||||||
|
})
|
||||||
|
.hexSideColor((d: any) => {
|
||||||
|
const intensity = d.sumWeight || 0;
|
||||||
|
return weightColor(intensity * 0.8);
|
||||||
|
})
|
||||||
|
.hexAltitude((d: any) => {
|
||||||
|
const intensity = d.sumWeight || 0;
|
||||||
|
return Math.max(0.01, intensity * 0.8);
|
||||||
|
});
|
||||||
|
|
||||||
|
globe.onGlobeReady(() => {
|
||||||
|
if (!mountedRef.current) return;
|
||||||
|
|
||||||
|
const lat = currentLocation.latitude || 0;
|
||||||
|
const lng = currentLocation.longitude || 0;
|
||||||
|
|
||||||
|
globe.pointOfView({
|
||||||
|
lat: lat,
|
||||||
|
lng: lng,
|
||||||
|
altitude: rect.width > 768 ? 2.5 : 3.5,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (globe.controls()) {
|
||||||
|
globe.controls().autoRotate = true;
|
||||||
|
globe.controls().autoRotateSpeed = 0.5;
|
||||||
|
globe.controls().enableDamping = true;
|
||||||
|
globe.controls().dampingFactor = 0.1;
|
||||||
|
}
|
||||||
|
|
||||||
|
setIsLoaded(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
if (globe.controls()) {
|
||||||
|
globe.controls().addEventListener(
|
||||||
|
"end",
|
||||||
|
debounce(() => {
|
||||||
|
if (!mountedRef.current || !globeInstanceRef.current) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const distance = Math.round(globe.controls().getDistance());
|
||||||
|
let nextAlt = 0.005;
|
||||||
|
if (distance <= 300) nextAlt = 0.001;
|
||||||
|
else if (distance >= 600) nextAlt = 0.02;
|
||||||
|
|
||||||
|
if (nextAlt !== hexAltitude) {
|
||||||
|
setHexAltitude(nextAlt);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.warn("Error in controls event:", err);
|
||||||
|
}
|
||||||
|
}, 200),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
globeInstanceRef.current = globe;
|
||||||
|
} catch (err) {}
|
||||||
|
}, [
|
||||||
|
countries,
|
||||||
|
locations,
|
||||||
|
currentLocation,
|
||||||
|
hexAltitude,
|
||||||
|
loadGlobe,
|
||||||
|
weightColor,
|
||||||
|
]);
|
||||||
|
|
||||||
|
const cleanup = useCallback(() => {
|
||||||
|
if (globeInstanceRef.current) {
|
||||||
|
try {
|
||||||
|
if (typeof globeInstanceRef.current._destructor === "function") {
|
||||||
|
globeInstanceRef.current._destructor();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (globeRef.current) {
|
||||||
|
globeRef.current.innerHTML = "";
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.warn("Error during cleanup:", err);
|
||||||
|
}
|
||||||
|
globeInstanceRef.current = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
setIsLoaded(false);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// useEffect(() => {
|
||||||
|
// if (globeInstanceRef.current) {
|
||||||
|
// globeInstanceRef.current.width(wrapperWidth);
|
||||||
|
// globeInstanceRef.current.height(
|
||||||
|
// wrapperWidth > 728 ? wrapperWidth * 0.8 : wrapperWidth,
|
||||||
|
// );
|
||||||
|
// }
|
||||||
|
// }, [globeInstanceRef.current, wrapperWidth, wrapperHeight]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (
|
||||||
|
globeInstanceRef.current &&
|
||||||
|
mountedRef.current &&
|
||||||
|
locations.length > 0
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
globeInstanceRef.current.hexBinPointsData(locations);
|
||||||
|
} catch (err) {
|
||||||
|
console.warn("Error updating locations:", err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [locations]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const initializeData = async () => {
|
||||||
|
if (!mountedRef.current) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await Promise.all([getCurrentLocation(), getGlobeJSON()]);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error initializing data:", error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
initializeData();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (
|
||||||
|
countries.features &&
|
||||||
|
currentLocation &&
|
||||||
|
!globeInstanceRef.current &&
|
||||||
|
mountedRef.current
|
||||||
|
) {
|
||||||
|
const timer = setTimeout(initGlobe, 100);
|
||||||
|
return () => clearTimeout(timer);
|
||||||
|
}
|
||||||
|
}, [countries, currentLocation, initGlobe]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
mountedRef.current = true;
|
||||||
|
return () => {
|
||||||
|
mountedRef.current = false;
|
||||||
|
cleanup();
|
||||||
|
};
|
||||||
|
}, [cleanup]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
ref={wrapperRef}
|
||||||
|
className="relative -mt-8 max-h-screen overflow-hidden"
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
ref={globeRef}
|
||||||
|
className="flex justify-center"
|
||||||
|
style={{
|
||||||
|
maxWidth: `${wrapperWidth}px`, // 比较疑惑
|
||||||
|
minHeight: "100px",
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
127
app/(protected)/dashboard/urls/globe/realtime-logs.tsx
Normal file
127
app/(protected)/dashboard/urls/globe/realtime-logs.tsx
Normal file
@@ -0,0 +1,127 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import Link from "next/link";
|
||||||
|
import { AnimatePresence, motion } from "framer-motion";
|
||||||
|
import ReactCountryFlag from "react-country-flag";
|
||||||
|
|
||||||
|
import { formatTime } from "@/lib/utils";
|
||||||
|
|
||||||
|
import { Location } from "./index";
|
||||||
|
|
||||||
|
const RealtimeLogs = ({
|
||||||
|
className,
|
||||||
|
locations,
|
||||||
|
}: {
|
||||||
|
className?: string;
|
||||||
|
locations: Location[];
|
||||||
|
}) => {
|
||||||
|
const [displayedLocations, setDisplayedLocations] = useState<Location[]>([]);
|
||||||
|
const [pendingLocations, setPendingLocations] = useState<Location[]>([]);
|
||||||
|
|
||||||
|
// 生成唯一标识用于去重
|
||||||
|
const generateUniqueKey = (loc: Location): string => {
|
||||||
|
return `${loc.userUrl?.url || ""}-${loc.userUrl?.target || ""}-${loc.userUrl?.prefix || ""}-${loc.country || ""}-${loc.city || ""}-${loc.browser || ""}-${loc.device || ""}-${loc.updatedAt?.toString() || ""}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 当外部 locations 更新时,更新预备列表
|
||||||
|
useEffect(() => {
|
||||||
|
const sortedLocations = [...locations].sort((a, b) => {
|
||||||
|
const timeA = new Date(a.updatedAt?.toString() || "").getTime() || 0;
|
||||||
|
const timeB = new Date(b.updatedAt?.toString() || "").getTime() || 0;
|
||||||
|
return timeA - timeB;
|
||||||
|
});
|
||||||
|
|
||||||
|
setPendingLocations((prev) => {
|
||||||
|
// 去重:基于多个字段判断
|
||||||
|
const newLocations = sortedLocations.filter(
|
||||||
|
(loc) =>
|
||||||
|
!prev.some((p) => generateUniqueKey(p) === generateUniqueKey(loc)) &&
|
||||||
|
!displayedLocations.some(
|
||||||
|
(d) => generateUniqueKey(d) === generateUniqueKey(loc),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
return [...prev, ...newLocations];
|
||||||
|
});
|
||||||
|
}, [locations]);
|
||||||
|
|
||||||
|
// 每 2 秒从预备列表插入一条数据到显示列表
|
||||||
|
useEffect(() => {
|
||||||
|
if (pendingLocations.length === 0) return;
|
||||||
|
|
||||||
|
const interval = setInterval(() => {
|
||||||
|
setDisplayedLocations((prev) => {
|
||||||
|
if (pendingLocations.length > 0) {
|
||||||
|
const newLocation = pendingLocations[0];
|
||||||
|
// 插入新数据到顶部,限制显示列表最多 8 条
|
||||||
|
const newDisplayed = [newLocation, ...prev].slice(0, 8);
|
||||||
|
// 从预备列表移除已插入的数据
|
||||||
|
setPendingLocations((pending) => pending.slice(1));
|
||||||
|
return newDisplayed;
|
||||||
|
}
|
||||||
|
return prev;
|
||||||
|
});
|
||||||
|
}, 1500);
|
||||||
|
|
||||||
|
return () => clearInterval(interval);
|
||||||
|
}, [pendingLocations]);
|
||||||
|
|
||||||
|
// 动画配置
|
||||||
|
const itemVariants = {
|
||||||
|
initial: { opacity: 0, scale: 0.1, x: "25%", y: "25%" }, // 从中心缩放
|
||||||
|
animate: { opacity: 1, scale: 1, x: 0, y: 0 },
|
||||||
|
// exit: { opacity: 0, transition: { duration: 0.3 } }, // 渐出
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={`flex-1 overflow-y-auto ${className}`}
|
||||||
|
style={{ minHeight: "200px", maxHeight: "80vh" }}
|
||||||
|
>
|
||||||
|
<AnimatePresence initial={false}>
|
||||||
|
{displayedLocations.length > 0 &&
|
||||||
|
displayedLocations.map((loc) => (
|
||||||
|
<motion.div
|
||||||
|
key={generateUniqueKey(loc)}
|
||||||
|
variants={itemVariants}
|
||||||
|
initial="initial"
|
||||||
|
animate="animate"
|
||||||
|
exit="exit"
|
||||||
|
transition={{ duration: 0.2 }}
|
||||||
|
className="mb-2 flex w-full items-center justify-start gap-3 rounded-lg border p-3 text-xs shadow-inner backdrop-blur-xl sm:w-60"
|
||||||
|
>
|
||||||
|
<ReactCountryFlag
|
||||||
|
style={{ fontSize: "16px" }}
|
||||||
|
countryCode={loc.country || "US"}
|
||||||
|
/>
|
||||||
|
<div>
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<Link
|
||||||
|
className="text-sm font-semibold"
|
||||||
|
href={`https://${loc.userUrl?.prefix}/s/${loc.userUrl?.url}`}
|
||||||
|
target="_blank"
|
||||||
|
>
|
||||||
|
{loc.userUrl?.url}
|
||||||
|
</Link>
|
||||||
|
<span className="font-semibold">·</span>
|
||||||
|
<span className="text-muted-foreground">
|
||||||
|
{formatTime(loc.updatedAt?.toString() || "")}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{loc.browser && loc.browser !== "Unknown" && (
|
||||||
|
<div className="mt-1 line-clamp-1 break-words font-medium text-muted-foreground">
|
||||||
|
{loc.browser}
|
||||||
|
{loc.device &&
|
||||||
|
loc.device !== "Unknown" &&
|
||||||
|
`${", "}${loc.device}`}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</motion.div>
|
||||||
|
))}
|
||||||
|
</AnimatePresence>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default RealtimeLogs;
|
||||||
@@ -3,6 +3,7 @@
|
|||||||
import { useEffect, useRef, useState } from "react";
|
import { useEffect, useRef, useState } from "react";
|
||||||
import { AnimatePresence, motion } from "framer-motion";
|
import { AnimatePresence, motion } from "framer-motion";
|
||||||
import { RefreshCwIcon } from "lucide-react";
|
import { RefreshCwIcon } from "lucide-react";
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
import { useTheme } from "next-themes";
|
import { useTheme } from "next-themes";
|
||||||
import useSWR, { useSWRConfig } from "swr";
|
import useSWR, { useSWRConfig } from "swr";
|
||||||
|
|
||||||
@@ -24,7 +25,6 @@ import {
|
|||||||
SelectTrigger,
|
SelectTrigger,
|
||||||
SelectValue,
|
SelectValue,
|
||||||
} from "@/components/ui/select";
|
} from "@/components/ui/select";
|
||||||
import { Skeleton } from "@/components/ui/skeleton";
|
|
||||||
import {
|
import {
|
||||||
Table,
|
Table,
|
||||||
TableBody,
|
TableBody,
|
||||||
@@ -47,7 +47,7 @@ export interface LogEntry {
|
|||||||
isNew?: boolean; // New property to track newly added logs
|
isNew?: boolean; // New property to track newly added logs
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function LiveLog({ admin }: { admin: boolean }) {
|
export default function LiveLog({ admin = false }: { admin?: boolean }) {
|
||||||
const { theme } = useTheme();
|
const { theme } = useTheme();
|
||||||
const { mutate } = useSWRConfig();
|
const { mutate } = useSWRConfig();
|
||||||
const [isLive, setIsLive] = useState(false);
|
const [isLive, setIsLive] = useState(false);
|
||||||
@@ -55,6 +55,8 @@ export default function LiveLog({ admin }: { admin: boolean }) {
|
|||||||
const [limitDiplay, setLimitDisplay] = useState(100);
|
const [limitDiplay, setLimitDisplay] = useState(100);
|
||||||
const newLogsRef = useRef<Set<string>>(new Set()); // Track new log keys
|
const newLogsRef = useRef<Set<string>>(new Set()); // Track new log keys
|
||||||
|
|
||||||
|
const t = useTranslations("Components");
|
||||||
|
|
||||||
const {
|
const {
|
||||||
data: newLogs,
|
data: newLogs,
|
||||||
error,
|
error,
|
||||||
@@ -152,10 +154,10 @@ export default function LiveLog({ admin }: { admin: boolean }) {
|
|||||||
<div className="flex items-center justify-between gap-2">
|
<div className="flex items-center justify-between gap-2">
|
||||||
<div>
|
<div>
|
||||||
<CardTitle className="text-base text-gray-800 dark:text-gray-100">
|
<CardTitle className="text-base text-gray-800 dark:text-gray-100">
|
||||||
Live Log
|
{t("Live Logs")}
|
||||||
</CardTitle>
|
</CardTitle>
|
||||||
<CardDescription>
|
<CardDescription>
|
||||||
Real-time logs of short link visits.
|
{t("Real-time logs of short link visits")}.
|
||||||
</CardDescription>
|
</CardDescription>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -163,11 +165,12 @@ export default function LiveLog({ admin }: { admin: boolean }) {
|
|||||||
onClick={toggleLive}
|
onClick={toggleLive}
|
||||||
variant={"outline"}
|
variant={"outline"}
|
||||||
size="sm"
|
size="sm"
|
||||||
className={`ml-auto gap-2 bg-primary-foreground transition-colors hover:border-blue-600 hover:text-blue-600 ${
|
className={`ml-auto gap-2 text-nowrap bg-primary-foreground transition-colors hover:border-blue-600 hover:text-blue-600 ${
|
||||||
isLive ? "border-dashed border-blue-600 text-blue-500" : ""
|
isLive ? "border-dashed border-blue-600 text-blue-500" : ""
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
<Icons.CirclePlay className="h-4 w-4" /> {isLive ? "Stop" : "Live"}
|
<Icons.CirclePlay className="h-4 w-4" />{" "}
|
||||||
|
{isLive ? t("Stop") : t("Live")}
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
className="bg-primary-foreground"
|
className="bg-primary-foreground"
|
||||||
@@ -201,19 +204,30 @@ export default function LiveLog({ admin }: { admin: boolean }) {
|
|||||||
{error ? (
|
{error ? (
|
||||||
<div className="text-center text-red-500">{error.message}</div>
|
<div className="text-center text-red-500">{error.message}</div>
|
||||||
) : logs.length === 0 && !newLogs ? (
|
) : logs.length === 0 && !newLogs ? (
|
||||||
// <Skeleton className="h-8 w-full" />
|
|
||||||
<></>
|
<></>
|
||||||
) : (
|
) : (
|
||||||
<div className="scrollbar-hidden h-96 overflow-y-auto bg-primary-foreground">
|
<div className="scrollbar-hidden h-96 overflow-y-auto bg-primary-foreground">
|
||||||
<Table>
|
<Table>
|
||||||
<TableHeader>
|
<TableHeader>
|
||||||
<TableRow className="bg-gray-100/50 text-sm dark:bg-primary-foreground">
|
<TableRow className="grid grid-cols-5 bg-gray-100/50 text-sm dark:bg-primary-foreground sm:grid-cols-9">
|
||||||
<TableHead className="h-8 w-1/6 px-1">Time</TableHead>
|
<TableHead className="col-span-2 flex h-8 items-center">
|
||||||
<TableHead className="h-8 w-1/12 px-1">Slug</TableHead>
|
{t("Time")}
|
||||||
<TableHead className="h-8 px-1">Target</TableHead>
|
</TableHead>
|
||||||
<TableHead className="h-8 w-1/12 px-1">IP</TableHead>
|
<TableHead className="col-span-1 flex h-8 items-center">
|
||||||
<TableHead className="h-8 w-1/6 px-1">Location</TableHead>
|
{t("Slug")}
|
||||||
<TableHead className="h-8 w-1/12 px-1">Clicks</TableHead>
|
</TableHead>
|
||||||
|
<TableHead className="col-span-3 hidden h-8 items-center sm:flex">
|
||||||
|
{t("Target")}
|
||||||
|
</TableHead>
|
||||||
|
<TableHead className="col-span-1 hidden h-8 items-center sm:flex">
|
||||||
|
IP
|
||||||
|
</TableHead>
|
||||||
|
<TableHead className="col-span-1 flex h-8 items-center">
|
||||||
|
{t("Location")}
|
||||||
|
</TableHead>
|
||||||
|
<TableHead className="col-span-1 flex h-8 items-center">
|
||||||
|
{t("Clicks")}
|
||||||
|
</TableHead>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
</TableHeader>
|
</TableHeader>
|
||||||
<TableBody>
|
<TableBody>
|
||||||
@@ -235,23 +249,24 @@ export default function LiveLog({ admin }: { admin: boolean }) {
|
|||||||
ease: "linear",
|
ease: "linear",
|
||||||
},
|
},
|
||||||
}}
|
}}
|
||||||
className="font-mono text-xs hover:bg-gray-200 dark:border-gray-800"
|
className="grid grid-cols-5 font-mono text-xs hover:bg-gray-200 dark:border-gray-800 sm:grid-cols-9"
|
||||||
>
|
>
|
||||||
<TableCell className="whitespace-nowrap px-1 py-1.5">
|
<TableCell className="col-span-2 truncate py-1.5">
|
||||||
{new Date(log.updatedAt).toLocaleString()}
|
{new Date(log.updatedAt).toLocaleString()}
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell className="font-midium px-1 py-1.5 text-green-700">
|
<TableCell className="font-midium col-span-1 truncate py-1.5 text-green-700">
|
||||||
{log.slug}
|
{log.slug}
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell className="max-w-10 truncate px-1 py-1.5 hover:underline">
|
<TableCell className="col-span-3 hidden max-w-full truncate py-1.5 hover:underline sm:flex">
|
||||||
<a href={log.target} target="_blank" title={log.target}>
|
<a href={log.target} target="_blank" title={log.target}>
|
||||||
{log.target}
|
{log.target}
|
||||||
</a>
|
</a>
|
||||||
</TableCell>
|
</TableCell>
|
||||||
|
<TableCell className="col-span-1 hidden truncate py-1.5 sm:flex">
|
||||||
<TableCell className="px-1 py-1.5">{log.ip}</TableCell>
|
{log.ip}
|
||||||
|
</TableCell>
|
||||||
<TableCell
|
<TableCell
|
||||||
className="max-w-6 truncate px-1 py-1.5"
|
className="col-span-1 truncate py-1.5"
|
||||||
title={getCountryName(log.country || "")}
|
title={getCountryName(log.country || "")}
|
||||||
>
|
>
|
||||||
{decodeURIComponent(
|
{decodeURIComponent(
|
||||||
@@ -260,7 +275,7 @@ export default function LiveLog({ admin }: { admin: boolean }) {
|
|||||||
: "-",
|
: "-",
|
||||||
)}
|
)}
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell className="px-1 py-1.5 text-green-700">
|
<TableCell className="col-span-1 py-1.5 text-green-700">
|
||||||
{log.click}
|
{log.click}
|
||||||
</TableCell>
|
</TableCell>
|
||||||
</motion.tr>
|
</motion.tr>
|
||||||
@@ -272,7 +287,7 @@ export default function LiveLog({ admin }: { admin: boolean }) {
|
|||||||
)}
|
)}
|
||||||
{isLive && (
|
{isLive && (
|
||||||
<div className="flex w-full items-center justify-end gap-2 border-t border-dashed pt-4 text-sm text-gray-500">
|
<div className="flex w-full items-center justify-end gap-2 border-t border-dashed pt-4 text-sm text-gray-500">
|
||||||
<p>{logs.length}</p> of
|
<p>{logs.length}</p> {t("of")}
|
||||||
<Select
|
<Select
|
||||||
onValueChange={(value: string) => {
|
onValueChange={(value: string) => {
|
||||||
setLimitDisplay(Number(value));
|
setLimitDisplay(Number(value));
|
||||||
@@ -291,7 +306,7 @@ export default function LiveLog({ admin }: { admin: boolean }) {
|
|||||||
))}
|
))}
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
<p>total logs</p>
|
<p>{t("total logs")}</p>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</CardContent>
|
</CardContent>
|
||||||
|
|||||||
@@ -5,8 +5,8 @@ export default function DashboardUrlsLoading() {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<DashboardHeader
|
<DashboardHeader
|
||||||
heading="Manage Short URLs"
|
heading="Manage Short URLs"
|
||||||
text="List and manage short urls."
|
text="List and manage short urls"
|
||||||
/>
|
/>
|
||||||
<Skeleton className="h-32 w-full rounded-lg" />
|
<Skeleton className="h-32 w-full rounded-lg" />
|
||||||
<Skeleton className="h-[400px] w-full rounded-lg" />
|
<Skeleton className="h-[400px] w-full rounded-lg" />
|
||||||
|
|||||||
@@ -7,12 +7,21 @@ import { UrlMeta, User } from "@prisma/client";
|
|||||||
import { VisSingleContainer, VisTooltip, VisTopoJSONMap } from "@unovis/react";
|
import { VisSingleContainer, VisTooltip, VisTopoJSONMap } from "@unovis/react";
|
||||||
import { TopoJSONMap } from "@unovis/ts";
|
import { TopoJSONMap } from "@unovis/ts";
|
||||||
import { WorldMapTopoJSON } from "@unovis/ts/maps";
|
import { WorldMapTopoJSON } from "@unovis/ts/maps";
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
import { Area, AreaChart, CartesianGrid, XAxis, YAxis } from "recharts";
|
import { Area, AreaChart, CartesianGrid, XAxis, YAxis } from "recharts";
|
||||||
|
import useSWR from "swr";
|
||||||
|
|
||||||
import { TeamPlanQuota } from "@/config/team";
|
import {
|
||||||
import { getCountryName, getDeviceVendor } from "@/lib/contries";
|
getBotName,
|
||||||
|
getCountryName,
|
||||||
|
getDeviceVendor,
|
||||||
|
getEngineName,
|
||||||
|
getLanguageName,
|
||||||
|
getRegionName,
|
||||||
|
} from "@/lib/contries";
|
||||||
import { DATE_DIMENSION_ENUMS } from "@/lib/enums";
|
import { DATE_DIMENSION_ENUMS } from "@/lib/enums";
|
||||||
import { isLink, removeUrlSuffix, timeAgo } from "@/lib/utils";
|
import { fetcher, isLink, removeUrlSuffix } from "@/lib/utils";
|
||||||
|
import { useElementSize } from "@/hooks/use-element-size";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import {
|
import {
|
||||||
Card,
|
Card,
|
||||||
@@ -30,10 +39,13 @@ import {
|
|||||||
Select,
|
Select,
|
||||||
SelectContent,
|
SelectContent,
|
||||||
SelectItem,
|
SelectItem,
|
||||||
|
SelectSeparator,
|
||||||
SelectTrigger,
|
SelectTrigger,
|
||||||
SelectValue,
|
SelectValue,
|
||||||
} from "@/components/ui/select";
|
} from "@/components/ui/select";
|
||||||
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||||
import { Icons } from "@/components/shared/icons";
|
import { Icons } from "@/components/shared/icons";
|
||||||
|
import { TimeAgoIntl } from "@/components/shared/time-ago";
|
||||||
|
|
||||||
const chartConfig = {
|
const chartConfig = {
|
||||||
pv: {
|
pv: {
|
||||||
@@ -116,6 +128,14 @@ function generateStatsList(
|
|||||||
? getCountryName(rawValue as string) // 国家代码转为国家名称
|
? getCountryName(rawValue as string) // 国家代码转为国家名称
|
||||||
: dimension === "device"
|
: dimension === "device"
|
||||||
? getDeviceVendor(rawValue as string) // 设备型号转为厂商名称
|
? getDeviceVendor(rawValue as string) // 设备型号转为厂商名称
|
||||||
|
: dimension === "engine"
|
||||||
|
? getEngineName(rawValue as string) // 引擎名称
|
||||||
|
: dimension === "region"
|
||||||
|
? getRegionName(rawValue as string) // 区域名称
|
||||||
|
: dimension === "lang"
|
||||||
|
? getLanguageName(rawValue as string) // 语言名称
|
||||||
|
: dimension === "isBot"
|
||||||
|
? getBotName(rawValue as boolean) // 是否为机器人
|
||||||
: rawValue; // 其他维度直接使用原始值
|
: rawValue; // 其他维度直接使用原始值
|
||||||
|
|
||||||
const click = record.click || 0; // 确保 click 是数字,默认 0 如果未定义
|
const click = record.click || 0; // 确保 click 是数字,默认 0 如果未定义
|
||||||
@@ -153,20 +173,26 @@ export function DailyPVUVChart({
|
|||||||
setTimeRange: React.Dispatch<React.SetStateAction<string>>;
|
setTimeRange: React.Dispatch<React.SetStateAction<string>>;
|
||||||
user: Pick<User, "id" | "name" | "team">;
|
user: Pick<User, "id" | "name" | "team">;
|
||||||
}) {
|
}) {
|
||||||
|
const { ref: wrapperRef, width: wrapperWidth } = useElementSize();
|
||||||
const [activeChart, setActiveChart] =
|
const [activeChart, setActiveChart] =
|
||||||
React.useState<keyof typeof chartConfig>("pv");
|
React.useState<keyof typeof chartConfig>("pv");
|
||||||
|
|
||||||
|
const t = useTranslations("Components");
|
||||||
|
|
||||||
|
const { data: plan } = useSWR<{ slAnalyticsRetention: number }>(
|
||||||
|
`/api/plan?team=${user.team}`,
|
||||||
|
fetcher,
|
||||||
|
);
|
||||||
|
|
||||||
const processedData = processUrlMeta(data).map((entry) => ({
|
const processedData = processUrlMeta(data).map((entry) => ({
|
||||||
date: entry.date,
|
date: entry.date,
|
||||||
pv: entry.clicks,
|
pv: entry.clicks,
|
||||||
uv: new Set(entry.ips).size,
|
uv: new Set(entry.ips).size,
|
||||||
}));
|
}));
|
||||||
// .sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime());
|
|
||||||
|
|
||||||
const dataTotal = calculateUVAndPV(data);
|
const dataTotal = calculateUVAndPV(data);
|
||||||
|
|
||||||
const latestEntry = data[data.length - 1];
|
const latestEntry = data[data.length - 1];
|
||||||
const latestDate = timeAgo(latestEntry.updatedAt);
|
|
||||||
const latestFrom = [
|
const latestFrom = [
|
||||||
latestEntry.city ? decodeURIComponent(latestEntry.city) : "",
|
latestEntry.city ? decodeURIComponent(latestEntry.city) : "",
|
||||||
latestEntry.country ? `(${getCountryName(latestEntry.country)})` : "",
|
latestEntry.country ? `(${getCountryName(latestEntry.country)})` : "",
|
||||||
@@ -213,17 +239,27 @@ export function DailyPVUVChart({
|
|||||||
const deviceStats = generateStatsList(data, "device");
|
const deviceStats = generateStatsList(data, "device");
|
||||||
const browserStats = generateStatsList(data, "browser");
|
const browserStats = generateStatsList(data, "browser");
|
||||||
const countryStats = generateStatsList(data, "country");
|
const countryStats = generateStatsList(data, "country");
|
||||||
|
const osStats = generateStatsList(data, "os");
|
||||||
|
const cpuStats = generateStatsList(data, "cpu");
|
||||||
|
const engineStats = generateStatsList(data, "engine");
|
||||||
|
const languageStats = generateStatsList(data, "lang");
|
||||||
|
const regionStats = generateStatsList(data, "region");
|
||||||
|
const isBotStats = generateStatsList(data, "isBot");
|
||||||
|
|
||||||
|
const lastVisitorInfo = t.rich("last-visitor-info", {
|
||||||
|
location: latestFrom,
|
||||||
|
timeAgo: () => <TimeAgoIntl date={latestEntry.updatedAt} />,
|
||||||
|
});
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card className="rounded-t-none border-t-0">
|
<Card>
|
||||||
<CardHeader className="flex flex-col items-stretch space-y-0 border-b p-0 sm:flex-row">
|
<CardHeader className="flex flex-col items-stretch space-y-0 border-b p-0 sm:flex-row">
|
||||||
<div className="flex flex-1 flex-col justify-center gap-1 px-6 py-2 sm:py-3">
|
<div className="flex flex-1 flex-col justify-center gap-1 px-6 py-2 sm:py-3">
|
||||||
<CardTitle>Link Analytics</CardTitle>
|
<CardTitle>{t("Link Analytics")}</CardTitle>
|
||||||
<CardDescription>
|
<CardDescription>{lastVisitorInfo}</CardDescription>
|
||||||
Last visitor from {latestFrom} about {latestDate}.
|
|
||||||
</CardDescription>
|
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center">
|
<div className="flex items-center">
|
||||||
|
{plan && (
|
||||||
<Select
|
<Select
|
||||||
onValueChange={(value: string) => {
|
onValueChange={(value: string) => {
|
||||||
setTimeRange(value);
|
setTimeRange(value);
|
||||||
@@ -231,29 +267,31 @@ export function DailyPVUVChart({
|
|||||||
name="time range"
|
name="time range"
|
||||||
defaultValue={timeRange}
|
defaultValue={timeRange}
|
||||||
>
|
>
|
||||||
<SelectTrigger className="mx-4 w-full shadow-inner">
|
<SelectTrigger className="mx-4 w-full min-w-28 shadow-inner">
|
||||||
<SelectValue placeholder="Select a time" />
|
<SelectValue placeholder="Select a time" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
{DATE_DIMENSION_ENUMS.map((e) => (
|
{DATE_DIMENSION_ENUMS.map((e, i) => (
|
||||||
|
<div key={e.value}>
|
||||||
<SelectItem
|
<SelectItem
|
||||||
disabled={
|
disabled={e.key > plan.slAnalyticsRetention}
|
||||||
e.key > TeamPlanQuota[user.team!].SL_AnalyticsRetention
|
|
||||||
}
|
|
||||||
key={e.value}
|
|
||||||
value={e.value}
|
value={e.value}
|
||||||
>
|
>
|
||||||
<span className="flex items-center gap-1">
|
<span className="flex items-center gap-1">
|
||||||
{e.label}
|
{t(e.label)}
|
||||||
{e.key >
|
{e.key > plan.slAnalyticsRetention && (
|
||||||
TeamPlanQuota[user.team!].SL_AnalyticsRetention && (
|
|
||||||
<Icons.crown className="size-3" />
|
<Icons.crown className="size-3" />
|
||||||
)}
|
)}
|
||||||
</span>
|
</span>
|
||||||
</SelectItem>
|
</SelectItem>
|
||||||
|
{i % 2 === 0 && i !== DATE_DIMENSION_ENUMS.length - 1 && (
|
||||||
|
<SelectSeparator />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
))}
|
))}
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
|
)}
|
||||||
{["pv", "uv"].map((key) => {
|
{["pv", "uv"].map((key) => {
|
||||||
const chart = key as keyof typeof chartConfig;
|
const chart = key as keyof typeof chartConfig;
|
||||||
return (
|
return (
|
||||||
@@ -263,8 +301,8 @@ export function DailyPVUVChart({
|
|||||||
className="relative z-30 flex flex-1 flex-col items-center justify-center gap-1 border-t px-6 py-2 text-left even:border-l data-[active=true]:bg-muted/50 sm:border-l sm:border-t-0 sm:px-8 sm:py-3"
|
className="relative z-30 flex flex-1 flex-col items-center justify-center gap-1 border-t px-6 py-2 text-left even:border-l data-[active=true]:bg-muted/50 sm:border-l sm:border-t-0 sm:px-8 sm:py-3"
|
||||||
onClick={() => setActiveChart(chart)}
|
onClick={() => setActiveChart(chart)}
|
||||||
>
|
>
|
||||||
<span className="text-sm font-semibold text-muted-foreground">
|
<span className="text-nowrap text-sm font-semibold text-muted-foreground">
|
||||||
{chartConfig[chart].label}
|
{t(chartConfig[chart].label)}
|
||||||
</span>
|
</span>
|
||||||
<span className="text-lg font-bold leading-none">
|
<span className="text-lg font-bold leading-none">
|
||||||
{dataTotal[key as keyof typeof dataTotal].toLocaleString()}
|
{dataTotal[key as keyof typeof dataTotal].toLocaleString()}
|
||||||
@@ -274,7 +312,7 @@ export function DailyPVUVChart({
|
|||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="px-2 sm:p-6">
|
<CardContent className="px-2 sm:p-6" ref={wrapperRef}>
|
||||||
<ChartContainer
|
<ChartContainer
|
||||||
config={chartConfig}
|
config={chartConfig}
|
||||||
className="aspect-auto h-[225px] w-full"
|
className="aspect-auto h-[225px] w-full"
|
||||||
@@ -346,9 +384,6 @@ export function DailyPVUVChart({
|
|||||||
/>
|
/>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
{/* <Bar dataKey="uv" fill={`var(--color-uv)`} stackId="a" />
|
|
||||||
<Bar dataKey="pv" fill={`var(--color-pv)`} stackId="a" /> */}
|
|
||||||
|
|
||||||
<Area
|
<Area
|
||||||
type="monotone"
|
type="monotone"
|
||||||
dataKey="uv"
|
dataKey="uv"
|
||||||
@@ -366,31 +401,103 @@ export function DailyPVUVChart({
|
|||||||
</AreaChart>
|
</AreaChart>
|
||||||
</ChartContainer>
|
</ChartContainer>
|
||||||
|
|
||||||
<VisSingleContainer data={{ areas: areaData }}>
|
<VisSingleContainer
|
||||||
<VisTopoJSONMap
|
data={{ areas: areaData }}
|
||||||
topojson={WorldMapTopoJSON}
|
width={wrapperWidth * 0.99}
|
||||||
// pointRadius={1.6}
|
>
|
||||||
// mapFitToPoints={true}
|
<VisTopoJSONMap topojson={WorldMapTopoJSON} />
|
||||||
/>
|
|
||||||
<VisTooltip triggers={triggers} />
|
<VisTooltip triggers={triggers} />
|
||||||
</VisSingleContainer>
|
</VisSingleContainer>
|
||||||
|
|
||||||
<div className="my-5 grid grid-cols-1 gap-6 sm:grid-cols-2">
|
<div className="my-5 grid grid-cols-1 gap-6 sm:grid-cols-2">
|
||||||
|
{/* Referrers、isBotStats */}
|
||||||
|
<Tabs defaultValue="referrer">
|
||||||
|
<TabsList>
|
||||||
|
<TabsTrigger value="referrer">{t("Referrers")}</TabsTrigger>
|
||||||
|
<TabsTrigger value="isBot">{t("Traffic Type")}</TabsTrigger>
|
||||||
|
</TabsList>
|
||||||
|
<TabsContent className="h-[calc(100%-40px)]" value="referrer">
|
||||||
{refererStats.length > 0 && (
|
{refererStats.length > 0 && (
|
||||||
<StatsList data={refererStats} title="Referrers" />
|
<StatsList data={refererStats} title="Referrers" />
|
||||||
)}
|
)}
|
||||||
|
</TabsContent>
|
||||||
|
<TabsContent className="h-[calc(100%-40px)]" value="isBot">
|
||||||
|
{isBotStats.length > 0 && (
|
||||||
|
<StatsList data={isBotStats} title="Is Bot" />
|
||||||
|
)}
|
||||||
|
</TabsContent>
|
||||||
|
</Tabs>
|
||||||
|
{/* 国家、城市 */}
|
||||||
|
<Tabs defaultValue="country">
|
||||||
|
<TabsList>
|
||||||
|
<TabsTrigger value="country">{t("Country")}</TabsTrigger>
|
||||||
|
<TabsTrigger value="city">{t("City")}</TabsTrigger>
|
||||||
|
</TabsList>
|
||||||
|
<TabsContent className="h-[calc(100%-40px)]" value="country">
|
||||||
{countryStats.length > 0 && (
|
{countryStats.length > 0 && (
|
||||||
<StatsList data={countryStats} title="Countries" />
|
<StatsList data={countryStats} title="Countries" />
|
||||||
)}
|
)}
|
||||||
|
</TabsContent>
|
||||||
|
<TabsContent className="h-[calc(100%-40px)]" value="city">
|
||||||
{cityStats.length > 0 && (
|
{cityStats.length > 0 && (
|
||||||
<StatsList data={cityStats} title="Cities" />
|
<StatsList data={cityStats} title="Cities" />
|
||||||
)}
|
)}
|
||||||
|
</TabsContent>
|
||||||
|
</Tabs>
|
||||||
|
{/* browserStats、engineStats */}
|
||||||
|
<Tabs defaultValue="browser">
|
||||||
|
<TabsList>
|
||||||
|
<TabsTrigger value="browser">{t("Browser")}</TabsTrigger>
|
||||||
|
<TabsTrigger value="engine">{t("Engine")}</TabsTrigger>
|
||||||
|
</TabsList>
|
||||||
|
<TabsContent className="h-[calc(100%-40px)]" value="browser">
|
||||||
{browserStats.length > 0 && (
|
{browserStats.length > 0 && (
|
||||||
<StatsList data={browserStats} title="Browsers" />
|
<StatsList data={browserStats} title="Browsers" />
|
||||||
)}
|
)}
|
||||||
|
</TabsContent>
|
||||||
|
<TabsContent className="h-[calc(100%-40px)]" value="engine">
|
||||||
|
{engineStats.length > 0 && (
|
||||||
|
<StatsList data={engineStats} title="Engines" />
|
||||||
|
)}
|
||||||
|
</TabsContent>
|
||||||
|
</Tabs>
|
||||||
|
|
||||||
|
{/* Languages、regionStats */}
|
||||||
|
<Tabs className="h-full" defaultValue="language">
|
||||||
|
<TabsList>
|
||||||
|
<TabsTrigger value="language">{t("Language")}</TabsTrigger>
|
||||||
|
<TabsTrigger value="region">{t("Region")}</TabsTrigger>
|
||||||
|
</TabsList>
|
||||||
|
<TabsContent className="h-[calc(100%-40px)]" value="language">
|
||||||
|
{languageStats.length > 0 && (
|
||||||
|
<StatsList data={languageStats} title="Languages" />
|
||||||
|
)}
|
||||||
|
</TabsContent>
|
||||||
|
<TabsContent className="h-[calc(100%-40px)]" value="region">
|
||||||
|
{regionStats.length > 0 && (
|
||||||
|
<StatsList data={regionStats} title="Regions" />
|
||||||
|
)}
|
||||||
|
</TabsContent>
|
||||||
|
</Tabs>
|
||||||
|
{/* deviceStats、osStats、cpuStats */}
|
||||||
|
<Tabs defaultValue="device">
|
||||||
|
<TabsList>
|
||||||
|
<TabsTrigger value="device">{t("Device")}</TabsTrigger>
|
||||||
|
<TabsTrigger value="os">{t("OS")}</TabsTrigger>
|
||||||
|
<TabsTrigger value="cpu">CPU</TabsTrigger>
|
||||||
|
</TabsList>
|
||||||
|
<TabsContent className="h-[calc(100%-40px)]" value="device">
|
||||||
{deviceStats.length > 0 && (
|
{deviceStats.length > 0 && (
|
||||||
<StatsList data={deviceStats} title="Devices" />
|
<StatsList data={deviceStats} title="Devices" />
|
||||||
)}
|
)}
|
||||||
|
</TabsContent>
|
||||||
|
<TabsContent className="h-[calc(100%-40px)]" value="os">
|
||||||
|
{osStats.length > 0 && <StatsList data={osStats} title="OS" />}
|
||||||
|
</TabsContent>
|
||||||
|
<TabsContent className="h-[calc(100%-40px)]" value="cpu">
|
||||||
|
{cpuStats.length > 0 && <StatsList data={cpuStats} title="CPU" />}
|
||||||
|
</TabsContent>
|
||||||
|
</Tabs>
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
@@ -400,14 +507,17 @@ export function DailyPVUVChart({
|
|||||||
export function StatsList({ data, title }: { data: Stat[]; title: string }) {
|
export function StatsList({ data, title }: { data: Stat[]; title: string }) {
|
||||||
const [showAll, setShowAll] = useState(false);
|
const [showAll, setShowAll] = useState(false);
|
||||||
const displayedData = showAll ? data.slice(0, 50) : data.slice(0, 8);
|
const displayedData = showAll ? data.slice(0, 50) : data.slice(0, 8);
|
||||||
|
const t = useTranslations("Components");
|
||||||
return (
|
return (
|
||||||
<div className="rounded-lg border p-4">
|
<div className="h-full rounded-lg border">
|
||||||
<h1 className="text-lg font-bold">{title}</h1>
|
<div className="flex items-center justify-between border-b px-5 py-2 text-xs font-medium text-muted-foreground">
|
||||||
|
<span>{t("Name")}</span>
|
||||||
|
<span className="">{t("Visitors")}</span>
|
||||||
|
</div>
|
||||||
<div
|
<div
|
||||||
className={`scrollbar-hidden overflow-hidden overflow-y-auto transition-all duration-500 ease-in-out`}
|
className={`scrollbar-hidden overflow-hidden overflow-y-auto px-4 pb-4 pt-2 transition-all duration-500 ease-in-out`}
|
||||||
style={{
|
style={{
|
||||||
maxHeight: "18rem", // 动态计算最大高度
|
maxHeight: "18rem",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{displayedData.map((ref) => (
|
{displayedData.map((ref) => (
|
||||||
@@ -449,7 +559,7 @@ export function StatsList({ data, title }: { data: Stat[]; title: string }) {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{data.length > 8 && (
|
{data.length > 8 && (
|
||||||
<div className="mt-3 text-center">
|
<div className="mb-3 mt-1 text-center">
|
||||||
<Button
|
<Button
|
||||||
variant={"outline"}
|
variant={"outline"}
|
||||||
onClick={() => setShowAll(!showAll)}
|
onClick={() => setShowAll(!showAll)}
|
||||||
|
|||||||
@@ -2,15 +2,16 @@
|
|||||||
|
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { UrlMeta, User } from "@prisma/client";
|
import { UrlMeta, User } from "@prisma/client";
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
import useSWR from "swr";
|
import useSWR from "swr";
|
||||||
|
|
||||||
import { TeamPlanQuota } from "@/config/team";
|
|
||||||
import { DATE_DIMENSION_ENUMS } from "@/lib/enums";
|
import { DATE_DIMENSION_ENUMS } from "@/lib/enums";
|
||||||
import { fetcher } from "@/lib/utils";
|
import { fetcher } from "@/lib/utils";
|
||||||
import {
|
import {
|
||||||
Select,
|
Select,
|
||||||
SelectContent,
|
SelectContent,
|
||||||
SelectItem,
|
SelectItem,
|
||||||
|
SelectSeparator,
|
||||||
SelectTrigger,
|
SelectTrigger,
|
||||||
SelectValue,
|
SelectValue,
|
||||||
} from "@/components/ui/select";
|
} from "@/components/ui/select";
|
||||||
@@ -27,6 +28,7 @@ export interface UrlMetaProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function UserUrlMetaInfo({ user, action, urlId }: UrlMetaProps) {
|
export default function UserUrlMetaInfo({ user, action, urlId }: UrlMetaProps) {
|
||||||
|
const t = useTranslations("Components");
|
||||||
const [timeRange, setTimeRange] = useState<string>("24h");
|
const [timeRange, setTimeRange] = useState<string>("24h");
|
||||||
const { data, isLoading } = useSWR<UrlMeta[]>(
|
const { data, isLoading } = useSWR<UrlMeta[]>(
|
||||||
`${action}?id=${urlId}&range=${timeRange}`,
|
`${action}?id=${urlId}&range=${timeRange}`,
|
||||||
@@ -34,19 +36,30 @@ export default function UserUrlMetaInfo({ user, action, urlId }: UrlMetaProps) {
|
|||||||
{ focusThrottleInterval: 30000 }, // 30 seconds,
|
{ focusThrottleInterval: 30000 }, // 30 seconds,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const { data: plan } = useSWR<{ slAnalyticsRetention: number }>(
|
||||||
|
`/api/plan?team=${user.team}`,
|
||||||
|
fetcher,
|
||||||
|
);
|
||||||
|
|
||||||
if (isLoading)
|
if (isLoading)
|
||||||
return (
|
return (
|
||||||
<div className="space-y-2 p-2">
|
<div className="space-y-2">
|
||||||
<Skeleton className="h-40 w-full" />
|
<Skeleton className="h-[400px] w-full" />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|
||||||
if (!data || data.length === 0) {
|
if (!data || data.length === 0) {
|
||||||
return (
|
return (
|
||||||
<EmptyPlaceholder>
|
<EmptyPlaceholder className="shadow-none">
|
||||||
<EmptyPlaceholder.Title>No Visits</EmptyPlaceholder.Title>
|
<EmptyPlaceholder.Title>{t("No Visits")}</EmptyPlaceholder.Title>
|
||||||
<EmptyPlaceholder.Description>
|
<EmptyPlaceholder.Description>
|
||||||
You don't have any visits yet in last {timeRange}.
|
{t("You don't have any visits yet in")}{" "}
|
||||||
|
{t(
|
||||||
|
DATE_DIMENSION_ENUMS.find((e) => e.value === timeRange)?.label ||
|
||||||
|
"",
|
||||||
|
)}
|
||||||
|
.
|
||||||
|
{plan && (
|
||||||
<Select
|
<Select
|
||||||
onValueChange={(value: string) => {
|
onValueChange={(value: string) => {
|
||||||
setTimeRange(value);
|
setTimeRange(value);
|
||||||
@@ -58,26 +71,27 @@ export default function UserUrlMetaInfo({ user, action, urlId }: UrlMetaProps) {
|
|||||||
<SelectValue placeholder="Select a time" />
|
<SelectValue placeholder="Select a time" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
{DATE_DIMENSION_ENUMS.map((e) => (
|
{DATE_DIMENSION_ENUMS.map((e, i) => (
|
||||||
|
<div key={e.value}>
|
||||||
<SelectItem
|
<SelectItem
|
||||||
className=""
|
disabled={e.key > plan.slAnalyticsRetention}
|
||||||
disabled={
|
|
||||||
e.key > TeamPlanQuota[user.team!].SL_AnalyticsRetention
|
|
||||||
}
|
|
||||||
key={e.value}
|
|
||||||
value={e.value}
|
value={e.value}
|
||||||
>
|
>
|
||||||
<span className="flex items-center gap-1">
|
<span className="flex items-center gap-1">
|
||||||
{e.label}
|
{t(e.label)}
|
||||||
{e.key >
|
{e.key > plan.slAnalyticsRetention && (
|
||||||
TeamPlanQuota[user.team!].SL_AnalyticsRetention && (
|
|
||||||
<Icons.crown className="size-3" />
|
<Icons.crown className="size-3" />
|
||||||
)}
|
)}
|
||||||
</span>
|
</span>
|
||||||
</SelectItem>
|
</SelectItem>
|
||||||
|
{i % 2 === 0 && i !== DATE_DIMENSION_ENUMS.length - 1 && (
|
||||||
|
<SelectSeparator />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
))}
|
))}
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
|
)}
|
||||||
</EmptyPlaceholder.Description>
|
</EmptyPlaceholder.Description>
|
||||||
</EmptyPlaceholder>
|
</EmptyPlaceholder>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -4,12 +4,10 @@ import { getCurrentUser } from "@/lib/session";
|
|||||||
import { constructMetadata } from "@/lib/utils";
|
import { constructMetadata } from "@/lib/utils";
|
||||||
import { DashboardHeader } from "@/components/dashboard/header";
|
import { DashboardHeader } from "@/components/dashboard/header";
|
||||||
|
|
||||||
import ApiReference from "../../../../components/shared/api-reference";
|
|
||||||
import LiveLog from "./live-logs";
|
|
||||||
import UserUrlsList from "./url-list";
|
import UserUrlsList from "./url-list";
|
||||||
|
|
||||||
export const metadata = constructMetadata({
|
export const metadata = constructMetadata({
|
||||||
title: "Short URLs - WR.DO",
|
title: "Short URLs",
|
||||||
description: "List and manage records.",
|
description: "List and manage records.",
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -21,10 +19,10 @@ export default async function DashboardPage() {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<DashboardHeader
|
<DashboardHeader
|
||||||
heading="Manage Short URLs"
|
heading="Manage Short URLs"
|
||||||
text="List and manage short urls."
|
text="List and manage short urls"
|
||||||
link="/docs/short-urls"
|
link="/docs/short-urls"
|
||||||
linkText="short urls."
|
linkText="short urls"
|
||||||
/>
|
/>
|
||||||
<UserUrlsList
|
<UserUrlsList
|
||||||
user={{
|
user={{
|
||||||
@@ -36,12 +34,6 @@ export default async function DashboardPage() {
|
|||||||
}}
|
}}
|
||||||
action="/api/url"
|
action="/api/url"
|
||||||
/>
|
/>
|
||||||
<LiveLog admin={false} />
|
|
||||||
<ApiReference
|
|
||||||
badge="POST /api/v1/short"
|
|
||||||
target="creating short urls"
|
|
||||||
link="/docs/short-urls#api-reference"
|
|
||||||
/>
|
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState } from "react";
|
import { useEffect, useMemo, useState, useTransition } from "react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
|
import { usePathname } from "next/navigation";
|
||||||
import { User } from "@prisma/client";
|
import { User } from "@prisma/client";
|
||||||
import { PenLine, RefreshCwIcon } from "lucide-react";
|
import { PenLine, RefreshCwIcon } from "lucide-react";
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import useSWR, { useSWRConfig } from "swr";
|
import useSWR, { useSWRConfig } from "swr";
|
||||||
|
|
||||||
@@ -11,20 +13,23 @@ import { ShortUrlFormData } from "@/lib/dto/short-urls";
|
|||||||
import {
|
import {
|
||||||
cn,
|
cn,
|
||||||
expirationTime,
|
expirationTime,
|
||||||
|
extractHostname,
|
||||||
fetcher,
|
fetcher,
|
||||||
|
nFormatter,
|
||||||
removeUrlSuffix,
|
removeUrlSuffix,
|
||||||
timeAgo,
|
|
||||||
} from "@/lib/utils";
|
} from "@/lib/utils";
|
||||||
|
import { useMediaQuery } from "@/hooks/use-media-query";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import {
|
import {
|
||||||
Card,
|
DropdownMenu,
|
||||||
CardContent,
|
DropdownMenuContent,
|
||||||
CardDescription,
|
DropdownMenuItem,
|
||||||
CardHeader,
|
DropdownMenuSeparator,
|
||||||
CardTitle,
|
DropdownMenuTrigger,
|
||||||
} from "@/components/ui/card";
|
} from "@/components/ui/dropdown-menu";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { Modal } from "@/components/ui/modal";
|
import { Modal } from "@/components/ui/modal";
|
||||||
|
import { Separator } from "@/components/ui/separator";
|
||||||
import { Skeleton } from "@/components/ui/skeleton";
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
import { Switch } from "@/components/ui/switch";
|
import { Switch } from "@/components/ui/switch";
|
||||||
import {
|
import {
|
||||||
@@ -35,6 +40,7 @@ import {
|
|||||||
TableHeader,
|
TableHeader,
|
||||||
TableRow,
|
TableRow,
|
||||||
} from "@/components/ui/table";
|
} from "@/components/ui/table";
|
||||||
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||||
import {
|
import {
|
||||||
Tooltip,
|
Tooltip,
|
||||||
TooltipContent,
|
TooltipContent,
|
||||||
@@ -43,16 +49,18 @@ import {
|
|||||||
} from "@/components/ui/tooltip";
|
} from "@/components/ui/tooltip";
|
||||||
import { FormType } from "@/components/forms/record-form";
|
import { FormType } from "@/components/forms/record-form";
|
||||||
import { UrlForm } from "@/components/forms/url-form";
|
import { UrlForm } from "@/components/forms/url-form";
|
||||||
|
import ApiReference from "@/components/shared/api-reference";
|
||||||
|
import BlurImage from "@/components/shared/blur-image";
|
||||||
import { CopyButton } from "@/components/shared/copy-button";
|
import { CopyButton } from "@/components/shared/copy-button";
|
||||||
import { EmptyPlaceholder } from "@/components/shared/empty-placeholder";
|
import { EmptyPlaceholder } from "@/components/shared/empty-placeholder";
|
||||||
import { Icons } from "@/components/shared/icons";
|
import { Icons } from "@/components/shared/icons";
|
||||||
import {
|
import { LinkInfoPreviewer } from "@/components/shared/link-previewer";
|
||||||
LinkInfoPreviewer,
|
|
||||||
LinkPreviewer,
|
|
||||||
} from "@/components/shared/link-previewer";
|
|
||||||
import { PaginationWrapper } from "@/components/shared/pagination";
|
import { PaginationWrapper } from "@/components/shared/pagination";
|
||||||
import QRCodeEditor from "@/components/shared/qr";
|
import QRCodeEditor from "@/components/shared/qr";
|
||||||
|
import { TimeAgoIntl } from "@/components/shared/time-ago";
|
||||||
|
|
||||||
|
import Globe from "./globe";
|
||||||
|
import LiveLog from "./live-logs";
|
||||||
import UserUrlMetaInfo from "./meta";
|
import UserUrlMetaInfo from "./meta";
|
||||||
|
|
||||||
export interface UrlListProps {
|
export interface UrlListProps {
|
||||||
@@ -92,6 +100,10 @@ function TableColumnSekleton() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function UserUrlsList({ user, action }: UrlListProps) {
|
export default function UserUrlsList({ user, action }: UrlListProps) {
|
||||||
|
const pathname = usePathname();
|
||||||
|
const { isMobile } = useMediaQuery();
|
||||||
|
const t = useTranslations("List");
|
||||||
|
const [currentView, setCurrentView] = useState<string>("List");
|
||||||
const [isShowForm, setShowForm] = useState(false);
|
const [isShowForm, setShowForm] = useState(false);
|
||||||
const [formType, setFormType] = useState<FormType>("add");
|
const [formType, setFormType] = useState<FormType>("add");
|
||||||
const [currentEditUrl, setCurrentEditUrl] = useState<ShortUrlFormData | null>(
|
const [currentEditUrl, setCurrentEditUrl] = useState<ShortUrlFormData | null>(
|
||||||
@@ -107,6 +119,10 @@ export default function UserUrlsList({ user, action }: UrlListProps) {
|
|||||||
target: "",
|
target: "",
|
||||||
userName: "",
|
userName: "",
|
||||||
});
|
});
|
||||||
|
const [isPending, startTransition] = useTransition();
|
||||||
|
const [currentListClickData, setCurrentListClickData] = useState<
|
||||||
|
Record<string, number>
|
||||||
|
>({});
|
||||||
|
|
||||||
const { mutate } = useSWRConfig();
|
const { mutate } = useSWRConfig();
|
||||||
const { data, isLoading } = useSWR<{
|
const { data, isLoading } = useSWR<{
|
||||||
@@ -120,6 +136,29 @@ export default function UserUrlsList({ user, action }: UrlListProps) {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const currentListIds = useMemo(() => {
|
||||||
|
return data?.list?.map((item) => item.id ?? "") ?? [];
|
||||||
|
}, [data?.list]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
handleGetUrlClicks();
|
||||||
|
}, [currentListIds]);
|
||||||
|
|
||||||
|
const handleGetUrlClicks = async () => {
|
||||||
|
startTransition(async () => {
|
||||||
|
if (currentListIds.length > 0 && currentView !== "Realtime") {
|
||||||
|
const res = await fetch(action, {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({ ids: currentListIds }),
|
||||||
|
});
|
||||||
|
if (res.ok) {
|
||||||
|
const data = await res.json();
|
||||||
|
setCurrentListClickData(data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
const handleRefresh = () => {
|
const handleRefresh = () => {
|
||||||
mutate(
|
mutate(
|
||||||
`${action}?page=${currentPage}&size=${pageSize}&slug=${searchParams.slug}&userName=${searchParams.userName}&target=${searchParams.target}`,
|
`${action}?page=${currentPage}&size=${pageSize}&slug=${searchParams.slug}&userName=${searchParams.userName}&target=${searchParams.target}`,
|
||||||
@@ -145,50 +184,22 @@ export default function UserUrlsList({ user, action }: UrlListProps) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
const rendeEmpty = () => (
|
||||||
<>
|
<EmptyPlaceholder className="col-span-full shadow-none">
|
||||||
<Card className="xl:col-span-2">
|
<EmptyPlaceholder.Icon name="link" />
|
||||||
<CardHeader className="flex flex-row items-center">
|
<EmptyPlaceholder.Title>{t("No urls")}</EmptyPlaceholder.Title>
|
||||||
{action.includes("/admin") ? (
|
<EmptyPlaceholder.Description>
|
||||||
<CardDescription className="text-balance text-lg font-bold">
|
You don't have any url yet. Start creating url.
|
||||||
<span>Total URLs:</span>{" "}
|
</EmptyPlaceholder.Description>
|
||||||
<span className="font-bold">{data && data.total}</span>
|
</EmptyPlaceholder>
|
||||||
</CardDescription>
|
);
|
||||||
) : (
|
|
||||||
<CardTitle>Short URLs</CardTitle>
|
const rendeSeachInputs = () => (
|
||||||
)}
|
|
||||||
<div className="ml-auto flex items-center justify-end gap-3">
|
|
||||||
<Button
|
|
||||||
variant={"outline"}
|
|
||||||
onClick={() => handleRefresh()}
|
|
||||||
disabled={isLoading}
|
|
||||||
>
|
|
||||||
{isLoading ? (
|
|
||||||
<RefreshCwIcon className="size-4 animate-spin" />
|
|
||||||
) : (
|
|
||||||
<RefreshCwIcon className="size-4" />
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
className="w-[120px] shrink-0 gap-1"
|
|
||||||
variant="default"
|
|
||||||
onClick={() => {
|
|
||||||
setCurrentEditUrl(null);
|
|
||||||
setShowForm(false);
|
|
||||||
setFormType("add");
|
|
||||||
setShowForm(!isShowForm);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
Add URL
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
<div className="mb-2 flex-row items-center gap-2 space-y-2 sm:flex sm:space-y-0">
|
<div className="mb-2 flex-row items-center gap-2 space-y-2 sm:flex sm:space-y-0">
|
||||||
<div className="relative w-full">
|
<div className="relative w-full">
|
||||||
<Input
|
<Input
|
||||||
className="h-8 text-xs md:text-xs"
|
className="h-8 text-xs md:text-xs"
|
||||||
placeholder="Search by slug..."
|
placeholder={t("Search by slug") + "..."}
|
||||||
value={searchParams.slug}
|
value={searchParams.slug}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
setSearchParams({
|
setSearchParams({
|
||||||
@@ -211,7 +222,7 @@ export default function UserUrlsList({ user, action }: UrlListProps) {
|
|||||||
<div className="relative w-full">
|
<div className="relative w-full">
|
||||||
<Input
|
<Input
|
||||||
className="h-8 text-xs md:text-xs"
|
className="h-8 text-xs md:text-xs"
|
||||||
placeholder="Search by target..."
|
placeholder={t("Search by target") + "..."}
|
||||||
value={searchParams.target}
|
value={searchParams.target}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
setSearchParams({
|
setSearchParams({
|
||||||
@@ -223,9 +234,7 @@ export default function UserUrlsList({ user, action }: UrlListProps) {
|
|||||||
{searchParams.target && (
|
{searchParams.target && (
|
||||||
<Button
|
<Button
|
||||||
className="absolute right-2 top-1/2 h-6 -translate-y-1/2 rounded-full px-1 text-gray-500 hover:text-gray-700"
|
className="absolute right-2 top-1/2 h-6 -translate-y-1/2 rounded-full px-1 text-gray-500 hover:text-gray-700"
|
||||||
onClick={() =>
|
onClick={() => setSearchParams({ ...searchParams, target: "" })}
|
||||||
setSearchParams({ ...searchParams, target: "" })
|
|
||||||
}
|
|
||||||
variant={"ghost"}
|
variant={"ghost"}
|
||||||
>
|
>
|
||||||
<Icons.close className="size-3" />
|
<Icons.close className="size-3" />
|
||||||
@@ -237,7 +246,7 @@ export default function UserUrlsList({ user, action }: UrlListProps) {
|
|||||||
<div className="relative w-full">
|
<div className="relative w-full">
|
||||||
<Input
|
<Input
|
||||||
className="h-8 text-xs md:text-xs"
|
className="h-8 text-xs md:text-xs"
|
||||||
placeholder="Search by user name..."
|
placeholder={t("Search by username") + "..."}
|
||||||
value={searchParams.userName}
|
value={searchParams.userName}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
setSearchParams({
|
setSearchParams({
|
||||||
@@ -249,9 +258,7 @@ export default function UserUrlsList({ user, action }: UrlListProps) {
|
|||||||
{searchParams.userName && (
|
{searchParams.userName && (
|
||||||
<Button
|
<Button
|
||||||
className="absolute right-2 top-1/2 h-6 -translate-y-1/2 rounded-full px-1 text-gray-500 hover:text-gray-700"
|
className="absolute right-2 top-1/2 h-6 -translate-y-1/2 rounded-full px-1 text-gray-500 hover:text-gray-700"
|
||||||
onClick={() =>
|
onClick={() => setSearchParams({ ...searchParams, userName: "" })}
|
||||||
setSearchParams({ ...searchParams, userName: "" })
|
|
||||||
}
|
|
||||||
variant={"ghost"}
|
variant={"ghost"}
|
||||||
>
|
>
|
||||||
<Icons.close className="size-3" />
|
<Icons.close className="size-3" />
|
||||||
@@ -260,33 +267,62 @@ export default function UserUrlsList({ user, action }: UrlListProps) {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
const rendeClicks = (short: ShortUrlFormData) => (
|
||||||
|
<>
|
||||||
|
<Icons.mousePointerClick className="size-[14px]" />
|
||||||
|
{isPending ? (
|
||||||
|
<Skeleton className="h-4 w-6 rounded" />
|
||||||
|
) : (
|
||||||
|
<p className="text-xs font-medium text-gray-700 dark:text-gray-50">
|
||||||
|
{(short.id && nFormatter(currentListClickData[short.id], 2)) || "-"}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
|
||||||
|
const rendeStats = (short: ShortUrlFormData) =>
|
||||||
|
isShowStats &&
|
||||||
|
selectedUrl?.id === short.id && (
|
||||||
|
<UserUrlMetaInfo
|
||||||
|
user={{
|
||||||
|
id: user.id,
|
||||||
|
name: user.name || "",
|
||||||
|
team: user.team,
|
||||||
|
}}
|
||||||
|
action="/api/url/meta"
|
||||||
|
urlId={short.id!}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
|
const rendeList = () => (
|
||||||
<Table>
|
<Table>
|
||||||
<TableHeader className="bg-gray-100/50 dark:bg-primary-foreground">
|
<TableHeader className="bg-gray-100/50 dark:bg-primary-foreground">
|
||||||
<TableRow className="grid grid-cols-3 items-center sm:grid-cols-11">
|
<TableRow className="grid grid-cols-3 items-center sm:grid-cols-11">
|
||||||
<TableHead className="col-span-1 flex items-center font-bold sm:col-span-2">
|
<TableHead className="col-span-1 flex items-center font-bold sm:col-span-2">
|
||||||
Slug
|
{t("Slug")}
|
||||||
</TableHead>
|
</TableHead>
|
||||||
<TableHead className="col-span-1 flex items-center font-bold sm:col-span-2">
|
<TableHead className="col-span-1 flex items-center font-bold sm:col-span-2">
|
||||||
Target
|
{t("Target")}
|
||||||
</TableHead>
|
</TableHead>
|
||||||
<TableHead className="col-span-1 hidden items-center font-bold sm:flex">
|
<TableHead className="col-span-1 hidden items-center font-bold sm:flex">
|
||||||
User
|
{t("User")}
|
||||||
</TableHead>
|
</TableHead>
|
||||||
<TableHead className="col-span-1 hidden items-center font-bold sm:flex">
|
<TableHead className="col-span-1 hidden items-center font-bold sm:flex">
|
||||||
Enabled
|
{t("Enabled")}
|
||||||
</TableHead>
|
</TableHead>
|
||||||
<TableHead className="col-span-1 hidden items-center font-bold sm:flex">
|
<TableHead className="col-span-1 hidden items-center font-bold sm:flex">
|
||||||
Expiration
|
{t("Expiration")}
|
||||||
</TableHead>
|
</TableHead>
|
||||||
<TableHead className="col-span-1 hidden items-center font-bold sm:flex">
|
<TableHead className="col-span-1 hidden items-center font-bold sm:flex">
|
||||||
Updated
|
{t("Clicks")}
|
||||||
</TableHead>
|
</TableHead>
|
||||||
<TableHead className="col-span-1 hidden items-center font-bold sm:flex">
|
<TableHead className="col-span-1 hidden items-center font-bold sm:flex">
|
||||||
Created
|
{t("Updated")}
|
||||||
</TableHead>
|
</TableHead>
|
||||||
<TableHead className="col-span-1 flex items-center font-bold sm:col-span-2">
|
<TableHead className="col-span-1 flex items-center font-bold sm:col-span-2">
|
||||||
Actions
|
{t("Actions")}
|
||||||
</TableHead>
|
</TableHead>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
</TableHeader>
|
</TableHeader>
|
||||||
@@ -355,14 +391,16 @@ export default function UserUrlsList({ user, action }: UrlListProps) {
|
|||||||
{expirationTime(short.expiration, short.updatedAt)}
|
{expirationTime(short.expiration, short.updatedAt)}
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell className="col-span-1 hidden truncate sm:flex">
|
<TableCell className="col-span-1 hidden truncate sm:flex">
|
||||||
{timeAgo(short.updatedAt as Date)}
|
<div className="flex items-center gap-1 rounded-lg border bg-gray-50 px-2 py-1 dark:bg-gray-600/50">
|
||||||
|
{rendeClicks(short)}
|
||||||
|
</div>
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell className="col-span-1 hidden truncate sm:flex">
|
<TableCell className="col-span-1 hidden truncate sm:flex">
|
||||||
{timeAgo(short.createdAt as Date)}
|
<TimeAgoIntl date={short.updatedAt as Date} />
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell className="col-span-1 flex items-center gap-1 sm:col-span-2">
|
<TableCell className="col-span-1 flex items-center gap-1 sm:col-span-2">
|
||||||
<Button
|
<Button
|
||||||
className="h-7 px-1 text-xs hover:bg-slate-100 dark:hover:text-primary-foreground"
|
className="h-7 px-1 text-xs hover:bg-slate-100 dark:hover:text-primary-foreground sm:px-1.5"
|
||||||
size="sm"
|
size="sm"
|
||||||
variant={"outline"}
|
variant={"outline"}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
@@ -372,7 +410,7 @@ export default function UserUrlsList({ user, action }: UrlListProps) {
|
|||||||
setShowForm(!isShowForm);
|
setShowForm(!isShowForm);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<p className="hidden sm:block">Edit</p>
|
<p className="hidden text-nowrap sm:block">{t("Edit")}</p>
|
||||||
<PenLine className="mx-0.5 size-4 sm:ml-1 sm:size-3" />
|
<PenLine className="mx-0.5 size-4 sm:ml-1 sm:size-3" />
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
@@ -392,6 +430,7 @@ export default function UserUrlsList({ user, action }: UrlListProps) {
|
|||||||
variant="outline"
|
variant="outline"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
setSelectedUrl(short);
|
setSelectedUrl(short);
|
||||||
|
setCurrentView(short.id!);
|
||||||
if (isShowStats && selectedUrl?.id !== short.id) {
|
if (isShowStats && selectedUrl?.id !== short.id) {
|
||||||
} else {
|
} else {
|
||||||
setShowStats(!isShowStats);
|
setShowStats(!isShowStats);
|
||||||
@@ -402,31 +441,16 @@ export default function UserUrlsList({ user, action }: UrlListProps) {
|
|||||||
</Button>
|
</Button>
|
||||||
</TableCell>
|
</TableCell>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
{isShowStats && selectedUrl?.id === short.id && (
|
{/* {rendeStats(short)} */}
|
||||||
<UserUrlMetaInfo
|
|
||||||
user={{
|
|
||||||
id: user.id,
|
|
||||||
name: user.name || "",
|
|
||||||
team: user.team,
|
|
||||||
}}
|
|
||||||
action="/api/url/meta"
|
|
||||||
urlId={short.id!}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
))
|
))
|
||||||
) : (
|
) : (
|
||||||
<EmptyPlaceholder>
|
rendeEmpty()
|
||||||
<EmptyPlaceholder.Icon name="link" />
|
|
||||||
<EmptyPlaceholder.Title>No urls</EmptyPlaceholder.Title>
|
|
||||||
<EmptyPlaceholder.Description>
|
|
||||||
You don't have any url yet. Start creating url.
|
|
||||||
</EmptyPlaceholder.Description>
|
|
||||||
</EmptyPlaceholder>
|
|
||||||
)}
|
)}
|
||||||
</TableBody>
|
</TableBody>
|
||||||
{data && Math.ceil(data.total / pageSize) > 1 && (
|
{data && Math.ceil(data.total / pageSize) > 1 && (
|
||||||
<PaginationWrapper
|
<PaginationWrapper
|
||||||
|
layout={isMobile ? "right" : "split"}
|
||||||
total={data.total}
|
total={data.total}
|
||||||
currentPage={currentPage}
|
currentPage={currentPage}
|
||||||
setCurrentPage={setCurrentPage}
|
setCurrentPage={setCurrentPage}
|
||||||
@@ -435,8 +459,288 @@ export default function UserUrlsList({ user, action }: UrlListProps) {
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</Table>
|
</Table>
|
||||||
</CardContent>
|
);
|
||||||
</Card>
|
|
||||||
|
const rendeGrid = () => (
|
||||||
|
<>
|
||||||
|
<section className="grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-3">
|
||||||
|
{isLoading ? (
|
||||||
|
<>
|
||||||
|
{[1, 2, 3, 4, 5, 6].map((v) => (
|
||||||
|
<Skeleton key={v} className="h-24 w-full" />
|
||||||
|
))}
|
||||||
|
</>
|
||||||
|
) : data && data.list && data.list.length ? (
|
||||||
|
data.list.map((short) => (
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"h-24 rounded-lg border p-1 shadow-inner dark:bg-neutral-800",
|
||||||
|
)}
|
||||||
|
key={short.id}
|
||||||
|
>
|
||||||
|
<div className="flex h-full flex-col rounded-lg border border-dotted bg-white px-3 py-1.5 backdrop-blur-lg dark:bg-black">
|
||||||
|
<div className="flex items-center justify-between gap-1">
|
||||||
|
<BlurImage
|
||||||
|
src={`https://unavatar.io/${extractHostname(short.target)}?fallback=https://wr.do/logo.png`}
|
||||||
|
alt="logo"
|
||||||
|
width={30}
|
||||||
|
height={30}
|
||||||
|
className="rounded-md"
|
||||||
|
/>
|
||||||
|
<div className="ml-2 mr-auto flex flex-col justify-between truncate">
|
||||||
|
{/* url */}
|
||||||
|
<div className="flex items-center">
|
||||||
|
<Link
|
||||||
|
className="overflow-hidden text-ellipsis whitespace-normal text-sm font-semibold text-slate-600 hover:text-blue-400 hover:underline dark:text-slate-300"
|
||||||
|
href={`https://${short.prefix}/s/${short.url}${short.password ? `?password=${short.password}` : ""}`}
|
||||||
|
target="_blank"
|
||||||
|
prefetch={false}
|
||||||
|
title={short.url}
|
||||||
|
>
|
||||||
|
{short.url}
|
||||||
|
</Link>
|
||||||
|
<CopyButton
|
||||||
|
value={`${short.prefix}/s/${short.url}${short.password ? `?password=${short.password}` : ""}`}
|
||||||
|
className={cn(
|
||||||
|
"size-[25px]",
|
||||||
|
"duration-250 transition-all group-hover:opacity-100",
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
className="duration-250 size-[26px] p-1.5 text-foreground transition-all hover:border hover:text-foreground dark:text-foreground"
|
||||||
|
size="sm"
|
||||||
|
variant="ghost"
|
||||||
|
onClick={() => {
|
||||||
|
setSelectedUrl(short);
|
||||||
|
setShowQrcode(!isShowQrcode);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Icons.qrcode className="size-4" />
|
||||||
|
</Button>
|
||||||
|
{short.password && (
|
||||||
|
<Icons.lock className="size-3 text-neutral-600 dark:text-neutral-400" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* target */}
|
||||||
|
<div className="flex items-center gap-1 overflow-hidden truncate text-sm text-muted-foreground">
|
||||||
|
<Icons.forwardArrow className="size-4 shrink-0 text-gray-400" />
|
||||||
|
<LinkInfoPreviewer
|
||||||
|
apiKey={user.apiKey ?? ""}
|
||||||
|
url={short.target}
|
||||||
|
formatUrl={removeUrlSuffix(short.target)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="ml-2 flex items-center gap-1 rounded-md border bg-gray-50 px-2 py-1 dark:bg-gray-600/50">
|
||||||
|
{rendeClicks(short)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DropdownMenu>
|
||||||
|
<DropdownMenuTrigger asChild>
|
||||||
|
<Button
|
||||||
|
className="size-[25px] p-1.5"
|
||||||
|
size="sm"
|
||||||
|
variant="ghost"
|
||||||
|
>
|
||||||
|
<Icons.moreVertical className="size-4" />
|
||||||
|
</Button>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent>
|
||||||
|
<DropdownMenuItem asChild>
|
||||||
|
<Button
|
||||||
|
className="flex w-full items-center gap-2"
|
||||||
|
size="sm"
|
||||||
|
variant="ghost"
|
||||||
|
onClick={() => {
|
||||||
|
setSelectedUrl(short);
|
||||||
|
setCurrentView(short.id!);
|
||||||
|
if (isShowStats && selectedUrl?.id !== short.id) {
|
||||||
|
} else {
|
||||||
|
setShowStats(!isShowStats);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Icons.lineChart className="size-4" />
|
||||||
|
{t("Analytics")}
|
||||||
|
</Button>
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuSeparator />
|
||||||
|
<DropdownMenuItem asChild>
|
||||||
|
<Button
|
||||||
|
className="flex w-full items-center gap-2"
|
||||||
|
size="sm"
|
||||||
|
variant="ghost"
|
||||||
|
onClick={() => {
|
||||||
|
setCurrentEditUrl(short);
|
||||||
|
setShowForm(false);
|
||||||
|
setFormType("edit");
|
||||||
|
setShowForm(!isShowForm);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<PenLine className="size-4" />
|
||||||
|
{t("Edit URL")}
|
||||||
|
</Button>
|
||||||
|
</DropdownMenuItem>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-auto flex items-center justify-end gap-1.5 text-xs text-muted-foreground">
|
||||||
|
<TooltipProvider>
|
||||||
|
<Tooltip delayDuration={200}>
|
||||||
|
<TooltipTrigger className="truncate">
|
||||||
|
{short.userName ?? "Anonymous"}
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent>
|
||||||
|
{short.userName ?? "Anonymous"}
|
||||||
|
</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
</TooltipProvider>
|
||||||
|
<Separator
|
||||||
|
className="h-4/5"
|
||||||
|
orientation="vertical"
|
||||||
|
></Separator>
|
||||||
|
{short.expiration !== "-1" && (
|
||||||
|
<>
|
||||||
|
<span>
|
||||||
|
Expiration:{" "}
|
||||||
|
{expirationTime(short.expiration, short.updatedAt)}
|
||||||
|
</span>
|
||||||
|
<Separator
|
||||||
|
className="h-4/5"
|
||||||
|
orientation="vertical"
|
||||||
|
></Separator>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
<TimeAgoIntl date={short.updatedAt as Date} />
|
||||||
|
<Switch
|
||||||
|
className="scale-[0.6]"
|
||||||
|
defaultChecked={short.active === 1}
|
||||||
|
onCheckedChange={(value) =>
|
||||||
|
handleChangeStatu(value, short.id || "")
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
) : (
|
||||||
|
rendeEmpty()
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{data && Math.ceil(data.total / pageSize) > 1 && (
|
||||||
|
<PaginationWrapper
|
||||||
|
layout={isMobile ? "right" : "split"}
|
||||||
|
total={data.total}
|
||||||
|
currentPage={currentPage}
|
||||||
|
setCurrentPage={setCurrentPage}
|
||||||
|
pageSize={pageSize}
|
||||||
|
setPageSize={setPageSize}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
|
||||||
|
const rendLogs = () => (
|
||||||
|
<div className="mt-6 space-y-3">
|
||||||
|
{action.indexOf("admin") > -1 ? <LiveLog admin={true} /> : <LiveLog />}
|
||||||
|
<ApiReference
|
||||||
|
badge="POST /api/v1/short"
|
||||||
|
target="creating short urls"
|
||||||
|
link="/docs/short-urls#api-reference"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Tabs
|
||||||
|
className={cn("rounded-lg", pathname === "/dashboard" && "border p-6")}
|
||||||
|
value={currentView}
|
||||||
|
>
|
||||||
|
{/* Tabs */}
|
||||||
|
<div className="mb-4 flex items-center justify-between gap-2">
|
||||||
|
{pathname === "/dashboard" && (
|
||||||
|
<h2 className="mr-3 text-lg font-semibold">{t("Short URLs")}</h2>
|
||||||
|
)}
|
||||||
|
<TabsList>
|
||||||
|
<TabsTrigger onClick={() => setCurrentView("List")} value="List">
|
||||||
|
<Icons.list className="size-4" />
|
||||||
|
{/* List */}
|
||||||
|
</TabsTrigger>
|
||||||
|
<TabsTrigger onClick={() => setCurrentView("Grid")} value="Grid">
|
||||||
|
<Icons.layoutGrid className="size-4" />
|
||||||
|
{/* Grid */}
|
||||||
|
</TabsTrigger>
|
||||||
|
<TabsTrigger
|
||||||
|
onClick={() => setCurrentView("Realtime")}
|
||||||
|
value="Realtime"
|
||||||
|
>
|
||||||
|
<Icons.globe className="size-4 text-blue-500" />
|
||||||
|
{/* Realtime */}
|
||||||
|
</TabsTrigger>
|
||||||
|
{selectedUrl?.id && (
|
||||||
|
<TabsTrigger
|
||||||
|
className="flex items-center gap-1 text-muted-foreground"
|
||||||
|
value={selectedUrl.id}
|
||||||
|
onClick={() => setCurrentView(selectedUrl.id!)}
|
||||||
|
>
|
||||||
|
<Icons.lineChart className="size-4" />
|
||||||
|
{selectedUrl.url}
|
||||||
|
</TabsTrigger>
|
||||||
|
)}
|
||||||
|
</TabsList>
|
||||||
|
{/* <p>Total: {data?.total || 0}</p> */}
|
||||||
|
<div className="ml-auto flex items-center justify-end gap-3">
|
||||||
|
<Button
|
||||||
|
variant={"outline"}
|
||||||
|
onClick={() => handleRefresh()}
|
||||||
|
disabled={isLoading}
|
||||||
|
>
|
||||||
|
{isLoading ? (
|
||||||
|
<RefreshCwIcon className="size-4 animate-spin" />
|
||||||
|
) : (
|
||||||
|
<RefreshCwIcon className="size-4" />
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
className="flex shrink-0 gap-1"
|
||||||
|
variant="default"
|
||||||
|
onClick={() => {
|
||||||
|
setCurrentEditUrl(null);
|
||||||
|
setShowForm(false);
|
||||||
|
setFormType("add");
|
||||||
|
setShowForm(!isShowForm);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Icons.add className="size-4" />
|
||||||
|
<span className="hidden sm:inline">{t("Add URL")}</span>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<TabsContent className="space-y-3" value="List">
|
||||||
|
{rendeSeachInputs()}
|
||||||
|
{rendeList()}
|
||||||
|
{rendLogs()}
|
||||||
|
</TabsContent>
|
||||||
|
<TabsContent className="space-y-3" value="Grid">
|
||||||
|
{rendeSeachInputs()}
|
||||||
|
{rendeGrid()}
|
||||||
|
{rendLogs()}
|
||||||
|
</TabsContent>
|
||||||
|
<TabsContent value="Realtime">
|
||||||
|
{action.indexOf("admin") > -1 ? <Globe isAdmin={true} /> : <Globe />}
|
||||||
|
</TabsContent>
|
||||||
|
{selectedUrl?.id && (
|
||||||
|
<TabsContent value={selectedUrl.id}>
|
||||||
|
{rendeStats(selectedUrl)}
|
||||||
|
</TabsContent>
|
||||||
|
)}
|
||||||
|
</Tabs>
|
||||||
|
|
||||||
{/* QR code editor */}
|
{/* QR code editor */}
|
||||||
<Modal
|
<Modal
|
||||||
|
|||||||
57
app/(protected)/dashboard/urls/wrapper.tsx
Normal file
57
app/(protected)/dashboard/urls/wrapper.tsx
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { User } from "@prisma/client";
|
||||||
|
|
||||||
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||||
|
import ApiReference from "@/components/shared/api-reference";
|
||||||
|
|
||||||
|
import Globe from "./globe";
|
||||||
|
import LiveLog from "./live-logs";
|
||||||
|
import UserUrlsList from "./url-list";
|
||||||
|
|
||||||
|
export function Wrapper({
|
||||||
|
user,
|
||||||
|
}: {
|
||||||
|
user: Pick<User, "id" | "name" | "apiKey" | "role" | "team">;
|
||||||
|
}) {
|
||||||
|
const [tab, setTab] = useState("Links");
|
||||||
|
return (
|
||||||
|
<Tabs
|
||||||
|
value={tab}
|
||||||
|
onChangeCapture={(e) => console.log(e)}
|
||||||
|
defaultValue={tab}
|
||||||
|
>
|
||||||
|
<TabsList>
|
||||||
|
<TabsTrigger value="Links" onClick={() => setTab("Links")}>
|
||||||
|
Links
|
||||||
|
</TabsTrigger>
|
||||||
|
<TabsTrigger value="Realtime" onClick={() => setTab("Realtime")}>
|
||||||
|
Realtime
|
||||||
|
</TabsTrigger>
|
||||||
|
</TabsList>
|
||||||
|
)
|
||||||
|
<TabsContent className="space-y-3" value="Links">
|
||||||
|
<UserUrlsList
|
||||||
|
user={{
|
||||||
|
id: user.id,
|
||||||
|
name: user.name || "",
|
||||||
|
apiKey: user.apiKey || "",
|
||||||
|
role: user.role,
|
||||||
|
team: user.team,
|
||||||
|
}}
|
||||||
|
action="/api/url"
|
||||||
|
/>
|
||||||
|
<LiveLog admin={false} />
|
||||||
|
<ApiReference
|
||||||
|
badge="POST /api/v1/short"
|
||||||
|
target="creating short urls"
|
||||||
|
link="/docs/short-urls#api-reference"
|
||||||
|
/>
|
||||||
|
</TabsContent>
|
||||||
|
<TabsContent value="Realtime">
|
||||||
|
<Globe />
|
||||||
|
</TabsContent>
|
||||||
|
</Tabs>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -8,6 +8,7 @@ import {
|
|||||||
MobileSheetSidebar,
|
MobileSheetSidebar,
|
||||||
} from "@/components/layout/dashboard-sidebar";
|
} from "@/components/layout/dashboard-sidebar";
|
||||||
import { ModeToggle } from "@/components/layout/mode-toggle";
|
import { ModeToggle } from "@/components/layout/mode-toggle";
|
||||||
|
import { Notification } from "@/components/layout/notification";
|
||||||
import { UserAccountNav } from "@/components/layout/user-account-nav";
|
import { UserAccountNav } from "@/components/layout/user-account-nav";
|
||||||
import MaxWidthWrapper from "@/components/shared/max-width-wrapper";
|
import MaxWidthWrapper from "@/components/shared/max-width-wrapper";
|
||||||
|
|
||||||
@@ -32,6 +33,7 @@ export default async function Dashboard({ children }: ProtectedLayoutProps) {
|
|||||||
<DashboardSidebar links={filteredLinks} />
|
<DashboardSidebar links={filteredLinks} />
|
||||||
|
|
||||||
<div className="flex flex-1 flex-col">
|
<div className="flex flex-1 flex-col">
|
||||||
|
<Notification />
|
||||||
<header className="sticky top-0 z-50 flex h-14 bg-background px-4 lg:h-[60px] xl:px-8">
|
<header className="sticky top-0 z-50 flex h-14 bg-background px-4 lg:h-[60px] xl:px-8">
|
||||||
<MaxWidthWrapper className="flex max-w-7xl items-center gap-x-3 px-0">
|
<MaxWidthWrapper className="flex max-w-7xl items-center gap-x-3 px-0">
|
||||||
<MobileSheetSidebar links={filteredLinks} />
|
<MobileSheetSidebar links={filteredLinks} />
|
||||||
|
|||||||
@@ -1,19 +1,18 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useEffect, useState, useTransition } from "react";
|
import { useState, useTransition } from "react";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { AnimatePresence, motion } from "framer-motion";
|
import { AnimatePresence, motion } from "framer-motion";
|
||||||
import { ChevronLeft, ChevronRight } from "lucide-react";
|
import { ChevronLeft, ChevronRight } from "lucide-react";
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
|
|
||||||
import { siteConfig } from "@/config/site";
|
|
||||||
import { cn, removeUrlSuffix } from "@/lib/utils";
|
import { cn, removeUrlSuffix } from "@/lib/utils";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { Label } from "@/components/ui/label";
|
import { Label } from "@/components/ui/label";
|
||||||
import { Modal } from "@/components/ui/modal";
|
import { Modal } from "@/components/ui/modal";
|
||||||
import { Skeleton } from "@/components/ui/skeleton";
|
|
||||||
import { FormSectionColumns } from "@/components/dashboard/form-section-columns";
|
import { FormSectionColumns } from "@/components/dashboard/form-section-columns";
|
||||||
import { Icons } from "@/components/shared/icons";
|
import { Icons } from "@/components/shared/icons";
|
||||||
|
|
||||||
@@ -26,45 +25,27 @@ export default function StepGuide({
|
|||||||
const [currentStep, setCurrentStep] = useState(1);
|
const [currentStep, setCurrentStep] = useState(1);
|
||||||
const [direction, setDirection] = useState(0);
|
const [direction, setDirection] = useState(0);
|
||||||
const [completedSteps, setCompletedSteps] = useState<number[]>([]);
|
const [completedSteps, setCompletedSteps] = useState<number[]>([]);
|
||||||
const [isMobile, setIsMobile] = useState(false);
|
|
||||||
|
const t = useTranslations("Common");
|
||||||
|
|
||||||
const steps = [
|
const steps = [
|
||||||
{
|
{
|
||||||
id: 1,
|
id: 1,
|
||||||
title: "Set up an administrator",
|
title: t("Set up an administrator"),
|
||||||
description:
|
|
||||||
"Begin by entering your website URL or selecting an example site to reimagine your website with modern themes.",
|
|
||||||
component: () => <SetAdminRole id={user.id} email={user.email} />,
|
component: () => <SetAdminRole id={user.id} email={user.email} />,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 2,
|
id: 2,
|
||||||
title: "Add the first domain",
|
title: t("Add the first domain"),
|
||||||
description:
|
|
||||||
"Check out your reimagined site and click to Migrate & Download.",
|
|
||||||
component: () => <AddDomain onNextStep={goToNextStep} />,
|
component: () => <AddDomain onNextStep={goToNextStep} />,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 3,
|
id: 3,
|
||||||
title: "Congrats on completing setup 🎉",
|
title: t("Congrats on completing setup 🎉"),
|
||||||
description:
|
|
||||||
"Navigate to your GitHub dashboard where you'll manage your repository and project files.",
|
|
||||||
component: () => <Congrats />,
|
component: () => <Congrats />,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const checkMobile = () => {
|
|
||||||
setIsMobile(window.innerWidth < 768);
|
|
||||||
};
|
|
||||||
|
|
||||||
checkMobile();
|
|
||||||
window.addEventListener("resize", checkMobile);
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
window.removeEventListener("resize", checkMobile);
|
|
||||||
};
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const goToNextStep = () => {
|
const goToNextStep = () => {
|
||||||
if (currentStep < steps.length) {
|
if (currentStep < steps.length) {
|
||||||
setDirection(1);
|
setDirection(1);
|
||||||
@@ -106,7 +87,7 @@ export default function StepGuide({
|
|||||||
<Modal className="md:max-w-2xl">
|
<Modal className="md:max-w-2xl">
|
||||||
<div className="w-full px-4 py-2 md:px-8 md:py-4">
|
<div className="w-full px-4 py-2 md:px-8 md:py-4">
|
||||||
<div className="mb-6 mt-3 flex items-center justify-between gap-4">
|
<div className="mb-6 mt-3 flex items-center justify-between gap-4">
|
||||||
<h2 className="text-2xl font-bold">Admin Setup Guide</h2>
|
<h2 className="text-2xl font-bold">{t("Admin Setup Guide")}</h2>
|
||||||
<div className="flex items-center gap-2 rounded-full bg-muted/50 px-3 py-1.5 text-sm font-medium">
|
<div className="flex items-center gap-2 rounded-full bg-muted/50 px-3 py-1.5 text-sm font-medium">
|
||||||
<span className="flex size-6 items-center justify-center rounded-full bg-primary text-primary-foreground">
|
<span className="flex size-6 items-center justify-center rounded-full bg-primary text-primary-foreground">
|
||||||
{currentStep}
|
{currentStep}
|
||||||
@@ -130,7 +111,7 @@ export default function StepGuide({
|
|||||||
className="flex flex-col justify-center gap-6"
|
className="flex flex-col justify-center gap-6"
|
||||||
>
|
>
|
||||||
<div className="flex h-full w-full flex-col">
|
<div className="flex h-full w-full flex-col">
|
||||||
<div className="mb-2 flex items-center gap-1 rounded-lg bg-neutral-100 p-2">
|
<div className="mb-2 flex items-center gap-1 rounded-lg bg-neutral-100 p-2 dark:bg-neutral-800">
|
||||||
<span className="flex size-5 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground">
|
<span className="flex size-5 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground">
|
||||||
{currentStep}
|
{currentStep}
|
||||||
</span>
|
</span>
|
||||||
@@ -175,7 +156,7 @@ export default function StepGuide({
|
|||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<ChevronLeft className="h-4 w-4" />
|
<ChevronLeft className="h-4 w-4" />
|
||||||
Previous
|
{t("Previous")}
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
@@ -185,7 +166,7 @@ export default function StepGuide({
|
|||||||
"flex items-center gap-2 rounded-md bg-primary px-4 py-2 text-primary-foreground transition-colors hover:bg-primary/90",
|
"flex items-center gap-2 rounded-md bg-primary px-4 py-2 text-primary-foreground transition-colors hover:bg-primary/90",
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{currentStep === steps.length ? "🚀 Start" : "Next"}
|
{currentStep === steps.length ? t("🚀 Start") : t("Next")}
|
||||||
<ChevronRight className="h-4 w-4" />
|
<ChevronRight className="h-4 w-4" />
|
||||||
</button>
|
</button>
|
||||||
</motion.div>
|
</motion.div>
|
||||||
@@ -196,6 +177,7 @@ export default function StepGuide({
|
|||||||
function SetAdminRole({ id, email }: { id: string; email: string }) {
|
function SetAdminRole({ id, email }: { id: string; email: string }) {
|
||||||
const [isPending, startTransition] = useTransition();
|
const [isPending, startTransition] = useTransition();
|
||||||
const [isAdmin, setIsAdmin] = useState(false);
|
const [isAdmin, setIsAdmin] = useState(false);
|
||||||
|
const t = useTranslations("Common");
|
||||||
const handleSetAdmin = async () => {
|
const handleSetAdmin = async () => {
|
||||||
startTransition(async () => {
|
startTransition(async () => {
|
||||||
const res = await fetch("/api/setup");
|
const res = await fetch("/api/setup");
|
||||||
@@ -208,29 +190,28 @@ function SetAdminRole({ id, email }: { id: string; email: string }) {
|
|||||||
const ReadyBadge = (
|
const ReadyBadge = (
|
||||||
<Badge className="text-xs font-semibold" variant="green">
|
<Badge className="text-xs font-semibold" variant="green">
|
||||||
<Icons.check className="mr-1 size-3" />
|
<Icons.check className="mr-1 size-3" />
|
||||||
Ready
|
{t("Ready")}
|
||||||
</Badge>
|
</Badge>
|
||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-4 rounded-lg bg-neutral-50 p-4">
|
<div className="flex flex-col gap-4 rounded-lg bg-neutral-50 p-4 dark:bg-neutral-900">
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<span className="text-sm font-semibold text-neutral-500">
|
<span className="text-sm font-semibold text-muted-foreground">
|
||||||
Allow Sign Up:
|
{t("Allow Sign Up")}:
|
||||||
</span>
|
</span>
|
||||||
{siteConfig.openSignup ? ReadyBadge : <Skeleton className="h-4 w-12" />}
|
{ReadyBadge}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<span className="text-sm font-semibold text-neutral-500">
|
<span className="text-sm font-semibold text-muted-foreground">
|
||||||
Set {email} as ADMIN:
|
{t("Set {email} as ADMIN", { email })}:
|
||||||
</span>
|
</span>
|
||||||
{isAdmin ? (
|
{isAdmin ? (
|
||||||
ReadyBadge
|
ReadyBadge
|
||||||
) : (
|
) : (
|
||||||
<Button
|
<Button
|
||||||
className=""
|
variant={"default"}
|
||||||
variant={"outline"}
|
|
||||||
size={"sm"}
|
size={"sm"}
|
||||||
onClick={handleSetAdmin}
|
onClick={handleSetAdmin}
|
||||||
disabled={isPending}
|
disabled={isPending}
|
||||||
@@ -238,30 +219,36 @@ function SetAdminRole({ id, email }: { id: string; email: string }) {
|
|||||||
{isPending && (
|
{isPending && (
|
||||||
<Icons.spinner className="mr-2 size-4 animate-spin" />
|
<Icons.spinner className="mr-2 size-4 animate-spin" />
|
||||||
)}
|
)}
|
||||||
Active Now
|
{t("Active Now")}
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="rounded-md border border-dashed p-2 text-xs text-muted-foreground">
|
<div className="rounded-md border border-dashed p-2 text-xs text-muted-foreground">
|
||||||
<p className="flex items-start gap-1">
|
<p className="flex items-start gap-1">
|
||||||
📢 Only by becoming an administrator can one access the admin panel
|
•{" "}
|
||||||
and add domain names.
|
{t(
|
||||||
|
"Only by becoming an administrator can one access the admin panel and add domain names",
|
||||||
|
)}
|
||||||
|
.
|
||||||
</p>
|
</p>
|
||||||
<p className="my-1">
|
<p className="my-1">
|
||||||
📢 Administrators can set all user permissions, allocate quotas, view
|
•{" "}
|
||||||
and edit all resources (short links, subdomains, email), etc.
|
{t(
|
||||||
|
"Administrators can set all user permissions, allocate quotas, view and edit all resources (short links, subdomains, email), etc",
|
||||||
|
)}
|
||||||
|
.
|
||||||
</p>
|
</p>
|
||||||
<p>
|
<p>
|
||||||
📢 Via{" "}
|
•{t("Via")}{" "}
|
||||||
<a
|
<a
|
||||||
className="text-blue-500"
|
className="text-blue-500 after:content-['_↗']"
|
||||||
target="_blank"
|
target="_blank"
|
||||||
href="/docs/developer/quick-start"
|
href="/docs/developer/quick-start"
|
||||||
>
|
>
|
||||||
quick start
|
{t("quick start")}
|
||||||
</a>{" "}
|
</a>{" "}
|
||||||
docs to get more information.
|
{t("docs to get more information")}.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -271,6 +258,7 @@ function SetAdminRole({ id, email }: { id: string; email: string }) {
|
|||||||
function AddDomain({ onNextStep }: { onNextStep: () => void }) {
|
function AddDomain({ onNextStep }: { onNextStep: () => void }) {
|
||||||
const [isPending, startTransition] = useTransition();
|
const [isPending, startTransition] = useTransition();
|
||||||
const [domain, setDomain] = useState("");
|
const [domain, setDomain] = useState("");
|
||||||
|
const t = useTranslations("Common");
|
||||||
const handleCreateDomain = async () => {
|
const handleCreateDomain = async () => {
|
||||||
if (!domain) {
|
if (!domain) {
|
||||||
toast.warning("Domain name cannot be empty");
|
toast.warning("Domain name cannot be empty");
|
||||||
@@ -306,23 +294,26 @@ function AddDomain({ onNextStep }: { onNextStep: () => void }) {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-4 rounded-lg bg-neutral-50 p-4">
|
<div className="flex flex-col gap-4 rounded-lg bg-neutral-50 p-4 dark:bg-neutral-900">
|
||||||
<FormSectionColumns title="Domain Name">
|
<FormSectionColumns title={t("Domain Name")}>
|
||||||
<div className="flex w-full flex-col items-start justify-between gap-2">
|
<div className="flex w-full flex-col items-start justify-between gap-2">
|
||||||
<Label className="sr-only" htmlFor="domain_name">
|
<Label className="sr-only" htmlFor="domain_name">
|
||||||
Domain Name
|
{t("Domain Name")}
|
||||||
</Label>
|
</Label>
|
||||||
<div className="w-full">
|
<div className="w-full">
|
||||||
<Input
|
<Input
|
||||||
id="target"
|
id="target"
|
||||||
className="flex-1 bg-neutral-50 shadow-inner"
|
className="flex-1 bg-neutral-50 shadow-inner dark:bg-neutral-600"
|
||||||
size={32}
|
size={32}
|
||||||
placeholder="example.com"
|
placeholder="example.com"
|
||||||
onChange={(e) => setDomain(e.target.value)}
|
onChange={(e) => setDomain(e.target.value)}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<p className="text-xs text-muted-foreground">
|
<p className="text-xs text-muted-foreground">
|
||||||
Please enter a valid domain name (must be hosted on Cloudflare).
|
{t(
|
||||||
|
"Please enter a valid domain name (must be hosted on Cloudflare)",
|
||||||
|
)}
|
||||||
|
.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -333,7 +324,7 @@ function AddDomain({ onNextStep }: { onNextStep: () => void }) {
|
|||||||
size={"sm"}
|
size={"sm"}
|
||||||
onClick={onNextStep}
|
onClick={onNextStep}
|
||||||
>
|
>
|
||||||
Or add later
|
{t("Or add later")}
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
className="flex items-center gap-1"
|
className="flex items-center gap-1"
|
||||||
@@ -345,7 +336,7 @@ function AddDomain({ onNextStep }: { onNextStep: () => void }) {
|
|||||||
{isPending && (
|
{isPending && (
|
||||||
<Icons.spinner className="mr-2 size-4 animate-spin" />
|
<Icons.spinner className="mr-2 size-4 animate-spin" />
|
||||||
)}
|
)}
|
||||||
Submit
|
{t("Submit")}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</FormSectionColumns>
|
</FormSectionColumns>
|
||||||
|
|||||||
@@ -4,10 +4,7 @@ import { DashboardHeader } from "@/components/dashboard/header";
|
|||||||
export default function DashboardLoading() {
|
export default function DashboardLoading() {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<DashboardHeader
|
<DashboardHeader heading="Setup Guide" text="" />
|
||||||
heading="Manage Short URLs"
|
|
||||||
text="List and manage short urls."
|
|
||||||
/>
|
|
||||||
<Skeleton className="h-32 w-full rounded-lg" />
|
<Skeleton className="h-32 w-full rounded-lg" />
|
||||||
<Skeleton className="h-[400px] w-full rounded-lg" />
|
<Skeleton className="h-[400px] w-full rounded-lg" />
|
||||||
</>
|
</>
|
||||||
|
|||||||
55
app/api/admin/configs/route.ts
Normal file
55
app/api/admin/configs/route.ts
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
import { NextRequest } from "next/server";
|
||||||
|
|
||||||
|
import {
|
||||||
|
getMultipleConfigs,
|
||||||
|
updateSystemConfig,
|
||||||
|
} from "@/lib/dto/system-config";
|
||||||
|
import { checkUserStatus } from "@/lib/dto/user";
|
||||||
|
import { getCurrentUser } from "@/lib/session";
|
||||||
|
|
||||||
|
export async function GET(req: NextRequest) {
|
||||||
|
try {
|
||||||
|
const user = checkUserStatus(await getCurrentUser());
|
||||||
|
if (user instanceof Response) return user;
|
||||||
|
if (user.role !== "ADMIN") {
|
||||||
|
return Response.json("Unauthorized", { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const configs = await getMultipleConfigs([
|
||||||
|
"enable_user_registration",
|
||||||
|
"enable_subdomain_apply",
|
||||||
|
"system_notification",
|
||||||
|
]);
|
||||||
|
|
||||||
|
return Response.json(configs, { status: 200 });
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[Error]", error);
|
||||||
|
return Response.json(error.message || "Server error", { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(req: NextRequest) {
|
||||||
|
try {
|
||||||
|
const user = checkUserStatus(await getCurrentUser());
|
||||||
|
if (user instanceof Response) return user;
|
||||||
|
if (user.role !== "ADMIN") {
|
||||||
|
return Response.json("Unauthorized", { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const { key, value, type } = await req.json();
|
||||||
|
if (!key || !type) {
|
||||||
|
return Response.json("key and value is required", { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const configs = await getMultipleConfigs([key]);
|
||||||
|
|
||||||
|
if (key in configs) {
|
||||||
|
await updateSystemConfig(key, { value, type });
|
||||||
|
return Response.json("Success", { status: 200 });
|
||||||
|
}
|
||||||
|
return Response.json("Invalid key", { status: 400 });
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[Error]", error);
|
||||||
|
return Response.json(error.message || "Server error", { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,7 +4,6 @@ import {
|
|||||||
createDomain,
|
createDomain,
|
||||||
deleteDomain,
|
deleteDomain,
|
||||||
getAllDomains,
|
getAllDomains,
|
||||||
invalidateDomainConfigCache,
|
|
||||||
updateDomain,
|
updateDomain,
|
||||||
} from "@/lib/dto/domains";
|
} from "@/lib/dto/domains";
|
||||||
import { checkUserStatus } from "@/lib/dto/user";
|
import { checkUserStatus } from "@/lib/dto/user";
|
||||||
@@ -19,13 +18,18 @@ export async function GET(req: NextRequest) {
|
|||||||
return Response.json("Unauthorized", { status: 401 });
|
return Response.json("Unauthorized", { status: 401 });
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Add pagination
|
const url = new URL(req.url);
|
||||||
const domains = await getAllDomains();
|
const page = url.searchParams.get("page");
|
||||||
|
const size = url.searchParams.get("size");
|
||||||
|
const target = url.searchParams.get("target") || "";
|
||||||
|
|
||||||
return Response.json(
|
const data = await getAllDomains(
|
||||||
{ list: domains, total: domains.length },
|
Number(page || "1"),
|
||||||
{ status: 200 },
|
Number(size || "10"),
|
||||||
|
target,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
return Response.json(data, { status: 200 });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("[Error]", error);
|
console.error("[Error]", error);
|
||||||
return Response.json(error.message || "Server error", { status: 500 });
|
return Response.json(error.message || "Server error", { status: 500 });
|
||||||
@@ -55,14 +59,13 @@ export async function POST(req: NextRequest) {
|
|||||||
cf_api_key: data.cf_api_key,
|
cf_api_key: data.cf_api_key,
|
||||||
cf_email: data.cf_email,
|
cf_email: data.cf_email,
|
||||||
cf_api_key_encrypted: false,
|
cf_api_key_encrypted: false,
|
||||||
|
resend_api_key: data.resend_api_key,
|
||||||
max_short_links: data.max_short_links,
|
max_short_links: data.max_short_links,
|
||||||
max_email_forwards: data.max_email_forwards,
|
max_email_forwards: data.max_email_forwards,
|
||||||
max_dns_records: data.max_dns_records,
|
max_dns_records: data.max_dns_records,
|
||||||
active: true,
|
active: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
invalidateDomainConfigCache();
|
|
||||||
|
|
||||||
return Response.json(newDomain, { status: 200 });
|
return Response.json(newDomain, { status: 200 });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("[Error]", error);
|
console.error("[Error]", error);
|
||||||
@@ -87,6 +90,7 @@ export async function PUT(req: NextRequest) {
|
|||||||
cf_zone_id,
|
cf_zone_id,
|
||||||
cf_api_key,
|
cf_api_key,
|
||||||
cf_email,
|
cf_email,
|
||||||
|
resend_api_key,
|
||||||
max_short_links,
|
max_short_links,
|
||||||
max_email_forwards,
|
max_email_forwards,
|
||||||
max_dns_records,
|
max_dns_records,
|
||||||
@@ -107,13 +111,12 @@ export async function PUT(req: NextRequest) {
|
|||||||
cf_api_key,
|
cf_api_key,
|
||||||
cf_email,
|
cf_email,
|
||||||
cf_api_key_encrypted: false,
|
cf_api_key_encrypted: false,
|
||||||
|
resend_api_key,
|
||||||
max_short_links,
|
max_short_links,
|
||||||
max_email_forwards,
|
max_email_forwards,
|
||||||
max_dns_records,
|
max_dns_records,
|
||||||
});
|
});
|
||||||
|
|
||||||
invalidateDomainConfigCache();
|
|
||||||
|
|
||||||
return Response.json(updatedDomain, { status: 200 });
|
return Response.json(updatedDomain, { status: 200 });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("[Error]", error);
|
console.error("[Error]", error);
|
||||||
@@ -137,8 +140,6 @@ export async function DELETE(req: NextRequest) {
|
|||||||
|
|
||||||
const deletedDomain = await deleteDomain(domain_name);
|
const deletedDomain = await deleteDomain(domain_name);
|
||||||
|
|
||||||
invalidateDomainConfigCache();
|
|
||||||
|
|
||||||
return Response.json(deletedDomain, { status: 200 });
|
return Response.json(deletedDomain, { status: 200 });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("[Error]", error);
|
console.error("[Error]", error);
|
||||||
|
|||||||
138
app/api/admin/plan/route.ts
Normal file
138
app/api/admin/plan/route.ts
Normal file
@@ -0,0 +1,138 @@
|
|||||||
|
import { NextRequest } from "next/server";
|
||||||
|
|
||||||
|
import {
|
||||||
|
createPlan,
|
||||||
|
deletePlan,
|
||||||
|
getAllPlans,
|
||||||
|
updatePlanQuota,
|
||||||
|
} from "@/lib/dto/plan";
|
||||||
|
import { checkUserStatus } from "@/lib/dto/user";
|
||||||
|
import { getCurrentUser } from "@/lib/session";
|
||||||
|
|
||||||
|
export async function GET(req: NextRequest) {
|
||||||
|
try {
|
||||||
|
const user = checkUserStatus(await getCurrentUser());
|
||||||
|
if (user instanceof Response) return user;
|
||||||
|
if (user.role !== "ADMIN") {
|
||||||
|
return Response.json("Unauthorized", { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
// const url = new URL(req.url);
|
||||||
|
// const page = url.searchParams.get("page");
|
||||||
|
// const size = url.searchParams.get("size");
|
||||||
|
// const target = url.searchParams.get("target") || "";
|
||||||
|
|
||||||
|
const data = await getAllPlans();
|
||||||
|
|
||||||
|
return Response.json(data, { status: 200 });
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[Error]", error);
|
||||||
|
return Response.json(error.message || "Server error", { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(req: NextRequest) {
|
||||||
|
try {
|
||||||
|
const user = checkUserStatus(await getCurrentUser());
|
||||||
|
if (user instanceof Response) return user;
|
||||||
|
if (user.role !== "ADMIN") {
|
||||||
|
return Response.json("Unauthorized", { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const { plan } = await req.json();
|
||||||
|
|
||||||
|
const data = await createPlan({
|
||||||
|
name: plan.name,
|
||||||
|
slTrackedClicks: plan.slTrackedClicks,
|
||||||
|
slNewLinks: plan.slNewLinks,
|
||||||
|
slAnalyticsRetention: plan.slAnalyticsRetention,
|
||||||
|
slDomains: plan.slDomains,
|
||||||
|
slAdvancedAnalytics: plan.slAdvancedAnalytics,
|
||||||
|
slCustomQrCodeLogo: plan.slCustomQrCodeLogo,
|
||||||
|
rcNewRecords: plan.rcNewRecords,
|
||||||
|
emEmailAddresses: plan.emEmailAddresses,
|
||||||
|
emDomains: plan.emDomains,
|
||||||
|
emSendEmails: plan.emSendEmails,
|
||||||
|
appSupport: plan.appSupport.toUpperCase() as any,
|
||||||
|
appApiAccess: plan.appApiAccess,
|
||||||
|
isActive: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (data) {
|
||||||
|
return Response.json(data, { status: 200 });
|
||||||
|
}
|
||||||
|
|
||||||
|
return Response.json(null, { status: 400 });
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[Error]", error);
|
||||||
|
return Response.json(error.message || "Server error", { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function PUT(req: NextRequest) {
|
||||||
|
try {
|
||||||
|
const user = checkUserStatus(await getCurrentUser());
|
||||||
|
if (user instanceof Response) return user;
|
||||||
|
if (user.role !== "ADMIN") {
|
||||||
|
return Response.json("Unauthorized", { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const { plan } = await req.json();
|
||||||
|
if (!plan) {
|
||||||
|
return Response.json("Invalid request body", { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await updatePlanQuota({
|
||||||
|
id: plan.id,
|
||||||
|
name: plan.name,
|
||||||
|
slTrackedClicks: plan.slTrackedClicks,
|
||||||
|
slNewLinks: plan.slNewLinks,
|
||||||
|
slAnalyticsRetention: plan.slAnalyticsRetention,
|
||||||
|
slDomains: plan.slDomains,
|
||||||
|
slAdvancedAnalytics: plan.slAdvancedAnalytics,
|
||||||
|
slCustomQrCodeLogo: plan.slCustomQrCodeLogo,
|
||||||
|
rcNewRecords: plan.rcNewRecords,
|
||||||
|
emEmailAddresses: plan.emEmailAddresses,
|
||||||
|
emDomains: plan.emDomains,
|
||||||
|
emSendEmails: plan.emSendEmails,
|
||||||
|
appSupport: plan.appSupport.toUpperCase() as any,
|
||||||
|
appApiAccess: plan.appApiAccess,
|
||||||
|
isActive: plan.isActive,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (res) {
|
||||||
|
return Response.json(res, { status: 200 });
|
||||||
|
}
|
||||||
|
|
||||||
|
return Response.json(null, { status: 400 });
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[Error]", error);
|
||||||
|
return Response.json(error.message || "Server error", { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function DELETE(req: NextRequest) {
|
||||||
|
try {
|
||||||
|
const user = checkUserStatus(await getCurrentUser());
|
||||||
|
if (user instanceof Response) return user;
|
||||||
|
if (user.role !== "ADMIN") {
|
||||||
|
return Response.json("Unauthorized", { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const { id } = await req.json();
|
||||||
|
if (!id) {
|
||||||
|
return Response.json("id is required", { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await deletePlan(id);
|
||||||
|
|
||||||
|
if (data) {
|
||||||
|
return Response.json(data, { status: 200 });
|
||||||
|
}
|
||||||
|
|
||||||
|
return Response.json(null, { status: 400 });
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[Error]", error);
|
||||||
|
return Response.json(error.message || "Server error", { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
32
app/api/configs/route.ts
Normal file
32
app/api/configs/route.ts
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
import { NextRequest } from "next/server";
|
||||||
|
|
||||||
|
import { getMultipleConfigs } from "@/lib/dto/system-config";
|
||||||
|
import { checkUserStatus } from "@/lib/dto/user";
|
||||||
|
import { getCurrentUser } from "@/lib/session";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
export async function GET(req: NextRequest) {
|
||||||
|
try {
|
||||||
|
const user = checkUserStatus(await getCurrentUser());
|
||||||
|
if (user instanceof Response) return user;
|
||||||
|
|
||||||
|
const url = new URL(req.url);
|
||||||
|
const keys = url.searchParams.getAll("key") || [];
|
||||||
|
|
||||||
|
if (keys.length === 0) {
|
||||||
|
return Response.json("key is required", { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const configs = await getMultipleConfigs(keys);
|
||||||
|
|
||||||
|
// "enable_user_registration",
|
||||||
|
// "enable_subdomain_apply",
|
||||||
|
// "system_notification",
|
||||||
|
|
||||||
|
return Response.json(configs, { status: 200 });
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[Error]", error);
|
||||||
|
return Response.json(error.message || "Server error", { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
24
app/api/domain/check-cf/route.ts
Normal file
24
app/api/domain/check-cf/route.ts
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
import { NextRequest } from "next/server";
|
||||||
|
|
||||||
|
import { getZoneDetail } from "@/lib/cloudflare";
|
||||||
|
import { checkUserStatus } from "@/lib/dto/user";
|
||||||
|
import { getCurrentUser } from "@/lib/session";
|
||||||
|
|
||||||
|
export async function GET(req: NextRequest) {
|
||||||
|
try {
|
||||||
|
const user = checkUserStatus(await getCurrentUser());
|
||||||
|
if (user instanceof Response) return user;
|
||||||
|
|
||||||
|
const url = new URL(req.url);
|
||||||
|
const zone_id = url.searchParams.get("zone_id") || "";
|
||||||
|
const api_key = url.searchParams.get("api_key") || "";
|
||||||
|
const email = url.searchParams.get("email") || "";
|
||||||
|
|
||||||
|
const res = await getZoneDetail(zone_id, api_key, email);
|
||||||
|
|
||||||
|
if (res === 200) return Response.json(200, { status: 200 });
|
||||||
|
else return Response.json(400, { status: 400 });
|
||||||
|
} catch (error) {
|
||||||
|
return Response.json(500, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
37
app/api/domain/check-resend/route.ts
Normal file
37
app/api/domain/check-resend/route.ts
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
import { NextRequest } from "next/server";
|
||||||
|
import { Resend } from "resend";
|
||||||
|
|
||||||
|
import { checkUserStatus } from "@/lib/dto/user";
|
||||||
|
import { getCurrentUser } from "@/lib/session";
|
||||||
|
|
||||||
|
export async function GET(req: NextRequest) {
|
||||||
|
try {
|
||||||
|
const user = checkUserStatus(await getCurrentUser());
|
||||||
|
if (user instanceof Response) return user;
|
||||||
|
|
||||||
|
const url = new URL(req.url);
|
||||||
|
const api_key = url.searchParams.get("api_key") || "";
|
||||||
|
const domain = url.searchParams.get("domain") || "";
|
||||||
|
|
||||||
|
if (!api_key || !domain) {
|
||||||
|
return Response.json(400, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const resend = new Resend(api_key);
|
||||||
|
const { error } = await resend.emails.send({
|
||||||
|
from: `test@${domain}`,
|
||||||
|
to: user.email,
|
||||||
|
subject: "Test Resend API Key",
|
||||||
|
html: "This is a test email sent using Resend API Key.",
|
||||||
|
});
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
console.error(error);
|
||||||
|
return Response.json(400, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
return Response.json(200, { status: 200 });
|
||||||
|
} catch (error) {
|
||||||
|
return Response.json(500, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,6 +4,8 @@ import { FeatureMap, getDomainsByFeatureClient } from "@/lib/dto/domains";
|
|||||||
import { checkUserStatus } from "@/lib/dto/user";
|
import { checkUserStatus } from "@/lib/dto/user";
|
||||||
import { getCurrentUser } from "@/lib/session";
|
import { getCurrentUser } from "@/lib/session";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
// Get domains by feature for frontend
|
// Get domains by feature for frontend
|
||||||
export async function GET(req: NextRequest) {
|
export async function GET(req: NextRequest) {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
|
||||||
import { getEmailsByEmailAddress } from "@/lib/dto/email";
|
import { deleteEmailsByIds, getEmailsByEmailAddress } from "@/lib/dto/email";
|
||||||
import { checkUserStatus } from "@/lib/dto/user";
|
import { checkUserStatus } from "@/lib/dto/user";
|
||||||
import { getCurrentUser } from "@/lib/session";
|
import { getCurrentUser } from "@/lib/session";
|
||||||
|
|
||||||
@@ -35,3 +35,22 @@ export async function GET(req: NextRequest) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function DELETE(req: NextRequest) {
|
||||||
|
try {
|
||||||
|
const user = checkUserStatus(await getCurrentUser());
|
||||||
|
if (user instanceof Response) return user;
|
||||||
|
|
||||||
|
const { ids } = await req.json();
|
||||||
|
if (!ids) {
|
||||||
|
return Response.json("ids is required", { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
await deleteEmailsByIds(ids);
|
||||||
|
|
||||||
|
return Response.json("success", { status: 200 });
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[Error]", error);
|
||||||
|
return Response.json(error.message || "Server error", { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
|
||||||
import { TeamPlanQuota } from "@/config/team";
|
|
||||||
import { createUserEmail, getAllUserEmails } from "@/lib/dto/email";
|
import { createUserEmail, getAllUserEmails } from "@/lib/dto/email";
|
||||||
|
import { getPlanQuota } from "@/lib/dto/plan";
|
||||||
import { checkUserStatus } from "@/lib/dto/user";
|
import { checkUserStatus } from "@/lib/dto/user";
|
||||||
import { reservedAddressSuffix } from "@/lib/enums";
|
import { reservedAddressSuffix } from "@/lib/enums";
|
||||||
import { getCurrentUser } from "@/lib/session";
|
import { getCurrentUser } from "@/lib/session";
|
||||||
@@ -43,11 +43,13 @@ export async function POST(req: NextRequest) {
|
|||||||
const user = checkUserStatus(await getCurrentUser());
|
const user = checkUserStatus(await getCurrentUser());
|
||||||
if (user instanceof Response) return user;
|
if (user instanceof Response) return user;
|
||||||
|
|
||||||
|
const plan = await getPlanQuota(user.team);
|
||||||
|
|
||||||
// check limit
|
// check limit
|
||||||
const limit = await restrictByTimeRange({
|
const limit = await restrictByTimeRange({
|
||||||
model: "userEmail",
|
model: "userEmail",
|
||||||
userId: user.id,
|
userId: user.id,
|
||||||
limit: TeamPlanQuota[user.team].EM_EmailAddresses,
|
limit: plan.emEmailAddresses,
|
||||||
rangeType: "month",
|
rangeType: "month",
|
||||||
});
|
});
|
||||||
if (limit)
|
if (limit)
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
|
||||||
import { TeamPlanQuota } from "@/config/team";
|
import { checkDomainIsConfiguratedResend } from "@/lib/dto/domains";
|
||||||
import { getUserSendEmailCount, saveUserSendEmail } from "@/lib/dto/email";
|
import { getUserSendEmailCount, saveUserSendEmail } from "@/lib/dto/email";
|
||||||
|
import { getPlanQuota } from "@/lib/dto/plan";
|
||||||
import { checkUserStatus } from "@/lib/dto/user";
|
import { checkUserStatus } from "@/lib/dto/user";
|
||||||
import { resend } from "@/lib/email";
|
import { resend } from "@/lib/email";
|
||||||
import { getCurrentUser } from "@/lib/session";
|
import { getCurrentUser } from "@/lib/session";
|
||||||
@@ -13,11 +14,13 @@ export async function POST(req: NextRequest) {
|
|||||||
const user = checkUserStatus(await getCurrentUser());
|
const user = checkUserStatus(await getCurrentUser());
|
||||||
if (user instanceof Response) return user;
|
if (user instanceof Response) return user;
|
||||||
|
|
||||||
|
const plan = await getPlanQuota(user.team);
|
||||||
|
|
||||||
// check limit
|
// check limit
|
||||||
const limit = await restrictByTimeRange({
|
const limit = await restrictByTimeRange({
|
||||||
model: "userSendEmail",
|
model: "userSendEmail",
|
||||||
userId: user.id,
|
userId: user.id,
|
||||||
limit: TeamPlanQuota[user.team].EM_SendEmails,
|
limit: plan.emSendEmails,
|
||||||
rangeType: "month",
|
rangeType: "month",
|
||||||
});
|
});
|
||||||
if (limit)
|
if (limit)
|
||||||
@@ -33,6 +36,13 @@ export async function POST(req: NextRequest) {
|
|||||||
return NextResponse.json("Invalid email address", { status: 403 });
|
return NextResponse.json("Invalid email address", { status: 403 });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!(await checkDomainIsConfiguratedResend(from.split("@")[1]))) {
|
||||||
|
return NextResponse.json(
|
||||||
|
"This domain is not configured for sending emails",
|
||||||
|
{ status: 400 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const { error } = await resend.emails.send({
|
const { error } = await resend.emails.send({
|
||||||
from,
|
from,
|
||||||
to,
|
to,
|
||||||
|
|||||||
32
app/api/feature/route.ts
Normal file
32
app/api/feature/route.ts
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
import { env } from "@/env.mjs";
|
||||||
|
import { getConfigValue } from "@/lib/dto/system-config";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
export async function GET(req: Request) {
|
||||||
|
try {
|
||||||
|
const registration = await getConfigValue<boolean>(
|
||||||
|
"enable_user_registration",
|
||||||
|
);
|
||||||
|
if (process.env.VERCEL) {
|
||||||
|
return Response.json({
|
||||||
|
google: !!(env.GOOGLE_CLIENT_ID && env.GOOGLE_CLIENT_SECRET),
|
||||||
|
github: !!(env.GITHUB_ID && env.GITHUB_SECRET),
|
||||||
|
linuxdo: !!(env.LinuxDo_CLIENT_ID && env.LinuxDo_CLIENT_SECRET),
|
||||||
|
resend: !!(env.RESEND_API_KEY && env.RESEND_FROM_EMAIL),
|
||||||
|
registration,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
// TODO: (docker) cannot get env on docker environment
|
||||||
|
return Response.json({
|
||||||
|
google: true,
|
||||||
|
github: true,
|
||||||
|
linuxdo: true,
|
||||||
|
resend: true,
|
||||||
|
registration,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.log("[Error]", error);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
import { env } from "@/env.mjs";
|
|
||||||
import { generateApiKey } from "@/lib/dto/api-key";
|
import { generateApiKey } from "@/lib/dto/api-key";
|
||||||
import { checkUserStatus } from "@/lib/dto/user";
|
import { checkUserStatus } from "@/lib/dto/user";
|
||||||
import { getCurrentUser } from "@/lib/session";
|
import { getCurrentUser } from "@/lib/session";
|
||||||
|
|||||||
29
app/api/location/route.ts
Normal file
29
app/api/location/route.ts
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { geolocation } from "@vercel/functions";
|
||||||
|
|
||||||
|
interface CurrentLocation {
|
||||||
|
latitude: number;
|
||||||
|
longitude: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
export async function GET(req: NextRequest) {
|
||||||
|
try {
|
||||||
|
const geo = geolocation(req);
|
||||||
|
|
||||||
|
const location: CurrentLocation = {
|
||||||
|
latitude: Number(geo.latitude || "0"),
|
||||||
|
longitude: Number(geo.longitude || "0"),
|
||||||
|
};
|
||||||
|
|
||||||
|
return NextResponse.json(location, { status: 200 });
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching location:", error);
|
||||||
|
// Fallback to default coordinates
|
||||||
|
return NextResponse.json(
|
||||||
|
{ latitude: 40.7128, longitude: -74.006 },
|
||||||
|
{ status: 200 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
25
app/api/plan/names/route.ts
Normal file
25
app/api/plan/names/route.ts
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
import { NextRequest } from "next/server";
|
||||||
|
|
||||||
|
import { getPlanNames } from "@/lib/dto/plan";
|
||||||
|
import { checkUserStatus } from "@/lib/dto/user";
|
||||||
|
import { getCurrentUser } from "@/lib/session";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
// Get plan names for frontend
|
||||||
|
export async function GET(req: NextRequest) {
|
||||||
|
try {
|
||||||
|
const user = checkUserStatus(await getCurrentUser());
|
||||||
|
if (user instanceof Response) return user;
|
||||||
|
|
||||||
|
const res = await getPlanNames();
|
||||||
|
if (!res) {
|
||||||
|
return Response.json("Plans not found", { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
return Response.json(res, { status: 200 });
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[Error]", error);
|
||||||
|
return Response.json(error.message || "Server error", { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
30
app/api/plan/route.ts
Normal file
30
app/api/plan/route.ts
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
import { NextRequest } from "next/server";
|
||||||
|
|
||||||
|
import { getAllPlans, getPlanQuota } from "@/lib/dto/plan";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
// Get one plan by plan name for frontend
|
||||||
|
export async function GET(req: NextRequest) {
|
||||||
|
try {
|
||||||
|
const url = new URL(req.url);
|
||||||
|
const isAll = url.searchParams.get("all") || "0";
|
||||||
|
const team = url.searchParams.get("team") || "free";
|
||||||
|
|
||||||
|
if (isAll === "1") {
|
||||||
|
const res = await getAllPlans();
|
||||||
|
if (res) {
|
||||||
|
return Response.json(res, { status: 200 });
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const res = await getPlanQuota(team);
|
||||||
|
if (res) {
|
||||||
|
return Response.json(res, { status: 200 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Response.json("Plan not found", { status: 400 });
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[Error]", error);
|
||||||
|
return Response.json(error.message || "Server error", { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import { TeamPlanQuota } from "@/config/team";
|
import { env } from "@/env.mjs";
|
||||||
|
import { siteConfig } from "@/config/site";
|
||||||
import { createDNSRecord } from "@/lib/cloudflare";
|
import { createDNSRecord } from "@/lib/cloudflare";
|
||||||
import {
|
import {
|
||||||
createUserRecord,
|
createUserRecord,
|
||||||
@@ -6,7 +7,10 @@ import {
|
|||||||
getUserRecordCount,
|
getUserRecordCount,
|
||||||
} from "@/lib/dto/cloudflare-dns-record";
|
} from "@/lib/dto/cloudflare-dns-record";
|
||||||
import { getDomainsByFeature } from "@/lib/dto/domains";
|
import { getDomainsByFeature } from "@/lib/dto/domains";
|
||||||
import { checkUserStatus } from "@/lib/dto/user";
|
import { getPlanQuota } from "@/lib/dto/plan";
|
||||||
|
import { getConfigValue } from "@/lib/dto/system-config";
|
||||||
|
import { checkUserStatus, getFirstAdminUser } from "@/lib/dto/user";
|
||||||
|
import { applyRecordEmailHtml, resend } from "@/lib/email";
|
||||||
import { reservedDomains } from "@/lib/enums";
|
import { reservedDomains } from "@/lib/enums";
|
||||||
import { getCurrentUser } from "@/lib/session";
|
import { getCurrentUser } from "@/lib/session";
|
||||||
import { generateSecret } from "@/lib/utils";
|
import { generateSecret } from "@/lib/utils";
|
||||||
@@ -24,8 +28,10 @@ export async function POST(req: Request) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const plan = await getPlanQuota(user.team);
|
||||||
|
|
||||||
const { total } = await getUserRecordCount(user.id);
|
const { total } = await getUserRecordCount(user.id);
|
||||||
if (total >= TeamPlanQuota[user.team].RC_NewRecords) {
|
if (total >= plan.rcNewRecords) {
|
||||||
return Response.json("Your records have reached the free limit.", {
|
return Response.json("Your records have reached the free limit.", {
|
||||||
status: 409,
|
status: 409,
|
||||||
});
|
});
|
||||||
@@ -75,10 +81,57 @@ export async function POST(req: Request) {
|
|||||||
);
|
);
|
||||||
if (user_record && user_record.length > 0) {
|
if (user_record && user_record.length > 0) {
|
||||||
return Response.json("Record already exists", {
|
return Response.json("Record already exists", {
|
||||||
status: 403,
|
status: 400,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const enableSubdomainApply = await getConfigValue<boolean>(
|
||||||
|
"enable_subdomain_apply",
|
||||||
|
);
|
||||||
|
|
||||||
|
// apply subdomain
|
||||||
|
if (enableSubdomainApply) {
|
||||||
|
const res = await createUserRecord(user.id, {
|
||||||
|
record_id: generateSecret(16),
|
||||||
|
zone_id: matchedZone.cf_zone_id,
|
||||||
|
zone_name: matchedZone.domain_name,
|
||||||
|
name: record.name,
|
||||||
|
type: record.type,
|
||||||
|
content: record.content,
|
||||||
|
proxied: record.proxied,
|
||||||
|
proxiable: false,
|
||||||
|
ttl: record.ttl,
|
||||||
|
comment: record.comment,
|
||||||
|
tags: "",
|
||||||
|
created_on: new Date().toISOString(),
|
||||||
|
modified_on: new Date().toISOString(),
|
||||||
|
active: 2, // pending
|
||||||
|
});
|
||||||
|
|
||||||
|
if (res.status !== "success") {
|
||||||
|
return Response.json(res.status, {
|
||||||
|
status: 502,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const admin_user = await getFirstAdminUser();
|
||||||
|
if (admin_user) {
|
||||||
|
await resend.emails.send({
|
||||||
|
from: env.RESEND_FROM_EMAIL,
|
||||||
|
to: admin_user.email || "",
|
||||||
|
subject: "New record pending approval",
|
||||||
|
html: applyRecordEmailHtml({
|
||||||
|
appUrl: siteConfig.url,
|
||||||
|
appName: siteConfig.name,
|
||||||
|
zone_name: record.zone_name,
|
||||||
|
type: record.type,
|
||||||
|
name: record.name,
|
||||||
|
content: record.content,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return Response.json(res.data?.id);
|
||||||
|
}
|
||||||
|
|
||||||
const data = await createDNSRecord(
|
const data = await createDNSRecord(
|
||||||
matchedZone.cf_zone_id,
|
matchedZone.cf_zone_id,
|
||||||
matchedZone.cf_api_key,
|
matchedZone.cf_api_key,
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import { TeamPlanQuota } from "@/config/team";
|
|
||||||
import { createDNSRecord } from "@/lib/cloudflare";
|
import { createDNSRecord } from "@/lib/cloudflare";
|
||||||
import {
|
import {
|
||||||
createUserRecord,
|
createUserRecord,
|
||||||
@@ -6,6 +5,7 @@ import {
|
|||||||
getUserRecordCount,
|
getUserRecordCount,
|
||||||
} from "@/lib/dto/cloudflare-dns-record";
|
} from "@/lib/dto/cloudflare-dns-record";
|
||||||
import { getDomainsByFeature } from "@/lib/dto/domains";
|
import { getDomainsByFeature } from "@/lib/dto/domains";
|
||||||
|
import { getPlanQuota } from "@/lib/dto/plan";
|
||||||
import { checkUserStatus, getUserByEmail } from "@/lib/dto/user";
|
import { checkUserStatus, getUserByEmail } from "@/lib/dto/user";
|
||||||
import { reservedDomains } from "@/lib/enums";
|
import { reservedDomains } from "@/lib/enums";
|
||||||
import { getCurrentUser } from "@/lib/session";
|
import { getCurrentUser } from "@/lib/session";
|
||||||
@@ -39,8 +39,10 @@ export async function POST(req: Request) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const plan = await getPlanQuota(user.team);
|
||||||
|
|
||||||
const { total } = await getUserRecordCount(target_user.id);
|
const { total } = await getUserRecordCount(target_user.id);
|
||||||
if (total >= TeamPlanQuota[target_user.team!].RC_NewRecords) {
|
if (total >= plan.rcNewRecords) {
|
||||||
return Response.json("Your records have reached the free limit.", {
|
return Response.json("Your records have reached the free limit.", {
|
||||||
status: 409,
|
status: 409,
|
||||||
});
|
});
|
||||||
|
|||||||
78
app/api/record/admin/apply/route.ts
Normal file
78
app/api/record/admin/apply/route.ts
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
import { createDNSRecord } from "@/lib/cloudflare";
|
||||||
|
import { updateUserRecordReview } from "@/lib/dto/cloudflare-dns-record";
|
||||||
|
import { getDomainsByFeature } from "@/lib/dto/domains";
|
||||||
|
import { checkUserStatus } from "@/lib/dto/user";
|
||||||
|
import { getCurrentUser } from "@/lib/session";
|
||||||
|
|
||||||
|
export async function POST(req: Request) {
|
||||||
|
try {
|
||||||
|
const user = checkUserStatus(await getCurrentUser());
|
||||||
|
if (user instanceof Response) return user;
|
||||||
|
|
||||||
|
const zones = await getDomainsByFeature("enable_dns", true);
|
||||||
|
if (!zones.length) {
|
||||||
|
return Response.json("Please add at least one domain", {
|
||||||
|
status: 400,
|
||||||
|
statusText: "Please add at least one domain",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const { record: reviewRecord, userId, id } = await req.json();
|
||||||
|
const record = {
|
||||||
|
...reviewRecord,
|
||||||
|
// comment: "Created by wr.do (review mode)",
|
||||||
|
id,
|
||||||
|
};
|
||||||
|
|
||||||
|
let matchedZone;
|
||||||
|
|
||||||
|
for (const zone of zones) {
|
||||||
|
if (record.zone_name === zone.domain_name) {
|
||||||
|
matchedZone = zone;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await createDNSRecord(
|
||||||
|
matchedZone.cf_zone_id,
|
||||||
|
matchedZone.cf_api_key,
|
||||||
|
matchedZone.cf_email,
|
||||||
|
record,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!data.success || !data.result?.id) {
|
||||||
|
return Response.json(data.messages, {
|
||||||
|
status: 501,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
const res = await updateUserRecordReview(userId, id, {
|
||||||
|
record_id: data.result.id,
|
||||||
|
zone_id: matchedZone.cf_zone_id,
|
||||||
|
zone_name: matchedZone.domain_name,
|
||||||
|
name: data.result.name,
|
||||||
|
type: data.result.type,
|
||||||
|
content: data.result.content,
|
||||||
|
proxied: data.result.proxied,
|
||||||
|
proxiable: data.result.proxiable,
|
||||||
|
ttl: data.result.ttl,
|
||||||
|
comment: data.result.comment ?? "",
|
||||||
|
tags: data.result.tags?.join("") ?? "",
|
||||||
|
created_on: data.result.created_on,
|
||||||
|
modified_on: data.result.modified_on,
|
||||||
|
active: 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (res.status !== "success") {
|
||||||
|
return Response.json(res.status, {
|
||||||
|
status: 502,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return Response.json(res.data);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[错误]", error);
|
||||||
|
return Response.json(error, {
|
||||||
|
status: error?.status || 500,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
71
app/api/record/admin/reject/route.ts
Normal file
71
app/api/record/admin/reject/route.ts
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
import { createDNSRecord } from "@/lib/cloudflare";
|
||||||
|
import { updateUserRecordReview } from "@/lib/dto/cloudflare-dns-record";
|
||||||
|
import { getDomainsByFeature } from "@/lib/dto/domains";
|
||||||
|
import { checkUserStatus } from "@/lib/dto/user";
|
||||||
|
import { getCurrentUser } from "@/lib/session";
|
||||||
|
|
||||||
|
export async function POST(req: Request) {
|
||||||
|
try {
|
||||||
|
const user = checkUserStatus(await getCurrentUser());
|
||||||
|
if (user instanceof Response) return user;
|
||||||
|
|
||||||
|
const zones = await getDomainsByFeature("enable_dns", true);
|
||||||
|
if (!zones.length) {
|
||||||
|
return Response.json("Please add at least one domain", {
|
||||||
|
status: 400,
|
||||||
|
statusText: "Please add at least one domain",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const { record: reviewRecord, userId, recordId } = await req.json();
|
||||||
|
const record = {
|
||||||
|
...reviewRecord,
|
||||||
|
recordId,
|
||||||
|
};
|
||||||
|
|
||||||
|
let matchedZone;
|
||||||
|
|
||||||
|
for (const zone of zones) {
|
||||||
|
if (record.zone_name === zone.domain_name) {
|
||||||
|
matchedZone = zone;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// const data = await createDNSRecord(
|
||||||
|
// matchedZone.cf_zone_id,
|
||||||
|
// matchedZone.cf_api_key,
|
||||||
|
// matchedZone.cf_email,
|
||||||
|
// record,
|
||||||
|
// );
|
||||||
|
|
||||||
|
const res = await updateUserRecordReview(userId, recordId, {
|
||||||
|
record_id: recordId,
|
||||||
|
zone_id: matchedZone.cf_zone_id,
|
||||||
|
zone_name: matchedZone.domain_name,
|
||||||
|
name: record.name,
|
||||||
|
type: record.type,
|
||||||
|
content: record.content,
|
||||||
|
proxied: record.proxied,
|
||||||
|
proxiable: record.proxiable,
|
||||||
|
ttl: record.ttl,
|
||||||
|
comment: record.comment ?? "",
|
||||||
|
tags: "",
|
||||||
|
created_on: new Date().toISOString(),
|
||||||
|
modified_on: new Date().toISOString(),
|
||||||
|
active: 3,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (res.status !== "success") {
|
||||||
|
return Response.json(res.status, {
|
||||||
|
status: 502,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return Response.json(res.data);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[错误]", error);
|
||||||
|
return Response.json(error, {
|
||||||
|
status: error?.status || 500,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -16,6 +16,10 @@ export async function POST(req: NextRequest) {
|
|||||||
lang,
|
lang,
|
||||||
device,
|
device,
|
||||||
browser,
|
browser,
|
||||||
|
engine,
|
||||||
|
os,
|
||||||
|
cpu,
|
||||||
|
isBot,
|
||||||
password,
|
password,
|
||||||
} = await req.json();
|
} = await req.json();
|
||||||
|
|
||||||
@@ -57,6 +61,10 @@ export async function POST(req: NextRequest) {
|
|||||||
lang,
|
lang,
|
||||||
device,
|
device,
|
||||||
browser,
|
browser,
|
||||||
|
engine,
|
||||||
|
os,
|
||||||
|
cpu,
|
||||||
|
isBot,
|
||||||
});
|
});
|
||||||
return Response.json(res.target);
|
return Response.json(res.target);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { TeamPlanQuota } from "@/config/team";
|
|
||||||
import { getDomainsByFeature } from "@/lib/dto/domains";
|
import { getDomainsByFeature } from "@/lib/dto/domains";
|
||||||
|
import { getPlanQuota } from "@/lib/dto/plan";
|
||||||
import { createUserShortUrl } from "@/lib/dto/short-urls";
|
import { createUserShortUrl } from "@/lib/dto/short-urls";
|
||||||
import { checkUserStatus } from "@/lib/dto/user";
|
import { checkUserStatus } from "@/lib/dto/user";
|
||||||
import { getCurrentUser } from "@/lib/session";
|
import { getCurrentUser } from "@/lib/session";
|
||||||
@@ -11,11 +11,12 @@ export async function POST(req: Request) {
|
|||||||
const user = checkUserStatus(await getCurrentUser());
|
const user = checkUserStatus(await getCurrentUser());
|
||||||
if (user instanceof Response) return user;
|
if (user instanceof Response) return user;
|
||||||
|
|
||||||
|
const plan = await getPlanQuota(user.team);
|
||||||
// check limit
|
// check limit
|
||||||
const limit = await restrictByTimeRange({
|
const limit = await restrictByTimeRange({
|
||||||
model: "userUrl",
|
model: "userUrl",
|
||||||
userId: user.id,
|
userId: user.id,
|
||||||
limit: TeamPlanQuota[user.team].SL_NewLinks,
|
limit: plan.slNewLinks,
|
||||||
rangeType: "month",
|
rangeType: "month",
|
||||||
});
|
});
|
||||||
if (limit) return Response.json(limit.statusText, { status: limit.status });
|
if (limit) return Response.json(limit.statusText, { status: limit.status });
|
||||||
|
|||||||
@@ -5,12 +5,12 @@ import { getCurrentUser } from "@/lib/session";
|
|||||||
export async function GET(req: Request) {
|
export async function GET(req: Request) {
|
||||||
try {
|
try {
|
||||||
const user = checkUserStatus(await getCurrentUser());
|
const user = checkUserStatus(await getCurrentUser());
|
||||||
|
if (user instanceof Response) return user;
|
||||||
|
|
||||||
const url = new URL(req.url);
|
const url = new URL(req.url);
|
||||||
const isAdmin = url.searchParams.get("admin");
|
const isAdmin = url.searchParams.get("admin");
|
||||||
|
|
||||||
if (isAdmin === "true") {
|
if (isAdmin === "true") {
|
||||||
if (user instanceof Response) return user;
|
|
||||||
if (user.role !== "ADMIN") {
|
if (user.role !== "ADMIN") {
|
||||||
return Response.json("Unauthorized", {
|
return Response.json("Unauthorized", {
|
||||||
status: 401,
|
status: 401,
|
||||||
|
|||||||
268
app/api/url/admin/locations/route.ts
Normal file
268
app/api/url/admin/locations/route.ts
Normal file
@@ -0,0 +1,268 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { create } from "lodash";
|
||||||
|
|
||||||
|
import { prisma } from "@/lib/db";
|
||||||
|
import { checkUserStatus } from "@/lib/dto/user";
|
||||||
|
import { getCurrentUser } from "@/lib/session";
|
||||||
|
|
||||||
|
export async function GET(request: NextRequest) {
|
||||||
|
try {
|
||||||
|
const user = checkUserStatus(await getCurrentUser());
|
||||||
|
if (user instanceof Response) return user;
|
||||||
|
|
||||||
|
const searchParams = request.nextUrl.searchParams;
|
||||||
|
const isAdmin = searchParams.get("isAdmin");
|
||||||
|
if (isAdmin === "true") {
|
||||||
|
if (user.role !== "ADMIN") {
|
||||||
|
return Response.json("Unauthorized", {
|
||||||
|
status: 401,
|
||||||
|
statusText: "Unauthorized",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const startAtParam = searchParams.get("startAt");
|
||||||
|
const endAtParam = searchParams.get("endAt");
|
||||||
|
const country = searchParams.get("country");
|
||||||
|
|
||||||
|
let startDate: Date;
|
||||||
|
let endDate: Date;
|
||||||
|
|
||||||
|
if (startAtParam && endAtParam) {
|
||||||
|
startDate = new Date(parseInt(startAtParam) * 1000);
|
||||||
|
endDate = new Date(parseInt(endAtParam) * 1000);
|
||||||
|
} else {
|
||||||
|
endDate = new Date();
|
||||||
|
startDate = new Date(Date.now() - 30 * 60 * 1000); // 30分钟前
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) {
|
||||||
|
throw new Error("Invalid startAt or endAt parameters");
|
||||||
|
}
|
||||||
|
|
||||||
|
const whereClause: any = {
|
||||||
|
...(isAdmin === "true" ? {} : { userUrl: { userId: user.id } }),
|
||||||
|
createdAt: {
|
||||||
|
gte: startDate,
|
||||||
|
lte: endDate,
|
||||||
|
},
|
||||||
|
latitude: {
|
||||||
|
not: null,
|
||||||
|
},
|
||||||
|
longitude: {
|
||||||
|
not: null,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
if (country && country !== "") {
|
||||||
|
whereClause.country = country;
|
||||||
|
}
|
||||||
|
|
||||||
|
const rawData = await prisma.urlMeta.findMany({
|
||||||
|
where: whereClause,
|
||||||
|
select: {
|
||||||
|
latitude: true,
|
||||||
|
longitude: true,
|
||||||
|
click: true,
|
||||||
|
city: true,
|
||||||
|
country: true,
|
||||||
|
device: true,
|
||||||
|
browser: true,
|
||||||
|
createdAt: true,
|
||||||
|
updatedAt: true,
|
||||||
|
userUrl: {
|
||||||
|
select: {
|
||||||
|
url: true,
|
||||||
|
target: true,
|
||||||
|
prefix: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
orderBy: { updatedAt: "desc" },
|
||||||
|
take: 2000,
|
||||||
|
});
|
||||||
|
|
||||||
|
// console.log("Raw data fetched:", rawData.length, "records");
|
||||||
|
|
||||||
|
const locationMap = new Map<
|
||||||
|
string,
|
||||||
|
{
|
||||||
|
latitude: number;
|
||||||
|
longitude: number;
|
||||||
|
count: number;
|
||||||
|
city: string;
|
||||||
|
country: string;
|
||||||
|
lastUpdate: Date;
|
||||||
|
updatedAt: Date;
|
||||||
|
createdAt: Date;
|
||||||
|
device: string;
|
||||||
|
browser: string;
|
||||||
|
userUrl: {
|
||||||
|
url: string;
|
||||||
|
target: string;
|
||||||
|
prefix: string;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
>();
|
||||||
|
|
||||||
|
rawData.forEach((item) => {
|
||||||
|
if (item.latitude && item.longitude) {
|
||||||
|
const lat = Math.round(Number(item.latitude) * 100) / 100;
|
||||||
|
const lng = Math.round(Number(item.longitude) * 100) / 100;
|
||||||
|
const key = `${lat},${lng},${item.createdAt},${item.userUrl.url},${item.userUrl.prefix}`;
|
||||||
|
|
||||||
|
if (locationMap.has(key)) {
|
||||||
|
const existing = locationMap.get(key)!;
|
||||||
|
existing.count += item.click || 1;
|
||||||
|
if (item.updatedAt > existing.lastUpdate) {
|
||||||
|
existing.lastUpdate = item.updatedAt;
|
||||||
|
existing.city = item.city || existing.city;
|
||||||
|
existing.country = item.country || existing.country;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
locationMap.set(key, {
|
||||||
|
latitude: lat,
|
||||||
|
longitude: lng,
|
||||||
|
count: item.click || 1,
|
||||||
|
city: item.city || "",
|
||||||
|
country: item.country || "",
|
||||||
|
lastUpdate: item.updatedAt,
|
||||||
|
updatedAt: item.updatedAt,
|
||||||
|
createdAt: item.createdAt,
|
||||||
|
device: item.device || "",
|
||||||
|
browser: item.browser || "",
|
||||||
|
userUrl: item.userUrl,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const aggregatedData = Array.from(locationMap.values()).sort(
|
||||||
|
(a, b) => b.count - a.count,
|
||||||
|
);
|
||||||
|
// .slice(0, 500);
|
||||||
|
|
||||||
|
const totalClicks = aggregatedData.reduce(
|
||||||
|
(sum, item) => sum + item.count,
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
const uniqueLocations = aggregatedData.length;
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
data: aggregatedData,
|
||||||
|
total: uniqueLocations,
|
||||||
|
totalClicks,
|
||||||
|
rawRecords: rawData.length,
|
||||||
|
timeRange: {
|
||||||
|
startAt: startDate.toISOString(),
|
||||||
|
endAt: endDate.toISOString(),
|
||||||
|
},
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching location data:", error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{
|
||||||
|
data: [],
|
||||||
|
total: 0,
|
||||||
|
totalClicks: 0,
|
||||||
|
rawRecords: 0,
|
||||||
|
error:
|
||||||
|
error instanceof Error
|
||||||
|
? error.message
|
||||||
|
: "Failed to fetch location data",
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
},
|
||||||
|
{ status: 500 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// POST endpoint remains the same
|
||||||
|
export async function POST(request: NextRequest) {
|
||||||
|
try {
|
||||||
|
const user = checkUserStatus(await getCurrentUser());
|
||||||
|
if (user instanceof Response) return user;
|
||||||
|
|
||||||
|
const body = await request.json();
|
||||||
|
const { lastUpdate, isAdmin } = body;
|
||||||
|
|
||||||
|
if (isAdmin) {
|
||||||
|
if (user.role !== "ADMIN") {
|
||||||
|
return Response.json("Unauthorized", {
|
||||||
|
status: 401,
|
||||||
|
statusText: "Unauthorized",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const sinceDate = lastUpdate
|
||||||
|
? new Date(lastUpdate)
|
||||||
|
: new Date(Date.now() - 5000);
|
||||||
|
|
||||||
|
// console.log("lastUpdate", lastUpdate, sinceDate);
|
||||||
|
|
||||||
|
if (isNaN(sinceDate.getTime())) {
|
||||||
|
throw new Error("Invalid lastUpdate parameter");
|
||||||
|
}
|
||||||
|
|
||||||
|
const whereClause: any = {
|
||||||
|
...(isAdmin ? {} : { userUrl: { userId: user.id } }),
|
||||||
|
createdAt: {
|
||||||
|
gt: sinceDate,
|
||||||
|
},
|
||||||
|
latitude: {
|
||||||
|
not: null,
|
||||||
|
},
|
||||||
|
longitude: {
|
||||||
|
not: null,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const newData = await prisma.urlMeta.findMany({
|
||||||
|
where: whereClause,
|
||||||
|
select: {
|
||||||
|
latitude: true,
|
||||||
|
longitude: true,
|
||||||
|
click: true,
|
||||||
|
city: true,
|
||||||
|
country: true,
|
||||||
|
device: true,
|
||||||
|
browser: true,
|
||||||
|
createdAt: true,
|
||||||
|
updatedAt: true,
|
||||||
|
userUrl: {
|
||||||
|
select: {
|
||||||
|
url: true,
|
||||||
|
target: true,
|
||||||
|
prefix: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
orderBy: { updatedAt: "desc" },
|
||||||
|
take: 1000,
|
||||||
|
});
|
||||||
|
|
||||||
|
// console.log("Realtime updates fetched:", newData.length, "records");
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
data: newData,
|
||||||
|
count: newData.length,
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching realtime updates:", error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{
|
||||||
|
data: [],
|
||||||
|
count: 0,
|
||||||
|
error:
|
||||||
|
error instanceof Error
|
||||||
|
? error.message
|
||||||
|
: "Failed to fetch realtime updates",
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
},
|
||||||
|
{ status: 500 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { getUserShortUrls } from "@/lib/dto/short-urls";
|
import { getUrlClicksByIds, getUserShortUrls } from "@/lib/dto/short-urls";
|
||||||
import { checkUserStatus } from "@/lib/dto/user";
|
import { checkUserStatus } from "@/lib/dto/user";
|
||||||
import { getCurrentUser } from "@/lib/session";
|
import { getCurrentUser } from "@/lib/session";
|
||||||
|
|
||||||
@@ -34,11 +34,31 @@ export async function GET(req: Request) {
|
|||||||
|
|
||||||
return Response.json(data);
|
return Response.json(data);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(error);
|
// console.log(error);
|
||||||
|
|
||||||
return Response.json(error?.statusText || error, {
|
return Response.json(error?.statusText || error, {
|
||||||
status: error.status || 500,
|
status: error.status || 500,
|
||||||
statusText: error.statusText || "Server error",
|
statusText: error.statusText || "Server error",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function POST(req: Request) {
|
||||||
|
try {
|
||||||
|
const user = checkUserStatus(await getCurrentUser());
|
||||||
|
if (user instanceof Response) return user;
|
||||||
|
if (user.role !== "ADMIN") {
|
||||||
|
return Response.json("Unauthorized", {
|
||||||
|
status: 401,
|
||||||
|
statusText: "Unauthorized",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const { ids } = await req.json();
|
||||||
|
const data = await getUrlClicksByIds(ids, user.id, "ADMIN");
|
||||||
|
return Response.json(data);
|
||||||
|
} catch (error) {
|
||||||
|
return Response.json(error?.statusText || error, {
|
||||||
|
status: error.status || 500,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { getUserShortUrls } from "@/lib/dto/short-urls";
|
import { getUrlClicksByIds, getUserShortUrls } from "@/lib/dto/short-urls";
|
||||||
import { checkUserStatus } from "@/lib/dto/user";
|
import { checkUserStatus } from "@/lib/dto/user";
|
||||||
import { getCurrentUser } from "@/lib/session";
|
import { getCurrentUser } from "@/lib/session";
|
||||||
|
|
||||||
@@ -31,3 +31,18 @@ export async function GET(req: Request) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function POST(req: Request) {
|
||||||
|
try {
|
||||||
|
const user = checkUserStatus(await getCurrentUser());
|
||||||
|
if (user instanceof Response) return user;
|
||||||
|
|
||||||
|
const { ids } = await req.json();
|
||||||
|
const data = await getUrlClicksByIds(ids, user.id, "USER");
|
||||||
|
return Response.json(data);
|
||||||
|
} catch (error) {
|
||||||
|
return Response.json(error?.statusText || error, {
|
||||||
|
status: error.status || 500,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,10 +1,9 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
|
||||||
import { siteConfig } from "@/config/site";
|
|
||||||
import { TeamPlanQuota } from "@/config/team";
|
|
||||||
import { checkApiKey } from "@/lib/dto/api-key";
|
import { checkApiKey } from "@/lib/dto/api-key";
|
||||||
import { getDomainsByFeature } from "@/lib/dto/domains";
|
import { getDomainsByFeature } from "@/lib/dto/domains";
|
||||||
import { createUserEmail, deleteUserEmailByAddress } from "@/lib/dto/email";
|
import { createUserEmail, deleteUserEmailByAddress } from "@/lib/dto/email";
|
||||||
|
import { getPlanQuota } from "@/lib/dto/plan";
|
||||||
import { reservedAddressSuffix } from "@/lib/enums";
|
import { reservedAddressSuffix } from "@/lib/enums";
|
||||||
import { restrictByTimeRange } from "@/lib/team";
|
import { restrictByTimeRange } from "@/lib/team";
|
||||||
|
|
||||||
@@ -32,11 +31,13 @@ export async function POST(req: NextRequest) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const plan = await getPlanQuota(user.team!);
|
||||||
|
|
||||||
// check limit
|
// check limit
|
||||||
const limit = await restrictByTimeRange({
|
const limit = await restrictByTimeRange({
|
||||||
model: "userEmail",
|
model: "userEmail",
|
||||||
userId: user.id,
|
userId: user.id,
|
||||||
limit: TeamPlanQuota[user.team!].EM_EmailAddresses,
|
limit: plan.emEmailAddresses,
|
||||||
rangeType: "month",
|
rangeType: "month",
|
||||||
});
|
});
|
||||||
if (limit)
|
if (limit)
|
||||||
|
|||||||
@@ -1,14 +1,11 @@
|
|||||||
import { ipAddress } from "@vercel/functions";
|
import { getIpInfo } from "@/lib/geo";
|
||||||
|
|
||||||
import { getIpInfo } from "@/lib/utils";
|
|
||||||
|
|
||||||
export async function GET(req: Request) {
|
export async function GET(req: Request) {
|
||||||
try {
|
try {
|
||||||
const data = getIpInfo(req);
|
const data = await getIpInfo(req);
|
||||||
const ip = ipAddress(req);
|
|
||||||
|
|
||||||
return Response.json({
|
return Response.json({
|
||||||
ip,
|
ip: data.ip,
|
||||||
city: data.city,
|
city: data.city,
|
||||||
region: data.region,
|
region: data.region,
|
||||||
country: data.country,
|
country: data.country,
|
||||||
|
|||||||
@@ -3,7 +3,8 @@ import TurndownService from "turndown";
|
|||||||
|
|
||||||
import { checkApiKey } from "@/lib/dto/api-key";
|
import { checkApiKey } from "@/lib/dto/api-key";
|
||||||
import { createScrapeMeta } from "@/lib/dto/scrape";
|
import { createScrapeMeta } from "@/lib/dto/scrape";
|
||||||
import { getIpInfo, isLink } from "@/lib/utils";
|
import { getIpInfo } from "@/lib/geo";
|
||||||
|
import { isLink } from "@/lib/utils";
|
||||||
|
|
||||||
export const revalidate = 600;
|
export const revalidate = 600;
|
||||||
export const dynamic = "force-dynamic";
|
export const dynamic = "force-dynamic";
|
||||||
@@ -70,9 +71,9 @@ export async function GET(req: Request) {
|
|||||||
|
|
||||||
const markdown = turndownService.turndown(mainContent || "");
|
const markdown = turndownService.turndown(mainContent || "");
|
||||||
|
|
||||||
const stats = getIpInfo(req);
|
const stats = await getIpInfo(req);
|
||||||
await createScrapeMeta({
|
await createScrapeMeta({
|
||||||
ip: stats.ip,
|
ip: stats.ip || "::1",
|
||||||
type: "markdown",
|
type: "markdown",
|
||||||
referer: stats.referer,
|
referer: stats.referer,
|
||||||
city: stats.city,
|
city: stats.city,
|
||||||
|
|||||||
@@ -2,7 +2,8 @@ import cheerio from "cheerio";
|
|||||||
|
|
||||||
import { checkApiKey } from "@/lib/dto/api-key";
|
import { checkApiKey } from "@/lib/dto/api-key";
|
||||||
import { createScrapeMeta } from "@/lib/dto/scrape";
|
import { createScrapeMeta } from "@/lib/dto/scrape";
|
||||||
import { getIpInfo, isLink, removeUrlSuffix } from "@/lib/utils";
|
import { getIpInfo } from "@/lib/geo";
|
||||||
|
import { isLink, removeUrlSuffix } from "@/lib/utils";
|
||||||
|
|
||||||
export const revalidate = 600;
|
export const revalidate = 600;
|
||||||
export const dynamic = "force-dynamic";
|
export const dynamic = "force-dynamic";
|
||||||
@@ -84,9 +85,9 @@ export async function GET(req: Request) {
|
|||||||
$("meta[name='author']").attr("content") ||
|
$("meta[name='author']").attr("content") ||
|
||||||
$("meta[property='author']").attr("content");
|
$("meta[property='author']").attr("content");
|
||||||
|
|
||||||
const stats = getIpInfo(req);
|
const stats = await getIpInfo(req);
|
||||||
await createScrapeMeta({
|
await createScrapeMeta({
|
||||||
ip: stats.ip,
|
ip: stats.ip || "::1",
|
||||||
type: "meta-info",
|
type: "meta-info",
|
||||||
referer: stats.referer,
|
referer: stats.referer,
|
||||||
city: stats.city,
|
city: stats.city,
|
||||||
|
|||||||
@@ -2,9 +2,10 @@ import { ImageResponse } from "@vercel/og";
|
|||||||
|
|
||||||
import { checkApiKey } from "@/lib/dto/api-key";
|
import { checkApiKey } from "@/lib/dto/api-key";
|
||||||
import { createScrapeMeta } from "@/lib/dto/scrape";
|
import { createScrapeMeta } from "@/lib/dto/scrape";
|
||||||
|
import { getIpInfo } from "@/lib/geo";
|
||||||
import { WRDO_QR_LOGO } from "@/lib/qr/constants";
|
import { WRDO_QR_LOGO } from "@/lib/qr/constants";
|
||||||
import { QRCodeSVG } from "@/lib/qr/utils";
|
import { QRCodeSVG } from "@/lib/qr/utils";
|
||||||
import { getIpInfo, getSearchParams } from "@/lib/utils";
|
import { getSearchParams } from "@/lib/utils";
|
||||||
import { getQRCodeQuerySchema } from "@/lib/validations/qr";
|
import { getQRCodeQuerySchema } from "@/lib/validations/qr";
|
||||||
|
|
||||||
const CORS_HEADERS = {
|
const CORS_HEADERS = {
|
||||||
@@ -41,9 +42,9 @@ export async function GET(req: Request) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const stats = getIpInfo(req);
|
const stats = await getIpInfo(req);
|
||||||
await createScrapeMeta({
|
await createScrapeMeta({
|
||||||
ip: stats.ip,
|
ip: stats.ip || "::1",
|
||||||
type: "qrcode",
|
type: "qrcode",
|
||||||
referer: stats.referer,
|
referer: stats.referer,
|
||||||
city: stats.city,
|
city: stats.city,
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import { env } from "@/env.mjs";
|
import { env } from "@/env.mjs";
|
||||||
import { checkApiKey } from "@/lib/dto/api-key";
|
import { checkApiKey } from "@/lib/dto/api-key";
|
||||||
import { createScrapeMeta } from "@/lib/dto/scrape";
|
import { createScrapeMeta } from "@/lib/dto/scrape";
|
||||||
import { getIpInfo, isLink } from "@/lib/utils";
|
import { getIpInfo } from "@/lib/geo";
|
||||||
|
import { isLink } from "@/lib/utils";
|
||||||
|
|
||||||
export const revalidate = 60;
|
export const revalidate = 60;
|
||||||
|
|
||||||
@@ -69,9 +70,9 @@ export async function GET(req: Request) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const stats = getIpInfo(req);
|
const stats = await getIpInfo(req);
|
||||||
await createScrapeMeta({
|
await createScrapeMeta({
|
||||||
ip: stats.ip,
|
ip: stats.ip || "::1",
|
||||||
type: "screenshot",
|
type: "screenshot",
|
||||||
referer: stats.referer,
|
referer: stats.referer,
|
||||||
city: stats.city,
|
city: stats.city,
|
||||||
|
|||||||
@@ -2,7 +2,8 @@ import cheerio from "cheerio";
|
|||||||
|
|
||||||
import { checkApiKey } from "@/lib/dto/api-key";
|
import { checkApiKey } from "@/lib/dto/api-key";
|
||||||
import { createScrapeMeta } from "@/lib/dto/scrape";
|
import { createScrapeMeta } from "@/lib/dto/scrape";
|
||||||
import { getIpInfo, isLink } from "@/lib/utils";
|
import { getIpInfo } from "@/lib/geo";
|
||||||
|
import { isLink } from "@/lib/utils";
|
||||||
|
|
||||||
export const revalidate = 600;
|
export const revalidate = 600;
|
||||||
export const dynamic = "force-dynamic";
|
export const dynamic = "force-dynamic";
|
||||||
@@ -63,9 +64,9 @@ export async function GET(req: Request) {
|
|||||||
$("style").remove();
|
$("style").remove();
|
||||||
const text = $("body").text().trim();
|
const text = $("body").text().trim();
|
||||||
|
|
||||||
const stats = getIpInfo(req);
|
const stats = await getIpInfo(req);
|
||||||
await createScrapeMeta({
|
await createScrapeMeta({
|
||||||
ip: stats.ip,
|
ip: stats.ip || "::1",
|
||||||
type: "text",
|
type: "text",
|
||||||
referer: stats.referer,
|
referer: stats.referer,
|
||||||
city: stats.city,
|
city: stats.city,
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { TeamPlanQuota } from "@/config/team";
|
|
||||||
import { checkApiKey } from "@/lib/dto/api-key";
|
import { checkApiKey } from "@/lib/dto/api-key";
|
||||||
import { getDomainsByFeature } from "@/lib/dto/domains";
|
import { getDomainsByFeature } from "@/lib/dto/domains";
|
||||||
|
import { getPlanQuota } from "@/lib/dto/plan";
|
||||||
import { createUserShortUrl } from "@/lib/dto/short-urls";
|
import { createUserShortUrl } from "@/lib/dto/short-urls";
|
||||||
import { restrictByTimeRange } from "@/lib/team";
|
import { restrictByTimeRange } from "@/lib/team";
|
||||||
import { createUrlSchema } from "@/lib/validations/url";
|
import { createUrlSchema } from "@/lib/validations/url";
|
||||||
@@ -23,11 +23,13 @@ export async function POST(req: Request) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const plan = await getPlanQuota(user.team!);
|
||||||
|
|
||||||
// check limit
|
// check limit
|
||||||
const limit = await restrictByTimeRange({
|
const limit = await restrictByTimeRange({
|
||||||
model: "userUrl",
|
model: "userUrl",
|
||||||
userId: user.id,
|
userId: user.id,
|
||||||
limit: TeamPlanQuota[user.team!].SL_NewLinks,
|
limit: plan.slNewLinks,
|
||||||
rangeType: "month",
|
rangeType: "month",
|
||||||
});
|
});
|
||||||
if (limit) return Response.json(limit.statusText, { status: limit.status });
|
if (limit) return Response.json(limit.statusText, { status: limit.status });
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import { constructMetadata } from "@/lib/utils";
|
|||||||
import { EmailDashboard } from "./email";
|
import { EmailDashboard } from "./email";
|
||||||
|
|
||||||
export const metadata = constructMetadata({
|
export const metadata = constructMetadata({
|
||||||
title: "Emails - WR.DO",
|
title: "Emails",
|
||||||
description: "List and manage emails.",
|
description: "List and manage emails.",
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ import "@/styles/globals.css";
|
|||||||
|
|
||||||
import { fontHeading, fontSans, fontSatoshi } from "@/assets/fonts";
|
import { fontHeading, fontSans, fontSatoshi } from "@/assets/fonts";
|
||||||
import { SessionProvider } from "next-auth/react";
|
import { SessionProvider } from "next-auth/react";
|
||||||
|
import { NextIntlClientProvider } from "next-intl";
|
||||||
|
import { getLocale, getMessages } from "next-intl/server";
|
||||||
import { ThemeProvider } from "next-themes";
|
import { ThemeProvider } from "next-themes";
|
||||||
import { ViewTransitions } from "next-view-transitions";
|
import { ViewTransitions } from "next-view-transitions";
|
||||||
|
|
||||||
@@ -18,10 +20,12 @@ interface RootLayoutProps {
|
|||||||
|
|
||||||
export const metadata = constructMetadata();
|
export const metadata = constructMetadata();
|
||||||
|
|
||||||
export default function RootLayout({ children }: RootLayoutProps) {
|
export default async function RootLayout({ children }: RootLayoutProps) {
|
||||||
|
const locale = await getLocale();
|
||||||
|
const messages = await getMessages();
|
||||||
return (
|
return (
|
||||||
<ViewTransitions>
|
<ViewTransitions>
|
||||||
<html lang="en" suppressHydrationWarning>
|
<html lang={locale} suppressHydrationWarning>
|
||||||
<head>
|
<head>
|
||||||
<script
|
<script
|
||||||
defer
|
defer
|
||||||
@@ -37,6 +41,7 @@ export default function RootLayout({ children }: RootLayoutProps) {
|
|||||||
fontSatoshi.variable,
|
fontSatoshi.variable,
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
|
<NextIntlClientProvider messages={messages}>
|
||||||
<SessionProvider>
|
<SessionProvider>
|
||||||
<ThemeProvider
|
<ThemeProvider
|
||||||
attribute="class"
|
attribute="class"
|
||||||
@@ -49,6 +54,7 @@ export default function RootLayout({ children }: RootLayoutProps) {
|
|||||||
<TailwindIndicator />
|
<TailwindIndicator />
|
||||||
</ThemeProvider>
|
</ThemeProvider>
|
||||||
</SessionProvider>
|
</SessionProvider>
|
||||||
|
</NextIntlClientProvider>
|
||||||
<GoogleAnalytics />
|
<GoogleAnalytics />
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
"short_name": "WR.DO",
|
"short_name": "WR.DO",
|
||||||
"description": "Shorten links with analytics, manage emails and control subdomains—all on one platform.",
|
"description": "Shorten links with analytics, manage emails and control subdomains—all on one platform.",
|
||||||
"appid": "com.wr.do",
|
"appid": "com.wr.do",
|
||||||
"versionName": "0.6.1",
|
"versionName": "1.0.0",
|
||||||
"versionCode": "1",
|
"versionCode": "1",
|
||||||
"start_url": "/",
|
"start_url": "/",
|
||||||
"orientation": "portrait",
|
"orientation": "portrait",
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { useEffect, useRef, useState, useTransition } from "react";
|
|||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { useRouter, useSearchParams } from "next/navigation";
|
import { useRouter, useSearchParams } from "next/navigation";
|
||||||
import { Eye, EyeOff } from "lucide-react";
|
import { Eye, EyeOff } from "lucide-react";
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
|
|
||||||
import { siteConfig } from "@/config/site";
|
import { siteConfig } from "@/config/site";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
@@ -23,6 +24,8 @@ export default function PasswordPrompt() {
|
|||||||
const [isPending, startTransition] = useTransition();
|
const [isPending, startTransition] = useTransition();
|
||||||
const inputRefs = useRef<(HTMLInputElement | null)[]>(Array(6).fill(null));
|
const inputRefs = useRef<(HTMLInputElement | null)[]>(Array(6).fill(null));
|
||||||
|
|
||||||
|
const t = useTranslations("Components");
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (initialPassword) {
|
if (initialPassword) {
|
||||||
const paddedPassword = initialPassword
|
const paddedPassword = initialPassword
|
||||||
@@ -83,20 +86,22 @@ export default function PasswordPrompt() {
|
|||||||
<div className="flex flex-1 items-center justify-center">
|
<div className="flex flex-1 items-center justify-center">
|
||||||
<div className="mx-3 w-full max-w-md rounded-lg bg-black/70 px-6 py-6 shadow-md shadow-neutral-900 backdrop-blur-xl md:px-[50px]">
|
<div className="mx-3 w-full max-w-md rounded-lg bg-black/70 px-6 py-6 shadow-md shadow-neutral-900 backdrop-blur-xl md:px-[50px]">
|
||||||
<h1 className="mb-4 flex items-center justify-center gap-2 text-center text-2xl font-bold text-neutral-50">
|
<h1 className="mb-4 flex items-center justify-center gap-2 text-center text-2xl font-bold text-neutral-50">
|
||||||
Protected Link
|
{t("Protected Link")}
|
||||||
</h1>
|
</h1>
|
||||||
|
|
||||||
<div className="mb-4 break-all text-left text-sm text-neutral-400">
|
<div className="mb-4 break-all text-left text-sm text-neutral-400">
|
||||||
<p>
|
<p>
|
||||||
You are attempting to access a password-protected link.{" "}
|
{t("You are attempting to access a password-protected link")}.{" "}
|
||||||
<strong>Please contact the owner to get the password.</strong>{" "}
|
<strong>
|
||||||
Learn more about this from our{" "}
|
{t("Please contact the owner to get the password")}
|
||||||
|
</strong>
|
||||||
|
. {t("Learn more about this from our")}{" "}
|
||||||
<Link
|
<Link
|
||||||
className="underline"
|
className="underline"
|
||||||
target="_blank"
|
target="_blank"
|
||||||
href="/docs/short-urls#password"
|
href="/docs/short-urls#password"
|
||||||
>
|
>
|
||||||
docs
|
{t("docs")}
|
||||||
</Link>
|
</Link>
|
||||||
.
|
.
|
||||||
</p>
|
</p>
|
||||||
@@ -121,7 +126,7 @@ export default function PasswordPrompt() {
|
|||||||
|
|
||||||
{isError && (
|
{isError && (
|
||||||
<p className="mb-2 animate-fade-in text-left text-sm text-red-500">
|
<p className="mb-2 animate-fade-in text-left text-sm text-red-500">
|
||||||
Incorrect password. Please try again.
|
{t("Incorrect password")}! {t("Please try again")}.
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -151,7 +156,7 @@ export default function PasswordPrompt() {
|
|||||||
) : (
|
) : (
|
||||||
<Icons.unLock className="size-4" />
|
<Icons.unLock className="size-4" />
|
||||||
)}
|
)}
|
||||||
{isPending ? "Unlocking..." : "Unlock"}
|
{isPending ? t("Unlocking") : t("Unlock")}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
|
|||||||
@@ -47,7 +47,7 @@ export default {
|
|||||||
}),
|
}),
|
||||||
Resend({
|
Resend({
|
||||||
apiKey: env.RESEND_API_KEY,
|
apiKey: env.RESEND_API_KEY,
|
||||||
from: "wrdo <support@wr.do>",
|
from: env.RESEND_FROM_EMAIL || "wrdo <support@wr.do>",
|
||||||
async sendVerificationRequest({ identifier: email, url, provider }) {
|
async sendVerificationRequest({ identifier: email, url, provider }) {
|
||||||
try {
|
try {
|
||||||
const { error } = await resend.emails.send({
|
const { error } = await resend.emails.send({
|
||||||
|
|||||||
1
auth.ts
1
auth.ts
@@ -22,6 +22,7 @@ export const {
|
|||||||
handlers: { GET, POST },
|
handlers: { GET, POST },
|
||||||
auth,
|
auth,
|
||||||
} = NextAuth({
|
} = NextAuth({
|
||||||
|
trustHost: true, // TODO: Test with docker
|
||||||
adapter: PrismaAdapter(prisma),
|
adapter: PrismaAdapter(prisma),
|
||||||
session: { strategy: "jwt" },
|
session: { strategy: "jwt" },
|
||||||
pages: {
|
pages: {
|
||||||
|
|||||||
@@ -2,11 +2,13 @@
|
|||||||
|
|
||||||
import * as React from "react";
|
import * as React from "react";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
import { Bar, BarChart, CartesianGrid, XAxis, YAxis } from "recharts";
|
import { Bar, BarChart, CartesianGrid, XAxis, YAxis } from "recharts";
|
||||||
import useSWR from "swr";
|
import useSWR from "swr";
|
||||||
|
|
||||||
import { DATE_DIMENSION_ENUMS } from "@/lib/enums";
|
import { DATE_DIMENSION_ENUMS } from "@/lib/enums";
|
||||||
import { cn, fetcher, nFormatter } from "@/lib/utils";
|
import { cn, fetcher, nFormatter } from "@/lib/utils";
|
||||||
|
import { useElementSize } from "@/hooks/use-element-size";
|
||||||
import {
|
import {
|
||||||
Card,
|
Card,
|
||||||
CardContent,
|
CardContent,
|
||||||
@@ -21,11 +23,11 @@ import {
|
|||||||
ChartTooltipContent,
|
ChartTooltipContent,
|
||||||
} from "@/components/ui/chart";
|
} from "@/components/ui/chart";
|
||||||
|
|
||||||
import CountUp from "../dashboard/count-up";
|
|
||||||
import {
|
import {
|
||||||
Select,
|
Select,
|
||||||
SelectContent,
|
SelectContent,
|
||||||
SelectItem,
|
SelectItem,
|
||||||
|
SelectSeparator,
|
||||||
SelectTrigger,
|
SelectTrigger,
|
||||||
SelectValue,
|
SelectValue,
|
||||||
} from "../ui/select";
|
} from "../ui/select";
|
||||||
@@ -62,10 +64,13 @@ const chartConfig = {
|
|||||||
} satisfies ChartConfig;
|
} satisfies ChartConfig;
|
||||||
|
|
||||||
export function InteractiveBarChart() {
|
export function InteractiveBarChart() {
|
||||||
|
const { ref: wrapperRef, width: wrapperWidth } = useElementSize();
|
||||||
const [timeRange, setTimeRange] = useState<string>("7d");
|
const [timeRange, setTimeRange] = useState<string>("7d");
|
||||||
const [activeChart, setActiveChart] =
|
const [activeChart, setActiveChart] =
|
||||||
React.useState<keyof typeof chartConfig>("users");
|
React.useState<keyof typeof chartConfig>("users");
|
||||||
|
|
||||||
|
const t = useTranslations("Components");
|
||||||
|
|
||||||
const { data, isLoading } = useSWR<{
|
const { data, isLoading } = useSWR<{
|
||||||
list: [
|
list: [
|
||||||
{
|
{
|
||||||
@@ -108,8 +113,8 @@ export function InteractiveBarChart() {
|
|||||||
<CardHeader className="flex flex-col items-stretch space-y-0 border-b p-0 sm:flex-row">
|
<CardHeader className="flex flex-col items-stretch space-y-0 border-b p-0 sm:flex-row">
|
||||||
<div className="flex w-full flex-1 justify-between gap-2 px-6 py-5 sm:flex-col sm:py-6">
|
<div className="flex w-full flex-1 justify-between gap-2 px-6 py-5 sm:flex-col sm:py-6">
|
||||||
<div className="flex flex-col justify-center gap-1">
|
<div className="flex flex-col justify-center gap-1">
|
||||||
<CardTitle>Data Increase</CardTitle>
|
<CardTitle>{t("Data Increase")}</CardTitle>
|
||||||
<CardDescription>Showing data increase in:</CardDescription>
|
<CardDescription>{t("Showing data increase in")}:</CardDescription>
|
||||||
</div>
|
</div>
|
||||||
<Select
|
<Select
|
||||||
onValueChange={(value: string) => {
|
onValueChange={(value: string) => {
|
||||||
@@ -122,16 +127,19 @@ export function InteractiveBarChart() {
|
|||||||
<SelectValue placeholder="Select a time" />
|
<SelectValue placeholder="Select a time" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
{DATE_DIMENSION_ENUMS.map((e) => (
|
{DATE_DIMENSION_ENUMS.map((e, i) => (
|
||||||
<SelectItem key={e.value} value={e.value}>
|
<div key={e.value}>
|
||||||
{e.label}
|
<SelectItem value={e.value}>{t(e.label)}</SelectItem>
|
||||||
</SelectItem>
|
{i % 2 === 0 && i !== DATE_DIMENSION_ENUMS.length - 1 && (
|
||||||
|
<SelectSeparator />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
))}
|
))}
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex">
|
<div className="grid grid-cols-3 sm:grid-cols-6">
|
||||||
{["users", "records", "urls", "emails", "inbox", "sends"].map(
|
{["users", "records", "urls", "emails", "inbox", "sends"].map(
|
||||||
(key) => {
|
(key) => {
|
||||||
const chart = key as keyof typeof chartConfig;
|
const chart = key as keyof typeof chartConfig;
|
||||||
@@ -141,13 +149,13 @@ export function InteractiveBarChart() {
|
|||||||
<button
|
<button
|
||||||
key={chart}
|
key={chart}
|
||||||
data-active={activeChart === chart}
|
data-active={activeChart === chart}
|
||||||
className="relative z-30 flex flex-1 flex-col justify-center gap-1 border-l border-t p-4 text-left data-[active=true]:bg-muted/50 sm:border-l sm:border-t-0 sm:p-6"
|
className="relative z-30 flex flex-col justify-center gap-1 border-l border-t p-3 text-left transition-colors hover:bg-muted/30 data-[active=true]:bg-muted/50 sm:border-t-0 sm:p-4"
|
||||||
onClick={() => setActiveChart(chart)}
|
onClick={() => setActiveChart(chart)}
|
||||||
>
|
>
|
||||||
<span className="text-xs text-muted-foreground">
|
<span className="text-xs text-muted-foreground">
|
||||||
{chartConfig[chart].label}
|
{t(chartConfig[chart].label)}
|
||||||
</span>
|
</span>
|
||||||
<span className="text-lg font-bold leading-none sm:text-3xl">
|
<span className="text-base font-bold leading-none sm:text-lg">
|
||||||
{nFormatter(data.total[key])}
|
{nFormatter(data.total[key])}
|
||||||
</span>
|
</span>
|
||||||
<span
|
<span
|
||||||
@@ -167,7 +175,7 @@ export function InteractiveBarChart() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="px-2 sm:p-6">
|
<CardContent ref={wrapperRef} className="px-2 sm:p-6">
|
||||||
<ChartContainer
|
<ChartContainer
|
||||||
config={chartConfig}
|
config={chartConfig}
|
||||||
className="aspect-auto h-[200px] w-full"
|
className="aspect-auto h-[200px] w-full"
|
||||||
@@ -175,6 +183,7 @@ export function InteractiveBarChart() {
|
|||||||
<BarChart
|
<BarChart
|
||||||
accessibilityLayer
|
accessibilityLayer
|
||||||
data={data.list}
|
data={data.list}
|
||||||
|
width={wrapperWidth}
|
||||||
margin={{
|
margin={{
|
||||||
left: 12,
|
left: 12,
|
||||||
right: 12,
|
right: 12,
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user