Compare commits
24 Commits
72a9fbdd74
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 93573f0efd | |||
|
|
1a5548d507 | ||
|
|
75fd2f5120 | ||
|
|
1a066e14df | ||
|
|
0a8e161c8d | ||
|
|
9bdbe8e153 | ||
| 51a376400c | |||
|
|
2df4a96ccd | ||
|
|
4ef8913759 | ||
|
|
61f426ef3c | ||
|
|
0ce9c1be39 | ||
|
|
d5d7b15f16 | ||
|
|
9642f2511a | ||
|
|
cd15c81b53 | ||
|
|
0dca836cf5 | ||
|
|
6c857b67a5 | ||
|
|
37d53f4508 | ||
|
|
9cd7f9faef | ||
|
|
179cc66813 | ||
|
|
2728852792 | ||
|
|
a123482b89 | ||
|
|
930b24a19d | ||
|
|
15df667a26 | ||
|
|
1180a9b04d |
26
.env.example
Normal file
26
.env.example
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
# Environment variables declared in this file are NOT automatically loaded by Prisma.
|
||||||
|
# Please add `import "dotenv/config";` to your `prisma.config.ts` file, or use the Prisma CLI with Bun
|
||||||
|
# to load environment variables from .env files: https://pris.ly/prisma-config-env-vars.
|
||||||
|
|
||||||
|
# Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.
|
||||||
|
# See the documentation for all the connection string options: https://pris.ly/d/connection-strings
|
||||||
|
|
||||||
|
# The following `prisma+postgres` URL is similar to the URL produced by running a local Prisma Postgres
|
||||||
|
# server with the `prisma dev` CLI command, when not choosing any non-default ports or settings. The API key, unlike the
|
||||||
|
# one found in a remote Prisma Postgres URL, does not contain any sensitive information.
|
||||||
|
|
||||||
|
NODE_ENV=production
|
||||||
|
|
||||||
|
DATABASE_URL="postgresql://wyview:wyview@localhost:5432/wyview"
|
||||||
|
|
||||||
|
NEXT_PUBLIC_PASSWORD=Azerty123
|
||||||
|
NEXTAUTH_SECRET=***
|
||||||
|
NEXTAUTH_URL=*vps_ip_address*
|
||||||
|
AUTH_SECRET=***
|
||||||
|
|
||||||
|
|
||||||
|
# TikTok API credentials
|
||||||
|
TIKTOK_CLIENT_KEY=***
|
||||||
|
TIKTOK_CLIENT_SECRET=***
|
||||||
|
TIKTOK_REDIRECT_URI_DEV=http://localhost:3000/api/tiktok/callback
|
||||||
|
TIKTOK_REDIRECT_URI_PROD=*vps_ip_address*/api/tiktok/callback
|
||||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -10,3 +10,5 @@ npm-debug.log*
|
|||||||
dist/
|
dist/
|
||||||
build/
|
build/
|
||||||
/app/generated/prisma
|
/app/generated/prisma
|
||||||
|
docker-compose.yml
|
||||||
|
deploy.sh
|
||||||
|
|||||||
@@ -7,6 +7,12 @@ WORKDIR /app
|
|||||||
ARG DATABASE_URL
|
ARG DATABASE_URL
|
||||||
ENV DATABASE_URL=$DATABASE_URL
|
ENV DATABASE_URL=$DATABASE_URL
|
||||||
|
|
||||||
|
ARG AUTH_SECRET
|
||||||
|
ENV AUTH_SECRET=$AUTH_SECRET
|
||||||
|
|
||||||
|
ARG NEXTAUTH_SECRET
|
||||||
|
ENV NEXTAUTH_SECRET=$NEXTAUTH_SECRET
|
||||||
|
|
||||||
# Copy package files
|
# Copy package files
|
||||||
COPY package*.json ./
|
COPY package*.json ./
|
||||||
COPY prisma.config.ts ./
|
COPY prisma.config.ts ./
|
||||||
|
|||||||
59
app/api/auth/callback/tiktok/route.ts
Normal file
59
app/api/auth/callback/tiktok/route.ts
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { exchangeCodeForTokens } from "@/lib/tiktok";
|
||||||
|
import { prisma } from "@/lib/prisma";
|
||||||
|
|
||||||
|
export async function GET(request: NextRequest) {
|
||||||
|
const { searchParams } = new URL(request.url);
|
||||||
|
const code = searchParams.get("code");
|
||||||
|
const state = searchParams.get("state");
|
||||||
|
const error = searchParams.get("error");
|
||||||
|
|
||||||
|
if (error || !code || !state) {
|
||||||
|
return NextResponse.redirect(new URL("/tiktok?error=access_denied", request.url));
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Récupérer verifier + userId depuis la DB via le state
|
||||||
|
const pkceRecord = await prisma.tikTokPKCE.findUnique({ where: { state } });
|
||||||
|
if (!pkceRecord) {
|
||||||
|
return NextResponse.redirect(new URL("/tiktok?error=missing_verifier", request.url));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Supprimer le record PKCE (usage unique)
|
||||||
|
await prisma.tikTokPKCE.delete({ where: { state } });
|
||||||
|
|
||||||
|
const { userId, codeVerifier } = pkceRecord;
|
||||||
|
|
||||||
|
const tokens = await exchangeCodeForTokens(code, codeVerifier);
|
||||||
|
const expiresAt = new Date(Date.now() + tokens.expires_in * 1000);
|
||||||
|
|
||||||
|
await prisma.tikTokToken.upsert({
|
||||||
|
where: { userId },
|
||||||
|
create: {
|
||||||
|
userId,
|
||||||
|
openId: tokens.open_id,
|
||||||
|
accessToken: tokens.access_token,
|
||||||
|
refreshToken: tokens.refresh_token,
|
||||||
|
expiresAt,
|
||||||
|
},
|
||||||
|
update: {
|
||||||
|
openId: tokens.open_id,
|
||||||
|
accessToken: tokens.access_token,
|
||||||
|
refreshToken: tokens.refresh_token,
|
||||||
|
expiresAt,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const existing = await prisma.trackedAccount.findFirst({ where: { userId, platform: "tiktok" } });
|
||||||
|
if (!existing) {
|
||||||
|
await prisma.trackedAccount.create({
|
||||||
|
data: { userId, platform: "tiktok", username: tokens.open_id, accountId: tokens.open_id },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.redirect(new URL("/tiktok?connected=1", request.url));
|
||||||
|
} catch (err) {
|
||||||
|
console.error("[TikTok callback error]", err);
|
||||||
|
return NextResponse.redirect(new URL("/tiktok?error=token_exchange", request.url));
|
||||||
|
}
|
||||||
|
}
|
||||||
77
app/api/tiktok/callback/route.ts
Normal file
77
app/api/tiktok/callback/route.ts
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { exchangeCodeForTokens } from "@/lib/tiktok";
|
||||||
|
import { prisma } from "@/lib/prisma";
|
||||||
|
|
||||||
|
const baseUrl = process.env.NEXT_PUBLIC_APP_URL ?? "";
|
||||||
|
|
||||||
|
export async function GET(request: NextRequest) {
|
||||||
|
const { searchParams } = new URL(request.url);
|
||||||
|
const code = searchParams.get("code");
|
||||||
|
const state = searchParams.get("state");
|
||||||
|
const error = searchParams.get("error");
|
||||||
|
|
||||||
|
if (error || !code || !state) {
|
||||||
|
return NextResponse.redirect(`${baseUrl}/tiktok?error=access_denied`);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const pkceRecord = await prisma.tikTokPKCE.findUnique({ where: { state } });
|
||||||
|
if (!pkceRecord) {
|
||||||
|
return NextResponse.redirect(`${baseUrl}/tiktok?error=missing_verifier`);
|
||||||
|
}
|
||||||
|
|
||||||
|
await prisma.tikTokPKCE.delete({ where: { state } });
|
||||||
|
|
||||||
|
const { userId, codeVerifier } = pkceRecord;
|
||||||
|
|
||||||
|
console.log("[TikTok callback] codeVerifier from DB:", codeVerifier);
|
||||||
|
console.log("[TikTok callback] code from TikTok:", code);
|
||||||
|
|
||||||
|
const tokens = await exchangeCodeForTokens(code, codeVerifier);
|
||||||
|
const expiresAt = new Date(Date.now() + tokens.expires_in * 1000);
|
||||||
|
|
||||||
|
// Upsert sur userId — plusieurs users peuvent partager le même compte TikTok
|
||||||
|
await prisma.tikTokToken.upsert({
|
||||||
|
where: { userId },
|
||||||
|
update: {
|
||||||
|
openId: tokens.open_id,
|
||||||
|
accessToken: tokens.access_token,
|
||||||
|
refreshToken: tokens.refresh_token,
|
||||||
|
expiresAt,
|
||||||
|
},
|
||||||
|
create: {
|
||||||
|
userId,
|
||||||
|
openId: tokens.open_id,
|
||||||
|
accessToken: tokens.access_token,
|
||||||
|
refreshToken: tokens.refresh_token,
|
||||||
|
expiresAt,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// TrackedAccount : update si existe, sinon create
|
||||||
|
const existing = await prisma.trackedAccount.findFirst({
|
||||||
|
where: { userId, platform: "tiktok" },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (existing) {
|
||||||
|
await prisma.trackedAccount.update({
|
||||||
|
where: { id: existing.id },
|
||||||
|
data: { username: tokens.open_id, accountId: tokens.open_id },
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
await prisma.trackedAccount.create({
|
||||||
|
data: {
|
||||||
|
userId,
|
||||||
|
platform: "tiktok",
|
||||||
|
username: tokens.open_id,
|
||||||
|
accountId: tokens.open_id,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.redirect(`${baseUrl}/tiktok?connected=1`);
|
||||||
|
} catch (err) {
|
||||||
|
console.error("[TikTok callback error]", err);
|
||||||
|
return NextResponse.redirect(`${baseUrl}/tiktok?error=token_exchange`);
|
||||||
|
}
|
||||||
|
}
|
||||||
34
app/api/tiktok/connect/route.ts
Normal file
34
app/api/tiktok/connect/route.ts
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { getTikTokAuthUrl, generateCodeVerifier, generateCodeChallenge } from "@/lib/tiktok";
|
||||||
|
import { prisma } from "@/lib/prisma";
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user) {
|
||||||
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const userId = (session.user as { id?: string }).id;
|
||||||
|
if (!userId) {
|
||||||
|
return NextResponse.json({ error: "Session error" }, { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const state = crypto.randomUUID();
|
||||||
|
const codeVerifier = generateCodeVerifier();
|
||||||
|
const codeChallenge = await generateCodeChallenge(codeVerifier);
|
||||||
|
|
||||||
|
console.log("[TikTok PKCE] verifier:", codeVerifier);
|
||||||
|
console.log("[TikTok PKCE] challenge:", codeChallenge);
|
||||||
|
console.log("[TikTok PKCE] verifier length:", codeVerifier.length);
|
||||||
|
|
||||||
|
// Stocker state + verifier + userId en DB
|
||||||
|
await prisma.tikTokPKCE.create({
|
||||||
|
data: { state, codeVerifier, userId },
|
||||||
|
});
|
||||||
|
|
||||||
|
const authUrl = getTikTokAuthUrl(state, codeChallenge);
|
||||||
|
console.log("[TikTok PKCE] authUrl:", authUrl);
|
||||||
|
return NextResponse.redirect(authUrl);
|
||||||
|
}
|
||||||
26
app/api/tiktok/disconnect/route.ts
Normal file
26
app/api/tiktok/disconnect/route.ts
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { prisma } from "@/lib/prisma";
|
||||||
|
|
||||||
|
export async function POST() {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user) {
|
||||||
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const userId = (session.user as { id?: string }).id;
|
||||||
|
if (!userId) {
|
||||||
|
return NextResponse.json({ error: "Session error" }, { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await prisma.tikTokToken.deleteMany({ where: { userId } });
|
||||||
|
|
||||||
|
return NextResponse.json({ success: true });
|
||||||
|
} catch (err) {
|
||||||
|
console.error("[TikTok disconnect error]", err);
|
||||||
|
return NextResponse.json({ error: "Disconnect failed" }, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
125
app/api/tiktok/snapshots/route.ts
Normal file
125
app/api/tiktok/snapshots/route.ts
Normal file
@@ -0,0 +1,125 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { prisma } from "@/lib/prisma";
|
||||||
|
|
||||||
|
const PLAN_RANK: Record<string, number> = { free: 0, pro: 1, elite: 2, team: 3 };
|
||||||
|
|
||||||
|
const PERIOD_MIN_PLAN: Record<string, string> = {
|
||||||
|
"7d": "free",
|
||||||
|
"30d": "pro",
|
||||||
|
"90d": "pro",
|
||||||
|
"all": "elite",
|
||||||
|
};
|
||||||
|
|
||||||
|
const PERIOD_DAYS: Record<string, number | null> = {
|
||||||
|
"7d": 7,
|
||||||
|
"30d": 30,
|
||||||
|
"90d": 90,
|
||||||
|
"all": null,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Plan max history cap (even for "all")
|
||||||
|
const PLAN_MAX_DAYS: Record<string, number | null> = {
|
||||||
|
free: 7,
|
||||||
|
pro: 90,
|
||||||
|
elite: null, // illimité
|
||||||
|
team: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
async function getAuthedUserId() {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user) return null;
|
||||||
|
return (session.user as { id?: string }).id ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function GET(req: NextRequest) {
|
||||||
|
const userId = await getAuthedUserId();
|
||||||
|
if (!userId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||||
|
|
||||||
|
const period = req.nextUrl.searchParams.get("period") ?? "7d";
|
||||||
|
|
||||||
|
const user = await prisma.user.findUnique({ where: { id: userId } });
|
||||||
|
if (!user) return NextResponse.json({ error: "User not found" }, { status: 404 });
|
||||||
|
|
||||||
|
const plan = (user as any).plan ?? "free";
|
||||||
|
|
||||||
|
// Vérif accès à la période demandée
|
||||||
|
const requiredPlan = PERIOD_MIN_PLAN[period] ?? "free";
|
||||||
|
if (PLAN_RANK[plan] < PLAN_RANK[requiredPlan]) {
|
||||||
|
return NextResponse.json({ error: "Plan insuffisant pour cette période" }, { status: 403 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const account = await prisma.trackedAccount.findFirst({
|
||||||
|
where: { userId, platform: "tiktok" },
|
||||||
|
});
|
||||||
|
if (!account) return NextResponse.json([], { status: 200 });
|
||||||
|
|
||||||
|
// Calcul de la date de début
|
||||||
|
const periodDays = PERIOD_DAYS[period];
|
||||||
|
const planMaxDays = PLAN_MAX_DAYS[plan];
|
||||||
|
|
||||||
|
let since: Date | undefined;
|
||||||
|
if (periodDays !== null) {
|
||||||
|
since = new Date(Date.now() - periodDays * 86_400_000);
|
||||||
|
} else if (planMaxDays !== null) {
|
||||||
|
since = new Date(Date.now() - planMaxDays * 86_400_000);
|
||||||
|
}
|
||||||
|
// sinon : illimité (team/elite + all)
|
||||||
|
|
||||||
|
const snapshots = await prisma.snapshot.findMany({
|
||||||
|
where: {
|
||||||
|
accountId: account.id,
|
||||||
|
...(since ? { createdAt: { gte: since } } : {}),
|
||||||
|
},
|
||||||
|
orderBy: { createdAt: "asc" },
|
||||||
|
select: {
|
||||||
|
createdAt: true,
|
||||||
|
followers: true,
|
||||||
|
likes: true,
|
||||||
|
videoCount: true,
|
||||||
|
views: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json(snapshots);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(req: NextRequest) {
|
||||||
|
const userId = await getAuthedUserId();
|
||||||
|
if (!userId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||||
|
|
||||||
|
const body = await req.json();
|
||||||
|
const { followers, likes, videoCount, views, displayName, openId } = body;
|
||||||
|
|
||||||
|
if (followers === undefined) {
|
||||||
|
return NextResponse.json({ error: "Champ 'followers' requis" }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Upsert TrackedAccount
|
||||||
|
let account = await prisma.trackedAccount.findFirst({
|
||||||
|
where: { userId, platform: "tiktok" },
|
||||||
|
});
|
||||||
|
if (!account) {
|
||||||
|
account = await prisma.trackedAccount.create({
|
||||||
|
data: {
|
||||||
|
userId,
|
||||||
|
platform: "tiktok",
|
||||||
|
username: displayName ?? openId ?? "unknown",
|
||||||
|
accountId: openId ?? userId,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const snapshot = await prisma.snapshot.create({
|
||||||
|
data: {
|
||||||
|
accountId: account.id,
|
||||||
|
followers: followers ?? 0,
|
||||||
|
likes: likes ?? 0,
|
||||||
|
videoCount: videoCount ?? 0,
|
||||||
|
views: views ?? 0,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json(snapshot, { status: 201 });
|
||||||
|
}
|
||||||
|
|
||||||
95
app/api/tiktok/stats/route.ts
Normal file
95
app/api/tiktok/stats/route.ts
Normal file
@@ -0,0 +1,95 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { auth } from "@/lib/auth";
|
||||||
|
import { fetchUserStats, refreshAccessToken } from "@/lib/tiktok";
|
||||||
|
import { prisma } from "@/lib/prisma";
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
if (!session?.user) {
|
||||||
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const userId = (session.user as { id?: string }).id;
|
||||||
|
if (!userId) {
|
||||||
|
return NextResponse.json({ error: "Session error" }, { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (process.env.NODE_ENV === "development") {
|
||||||
|
const user = await prisma.user.findUnique({ where: { id: userId } });
|
||||||
|
return NextResponse.json({
|
||||||
|
followers: 124,
|
||||||
|
likes: 856,
|
||||||
|
videoCount: 1,
|
||||||
|
views: 3432,
|
||||||
|
profileViews: 287,
|
||||||
|
displayName: "CrowMate studio",
|
||||||
|
avatarUrl: "",
|
||||||
|
plan: (user as any)?.plan ?? "free",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const tokenRecord = await prisma.tikTokToken.findUnique({ where: { userId } });
|
||||||
|
|
||||||
|
if (!tokenRecord) {
|
||||||
|
return NextResponse.json({ error: "Not connected" }, { status: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
let { accessToken, refreshToken, openId, expiresAt } = tokenRecord;
|
||||||
|
|
||||||
|
if (expiresAt.getTime() - Date.now() < 60_000) {
|
||||||
|
try {
|
||||||
|
const refreshed = await refreshAccessToken(refreshToken);
|
||||||
|
await prisma.tikTokToken.update({
|
||||||
|
where: { userId },
|
||||||
|
data: {
|
||||||
|
accessToken: refreshed.access_token,
|
||||||
|
refreshToken: refreshed.refresh_token,
|
||||||
|
expiresAt: new Date(Date.now() + refreshed.expires_in * 1000),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
accessToken = refreshed.access_token;
|
||||||
|
} catch (err) {
|
||||||
|
console.error("[TikTok stats refresh error]", err);
|
||||||
|
return NextResponse.json({ error: "Token refresh failed" }, { status: 401 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const stats = await fetchUserStats(accessToken, openId);
|
||||||
|
|
||||||
|
try {
|
||||||
|
let account = await prisma.trackedAccount.findFirst({
|
||||||
|
where: { userId, platform: "tiktok" },
|
||||||
|
});
|
||||||
|
if (!account) {
|
||||||
|
account = await prisma.trackedAccount.create({
|
||||||
|
data: {
|
||||||
|
userId,
|
||||||
|
platform: "tiktok",
|
||||||
|
username: stats.displayName ?? openId,
|
||||||
|
accountId: openId,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
await prisma.snapshot.create({
|
||||||
|
data: {
|
||||||
|
accountId: account.id,
|
||||||
|
followers: stats.followers ?? 0,
|
||||||
|
likes: stats.likes ?? 0,
|
||||||
|
videoCount: stats.videoCount ?? 0,
|
||||||
|
views: stats.views ?? 0,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (snapshotErr) {
|
||||||
|
console.error("[TikTok snapshot save error]", snapshotErr);
|
||||||
|
}
|
||||||
|
const user = await prisma.user.findUnique({ where: { id: userId } });
|
||||||
|
return NextResponse.json({ ...stats, plan: (user as any)?.plan ?? "free" });
|
||||||
|
} catch (err) {
|
||||||
|
console.error("[TikTok stats fetch error]", err);
|
||||||
|
return NextResponse.json({ error: "Failed to fetch stats" }, { status: 500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -1,38 +1,5 @@
|
|||||||
"use client";
|
import AppLayout from "@/components/AppLayout";
|
||||||
|
|
||||||
import { useEffect } from "react";
|
|
||||||
import { useRouter } from "next/navigation";
|
|
||||||
import { useSession } from "next-auth/react";
|
|
||||||
import Sidebar from "@/components/Sidebar";
|
|
||||||
|
|
||||||
export default function AuthLayout({ children }: { children: React.ReactNode }) {
|
export default function AuthLayout({ children }: { children: React.ReactNode }) {
|
||||||
const { status } = useSession();
|
return <AppLayout>{children}</AppLayout>;
|
||||||
const router = useRouter();
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (status === "unauthenticated") {
|
|
||||||
router.push("/");
|
|
||||||
}
|
|
||||||
}, [status, router]);
|
|
||||||
|
|
||||||
if (status === "loading") {
|
|
||||||
return (
|
|
||||||
<div className="min-h-screen bg-[#0a0d0f] flex items-center justify-center">
|
|
||||||
<span className="text-[#4aff8c]/40 font-mono text-xs tracking-widest animate-pulse">
|
|
||||||
CHARGEMENT...
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (status !== "authenticated") return null;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="flex min-h-screen">
|
|
||||||
<Sidebar />
|
|
||||||
<main className="ml-56 flex-1 p-8">
|
|
||||||
{children}
|
|
||||||
</main>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
export default function DashboardPage() {
|
export default function DashboardPage() {
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<div className="text-[9px] font-mono tracking-[0.3em] text-[#4aff8c]/50 uppercase mb-1">Vue générale</div>
|
<div className="text-sm font-mono tracking-widest uppercase mb-1" style={{ color: "var(--accent)" }}>Vue générale</div>
|
||||||
<h1 className="text-2xl font-black tracking-widest text-white uppercase mb-8">Tableau de bord</h1>
|
<h1 className="text-3xl font-black tracking-widest uppercase mb-8" style={{ color: "var(--text-primary)" }}>Tableau de bord</h1>
|
||||||
<p className="text-[#3a5a3a] font-mono text-sm">Données à venir...</p>
|
<p className="font-mono text-sm" style={{ color: "var(--text-secondary)" }}>Données à venir...</p>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,29 +1,5 @@
|
|||||||
"use client";
|
import AppLayout from "@/components/AppLayout";
|
||||||
|
|
||||||
import { useEffect } from "react";
|
|
||||||
import { useRouter } from "next/navigation";
|
|
||||||
import { useSession } from "next-auth/react";
|
|
||||||
import Sidebar from "@/components/Sidebar";
|
|
||||||
|
|
||||||
export default function AuthLayout({ children }: { children: React.ReactNode }) {
|
export default function AuthLayout({ children }: { children: React.ReactNode }) {
|
||||||
const { status } = useSession();
|
return <AppLayout>{children}</AppLayout>;
|
||||||
const router = useRouter();
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (status === "unauthenticated") {
|
|
||||||
router.push("/");
|
|
||||||
}
|
|
||||||
}, [status, router]);
|
|
||||||
|
|
||||||
if (status === "loading") return null;
|
|
||||||
if (status !== "authenticated") return null;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="flex min-h-screen">
|
|
||||||
<Sidebar />
|
|
||||||
<main className="ml-56 flex-1 p-8">
|
|
||||||
{children}
|
|
||||||
</main>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import StatCard from "@/components/StatCard";
|
||||||
|
import { DollarSign } from "lucide-react";
|
||||||
|
|
||||||
|
export default function FinancesPage() {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div className="flex items-center gap-3 mb-8">
|
||||||
|
<div className="p-2 rounded-sm bg-yellow-500/10 border border-yellow-500/25">
|
||||||
|
<DollarSign size={18} className="text-yellow-400" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="text-[9px] font-mono tracking-[0.3em] text-yellow-400/70 uppercase mb-0.5">Revenus</div>
|
||||||
|
<h1 className="text-2xl font-black tracking-widest uppercase" style={{ color: "var(--text-primary)" }}>Finances</h1>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-2 xl:grid-cols-4 gap-4 mb-8">
|
||||||
|
<StatCard label="Revenus du mois" value="—" sub="Aucune donnée" accent="gold" />
|
||||||
|
<StatCard label="Revenus totaux" value="—" sub="Aucune donnée" accent="gold" />
|
||||||
|
<StatCard label="Donations" value="—" sub="Aucune donnée" accent="gold" />
|
||||||
|
<StatCard label="Abonnements" value="—" sub="Aucune donnée" accent="gold" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="border rounded-sm p-8 flex flex-col items-center justify-center gap-3 min-h-[200px]"
|
||||||
|
style={{ background: "var(--surface)", borderColor: "var(--border)" }}>
|
||||||
|
<DollarSign size={32} className="text-yellow-400/30" />
|
||||||
|
<p className="font-mono text-xs tracking-widest text-center" style={{ color: "var(--text-secondary)" }}>
|
||||||
|
AUCUNE DONNÉE FINANCIÈRE DISPONIBLE<br />POUR LE MOMENT
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,6 +2,36 @@
|
|||||||
@tailwind components;
|
@tailwind components;
|
||||||
@tailwind utilities;
|
@tailwind utilities;
|
||||||
|
|
||||||
|
/* ── Dark theme (default) ── */
|
||||||
|
:root {
|
||||||
|
--bg: #0d1117;
|
||||||
|
--surface: #161b22;
|
||||||
|
--border: #30363d;
|
||||||
|
--text-primary: #c9d1d9;
|
||||||
|
--text-secondary: #8b949e;
|
||||||
|
--accent: #4aff8c;
|
||||||
|
--accent-dim: rgba(74,255,140,0.1);
|
||||||
|
--accent-border: rgba(74,255,140,0.3);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Light theme ── */
|
||||||
|
html.light {
|
||||||
|
--bg: #f0f6ff;
|
||||||
|
--surface: #ffffff;
|
||||||
|
--border: #d0d7de;
|
||||||
|
--text-primary: #1c2128;
|
||||||
|
--text-secondary: #57606a;
|
||||||
|
--accent: #0ea5e9;
|
||||||
|
--accent-dim: rgba(14,165,233,0.1);
|
||||||
|
--accent-border: rgba(14,165,233,0.3);
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
background-color: var(--bg);
|
||||||
|
color: var(--text-primary);
|
||||||
|
transition: background-color 0.2s ease, color 0.2s ease;
|
||||||
|
}
|
||||||
|
|
||||||
::-webkit-scrollbar { width: 4px; }
|
::-webkit-scrollbar { width: 4px; }
|
||||||
::-webkit-scrollbar-track { background: transparent; }
|
::-webkit-scrollbar-track { background: transparent; }
|
||||||
::-webkit-scrollbar-thumb { background: #1a2a1a; border-radius: 2px; }
|
::-webkit-scrollbar-thumb { background: var(--border); border-radius: 2px; }
|
||||||
|
|||||||
@@ -1,29 +1,5 @@
|
|||||||
"use client";
|
import AppLayout from "@/components/AppLayout";
|
||||||
|
|
||||||
import { useEffect } from "react";
|
|
||||||
import { useRouter } from "next/navigation";
|
|
||||||
import { useSession } from "next-auth/react";
|
|
||||||
import Sidebar from "@/components/Sidebar";
|
|
||||||
|
|
||||||
export default function AuthLayout({ children }: { children: React.ReactNode }) {
|
export default function AuthLayout({ children }: { children: React.ReactNode }) {
|
||||||
const { status } = useSession();
|
return <AppLayout>{children}</AppLayout>;
|
||||||
const router = useRouter();
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (status === "unauthenticated") {
|
|
||||||
router.push("/");
|
|
||||||
}
|
|
||||||
}, [status, router]);
|
|
||||||
|
|
||||||
if (status === "loading") return null;
|
|
||||||
if (status !== "authenticated") return null;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="flex min-h-screen">
|
|
||||||
<Sidebar />
|
|
||||||
<main className="ml-56 flex-1 p-8">
|
|
||||||
{children}
|
|
||||||
</main>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import StatCard from "@/components/StatCard";
|
||||||
|
import { Camera } from "lucide-react";
|
||||||
|
|
||||||
|
export default function InstagramPage() {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div className="flex items-center gap-3 mb-8">
|
||||||
|
<div className="p-2 rounded-sm bg-orange-500/10 border border-orange-500/25">
|
||||||
|
<Camera size={18} className="text-orange-400" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="text-[9px] font-mono tracking-[0.3em] text-orange-400/70 uppercase mb-0.5">Plateforme</div>
|
||||||
|
<h1 className="text-2xl font-black tracking-widest uppercase" style={{ color: "var(--text-primary)" }}>Instagram</h1>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-2 xl:grid-cols-4 gap-4 mb-8">
|
||||||
|
<StatCard label="Abonnés" value="—" sub="Aucune donnée" accent="gold" />
|
||||||
|
<StatCard label="Likes totaux" value="—" sub="Aucune donnée" accent="gold" />
|
||||||
|
<StatCard label="Posts publiés" value="—" sub="Aucune donnée" accent="gold" />
|
||||||
|
<StatCard label="Portée moy." value="—" sub="Aucune donnée" accent="gold" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="border rounded-sm p-8 flex flex-col items-center justify-center gap-3 min-h-[200px]"
|
||||||
|
style={{ background: "var(--surface)", borderColor: "var(--border)" }}>
|
||||||
|
<Camera size={32} className="text-orange-400/30" />
|
||||||
|
<p className="font-mono text-xs tracking-widest text-center" style={{ color: "var(--text-secondary)" }}>
|
||||||
|
CONNECTEZ VOTRE COMPTE INSTAGRAM<br />POUR AFFICHER VOS STATISTIQUES
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import type { Metadata } from "next";
|
import type { Metadata } from "next";
|
||||||
import "./globals.css";
|
import "./globals.css";
|
||||||
import { SessionProvider } from "next-auth/react";
|
import { SessionProvider } from "next-auth/react";
|
||||||
|
import { ThemeProvider } from "@/lib/theme";
|
||||||
|
|
||||||
export const metadata: Metadata = {
|
export const metadata: Metadata = {
|
||||||
title: "WYVIEW",
|
title: "WYVIEW",
|
||||||
@@ -10,9 +11,11 @@ export const metadata: Metadata = {
|
|||||||
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
||||||
return (
|
return (
|
||||||
<html lang="fr">
|
<html lang="fr">
|
||||||
<body className="bg-[#0a0d0f] text-white antialiased">
|
<body className="bg-wy-dark text-wy-text-primary antialiased">
|
||||||
<SessionProvider>
|
<SessionProvider>
|
||||||
|
<ThemeProvider>
|
||||||
{children}
|
{children}
|
||||||
|
</ThemeProvider>
|
||||||
</SessionProvider>
|
</SessionProvider>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
70
app/page.tsx
70
app/page.tsx
@@ -8,13 +8,11 @@ import DragonEye from "@/components/DragonEye";
|
|||||||
export default function AuthPage() {
|
export default function AuthPage() {
|
||||||
const [tab, setTab] = useState<"login" | "register">("login");
|
const [tab, setTab] = useState<"login" | "register">("login");
|
||||||
|
|
||||||
// Login state
|
|
||||||
const [loginEmail, setLoginEmail] = useState("");
|
const [loginEmail, setLoginEmail] = useState("");
|
||||||
const [loginPassword, setLoginPassword] = useState("");
|
const [loginPassword, setLoginPassword] = useState("");
|
||||||
const [loginError, setLoginError] = useState("");
|
const [loginError, setLoginError] = useState("");
|
||||||
const [loginLoading, setLoginLoading] = useState(false);
|
const [loginLoading, setLoginLoading] = useState(false);
|
||||||
|
|
||||||
// Register state
|
|
||||||
const [regName, setRegName] = useState("");
|
const [regName, setRegName] = useState("");
|
||||||
const [regEmail, setRegEmail] = useState("");
|
const [regEmail, setRegEmail] = useState("");
|
||||||
const [regPassword, setRegPassword] = useState("");
|
const [regPassword, setRegPassword] = useState("");
|
||||||
@@ -37,7 +35,7 @@ export default function AuthPage() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (result?.ok) {
|
if (result?.ok) {
|
||||||
router.push("/dashboard");
|
window.location.href = "/dashboard";
|
||||||
} else {
|
} else {
|
||||||
setLoginError("Email ou mot de passe incorrect.");
|
setLoginError("Email ou mot de passe incorrect.");
|
||||||
setLoginLoading(false);
|
setLoginLoading(false);
|
||||||
@@ -85,61 +83,64 @@ export default function AuthPage() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const inputStyle: React.CSSProperties = {
|
||||||
|
background: "var(--surface)",
|
||||||
|
color: "var(--text-primary)",
|
||||||
|
borderColor: "var(--border)",
|
||||||
|
};
|
||||||
|
|
||||||
const inputClass = (hasError: boolean) =>
|
const inputClass = (hasError: boolean) =>
|
||||||
`w-full bg-[#0d1210] border px-4 py-3 text-sm font-mono text-white placeholder-[#2a3a2a] outline-none rounded-sm transition-all duration-200 ${
|
`w-full px-4 py-3 text-sm font-mono outline-none rounded-md transition-all duration-200 border ${
|
||||||
hasError ? "border-red-500/50" : "border-[#1a2a1a] focus:border-[#4aff8c]/40"
|
hasError ? "border-red-500/60" : "focus:border-[color:var(--accent)]"
|
||||||
}`;
|
}`;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="min-h-screen bg-[#0a0d0f] flex flex-col items-center justify-center relative overflow-hidden">
|
<main className="min-h-screen flex flex-col items-center justify-center relative overflow-hidden"
|
||||||
|
style={{ background: "var(--bg)", color: "var(--text-primary)" }}>
|
||||||
<div
|
<div
|
||||||
className="absolute inset-0 opacity-20 pointer-events-none"
|
className="absolute inset-0 opacity-20 pointer-events-none"
|
||||||
style={{
|
style={{
|
||||||
backgroundImage: `linear-gradient(rgba(74,255,140,0.05) 1px, transparent 1px), linear-gradient(90deg, rgba(74,255,140,0.05) 1px, transparent 1px)`,
|
backgroundImage: `linear-gradient(var(--accent-border) 1px, transparent 1px), linear-gradient(90deg, var(--accent-border) 1px, transparent 1px)`,
|
||||||
backgroundSize: "40px 40px",
|
backgroundSize: "40px 40px",
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[500px] h-[500px] rounded-full bg-[#4aff8c]/[0.02] blur-3xl pointer-events-none" />
|
<div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[500px] h-[500px] rounded-full blur-3xl pointer-events-none"
|
||||||
|
style={{ background: "var(--accent-dim)" }} />
|
||||||
|
|
||||||
<div className="relative z-10 flex flex-col items-center gap-8 w-full max-w-sm px-6">
|
<div className="relative z-10 flex flex-col items-center gap-8 w-full max-w-sm px-6">
|
||||||
{/* Header */}
|
|
||||||
<div className="flex flex-col items-center gap-5">
|
<div className="flex flex-col items-center gap-5">
|
||||||
<DragonEye size={80} />
|
<DragonEye size={80} />
|
||||||
<div className="text-center">
|
<div className="text-center">
|
||||||
<div className="text-[9px] tracking-[0.45em] text-[#4aff8c]/50 uppercase mb-2 font-mono">
|
<div className="text-[9px] tracking-[0.45em] uppercase mb-2 font-mono" style={{ color: "var(--accent)" }}>
|
||||||
Analytics Dashboard
|
Analytics Dashboard
|
||||||
</div>
|
</div>
|
||||||
<h1 className="text-4xl font-black tracking-[0.15em] uppercase text-white">
|
<h1 className="text-4xl font-black tracking-[0.15em] uppercase" style={{ color: "var(--text-primary)" }}>
|
||||||
WYVIEW
|
WYVIEW
|
||||||
</h1>
|
</h1>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Tabs */}
|
{/* Tabs */}
|
||||||
<div className="w-full flex border border-[#1a2a1a] rounded-sm overflow-hidden">
|
<div className="w-full flex rounded-md overflow-hidden" style={{ border: "1px solid var(--border)" }}>
|
||||||
<button
|
<button
|
||||||
onClick={() => { setTab("login"); setLoginError(""); }}
|
onClick={() => { setTab("login"); setLoginError(""); }}
|
||||||
className={`flex-1 py-2 text-[10px] font-mono tracking-[0.3em] uppercase transition-all duration-200 ${
|
className="flex-1 py-2 text-[10px] font-mono tracking-[0.3em] uppercase transition-all duration-200"
|
||||||
tab === "login"
|
style={tab === "login"
|
||||||
? "bg-[#4aff8c]/10 text-[#4aff8c] border-r border-[#1a2a1a]"
|
? { background: "var(--accent-dim)", color: "var(--accent)", borderRight: "1px solid var(--border)" }
|
||||||
: "text-[#2a4a2a] hover:text-[#4aff8c]/60 border-r border-[#1a2a1a]"
|
: { color: "var(--text-secondary)", borderRight: "1px solid var(--border)" }}
|
||||||
}`}
|
|
||||||
>
|
>
|
||||||
CONNEXION
|
CONNEXION
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
onClick={() => { setTab("register"); setRegError(""); setRegSuccess(""); }}
|
onClick={() => { setTab("register"); setRegError(""); setRegSuccess(""); }}
|
||||||
className={`flex-1 py-2 text-[10px] font-mono tracking-[0.3em] uppercase transition-all duration-200 ${
|
className="flex-1 py-2 text-[10px] font-mono tracking-[0.3em] uppercase transition-all duration-200"
|
||||||
tab === "register"
|
style={tab === "register"
|
||||||
? "bg-[#4aff8c]/10 text-[#4aff8c]"
|
? { background: "var(--accent-dim)", color: "var(--accent)" }
|
||||||
: "text-[#2a4a2a] hover:text-[#4aff8c]/60"
|
: { color: "var(--text-secondary)" }}
|
||||||
}`}
|
|
||||||
>
|
>
|
||||||
INSCRIPTION
|
INSCRIPTION
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Login Form */}
|
|
||||||
{tab === "login" && (
|
{tab === "login" && (
|
||||||
<form onSubmit={handleLogin} className="w-full flex flex-col gap-3">
|
<form onSubmit={handleLogin} className="w-full flex flex-col gap-3">
|
||||||
<input
|
<input
|
||||||
@@ -149,6 +150,7 @@ export default function AuthPage() {
|
|||||||
autoComplete="email"
|
autoComplete="email"
|
||||||
onChange={(e) => { setLoginEmail(e.target.value); setLoginError(""); }}
|
onChange={(e) => { setLoginEmail(e.target.value); setLoginError(""); }}
|
||||||
className={inputClass(!!loginError)}
|
className={inputClass(!!loginError)}
|
||||||
|
style={inputStyle}
|
||||||
/>
|
/>
|
||||||
<input
|
<input
|
||||||
type="password"
|
type="password"
|
||||||
@@ -157,6 +159,7 @@ export default function AuthPage() {
|
|||||||
autoComplete="current-password"
|
autoComplete="current-password"
|
||||||
onChange={(e) => { setLoginPassword(e.target.value); setLoginError(""); }}
|
onChange={(e) => { setLoginPassword(e.target.value); setLoginError(""); }}
|
||||||
className={inputClass(!!loginError)}
|
className={inputClass(!!loginError)}
|
||||||
|
style={inputStyle}
|
||||||
/>
|
/>
|
||||||
{loginError && (
|
{loginError && (
|
||||||
<p className="text-red-400/80 text-[11px] font-mono tracking-widest">— {loginError}</p>
|
<p className="text-red-400/80 text-[11px] font-mono tracking-widest">— {loginError}</p>
|
||||||
@@ -164,14 +167,16 @@ export default function AuthPage() {
|
|||||||
<button
|
<button
|
||||||
type="submit"
|
type="submit"
|
||||||
disabled={loginLoading || !loginEmail || !loginPassword}
|
disabled={loginLoading || !loginEmail || !loginPassword}
|
||||||
className="w-full py-3 text-[11px] font-mono tracking-[0.3em] uppercase font-bold border border-[#4aff8c]/30 text-[#4aff8c] hover:bg-[#4aff8c]/8 hover:border-[#4aff8c]/60 transition-all duration-200 rounded-sm disabled:opacity-30 disabled:cursor-not-allowed"
|
className="w-full py-3 text-[11px] font-mono tracking-[0.3em] uppercase font-bold rounded-md border transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||||
|
style={{ borderColor: "var(--accent)", color: "var(--accent)" }}
|
||||||
|
onMouseEnter={e => (e.currentTarget.style.background = "var(--accent-dim)")}
|
||||||
|
onMouseLeave={e => (e.currentTarget.style.background = "transparent")}
|
||||||
>
|
>
|
||||||
{loginLoading ? "CONNEXION..." : "ACCÉDER"}
|
{loginLoading ? "CONNEXION..." : "ACCÉDER"}
|
||||||
</button>
|
</button>
|
||||||
</form>
|
</form>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Register Form */}
|
|
||||||
{tab === "register" && (
|
{tab === "register" && (
|
||||||
<form onSubmit={handleRegister} className="w-full flex flex-col gap-3">
|
<form onSubmit={handleRegister} className="w-full flex flex-col gap-3">
|
||||||
<input
|
<input
|
||||||
@@ -181,6 +186,7 @@ export default function AuthPage() {
|
|||||||
autoComplete="name"
|
autoComplete="name"
|
||||||
onChange={(e) => { setRegName(e.target.value); setRegError(""); }}
|
onChange={(e) => { setRegName(e.target.value); setRegError(""); }}
|
||||||
className={inputClass(false)}
|
className={inputClass(false)}
|
||||||
|
style={inputStyle}
|
||||||
/>
|
/>
|
||||||
<input
|
<input
|
||||||
type="email"
|
type="email"
|
||||||
@@ -189,6 +195,7 @@ export default function AuthPage() {
|
|||||||
autoComplete="email"
|
autoComplete="email"
|
||||||
onChange={(e) => { setRegEmail(e.target.value); setRegError(""); }}
|
onChange={(e) => { setRegEmail(e.target.value); setRegError(""); }}
|
||||||
className={inputClass(!!regError)}
|
className={inputClass(!!regError)}
|
||||||
|
style={inputStyle}
|
||||||
/>
|
/>
|
||||||
<input
|
<input
|
||||||
type="password"
|
type="password"
|
||||||
@@ -197,6 +204,7 @@ export default function AuthPage() {
|
|||||||
autoComplete="new-password"
|
autoComplete="new-password"
|
||||||
onChange={(e) => { setRegPassword(e.target.value); setRegError(""); }}
|
onChange={(e) => { setRegPassword(e.target.value); setRegError(""); }}
|
||||||
className={inputClass(!!regError)}
|
className={inputClass(!!regError)}
|
||||||
|
style={inputStyle}
|
||||||
/>
|
/>
|
||||||
<input
|
<input
|
||||||
type="password"
|
type="password"
|
||||||
@@ -205,24 +213,28 @@ export default function AuthPage() {
|
|||||||
autoComplete="new-password"
|
autoComplete="new-password"
|
||||||
onChange={(e) => { setRegConfirm(e.target.value); setRegError(""); }}
|
onChange={(e) => { setRegConfirm(e.target.value); setRegError(""); }}
|
||||||
className={inputClass(!!regError && regPassword !== regConfirm)}
|
className={inputClass(!!regError && regPassword !== regConfirm)}
|
||||||
|
style={inputStyle}
|
||||||
/>
|
/>
|
||||||
{regError && (
|
{regError && (
|
||||||
<p className="text-red-400/80 text-[11px] font-mono tracking-widest">— {regError}</p>
|
<p className="text-red-400/80 text-[11px] font-mono tracking-widest">— {regError}</p>
|
||||||
)}
|
)}
|
||||||
{regSuccess && (
|
{regSuccess && (
|
||||||
<p className="text-[#4aff8c]/80 text-[11px] font-mono tracking-widest">✓ {regSuccess}</p>
|
<p className="text-[11px] font-mono tracking-widest" style={{ color: "var(--accent)" }}>✓ {regSuccess}</p>
|
||||||
)}
|
)}
|
||||||
<button
|
<button
|
||||||
type="submit"
|
type="submit"
|
||||||
disabled={regLoading || !regEmail || !regPassword || !regConfirm}
|
disabled={regLoading || !regEmail || !regPassword || !regConfirm}
|
||||||
className="w-full py-3 text-[11px] font-mono tracking-[0.3em] uppercase font-bold border border-[#4aff8c]/30 text-[#4aff8c] hover:bg-[#4aff8c]/8 hover:border-[#4aff8c]/60 transition-all duration-200 rounded-sm disabled:opacity-30 disabled:cursor-not-allowed"
|
className="w-full py-3 text-[11px] font-mono tracking-[0.3em] uppercase font-bold rounded-md border transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||||
|
style={{ borderColor: "var(--accent)", color: "var(--accent)" }}
|
||||||
|
onMouseEnter={e => (e.currentTarget.style.background = "var(--accent-dim)")}
|
||||||
|
onMouseLeave={e => (e.currentTarget.style.background = "transparent")}
|
||||||
>
|
>
|
||||||
{regLoading ? "CRÉATION..." : "CRÉER UN COMPTE"}
|
{regLoading ? "CRÉATION..." : "CRÉER UN COMPTE"}
|
||||||
</button>
|
</button>
|
||||||
</form>
|
</form>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div className="text-[9px] font-mono text-[#1a3a1a] tracking-[0.3em]">
|
<div className="text-[9px] font-mono tracking-[0.3em]" style={{ color: "var(--text-secondary)" }}>
|
||||||
WYVIEW v1.0 /// CROWMATE
|
WYVIEW v1.0 /// CROWMATE
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,29 +1,5 @@
|
|||||||
"use client";
|
import AppLayout from "@/components/AppLayout";
|
||||||
|
|
||||||
import { useEffect } from "react";
|
|
||||||
import { useRouter } from "next/navigation";
|
|
||||||
import { useSession } from "next-auth/react";
|
|
||||||
import Sidebar from "@/components/Sidebar";
|
|
||||||
|
|
||||||
export default function AuthLayout({ children }: { children: React.ReactNode }) {
|
export default function AuthLayout({ children }: { children: React.ReactNode }) {
|
||||||
const { status } = useSession();
|
return <AppLayout>{children}</AppLayout>;
|
||||||
const router = useRouter();
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (status === "unauthenticated") {
|
|
||||||
router.push("/");
|
|
||||||
}
|
|
||||||
}, [status, router]);
|
|
||||||
|
|
||||||
if (status === "loading") return null;
|
|
||||||
if (status !== "authenticated") return null;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="flex min-h-screen">
|
|
||||||
<Sidebar />
|
|
||||||
<main className="ml-56 flex-1 p-8">
|
|
||||||
{children}
|
|
||||||
</main>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,342 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { Music2, Link2, Unlink, Loader2, AlertTriangle, Eye, EyeOff } from "lucide-react";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { useRouter, useSearchParams } from "next/navigation";
|
||||||
|
|
||||||
|
import StatCard from "@/components/StatCard";
|
||||||
|
import StatsChart from "@/components/StatsCharts";
|
||||||
|
|
||||||
|
interface TikTokStats {
|
||||||
|
followers: number;
|
||||||
|
likes: number;
|
||||||
|
videoCount: number;
|
||||||
|
views: number;
|
||||||
|
displayName: string;
|
||||||
|
avatarUrl: string;
|
||||||
|
plan: "free" | "pro" | "elite" | "team";
|
||||||
|
}
|
||||||
|
|
||||||
|
type CardId = "followers" | "likes" | "videos" | "views" | "ratio";
|
||||||
|
|
||||||
|
const defaultVisibleCards: Record<CardId, boolean> = {
|
||||||
|
followers: true,
|
||||||
|
likes: true,
|
||||||
|
videos: true,
|
||||||
|
views: true,
|
||||||
|
ratio: true,
|
||||||
|
};
|
||||||
|
|
||||||
|
const visibleCardsStorageKey = "tiktok.visibleCards";
|
||||||
|
|
||||||
|
function parseVisibleCards(value: string | null): Record<CardId, boolean> {
|
||||||
|
if (!value) return defaultVisibleCards;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(value) as Partial<Record<CardId, unknown>>;
|
||||||
|
return {
|
||||||
|
followers: typeof parsed.followers === "boolean" ? parsed.followers : defaultVisibleCards.followers,
|
||||||
|
likes: typeof parsed.likes === "boolean" ? parsed.likes : defaultVisibleCards.likes,
|
||||||
|
videos: typeof parsed.videos === "boolean" ? parsed.videos : defaultVisibleCards.videos,
|
||||||
|
views: typeof parsed.views === "boolean" ? parsed.views : defaultVisibleCards.views,
|
||||||
|
ratio: typeof parsed.ratio === "boolean" ? parsed.ratio : defaultVisibleCards.ratio,
|
||||||
|
};
|
||||||
|
} catch {
|
||||||
|
return defaultVisibleCards;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function TikTokPage() {
|
||||||
|
const [stats, setStats] = useState<TikTokStats | null>(null);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [disconnecting, setDisconnecting] = useState(false);
|
||||||
|
const [showDisconnectConfirm, setShowDisconnectConfirm] = useState(false);
|
||||||
|
const [visibleCards, setVisibleCards] = useState<Record<CardId, boolean>>(defaultVisibleCards);
|
||||||
|
const [visibleCardsHydrated, setVisibleCardsHydrated] = useState(false);
|
||||||
|
const searchParams = useSearchParams();
|
||||||
|
const router = useRouter();
|
||||||
|
|
||||||
|
async function loadStats() {
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const res = await fetch("/api/tiktok/stats");
|
||||||
|
if (res.status === 404) {
|
||||||
|
setStats(null);
|
||||||
|
} else if (!res.ok) {
|
||||||
|
const data = await res.json();
|
||||||
|
setError(data.error ?? "Erreur inconnue");
|
||||||
|
} else {
|
||||||
|
const data = await res.json();
|
||||||
|
setStats(data);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
setError("Erreur réseau");
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const persisted = parseVisibleCards(window.localStorage.getItem(visibleCardsStorageKey));
|
||||||
|
setVisibleCards(persisted);
|
||||||
|
setVisibleCardsHydrated(true);
|
||||||
|
loadStats();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!visibleCardsHydrated) return;
|
||||||
|
window.localStorage.setItem(visibleCardsStorageKey, JSON.stringify(visibleCards));
|
||||||
|
}, [visibleCards, visibleCardsHydrated]);
|
||||||
|
|
||||||
|
async function handleDisconnect() {
|
||||||
|
if (disconnecting) return;
|
||||||
|
setDisconnecting(true);
|
||||||
|
try {
|
||||||
|
await fetch("/api/tiktok/disconnect", { method: "POST" });
|
||||||
|
setStats(null);
|
||||||
|
setShowDisconnectConfirm(false);
|
||||||
|
router.replace("/tiktok");
|
||||||
|
} finally {
|
||||||
|
setDisconnecting(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const urlError = searchParams.get("error");
|
||||||
|
|
||||||
|
const cards = stats
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
id: "followers" as const,
|
||||||
|
label: "Followers",
|
||||||
|
value: stats.followers.toLocaleString("fr-FR"),
|
||||||
|
sub: "Abonnés totaux",
|
||||||
|
accent: "purple" as const,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "likes" as const,
|
||||||
|
label: "Likes totaux",
|
||||||
|
value: stats.likes.toLocaleString("fr-FR"),
|
||||||
|
sub: "Cumul likes",
|
||||||
|
accent: "red" as const,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "videos" as const,
|
||||||
|
label: "Vidéos publiées",
|
||||||
|
value: stats.videoCount.toLocaleString("fr-FR"),
|
||||||
|
sub: "Vidéos au total",
|
||||||
|
accent: "blue" as const,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "views" as const,
|
||||||
|
label: "Vues vidéos",
|
||||||
|
value: stats.views.toLocaleString("fr-FR"),
|
||||||
|
sub: "Vues totales des vidéos",
|
||||||
|
accent: "green" as const,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "ratio" as const,
|
||||||
|
label: "Ratio likes/vidéo",
|
||||||
|
value: stats.videoCount > 0 ? Math.round(stats.likes / stats.videoCount).toLocaleString("fr-FR") : "—",
|
||||||
|
sub: "Moy. likes par vidéo",
|
||||||
|
accent: "gold" as const,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: [];
|
||||||
|
|
||||||
|
const shownCards = cards.filter((card) => visibleCards[card.id]);
|
||||||
|
const hiddenCards = cards.filter((card) => !visibleCards[card.id]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
{/* Header */}
|
||||||
|
<div className="flex items-center justify-between mb-8">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="p-2 rounded-sm bg-pink-500/10 border border-pink-500/20">
|
||||||
|
<Music2 size={18} className="text-pink-400" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="text-[9px] font-mono tracking-[0.3em] text-pink-400/70 uppercase mb-0.5">Plateforme</div>
|
||||||
|
<h1 className="text-2xl font-black tracking-widest uppercase" style={{ color: "var(--text-primary)" }}>TikTok</h1>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{stats && !loading && (
|
||||||
|
<button
|
||||||
|
onClick={() => setShowDisconnectConfirm(true)}
|
||||||
|
disabled={disconnecting}
|
||||||
|
className="flex items-center gap-2 px-4 py-2 text-[10px] font-mono tracking-widest uppercase border border-red-500/30 text-red-400/70 hover:text-red-400 hover:border-red-500/60 rounded-sm transition-colors disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{disconnecting ? <Loader2 size={12} className="animate-spin" /> : <Unlink size={12} />}
|
||||||
|
Déconnecter
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Erreur URL */}
|
||||||
|
{urlError && (
|
||||||
|
<div className="flex items-center gap-2 mb-6 px-4 py-3 bg-red-500/5 border border-red-500/20 rounded-sm text-red-400 text-xs font-mono">
|
||||||
|
<AlertTriangle size={14} />
|
||||||
|
{urlError === "access_denied" && "Accès refusé par TikTok."}
|
||||||
|
{urlError === "token_exchange" && "Erreur lors de l'échange du token."}
|
||||||
|
{urlError === "session_error" && "Erreur de session."}
|
||||||
|
{!["access_denied", "token_exchange", "session_error"].includes(urlError) && `Erreur : ${urlError}`}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Chargement */}
|
||||||
|
{loading && (
|
||||||
|
<div className="flex items-center justify-center min-h-[200px] gap-3 font-mono text-xs" style={{ color: "var(--text-secondary)" }}>
|
||||||
|
<Loader2 size={16} className="animate-spin text-pink-400/60" />
|
||||||
|
Chargement...
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Connecté : stats */}
|
||||||
|
{!loading && stats && (
|
||||||
|
<>
|
||||||
|
{stats.displayName && (
|
||||||
|
<div className="flex items-center gap-3 mb-6 px-4 py-3 bg-pink-500/8 border border-pink-500/25 rounded-sm">
|
||||||
|
{stats.avatarUrl && (
|
||||||
|
<img src={stats.avatarUrl} alt="avatar" className="w-8 h-8 rounded-full object-cover border border-pink-500/30" />
|
||||||
|
)}
|
||||||
|
<span className="text-pink-300 font-mono text-sm font-bold">{stats.displayName}</span>
|
||||||
|
<span className="text-[9px] font-mono tracking-widest text-pink-400/50 uppercase ml-auto">Connecté</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{hiddenCards.length > 0 && (
|
||||||
|
<div className="flex flex-wrap items-center gap-2 mb-3">
|
||||||
|
{hiddenCards.map((card) => (
|
||||||
|
<button
|
||||||
|
key={card.id}
|
||||||
|
type="button"
|
||||||
|
onClick={() => setVisibleCards((prev) => ({ ...prev, [card.id]: true }))}
|
||||||
|
className="inline-flex items-center gap-1 px-2 py-1 text-[10px] font-mono tracking-widest uppercase border rounded-sm transition-colors hover:text-pink-300"
|
||||||
|
style={{ borderColor: "var(--border)", color: "var(--text-secondary)" }}
|
||||||
|
aria-label={`Afficher la carte ${card.label}`}
|
||||||
|
>
|
||||||
|
<Eye size={12} />
|
||||||
|
{card.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setVisibleCards(defaultVisibleCards)}
|
||||||
|
className="px-2 py-1 text-[10px] font-mono tracking-widest uppercase border rounded-sm transition-colors hover:text-pink-300"
|
||||||
|
style={{ borderColor: "var(--border)", color: "var(--text-secondary)" }}
|
||||||
|
>
|
||||||
|
Tout afficher
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{shownCards.length > 0 ? (
|
||||||
|
<div id="tiktok-stat-cards" className="grid grid-cols-2 xl:grid-cols-5 gap-4 mb-8">
|
||||||
|
{shownCards.map((card) => (
|
||||||
|
<div key={card.id} className="relative">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setVisibleCards((prev) => ({ ...prev, [card.id]: false }))}
|
||||||
|
className="absolute top-2 right-2 z-10 p-1 rounded-sm border transition-colors"
|
||||||
|
style={{ borderColor: "var(--border)", color: "var(--text-secondary)", background: "var(--surface)" }}
|
||||||
|
aria-label={`Masquer la carte ${card.label}`}
|
||||||
|
>
|
||||||
|
<EyeOff size={12} />
|
||||||
|
</button>
|
||||||
|
<StatCard
|
||||||
|
label={card.label}
|
||||||
|
value={card.value}
|
||||||
|
sub={card.sub}
|
||||||
|
accent={card.accent}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="border rounded-sm p-6 mb-8 text-center" style={{ background: "var(--surface)", borderColor: "var(--border)" }}>
|
||||||
|
<p className="font-mono text-xs tracking-widest uppercase mb-3" style={{ color: "var(--text-secondary)" }}>
|
||||||
|
Toutes les cartes sont masquées
|
||||||
|
</p>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setVisibleCards(defaultVisibleCards)}
|
||||||
|
className="px-3 py-2 text-[10px] font-mono tracking-widest uppercase border rounded-sm transition-colors hover:text-pink-300"
|
||||||
|
style={{ borderColor: "var(--border)", color: "var(--text-secondary)" }}
|
||||||
|
>
|
||||||
|
Afficher toutes les cartes
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Graph */}
|
||||||
|
<StatsChart plan={stats.plan ?? "free"} />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!loading && !stats && !error && (
|
||||||
|
<div className="border rounded-sm p-12 flex flex-col items-center justify-center gap-5 min-h-[240px]"
|
||||||
|
style={{ background: "var(--surface)", borderColor: "var(--border)" }}>
|
||||||
|
<Music2 size={36} className="text-pink-400/30" />
|
||||||
|
<p className="font-mono text-xs tracking-widest text-center uppercase" style={{ color: "var(--text-secondary)" }}>
|
||||||
|
Connectez votre compte TikTok<br />pour afficher vos statistiques
|
||||||
|
</p>
|
||||||
|
<a
|
||||||
|
href="/api/tiktok/connect"
|
||||||
|
className="flex items-center gap-2 px-5 py-2.5 text-[10px] font-mono tracking-widest uppercase bg-pink-500/10 border border-pink-500/40 text-pink-300 hover:bg-pink-500/20 hover:border-pink-500/60 rounded-sm transition-colors"
|
||||||
|
>
|
||||||
|
<Link2 size={13} />
|
||||||
|
Connecter TikTok
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!loading && error && (
|
||||||
|
<div className="border border-red-500/25 rounded-sm p-8 flex flex-col items-center justify-center gap-3 min-h-[200px]"
|
||||||
|
style={{ background: "var(--surface)" }}>
|
||||||
|
<AlertTriangle size={28} className="text-red-400/60" />
|
||||||
|
<p className="text-red-400/80 font-mono text-xs tracking-widest text-center uppercase">{error}</p>
|
||||||
|
<button onClick={loadStats} className="text-[10px] font-mono tracking-widest uppercase transition-colors hover:text-pink-400"
|
||||||
|
style={{ color: "var(--text-secondary)" }}>
|
||||||
|
Réessayer
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{showDisconnectConfirm && (
|
||||||
|
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 px-4">
|
||||||
|
<div className="w-full max-w-md rounded-sm border p-5" style={{ background: "var(--surface)", borderColor: "var(--border)" }}>
|
||||||
|
<div className="flex items-center gap-2 mb-3 text-red-400">
|
||||||
|
<AlertTriangle size={16} />
|
||||||
|
<p className="text-xs font-mono tracking-widest uppercase">Confirmer la déconnexion</p>
|
||||||
|
</div>
|
||||||
|
<p className="text-sm mb-5" style={{ color: "var(--text-secondary)" }}>
|
||||||
|
Êtes-vous sûr de vouloir déconnecter votre compte TikTok ?
|
||||||
|
</p>
|
||||||
|
<div className="flex items-center justify-end gap-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setShowDisconnectConfirm(false)}
|
||||||
|
disabled={disconnecting}
|
||||||
|
className="px-3 py-2 text-[10px] font-mono tracking-widest uppercase border rounded-sm transition-colors disabled:opacity-50"
|
||||||
|
style={{ borderColor: "var(--border)", color: "var(--text-secondary)" }}
|
||||||
|
>
|
||||||
|
Annuler
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={handleDisconnect}
|
||||||
|
disabled={disconnecting}
|
||||||
|
className="flex items-center gap-2 px-3 py-2 text-[10px] font-mono tracking-widest uppercase border border-red-500/40 text-red-300 hover:text-red-200 hover:border-red-500/70 rounded-sm transition-colors disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{disconnecting ? <Loader2 size={12} className="animate-spin" /> : <Unlink size={12} />}
|
||||||
|
Confirmer
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,29 +1,5 @@
|
|||||||
"use client";
|
import AppLayout from "@/components/AppLayout";
|
||||||
|
|
||||||
import { useEffect } from "react";
|
|
||||||
import { useRouter } from "next/navigation";
|
|
||||||
import { useSession } from "next-auth/react";
|
|
||||||
import Sidebar from "@/components/Sidebar";
|
|
||||||
|
|
||||||
export default function AuthLayout({ children }: { children: React.ReactNode }) {
|
export default function AuthLayout({ children }: { children: React.ReactNode }) {
|
||||||
const { status } = useSession();
|
return <AppLayout>{children}</AppLayout>;
|
||||||
const router = useRouter();
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (status === "unauthenticated") {
|
|
||||||
router.push("/");
|
|
||||||
}
|
|
||||||
}, [status, router]);
|
|
||||||
|
|
||||||
if (status === "loading") return null;
|
|
||||||
if (status !== "authenticated") return null;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="flex min-h-screen">
|
|
||||||
<Sidebar />
|
|
||||||
<main className="ml-56 flex-1 p-8">
|
|
||||||
{children}
|
|
||||||
</main>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import StatCard from "@/components/StatCard";
|
||||||
|
import { TwitchIcon } from "lucide-react";
|
||||||
|
|
||||||
|
export default function TwitchPage() {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div className="flex items-center gap-3 mb-8">
|
||||||
|
<div className="p-2 rounded-sm bg-purple-500/10 border border-purple-500/25">
|
||||||
|
<TwitchIcon size={18} className="text-purple-400" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="text-[9px] font-mono tracking-[0.3em] text-purple-400/70 uppercase mb-0.5">Plateforme</div>
|
||||||
|
<h1 className="text-2xl font-black tracking-widest uppercase" style={{ color: "var(--text-primary)" }}>Twitch</h1>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-2 xl:grid-cols-4 gap-4 mb-8">
|
||||||
|
<StatCard label="Followers" value="—" sub="Aucune donnée" accent="purple" />
|
||||||
|
<StatCard label="Viewers moy." value="—" sub="Aucune donnée" accent="purple" />
|
||||||
|
<StatCard label="Heures streamées" value="—" sub="Aucune donnée" accent="purple" />
|
||||||
|
<StatCard label="Abonnés actifs" value="—" sub="Aucune donnée" accent="purple" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="border rounded-sm p-8 flex flex-col items-center justify-center gap-3 min-h-[200px]"
|
||||||
|
style={{ background: "var(--surface)", borderColor: "var(--border)" }}>
|
||||||
|
<TwitchIcon size={32} className="text-purple-400/30" />
|
||||||
|
<p className="font-mono text-xs tracking-widest text-center" style={{ color: "var(--text-secondary)" }}>
|
||||||
|
CONNECTEZ VOTRE COMPTE TWITCH<br />POUR AFFICHER VOS STATISTIQUES
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,29 +1,5 @@
|
|||||||
"use client";
|
import AppLayout from "@/components/AppLayout";
|
||||||
|
|
||||||
import { useEffect } from "react";
|
|
||||||
import { useRouter } from "next/navigation";
|
|
||||||
import { useSession } from "next-auth/react";
|
|
||||||
import Sidebar from "@/components/Sidebar";
|
|
||||||
|
|
||||||
export default function AuthLayout({ children }: { children: React.ReactNode }) {
|
export default function AuthLayout({ children }: { children: React.ReactNode }) {
|
||||||
const { status } = useSession();
|
return <AppLayout>{children}</AppLayout>;
|
||||||
const router = useRouter();
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (status === "unauthenticated") {
|
|
||||||
router.push("/");
|
|
||||||
}
|
|
||||||
}, [status, router]);
|
|
||||||
|
|
||||||
if (status === "loading") return null;
|
|
||||||
if (status !== "authenticated") return null;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="flex min-h-screen">
|
|
||||||
<Sidebar />
|
|
||||||
<main className="ml-56 flex-1 p-8">
|
|
||||||
{children}
|
|
||||||
</main>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import StatCard from "@/components/StatCard";
|
||||||
|
import { YoutubeIcon } from "lucide-react";
|
||||||
|
|
||||||
|
export default function YoutubePage() {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div className="flex items-center gap-3 mb-8">
|
||||||
|
<div className="p-2 rounded-sm bg-red-500/10 border border-red-500/25">
|
||||||
|
<YoutubeIcon size={18} className="text-red-400" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="text-[9px] font-mono tracking-[0.3em] text-red-400/70 uppercase mb-0.5">Plateforme</div>
|
||||||
|
<h1 className="text-2xl font-black tracking-widest uppercase" style={{ color: "var(--text-primary)" }}>YouTube</h1>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-2 xl:grid-cols-4 gap-4 mb-8">
|
||||||
|
<StatCard label="Abonnés" value="—" sub="Aucune donnée" accent="red" />
|
||||||
|
<StatCard label="Vues totales" value="—" sub="Aucune donnée" accent="red" />
|
||||||
|
<StatCard label="Vidéos publiées" value="—" sub="Aucune donnée" accent="red" />
|
||||||
|
<StatCard label="Watch time (h)" value="—" sub="Aucune donnée" accent="red" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="border rounded-sm p-8 flex flex-col items-center justify-center gap-3 min-h-[200px]"
|
||||||
|
style={{ background: "var(--surface)", borderColor: "var(--border)" }}>
|
||||||
|
<YoutubeIcon size={32} className="text-red-400/30" />
|
||||||
|
<p className="font-mono text-xs tracking-widest text-center" style={{ color: "var(--text-secondary)" }}>
|
||||||
|
CONNECTEZ VOTRE COMPTE YOUTUBE<br />POUR AFFICHER VOS STATISTIQUES
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
41
components/AppLayout.tsx
Normal file
41
components/AppLayout.tsx
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect } from "react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { useSession } from "next-auth/react";
|
||||||
|
import Sidebar from "@/components/Sidebar";
|
||||||
|
import { useTheme } from "@/lib/theme";
|
||||||
|
|
||||||
|
export default function AppLayout({ children }: { children: React.ReactNode }) {
|
||||||
|
const { status } = useSession();
|
||||||
|
const router = useRouter();
|
||||||
|
const { theme } = useTheme();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (status === "unauthenticated") {
|
||||||
|
router.push("/");
|
||||||
|
}
|
||||||
|
}, [status, router]);
|
||||||
|
|
||||||
|
if (status === "loading") {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center" style={{ background: "var(--bg)" }}>
|
||||||
|
<span className="font-mono text-xs tracking-widest animate-pulse" style={{ color: "var(--accent)" }}>
|
||||||
|
CHARGEMENT...
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (status !== "authenticated") return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-screen" style={{ background: "var(--bg)" }}>
|
||||||
|
<Sidebar />
|
||||||
|
<main className="ml-56 flex-1 p-8" style={{ background: "var(--bg)" }}>
|
||||||
|
{children}
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
@@ -1,9 +1,12 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useEffect, useRef } from "react";
|
import { useEffect, useRef } from "react";
|
||||||
|
import { useTheme } from "@/lib/theme";
|
||||||
|
|
||||||
export default function DragonEye({ size = 60 }: { size?: number }) {
|
export default function DragonEye({ size = 60 }: { size?: number }) {
|
||||||
const irisRef = useRef<HTMLDivElement>(null);
|
const irisRef = useRef<HTMLDivElement>(null);
|
||||||
|
const { theme } = useTheme();
|
||||||
|
const isLight = theme === "light";
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const handleMouseMove = (e: MouseEvent) => {
|
const handleMouseMove = (e: MouseEvent) => {
|
||||||
@@ -26,6 +29,22 @@ export default function DragonEye({ size = 60 }: { size?: number }) {
|
|||||||
const h = size;
|
const h = size;
|
||||||
const w = size * 1.6;
|
const w = size * 1.6;
|
||||||
|
|
||||||
|
// Light theme: sky-blue palette
|
||||||
|
const glowColor = isLight ? "#38bdf8" : "#4aff8c";
|
||||||
|
const eyeBg = isLight
|
||||||
|
? "radial-gradient(ellipse at 40% 35%, #e0f7ff, #b8eeff)"
|
||||||
|
: "radial-gradient(ellipse at 40% 35%, #0a1a0a, #020402)";
|
||||||
|
const eyeBorder = isLight ? "rgba(56,189,248,0.4)" : "rgba(74,255,140,0.25)";
|
||||||
|
const eyeShadow = isLight
|
||||||
|
? "0 0 20px rgba(56,189,248,0.25), inset 0 0 10px rgba(56,189,248,0.1)"
|
||||||
|
: "0 0 20px rgba(74,255,140,0.1), inset 0 0 20px rgba(0,0,0,0.8)";
|
||||||
|
const irisBg = isLight
|
||||||
|
? "radial-gradient(ellipse at 40% 35%, #7dd3fc 0%, #0ea5e9 35%, #0369a1 70%)"
|
||||||
|
: "radial-gradient(ellipse at 40% 35%, #1aff6a 0%, #0a8a3a 35%, #022a12 70%)";
|
||||||
|
const irisShadow = isLight ? "0 0 12px rgba(56,189,248,0.6)" : "0 0 12px rgba(74,255,140,0.4)";
|
||||||
|
const pupilBg = isLight ? "#001a2e" : "#010801";
|
||||||
|
const eyelidBg = isLight ? "#dbeafe" : "#0a0d0f";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className="relative flex-shrink-0"
|
className="relative flex-shrink-0"
|
||||||
@@ -35,7 +54,7 @@ export default function DragonEye({ size = 60 }: { size?: number }) {
|
|||||||
<div
|
<div
|
||||||
className="absolute inset-0 rounded-full blur-md opacity-30"
|
className="absolute inset-0 rounded-full blur-md opacity-30"
|
||||||
style={{
|
style={{
|
||||||
background: "radial-gradient(ellipse, #4aff8c 0%, transparent 70%)",
|
background: `radial-gradient(ellipse, ${glowColor} 0%, transparent 70%)`,
|
||||||
borderRadius: "50%",
|
borderRadius: "50%",
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
@@ -45,9 +64,9 @@ export default function DragonEye({ size = 60 }: { size?: number }) {
|
|||||||
className="absolute inset-0 overflow-hidden"
|
className="absolute inset-0 overflow-hidden"
|
||||||
style={{
|
style={{
|
||||||
borderRadius: "50%",
|
borderRadius: "50%",
|
||||||
background: "radial-gradient(ellipse at 40% 35%, #0a1a0a, #020402)",
|
background: eyeBg,
|
||||||
border: "1px solid rgba(74,255,140,0.25)",
|
border: `1px solid ${eyeBorder}`,
|
||||||
boxShadow: "0 0 20px rgba(74,255,140,0.1), inset 0 0 20px rgba(0,0,0,0.8)",
|
boxShadow: eyeShadow,
|
||||||
animation: "blink 9s ease-in-out infinite",
|
animation: "blink 9s ease-in-out infinite",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
@@ -60,8 +79,8 @@ export default function DragonEye({ size = 60 }: { size?: number }) {
|
|||||||
width: h * 0.65,
|
width: h * 0.65,
|
||||||
height: h * 0.65,
|
height: h * 0.65,
|
||||||
borderRadius: "50%",
|
borderRadius: "50%",
|
||||||
background: "radial-gradient(ellipse at 40% 35%, #1aff6a 0%, #0a8a3a 35%, #022a12 70%)",
|
background: irisBg,
|
||||||
boxShadow: "0 0 12px rgba(74,255,140,0.4)",
|
boxShadow: irisShadow,
|
||||||
transition: "transform 0.08s ease-out",
|
transition: "transform 0.08s ease-out",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
@@ -72,19 +91,20 @@ export default function DragonEye({ size = 60 }: { size?: number }) {
|
|||||||
transform: "translate(-50%, -50%)",
|
transform: "translate(-50%, -50%)",
|
||||||
width: h * 0.1,
|
width: h * 0.1,
|
||||||
height: h * 0.55,
|
height: h * 0.55,
|
||||||
background: "#010801",
|
background: pupilBg,
|
||||||
borderRadius: "50%",
|
borderRadius: "50%",
|
||||||
boxShadow: "0 0 6px rgba(0,0,0,0.9)",
|
boxShadow: "0 0 6px rgba(0,0,0,0.9)",
|
||||||
animation: "pupilDilate 7s ease-in-out infinite",
|
animation: "pupilDilate 7s ease-in-out infinite",
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* Highlight */}
|
{/* Highlight */}
|
||||||
<div
|
<div
|
||||||
className="absolute"
|
className="absolute"
|
||||||
style={{
|
style={{
|
||||||
top: "18%", left: "22%",
|
top: "18%", left: "22%",
|
||||||
width: h * 0.12, height: h * 0.08,
|
width: h * 0.12, height: h * 0.08,
|
||||||
background: "rgba(200,255,220,0.4)",
|
background: isLight ? "rgba(255,255,255,0.7)" : "rgba(200,255,220,0.4)",
|
||||||
borderRadius: "50%",
|
borderRadius: "50%",
|
||||||
transform: "rotate(-20deg)",
|
transform: "rotate(-20deg)",
|
||||||
filter: "blur(1px)",
|
filter: "blur(1px)",
|
||||||
@@ -97,7 +117,7 @@ export default function DragonEye({ size = 60 }: { size?: number }) {
|
|||||||
className="absolute top-0 left-0 right-0"
|
className="absolute top-0 left-0 right-0"
|
||||||
style={{
|
style={{
|
||||||
height: "30%",
|
height: "30%",
|
||||||
background: "linear-gradient(to bottom, #0a0d0f, rgba(10,13,15,0.5))",
|
background: `linear-gradient(to bottom, ${eyelidBg}, transparent)`,
|
||||||
borderRadius: "50% 50% 0 0 / 80% 80% 0 0",
|
borderRadius: "50% 50% 0 0 / 80% 80% 0 0",
|
||||||
zIndex: 2,
|
zIndex: 2,
|
||||||
}}
|
}}
|
||||||
@@ -107,7 +127,7 @@ export default function DragonEye({ size = 60 }: { size?: number }) {
|
|||||||
className="absolute bottom-0 left-0 right-0"
|
className="absolute bottom-0 left-0 right-0"
|
||||||
style={{
|
style={{
|
||||||
height: "22%",
|
height: "22%",
|
||||||
background: "linear-gradient(to top, #0a0d0f, rgba(10,13,15,0.5))",
|
background: `linear-gradient(to top, ${eyelidBg}, transparent)`,
|
||||||
borderRadius: "0 0 50% 50% / 0 0 80% 80%",
|
borderRadius: "0 0 50% 50% / 0 0 80% 80%",
|
||||||
zIndex: 2,
|
zIndex: 2,
|
||||||
}}
|
}}
|
||||||
|
|||||||
@@ -8,40 +8,40 @@ export type StreamInfo = {
|
|||||||
|
|
||||||
export default function LiveBanner({ stream }: { stream: StreamInfo }) {
|
export default function LiveBanner({ stream }: { stream: StreamInfo }) {
|
||||||
return (
|
return (
|
||||||
<div className={`border rounded-sm p-5 flex items-center gap-5 transition-colors duration-300 ${
|
<div className={`border rounded-lg p-5 flex items-center gap-5 transition-colors duration-300 ${
|
||||||
stream.live
|
stream.live
|
||||||
? "bg-[#4aff8c]/3 border-[#4aff8c]/20"
|
? "bg-acid-green/10 border-acid-green/30"
|
||||||
: "bg-white/[0.02] border-[#1a2a1a]"
|
: "bg-wy-surface border-wy-border"
|
||||||
}`}>
|
}`}>
|
||||||
<div className="flex-1 min-w-0">
|
<div className="flex-1 min-w-0">
|
||||||
<div className="flex items-center gap-2 mb-2">
|
<div className="flex items-center gap-2 mb-2">
|
||||||
{stream.live ? (
|
{stream.live ? (
|
||||||
<span className="flex items-center gap-1.5 text-[9px] font-mono tracking-[0.2em] text-red-400 bg-red-500/10 border border-red-500/20 px-2 py-1 rounded-sm">
|
<span className="flex items-center gap-1.5 text-xs font-mono tracking-widest text-red-400 bg-red-500/10 border border-red-500/30 px-2 py-1 rounded-md">
|
||||||
<span className="w-1.5 h-1.5 rounded-full bg-red-400 animate-pulse" />
|
<span className="w-1.5 h-1.5 rounded-full bg-red-400 animate-pulse" />
|
||||||
EN DIRECT
|
EN DIRECT
|
||||||
</span>
|
</span>
|
||||||
) : (
|
) : (
|
||||||
<span className="text-[9px] font-mono tracking-[0.2em] text-[#3a5a3a] bg-white/[0.02] border border-[#1a2a1a] px-2 py-1 rounded-sm">
|
<span className="text-xs font-mono tracking-widest text-wy-text-secondary bg-wy-surface border border-wy-border px-2 py-1 rounded-md">
|
||||||
HORS LIGNE
|
HORS LIGNE
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
{stream.duration && (
|
{stream.duration && (
|
||||||
<span className="text-[10px] font-mono text-[#3a5a3a]">{stream.duration}</span>
|
<span className="text-xs font-mono text-wy-text-secondary">{stream.duration}</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="text-white font-bold truncate">
|
<div className="text-white font-bold truncate">
|
||||||
{stream.title || "En attente du prochain stream..."}
|
{stream.title || "En attente du prochain stream..."}
|
||||||
</div>
|
</div>
|
||||||
{stream.game && (
|
{stream.game && (
|
||||||
<div className="text-[12px] text-[#3a5a3a] font-mono mt-1">🎮 {stream.game}</div>
|
<div className="text-sm text-wy-text-secondary font-mono mt-1">🎮 {stream.game}</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="text-right flex-shrink-0">
|
<div className="text-right flex-shrink-0">
|
||||||
<div className={`text-3xl font-black leading-none ${stream.live ? "text-[#4aff8c]" : "text-[#2a3a2a]"}`}>
|
<div className={`text-4xl font-black leading-none ${stream.live ? "text-acid-green" : "text-wy-text-secondary"}`}>
|
||||||
{stream.viewers ?? 0}
|
{stream.viewers ?? 0}
|
||||||
</div>
|
</div>
|
||||||
<div className="text-[9px] font-mono tracking-widest text-[#3a5a3a] mt-0.5">VIEWERS</div>
|
<div className="text-xs font-mono tracking-widest text-wy-text-secondary mt-0.5">VIEWERS</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -7,12 +7,12 @@ export type LogEntry = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const typeStyles = {
|
const typeStyles = {
|
||||||
info: { border: "border-l-[#4aff8c]/60", icon: "✅" },
|
info: { border: "border-l-acid-green/60", icon: "✅" },
|
||||||
warn: { border: "border-l-yellow-400/60", icon: "⚠️" },
|
warn: { border: "border-l-yellow-400/60", icon: "⚠️" },
|
||||||
ban: { border: "border-l-red-500/60", icon: "🔨" },
|
ban: { border: "border-l-red-500/60", icon: "🔨" },
|
||||||
unban: { border: "border-l-blue-400/60", icon: "🔓" },
|
unban: { border: "border-l-blue-400/60", icon: "🔓" },
|
||||||
twitch: { border: "border-l-purple-400/60", icon: "📡" },
|
twitch: { border: "border-l-purple-400/60", icon: "📡" },
|
||||||
sub: { border: "border-l-[#4aff8c]/60", icon: "🎖️" },
|
sub: { border: "border-l-acid-green/60", icon: "🎖️" },
|
||||||
};
|
};
|
||||||
|
|
||||||
const MOCK_LOGS: LogEntry[] = [
|
const MOCK_LOGS: LogEntry[] = [
|
||||||
@@ -32,17 +32,17 @@ export default function LogFeed({ logs = MOCK_LOGS }: { logs?: LogEntry[] }) {
|
|||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
key={log.id}
|
key={log.id}
|
||||||
className={`flex items-start gap-3 px-3 py-2.5 bg-white/[0.02] border border-[#1a2a1a] border-l-2 ${style.border} rounded-sm text-sm`}
|
className={`flex items-start gap-3 px-3 py-2.5 bg-wy-surface border border-wy-border border-l-2 ${style.border} rounded-md text-sm`}
|
||||||
style={{ animation: `fadeIn 0.3s ${i * 0.05}s both` }}
|
style={{ animation: `fadeIn 0.3s ${i * 0.05}s both` }}
|
||||||
>
|
>
|
||||||
<span className="text-base flex-shrink-0 mt-0.5">{style.icon}</span>
|
<span className="text-base flex-shrink-0 mt-0.5">{style.icon}</span>
|
||||||
<div className="flex-1 min-w-0">
|
<div className="flex-1 min-w-0">
|
||||||
<div className="text-[#b0c4b0] leading-snug">{log.text}</div>
|
<div className="text-wy-text-primary leading-snug">{log.text}</div>
|
||||||
{log.reason && (
|
{log.reason && (
|
||||||
<div className="text-[11px] text-[#3a5a3a] font-mono mt-0.5 italic">{log.reason}</div>
|
<div className="text-xs text-wy-text-secondary font-mono mt-0.5 italic">{log.reason}</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="text-[10px] font-mono text-[#2a4a2a] whitespace-nowrap mt-0.5">{log.time}</div>
|
<div className="text-xs font-mono text-wy-text-secondary whitespace-nowrap mt-0.5">{log.time}</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
|||||||
@@ -6,10 +6,10 @@ export type Member = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const roleStyles = {
|
const roleStyles = {
|
||||||
admin: { label: "ADMIN", cls: "text-red-400 bg-red-500/8 border-red-500/20" },
|
admin: { label: "ADMIN", cls: "text-red-400 bg-red-500/10 border-red-500/30" },
|
||||||
mod: { label: "MOD", cls: "text-yellow-400 bg-yellow-400/8 border-yellow-400/20" },
|
mod: { label: "MOD", cls: "text-yellow-400 bg-yellow-400/10 border-yellow-400/30" },
|
||||||
sub: { label: "SUB", cls: "text-[#4aff8c] bg-[#4aff8c]/8 border-[#4aff8c]/20" },
|
sub: { label: "SUB", cls: "text-acid-green bg-acid-green/10 border-acid-green/30" },
|
||||||
viewer: { label: "VIEWER", cls: "text-blue-400 bg-blue-400/8 border-blue-400/20" },
|
viewer: { label: "VIEWER", cls: "text-blue-400 bg-blue-400/10 border-blue-400/30" },
|
||||||
};
|
};
|
||||||
|
|
||||||
const AVATARS = ["🗡️", "🛡️", "🏹", "⚔️", "🔥", "💀", "🐉", "⚡"];
|
const AVATARS = ["🗡️", "🛡️", "🏹", "⚔️", "🔥", "💀", "🐉", "⚡"];
|
||||||
@@ -32,13 +32,13 @@ export default function MemberList({ members = MOCK_MEMBERS }: { members?: Membe
|
|||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
key={m.id}
|
key={m.id}
|
||||||
className="flex items-center gap-3 px-3 py-2 bg-white/[0.02] border border-[#1a2a1a] rounded-sm hover:bg-[#4aff8c]/3 transition-colors duration-150"
|
className="flex items-center gap-3 px-3 py-2 bg-wy-surface border border-wy-border rounded-md hover:bg-wy-surface/50 transition-colors duration-150"
|
||||||
>
|
>
|
||||||
<div className="w-7 h-7 rounded-full bg-[#0a1a0a] border border-[#1a2a1a] flex items-center justify-center text-xs flex-shrink-0">
|
<div className="w-8 h-8 rounded-full bg-wy-dark border border-wy-border flex items-center justify-center text-sm flex-shrink-0">
|
||||||
{avatar}
|
{avatar}
|
||||||
</div>
|
</div>
|
||||||
<div className="flex-1 text-sm text-[#b0c4b0] font-mono">{m.name}</div>
|
<div className="flex-1 text-sm text-wy-text-primary font-mono">{m.name}</div>
|
||||||
<span className={`text-[9px] font-mono tracking-wider px-2 py-0.5 border rounded-sm ${role.cls}`}>
|
<span className={`text-xs font-mono tracking-wider px-2 py-0.5 border rounded-md ${role.cls}`}>
|
||||||
{role.label}
|
{role.label}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -3,6 +3,8 @@
|
|||||||
import { useRouter, usePathname } from "next/navigation";
|
import { useRouter, usePathname } from "next/navigation";
|
||||||
import { signOut } from "next-auth/react";
|
import { signOut } from "next-auth/react";
|
||||||
import DragonEye from "@/components/DragonEye";
|
import DragonEye from "@/components/DragonEye";
|
||||||
|
import ThemeToggleButton from "@/components/ThemeToggleButton";
|
||||||
|
import { useTheme } from "@/lib/theme";
|
||||||
import {
|
import {
|
||||||
LayoutDashboard,
|
LayoutDashboard,
|
||||||
Twitch,
|
Twitch,
|
||||||
@@ -25,24 +27,31 @@ const nav = [
|
|||||||
export default function Sidebar() {
|
export default function Sidebar() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const pathname = usePathname();
|
const pathname = usePathname();
|
||||||
|
const { theme } = useTheme();
|
||||||
|
const isLight = theme === "light";
|
||||||
|
|
||||||
const handleLogout = () => {
|
const handleLogout = () => {
|
||||||
signOut({ callbackUrl: "/" });
|
signOut({ callbackUrl: "/" });
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const bg = isLight ? "bg-wy-light-surface" : "bg-wy-dark";
|
||||||
|
const border = isLight ? "border-wy-light-border" : "border-wy-border";
|
||||||
|
const textSec = isLight ? "text-wy-light-text-secondary" : "text-wy-text-secondary";
|
||||||
|
const textPri = isLight ? "text-wy-light-text-primary" : "text-wy-text-primary";
|
||||||
|
const title = isLight ? "text-wy-light-text-primary" : "text-white";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<aside className="fixed left-0 top-0 h-screen w-56 bg-[#0a0d0f] border-r border-[#1a2a1a] flex flex-col z-50">
|
<aside className={`fixed left-0 top-0 h-screen w-56 ${bg} border-r ${border} flex flex-col z-50`}>
|
||||||
|
|
||||||
{/* Logo */}
|
{/* Logo */}
|
||||||
<div className="flex items-center gap-3 px-5 py-6 border-b border-[#1a2a1a]">
|
<div className={`flex items-center gap-3 px-5 py-6 border-b ${border}`}>
|
||||||
<DragonEye size={32} />
|
<DragonEye size={32} />
|
||||||
<div>
|
<div>
|
||||||
<div className="text-[8px] font-mono tracking-[0.3em] text-[#4aff8c]/40 uppercase">Analytics</div>
|
<div className={`text-[8px] font-mono tracking-[0.3em] ${isLight ? "text-sky-400/80" : "text-acid-green/60"} uppercase`}>Analytics</div>
|
||||||
<div className="text-base font-black tracking-widest text-white">WYVIEW</div>
|
<div className={`text-base font-black tracking-widest ${title}`}>WYVIEW</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Nav */}
|
|
||||||
<nav className="flex-1 px-3 py-4 flex flex-col gap-1">
|
<nav className="flex-1 px-3 py-4 flex flex-col gap-1">
|
||||||
{nav.map(({ label, href, icon: Icon }) => {
|
{nav.map(({ label, href, icon: Icon }) => {
|
||||||
const active = pathname === href;
|
const active = pathname === href;
|
||||||
@@ -50,28 +59,35 @@ export default function Sidebar() {
|
|||||||
<button
|
<button
|
||||||
key={href}
|
key={href}
|
||||||
onClick={() => router.push(href)}
|
onClick={() => router.push(href)}
|
||||||
className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-sm text-left transition-all duration-150 group ${
|
className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-md text-left transition-all duration-150 group ${
|
||||||
active
|
active
|
||||||
? "bg-[#4aff8c]/8 border border-[#4aff8c]/20 text-[#4aff8c]"
|
? isLight
|
||||||
: "border border-transparent text-[#4a6a4a] hover:text-[#a0c4a0] hover:bg-white/[0.03]"
|
? "bg-sky-100 border border-sky-300 text-sky-600"
|
||||||
|
: "bg-acid-green/10 border border-acid-green/30 text-acid-green"
|
||||||
|
: `border border-transparent ${textSec} hover:${textPri} ${isLight ? "hover:bg-sky-50" : "hover:bg-white/[0.04]"}`
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
<Icon size={14} className="flex-shrink-0" />
|
<Icon size={16} className="flex-shrink-0" />
|
||||||
<span className="text-[11px] font-mono tracking-wider">{label}</span>
|
<span className="text-sm font-medium">{label}</span>
|
||||||
{active && <span className="ml-auto w-1 h-1 rounded-full bg-[#4aff8c]" />}
|
{active && (
|
||||||
|
<span className={`ml-auto w-1.5 h-1.5 rounded-full ${isLight ? "bg-sky-500" : "bg-acid-green"}`} />
|
||||||
|
)}
|
||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
{/* Footer */}
|
<div className={`px-3 py-4 border-t ${border} flex flex-col gap-2`}>
|
||||||
<div className="px-3 py-4 border-t border-[#1a2a1a]">
|
{/* Theme toggle */}
|
||||||
|
<div className="flex justify-end pr-1">
|
||||||
|
<ThemeToggleButton />
|
||||||
|
</div>
|
||||||
<button
|
<button
|
||||||
onClick={handleLogout}
|
onClick={handleLogout}
|
||||||
className="w-full flex items-center gap-3 px-3 py-2.5 rounded-sm text-[#3a5a3a] hover:text-red-400 hover:bg-red-500/5 border border-transparent hover:border-red-500/20 transition-all duration-150"
|
className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-md ${textSec} hover:text-red-400 hover:bg-red-500/10 border border-transparent hover:border-red-500/25 transition-all duration-150`}
|
||||||
>
|
>
|
||||||
<LogOut size={14} />
|
<LogOut size={16} />
|
||||||
<span className="text-[11px] font-mono tracking-wider">DÉCONNEXION</span>
|
<span className="text-sm font-medium">Déconnexion</span>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ interface StatCardProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const accentColors = {
|
const accentColors = {
|
||||||
green: { val: "text-[#4aff8c]", border: "border-t-[#4aff8c]/40" },
|
green: { val: "text-acid-green", border: "border-t-acid-green/40" },
|
||||||
red: { val: "text-red-400", border: "border-t-red-500/40" },
|
red: { val: "text-red-400", border: "border-t-red-500/40" },
|
||||||
blue: { val: "text-blue-400", border: "border-t-blue-400/40" },
|
blue: { val: "text-blue-400", border: "border-t-blue-400/40" },
|
||||||
purple: { val: "text-purple-400", border: "border-t-purple-400/40" },
|
purple: { val: "text-purple-400", border: "border-t-purple-400/40" },
|
||||||
@@ -18,23 +18,28 @@ const accentColors = {
|
|||||||
export default function StatCard({ label, value, sub, accent = "green", delta, deltaUp }: StatCardProps) {
|
export default function StatCard({ label, value, sub, accent = "green", delta, deltaUp }: StatCardProps) {
|
||||||
const colors = accentColors[accent];
|
const colors = accentColors[accent];
|
||||||
return (
|
return (
|
||||||
<div className={`bg-[#0d1210] border border-[#1a2a1a] border-t-2 ${colors.border} rounded-sm p-5 relative group hover:-translate-y-0.5 transition-transform duration-200`}>
|
<div
|
||||||
<div className="text-[9px] font-mono tracking-[0.25em] text-[#3a5a3a] uppercase mb-3">
|
className={`border border-t-2 ${colors.border} rounded-lg p-5 relative group hover:-translate-y-0.5 transition-transform duration-200`}
|
||||||
|
style={{ background: "var(--surface)", borderColor: "var(--border)" }}
|
||||||
|
>
|
||||||
|
<div className="text-xs font-mono tracking-widest uppercase mb-3" style={{ color: "var(--text-secondary)" }}>
|
||||||
{label}
|
{label}
|
||||||
</div>
|
</div>
|
||||||
<div className={`text-3xl font-black tracking-tight ${colors.val} leading-none mb-1`}>
|
<div className={`text-4xl font-black tracking-tight ${colors.val} leading-none mb-1`}>
|
||||||
{value === "—" || value === 0 ? <span className="text-[#2a3a2a]">—</span> : value}
|
{value === "—" || value === 0
|
||||||
|
? <span style={{ color: "var(--text-secondary)" }}>—</span>
|
||||||
|
: value}
|
||||||
</div>
|
</div>
|
||||||
{sub && (
|
{sub && (
|
||||||
<div className="text-[11px] text-[#3a4a3a] font-mono mt-1">{sub}</div>
|
<div className="text-xs font-mono mt-1" style={{ color: "var(--text-secondary)" }}>{sub}</div>
|
||||||
)}
|
)}
|
||||||
{delta && (
|
{delta && (
|
||||||
<div className={`absolute top-4 right-4 text-[9px] font-mono tracking-wider px-2 py-1 rounded-sm border ${
|
<div className={`absolute top-4 right-4 text-xs font-mono tracking-wider px-2 py-1 rounded-md border ${
|
||||||
deltaUp
|
deltaUp
|
||||||
? "text-[#4aff8c] bg-[#4aff8c]/5 border-[#4aff8c]/20"
|
? "text-acid-green bg-acid-green/10 border-acid-green/30"
|
||||||
: "text-red-400 bg-red-500/5 border-red-500/20"
|
: "text-red-400 bg-red-500/10 border-red-500/30"
|
||||||
}`}>
|
}`}>
|
||||||
{deltaUp ? "+" : ""}{delta}
|
{deltaUp ? "▲" : "▼"} {delta}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
280
components/StatsCharts.tsx
Normal file
280
components/StatsCharts.tsx
Normal file
@@ -0,0 +1,280 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState, useEffect } from "react";
|
||||||
|
import {
|
||||||
|
XAxis,
|
||||||
|
YAxis,
|
||||||
|
CartesianGrid,
|
||||||
|
Tooltip,
|
||||||
|
ResponsiveContainer,
|
||||||
|
Area,
|
||||||
|
AreaChart,
|
||||||
|
} from "recharts";
|
||||||
|
import { TrendingUp, TrendingDown, Minus, Lock } from "lucide-react";
|
||||||
|
|
||||||
|
type Period = "7d" | "30d" | "90d" | "all";
|
||||||
|
type Metric = "followers" | "likes" | "videoCount" | "views";
|
||||||
|
|
||||||
|
interface Snapshot {
|
||||||
|
createdAt: string;
|
||||||
|
followers: number;
|
||||||
|
likes: number;
|
||||||
|
videoCount: number;
|
||||||
|
views: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface StatsChartProps {
|
||||||
|
plan: "free" | "pro" | "elite" | "team";
|
||||||
|
}
|
||||||
|
|
||||||
|
const PERIOD_CONFIG: { value: Period; label: string; requiredPlan: "free" | "pro" | "elite" | "team" }[] = [
|
||||||
|
{ value: "7d", label: "7J", requiredPlan: "free" },
|
||||||
|
{ value: "30d", label: "30J", requiredPlan: "pro" },
|
||||||
|
{ value: "90d", label: "90J", requiredPlan: "pro" },
|
||||||
|
{ value: "all", label: "TOUT", requiredPlan: "elite"},
|
||||||
|
];
|
||||||
|
|
||||||
|
const PLAN_RANK: Record<string, number> = { free: 0, pro: 1, elite: 2, team: 3 };
|
||||||
|
|
||||||
|
const METRICS: { value: Metric; label: string; color: string; gradientId: string }[] = [
|
||||||
|
{ value: "followers", label: "Followers", color: "#c084fc", gradientId: "gradFollowers" },
|
||||||
|
{ value: "likes", label: "Likes", color: "#f472b6", gradientId: "gradLikes" },
|
||||||
|
{ value: "videoCount", label: "Vidéos", color: "#60a5fa", gradientId: "gradVideos" },
|
||||||
|
{ value: "views", label: "Vues", color: "#22c55e", gradientId: "gradViews" },
|
||||||
|
];
|
||||||
|
|
||||||
|
function canAccess(plan: string, required: string) {
|
||||||
|
return PLAN_RANK[plan] >= PLAN_RANK[required];
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatValue(value: number): string {
|
||||||
|
if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}M`;
|
||||||
|
if (value >= 1_000) return `${(value / 1_000).toFixed(1)}K`;
|
||||||
|
return value.toLocaleString("fr-FR");
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatDate(dateStr: string, period: Period): string {
|
||||||
|
const d = new Date(dateStr);
|
||||||
|
if (period === "7d") return d.toLocaleDateString("fr-FR", { weekday: "short", day: "numeric" });
|
||||||
|
if (period === "all") return d.toLocaleDateString("fr-FR", { month: "short", year: "2-digit" });
|
||||||
|
return d.toLocaleDateString("fr-FR", { day: "numeric", month: "short" });
|
||||||
|
}
|
||||||
|
|
||||||
|
function getDelta(snapshots: Snapshot[], metric: Metric) {
|
||||||
|
if (snapshots.length < 2) return null;
|
||||||
|
const first = snapshots[0][metric];
|
||||||
|
const last = snapshots[snapshots.length - 1][metric];
|
||||||
|
const diff = last - first;
|
||||||
|
const pct = first > 0 ? ((diff / first) * 100).toFixed(1) : null;
|
||||||
|
return { diff, pct };
|
||||||
|
}
|
||||||
|
|
||||||
|
function CustomTooltip({ active, payload, label, period }: any) {
|
||||||
|
if (!active || !payload?.length) return null;
|
||||||
|
return (
|
||||||
|
<div className="border rounded-sm px-3 py-2 font-mono text-[10px]"
|
||||||
|
style={{ background: "var(--surface)", borderColor: "var(--border)" }}>
|
||||||
|
<div className="mb-1 tracking-widest uppercase" style={{ color: "var(--text-secondary)" }}>
|
||||||
|
{formatDate(label, period)}
|
||||||
|
</div>
|
||||||
|
{payload.map((p: any) => (
|
||||||
|
<div key={p.dataKey} className="flex items-center gap-2" style={{ color: p.color }}>
|
||||||
|
<span className="uppercase tracking-widest">{p.name}</span>
|
||||||
|
<span className="ml-auto font-bold">{formatValue(p.value)}</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function StatsChart({ plan }: StatsChartProps) {
|
||||||
|
const [period, setPeriod] = useState<Period>("7d");
|
||||||
|
const [metric, setMetric] = useState<Metric>("followers");
|
||||||
|
const [snapshots, setSnapshots] = useState<Snapshot[]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!canAccess(plan, PERIOD_CONFIG.find(p => p.value === period)!.requiredPlan)) return;
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
fetch(`/api/tiktok/snapshots?period=${period}`)
|
||||||
|
.then(r => r.json())
|
||||||
|
.then(d => {
|
||||||
|
if (d.error) throw new Error(d.error);
|
||||||
|
setSnapshots(d);
|
||||||
|
})
|
||||||
|
.catch(e => setError(e.message))
|
||||||
|
.finally(() => setLoading(false));
|
||||||
|
}, [period, plan]);
|
||||||
|
|
||||||
|
const metricConfig = METRICS.find(m => m.value === metric)!;
|
||||||
|
const delta = getDelta(snapshots, metric);
|
||||||
|
const chartData = snapshots.map(s => ({ ...s, date: s.createdAt }));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="border rounded-sm" style={{ background: "var(--surface)", borderColor: "var(--border)" }}>
|
||||||
|
|
||||||
|
{/* Header */}
|
||||||
|
<div className="flex items-center justify-between px-4 pt-4 pb-3 border-b" style={{ borderColor: "var(--border)" }}>
|
||||||
|
<div>
|
||||||
|
<div className="text-[9px] font-mono tracking-[0.3em] text-pink-400/70 uppercase mb-0.5">Évolution</div>
|
||||||
|
<h2 className="text-sm font-black tracking-widest uppercase" style={{ color: "var(--text-primary)" }}>
|
||||||
|
Statistiques
|
||||||
|
</h2>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Period selector */}
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
{PERIOD_CONFIG.map(p => {
|
||||||
|
const accessible = canAccess(plan, p.requiredPlan);
|
||||||
|
const active = period === p.value;
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={p.value}
|
||||||
|
onClick={() => accessible && setPeriod(p.value)}
|
||||||
|
disabled={!accessible}
|
||||||
|
className={`
|
||||||
|
relative flex items-center gap-1 px-2.5 py-1 text-[9px] font-mono tracking-widest uppercase rounded-sm transition-all
|
||||||
|
${active
|
||||||
|
? "bg-pink-500/15 border border-pink-500/40 text-pink-300"
|
||||||
|
: accessible
|
||||||
|
? "border border-transparent hover:border-white/10"
|
||||||
|
: "border border-transparent cursor-not-allowed opacity-30"
|
||||||
|
}
|
||||||
|
`}
|
||||||
|
style={!active && accessible ? { color: "var(--text-secondary)" } : undefined}
|
||||||
|
>
|
||||||
|
{!accessible && <Lock size={7} className="opacity-50" />}
|
||||||
|
{p.label}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Metric selector */}
|
||||||
|
<div className="flex items-center gap-3 px-4 py-3 border-b" style={{ borderColor: "var(--border)" }}>
|
||||||
|
{METRICS.map(m => (
|
||||||
|
<button
|
||||||
|
key={m.value}
|
||||||
|
onClick={() => setMetric(m.value)}
|
||||||
|
className={`flex items-center gap-1.5 text-[9px] font-mono tracking-widest uppercase transition-all pb-0.5 ${
|
||||||
|
metric === m.value ? "border-b-2" : ""
|
||||||
|
}`}
|
||||||
|
style={metric === m.value
|
||||||
|
? { color: m.color, borderColor: m.color }
|
||||||
|
: { color: "var(--text-secondary)" }}
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
className="w-1.5 h-1.5 rounded-full"
|
||||||
|
style={{ background: metric === m.value ? m.color : "var(--border)" }}
|
||||||
|
/>
|
||||||
|
{m.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
|
||||||
|
{/* Delta badge */}
|
||||||
|
{delta && !loading && (
|
||||||
|
<div className="ml-auto flex items-center gap-1.5 text-[9px] font-mono">
|
||||||
|
{Number(delta.diff) > 0 ? (
|
||||||
|
<TrendingUp size={11} className="text-emerald-400" />
|
||||||
|
) : Number(delta.diff) < 0 ? (
|
||||||
|
<TrendingDown size={11} className="text-red-400" />
|
||||||
|
) : (
|
||||||
|
<Minus size={11} style={{ color: "var(--text-secondary)" }} />
|
||||||
|
)}
|
||||||
|
<span style={{ color: Number(delta.diff) > 0 ? "#34d399" : Number(delta.diff) < 0 ? "#f87171" : "var(--text-secondary)" }}>
|
||||||
|
{Number(delta.diff) > 0 ? "+" : ""}{formatValue(delta.diff)}
|
||||||
|
{delta.pct && ` (${Number(delta.diff) > 0 ? "+" : ""}${delta.pct}%)`}
|
||||||
|
</span>
|
||||||
|
<span className="tracking-widest uppercase" style={{ color: "var(--text-secondary)" }}>sur la période</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="px-2 pt-4 pb-2" style={{ height: 240 }}>
|
||||||
|
{loading ? (
|
||||||
|
<div className="flex items-center justify-center h-full gap-2 font-mono text-[10px] tracking-widest uppercase animate-pulse"
|
||||||
|
style={{ color: "var(--text-secondary)" }}>
|
||||||
|
Chargement...
|
||||||
|
</div>
|
||||||
|
) : error ? (
|
||||||
|
<div className="flex items-center justify-center h-full font-mono text-[10px] tracking-widest uppercase text-red-400/60">
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
) : snapshots.length < 2 ? (
|
||||||
|
<div className="flex flex-col items-center justify-center h-full gap-2">
|
||||||
|
<span className="font-mono text-[10px] tracking-widest uppercase" style={{ color: "var(--text-secondary)" }}>
|
||||||
|
Pas encore assez de données
|
||||||
|
</span>
|
||||||
|
<span className="font-mono text-[9px] tracking-widest uppercase" style={{ color: "var(--text-secondary)", opacity: 0.4 }}>
|
||||||
|
Les snapshots s'accumulent toutes les heures
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<ResponsiveContainer width="100%" height="100%">
|
||||||
|
<AreaChart data={chartData} margin={{ top: 4, right: 8, left: 0, bottom: 0 }}>
|
||||||
|
<defs>
|
||||||
|
<linearGradient id={metricConfig.gradientId} x1="0" y1="0" x2="0" y2="1">
|
||||||
|
<stop offset="5%" stopColor={metricConfig.color} stopOpacity={0.15} />
|
||||||
|
<stop offset="95%" stopColor={metricConfig.color} stopOpacity={0} />
|
||||||
|
</linearGradient>
|
||||||
|
</defs>
|
||||||
|
<CartesianGrid
|
||||||
|
strokeDasharray="2 4"
|
||||||
|
stroke="var(--border)"
|
||||||
|
strokeOpacity={0.5}
|
||||||
|
vertical={false}
|
||||||
|
/>
|
||||||
|
<XAxis
|
||||||
|
dataKey="date"
|
||||||
|
tickFormatter={d => formatDate(d, period)}
|
||||||
|
tick={{ fill: "var(--text-secondary)", fontSize: 9, fontFamily: "monospace" }}
|
||||||
|
tickLine={false}
|
||||||
|
axisLine={false}
|
||||||
|
interval="preserveStartEnd"
|
||||||
|
/>
|
||||||
|
<YAxis
|
||||||
|
tickFormatter={formatValue}
|
||||||
|
tick={{ fill: "var(--text-secondary)", fontSize: 9, fontFamily: "monospace" }}
|
||||||
|
tickLine={false}
|
||||||
|
axisLine={false}
|
||||||
|
width={40}
|
||||||
|
/>
|
||||||
|
<Tooltip
|
||||||
|
content={<CustomTooltip period={period} />}
|
||||||
|
cursor={{ stroke: "var(--border)", strokeWidth: 1 }}
|
||||||
|
/>
|
||||||
|
<Area
|
||||||
|
type="monotone"
|
||||||
|
dataKey={metric}
|
||||||
|
name={metricConfig.label}
|
||||||
|
stroke={metricConfig.color}
|
||||||
|
strokeWidth={1.5}
|
||||||
|
fill={`url(#${metricConfig.gradientId})`}
|
||||||
|
dot={false}
|
||||||
|
activeDot={{ r: 3, fill: metricConfig.color, strokeWidth: 0 }}
|
||||||
|
/>
|
||||||
|
</AreaChart>
|
||||||
|
</ResponsiveContainer>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{!canAccess(plan, PERIOD_CONFIG.find(p => p.value === period)!.requiredPlan) && (
|
||||||
|
<div className="mx-4 mb-4 px-4 py-3 border border-pink-500/20 rounded-sm bg-pink-500/5 flex items-center justify-between">
|
||||||
|
<span className="font-mono text-[10px] tracking-widest text-pink-400/60 uppercase">
|
||||||
|
<Lock size={9} className="inline mr-1.5 mb-0.5" />
|
||||||
|
Disponible en plan Pro
|
||||||
|
</span>
|
||||||
|
<a
|
||||||
|
href="/pricing"
|
||||||
|
className="font-mono text-[9px] tracking-widest uppercase text-pink-300 hover:text-pink-200 transition-colors border border-pink-500/30 hover:border-pink-500/60 px-2.5 py-1 rounded-sm"
|
||||||
|
>
|
||||||
|
Upgrader →
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
19
components/ThemeToggleButton.tsx
Normal file
19
components/ThemeToggleButton.tsx
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { Moon, Sun } from "lucide-react";
|
||||||
|
import { useTheme } from "@/lib/theme";
|
||||||
|
|
||||||
|
export default function ThemeToggleButton() {
|
||||||
|
const { theme, toggle } = useTheme();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
onClick={toggle}
|
||||||
|
aria-label="Changer de thème"
|
||||||
|
className="flex items-center justify-center w-8 h-8 rounded-md border border-wy-border text-wy-text-secondary hover:text-wy-text-primary hover:bg-white/[0.06] transition-all duration-150"
|
||||||
|
>
|
||||||
|
{theme === "dark" ? <Sun size={15} /> : <Moon size={15} />}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
@@ -1,5 +1,3 @@
|
|||||||
version: '3.8'
|
|
||||||
|
|
||||||
services:
|
services:
|
||||||
postgres:
|
postgres:
|
||||||
image: postgres:16-alpine
|
image: postgres:16-alpine
|
||||||
@@ -7,10 +5,10 @@ services:
|
|||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
environment:
|
environment:
|
||||||
POSTGRES_USER: wyview
|
POSTGRES_USER: wyview
|
||||||
POSTGRES_PASSWORD: wyview_password
|
POSTGRES_PASSWORD: wyview
|
||||||
POSTGRES_DB: wyview
|
POSTGRES_DB: wyview
|
||||||
ports:
|
ports:
|
||||||
- "5432:5432"
|
- "5433:5432"
|
||||||
volumes:
|
volumes:
|
||||||
- postgres_data:/var/lib/postgresql/data
|
- postgres_data:/var/lib/postgresql/data
|
||||||
healthcheck:
|
healthcheck:
|
||||||
@@ -24,20 +22,47 @@ services:
|
|||||||
context: .
|
context: .
|
||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
args:
|
args:
|
||||||
DATABASE_URL: postgresql://wyview:wyview_password@postgres:5432/wyview
|
DATABASE_URL: postgresql://wyview:wyview@postgres:5432/wyview
|
||||||
|
image: marouette/wyview:latest
|
||||||
container_name: wyview-app
|
container_name: wyview-app
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
ports:
|
ports:
|
||||||
- "3001:3001"
|
- "3001:3001"
|
||||||
environment:
|
environment:
|
||||||
- NODE_ENV=production
|
- NODE_ENV=production
|
||||||
- DATABASE_URL=postgresql://wyview:wyview_password@postgres:5432/wyview
|
- DATABASE_URL=postgresql://wyview:wyview@postgres:5432/wyview
|
||||||
- NEXTAUTH_URL=http://localhost:3001
|
- AUTH_URL=${AUTH_URL}
|
||||||
- NEXTAUTH_SECRET=your-secret-key-change-this-in-production
|
- NEXT_PUBLIC_APP_URL=${NEXT_PUBLIC_APP_URL}
|
||||||
|
- NEXTAUTH_URL=${NEXTAUTH_URL}
|
||||||
|
- NEXTAUTH_SECRET=${NEXTAUTH_SECRET}
|
||||||
|
- AUTH_SECRET=${AUTH_SECRET}
|
||||||
|
- TIKTOK_CLIENT_KEY=${TIKTOK_CLIENT_KEY}
|
||||||
|
- TIKTOK_CLIENT_SECRET=${TIKTOK_CLIENT_SECRET}
|
||||||
|
- TIKTOK_REDIRECT_URI_PROD=${TIKTOK_REDIRECT_URI_PROD}
|
||||||
|
- TIKTOK_REDIRECT_URI_DEV=${TIKTOK_REDIRECT_URI_DEV}
|
||||||
depends_on:
|
depends_on:
|
||||||
postgres:
|
postgres:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
command: sh -c "npx prisma migrate deploy && npm start"
|
command: sh -c "npx prisma migrate deploy && npm start"
|
||||||
|
|
||||||
|
worker:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: worker/Dockerfile
|
||||||
|
image: marouette/wyview-worker:latest
|
||||||
|
container_name: wyview-worker
|
||||||
|
restart: unless-stopped
|
||||||
|
environment:
|
||||||
|
- NODE_ENV=production
|
||||||
|
- DATABASE_URL=postgresql://wyview:wyview@postgres:5432/wyview
|
||||||
|
- TIKTOK_CLIENT_KEY=${TIKTOK_CLIENT_KEY}
|
||||||
|
- TIKTOK_CLIENT_SECRET=${TIKTOK_CLIENT_SECRET}
|
||||||
|
depends_on:
|
||||||
|
postgres:
|
||||||
|
condition: service_healthy
|
||||||
|
app:
|
||||||
|
condition: service_started
|
||||||
|
command: sh -c "sleep 30 && tsx worker/snapshot-worker.ts"
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
postgres_data:
|
postgres_data:
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import bcrypt from "bcryptjs";
|
|||||||
import { prisma } from "@/lib/prisma";
|
import { prisma } from "@/lib/prisma";
|
||||||
|
|
||||||
export const { handlers, signIn, signOut, auth } = NextAuth({
|
export const { handlers, signIn, signOut, auth } = NextAuth({
|
||||||
|
trustHost: true,
|
||||||
providers: [
|
providers: [
|
||||||
Credentials({
|
Credentials({
|
||||||
credentials: {
|
credentials: {
|
||||||
@@ -32,6 +33,9 @@ export const { handlers, signIn, signOut, auth } = NextAuth({
|
|||||||
],
|
],
|
||||||
callbacks: {
|
callbacks: {
|
||||||
async session({ session, token }) {
|
async session({ session, token }) {
|
||||||
|
if (token?.id && session.user) {
|
||||||
|
(session.user as { id?: string }).id = token.id as string;
|
||||||
|
}
|
||||||
return session;
|
return session;
|
||||||
},
|
},
|
||||||
async jwt({ token, user }) {
|
async jwt({ token, user }) {
|
||||||
|
|||||||
49
lib/theme.tsx
Normal file
49
lib/theme.tsx
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { createContext, useContext, useEffect, useState } from "react";
|
||||||
|
|
||||||
|
type Theme = "dark" | "light";
|
||||||
|
|
||||||
|
interface ThemeContextType {
|
||||||
|
theme: Theme;
|
||||||
|
toggle: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ThemeContext = createContext<ThemeContextType>({
|
||||||
|
theme: "dark",
|
||||||
|
toggle: () => {},
|
||||||
|
});
|
||||||
|
|
||||||
|
export function ThemeProvider({ children }: { children: React.ReactNode }) {
|
||||||
|
const [theme, setTheme] = useState<Theme>("dark");
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const stored = localStorage.getItem("wyview-theme") as Theme | null;
|
||||||
|
if (stored) setTheme(stored);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const root = document.documentElement;
|
||||||
|
if (theme === "light") {
|
||||||
|
root.classList.add("light");
|
||||||
|
root.classList.remove("dark");
|
||||||
|
} else {
|
||||||
|
root.classList.add("dark");
|
||||||
|
root.classList.remove("light");
|
||||||
|
}
|
||||||
|
localStorage.setItem("wyview-theme", theme);
|
||||||
|
}, [theme]);
|
||||||
|
|
||||||
|
const toggle = () => setTheme((t) => (t === "dark" ? "light" : "dark"));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ThemeContext.Provider value={{ theme, toggle }}>
|
||||||
|
{children}
|
||||||
|
</ThemeContext.Provider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useTheme() {
|
||||||
|
return useContext(ThemeContext);
|
||||||
|
}
|
||||||
|
|
||||||
211
lib/tiktok.ts
Normal file
211
lib/tiktok.ts
Normal file
@@ -0,0 +1,211 @@
|
|||||||
|
const TIKTOK_AUTH_URL = "https://www.tiktok.com/v2/auth/authorize";
|
||||||
|
const TIKTOK_TOKEN_URL = "https://open.tiktokapis.com/v2/oauth/token/";
|
||||||
|
const TIKTOK_USER_INFO_URL = "https://open.tiktokapis.com/v2/user/info/";
|
||||||
|
const TIKTOK_VIDEO_LIST_URL = "https://open.tiktokapis.com/v2/video/list/";
|
||||||
|
|
||||||
|
const CLIENT_KEY = process.env.TIKTOK_CLIENT_KEY!;
|
||||||
|
const CLIENT_SECRET = process.env.TIKTOK_CLIENT_SECRET!;
|
||||||
|
|
||||||
|
function getRedirectUri(): string {
|
||||||
|
return process.env.NODE_ENV === "production"
|
||||||
|
? process.env.TIKTOK_REDIRECT_URI_PROD!
|
||||||
|
: process.env.TIKTOK_REDIRECT_URI_DEV!;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── PKCE helpers ──────────────────────────────────────────────
|
||||||
|
export function generateCodeVerifier(): string {
|
||||||
|
const charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
||||||
|
let result = "";
|
||||||
|
const array = new Uint8Array(64);
|
||||||
|
crypto.getRandomValues(array);
|
||||||
|
for (let i = 0; i < 64; i++) {
|
||||||
|
result += charset[array[i] % charset.length];
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function generateCodeChallenge(verifier: string): Promise<string> {
|
||||||
|
const data = new TextEncoder().encode(verifier);
|
||||||
|
const digest = await globalThis.crypto.subtle.digest("SHA-256", data);
|
||||||
|
const bytes = Array.from(new Uint8Array(digest));
|
||||||
|
return btoa(bytes.map((b) => String.fromCharCode(b)).join(""))
|
||||||
|
.replace(/\+/g, "-")
|
||||||
|
.replace(/\//g, "_")
|
||||||
|
.replace(/=+$/, "");
|
||||||
|
}
|
||||||
|
// ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function getTikTokAuthUrl(state: string, codeChallenge: string): string {
|
||||||
|
const params = new URLSearchParams({
|
||||||
|
client_key: CLIENT_KEY,
|
||||||
|
response_type: "code",
|
||||||
|
// video.list is used as a fallback to compute total views from all videos.
|
||||||
|
scope: "user.info.basic,user.info.stats,video.list",
|
||||||
|
redirect_uri: getRedirectUri(),
|
||||||
|
state,
|
||||||
|
code_challenge: codeChallenge,
|
||||||
|
code_challenge_method: "S256",
|
||||||
|
// "select_account" seul est ignoré par TikTok si une session est active.
|
||||||
|
// On passe les deux pour forcer l'affichage du sélecteur de compte à chaque fois.
|
||||||
|
prompt: "select_account",
|
||||||
|
force_login: "true",
|
||||||
|
});
|
||||||
|
return `${TIKTOK_AUTH_URL}?${params.toString()}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TikTokTokenResponse {
|
||||||
|
access_token: string;
|
||||||
|
refresh_token: string;
|
||||||
|
open_id: string;
|
||||||
|
expires_in: number;
|
||||||
|
refresh_expires_in: number;
|
||||||
|
token_type: string;
|
||||||
|
scope: string;
|
||||||
|
error?: string;
|
||||||
|
error_description?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function exchangeCodeForTokens(code: string, codeVerifier: string): Promise<TikTokTokenResponse> {
|
||||||
|
const body = new URLSearchParams({
|
||||||
|
client_key: CLIENT_KEY,
|
||||||
|
client_secret: CLIENT_SECRET,
|
||||||
|
code,
|
||||||
|
grant_type: "authorization_code",
|
||||||
|
redirect_uri: getRedirectUri(),
|
||||||
|
code_verifier: codeVerifier,
|
||||||
|
});
|
||||||
|
|
||||||
|
const res = await fetch(TIKTOK_TOKEN_URL, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||||
|
body: body.toString(),
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await res.json();
|
||||||
|
|
||||||
|
if (!res.ok || data.error) {
|
||||||
|
throw new Error(data.error_description || data.error || "TikTok token exchange failed");
|
||||||
|
}
|
||||||
|
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function refreshAccessToken(refreshToken: string): Promise<TikTokTokenResponse> {
|
||||||
|
const body = new URLSearchParams({
|
||||||
|
client_key: CLIENT_KEY,
|
||||||
|
client_secret: CLIENT_SECRET,
|
||||||
|
grant_type: "refresh_token",
|
||||||
|
refresh_token: refreshToken,
|
||||||
|
});
|
||||||
|
|
||||||
|
const res = await fetch(TIKTOK_TOKEN_URL, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||||
|
body: body.toString(),
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await res.json();
|
||||||
|
|
||||||
|
if (!res.ok || data.error) {
|
||||||
|
throw new Error(data.error_description || data.error || "TikTok token refresh failed");
|
||||||
|
}
|
||||||
|
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TikTokUserStats {
|
||||||
|
followers: number;
|
||||||
|
likes: number;
|
||||||
|
videoCount: number;
|
||||||
|
views: number;
|
||||||
|
profileViews: number;
|
||||||
|
username: string;
|
||||||
|
displayName: string;
|
||||||
|
avatarUrl: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchTotalVideoViews(accessToken: string): Promise<number> {
|
||||||
|
const fields = "id,view_count";
|
||||||
|
let cursor = 0;
|
||||||
|
let totalViews = 0;
|
||||||
|
|
||||||
|
for (let page = 0; page < 50; page++) {
|
||||||
|
const res = await fetch(`${TIKTOK_VIDEO_LIST_URL}?fields=${fields}`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${accessToken}`,
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ max_count: 20, cursor }),
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await res.json();
|
||||||
|
|
||||||
|
if (!res.ok || data.error?.code !== "ok") {
|
||||||
|
throw new Error(data.error?.message || "TikTok video list fetch failed");
|
||||||
|
}
|
||||||
|
|
||||||
|
const videos = Array.isArray(data.data?.videos) ? data.data.videos : [];
|
||||||
|
for (const video of videos) {
|
||||||
|
totalViews += Number(video?.view_count ?? 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
const hasMore = Boolean(data.data?.has_more);
|
||||||
|
if (!hasMore) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
const nextCursor = Number(data.data?.cursor ?? cursor + videos.length);
|
||||||
|
if (!Number.isFinite(nextCursor) || nextCursor <= cursor) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
cursor = nextCursor;
|
||||||
|
}
|
||||||
|
|
||||||
|
return totalViews;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchUserStats(accessToken: string, openId: string): Promise<TikTokUserStats> {
|
||||||
|
const fields = "follower_count,following_count,likes_count,video_count,video_view_count,profile_view_count,display_name,avatar_url";
|
||||||
|
const url = `${TIKTOK_USER_INFO_URL}?fields=${fields}`;
|
||||||
|
|
||||||
|
const res = await fetch(url, {
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${accessToken}`,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await res.json();
|
||||||
|
|
||||||
|
if (!res.ok || data.error?.code !== "ok") {
|
||||||
|
throw new Error(data.error?.message || "TikTok user info fetch failed");
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = data.data?.user ?? {};
|
||||||
|
let views = user.video_view_count ?? user.profile_view_count ?? 0;
|
||||||
|
|
||||||
|
// Some TikTok apps do not receive video_view_count in user.info.stats.
|
||||||
|
// In that case we compute total views from the account video list.
|
||||||
|
if (user.video_view_count == null) {
|
||||||
|
try {
|
||||||
|
const computedViews = await fetchTotalVideoViews(accessToken);
|
||||||
|
if (computedViews > 0) {
|
||||||
|
views = computedViews;
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.warn("[TikTok views fallback error]", err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
followers: user.follower_count ?? 0,
|
||||||
|
likes: user.likes_count ?? 0,
|
||||||
|
videoCount: user.video_count ?? 0,
|
||||||
|
views,
|
||||||
|
profileViews: user.profile_view_count ?? 0,
|
||||||
|
username: openId,
|
||||||
|
displayName: user.display_name ?? "",
|
||||||
|
avatarUrl: user.avatar_url ?? "",
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -7,7 +7,13 @@ export async function middleware(req: NextRequest) {
|
|||||||
const { pathname } = req.nextUrl;
|
const { pathname } = req.nextUrl;
|
||||||
const isProtected = protectedPaths.some((p) => pathname.startsWith(p));
|
const isProtected = protectedPaths.some((p) => pathname.startsWith(p));
|
||||||
|
|
||||||
const token = await getToken({ req, secret: process.env.AUTH_SECRET });
|
const token = await getToken({
|
||||||
|
req,
|
||||||
|
secret: process.env.AUTH_SECRET,
|
||||||
|
cookieName: process.env.NODE_ENV === "production"
|
||||||
|
? "__Secure-authjs.session-token"
|
||||||
|
: "authjs.session-token"
|
||||||
|
});
|
||||||
|
|
||||||
if (isProtected && !token) {
|
if (isProtected && !token) {
|
||||||
const loginUrl = new URL("/", req.url);
|
const loginUrl = new URL("/", req.url);
|
||||||
|
|||||||
934
package-lock.json
generated
934
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -27,6 +27,7 @@
|
|||||||
"@types/react-dom": "^19.2.3",
|
"@types/react-dom": "^19.2.3",
|
||||||
"autoprefixer": "^10.4.27",
|
"autoprefixer": "^10.4.27",
|
||||||
"bcryptjs": "^3.0.3",
|
"bcryptjs": "^3.0.3",
|
||||||
|
"dotenv": "^16.4.7",
|
||||||
"lucide-react": "^0.575.0",
|
"lucide-react": "^0.575.0",
|
||||||
"next": "^15.5.12",
|
"next": "^15.5.12",
|
||||||
"next-auth": "^5.0.0-beta.30",
|
"next-auth": "^5.0.0-beta.30",
|
||||||
@@ -34,12 +35,14 @@
|
|||||||
"postcss": "^8.5.6",
|
"postcss": "^8.5.6",
|
||||||
"react": "^19.2.4",
|
"react": "^19.2.4",
|
||||||
"react-dom": "^19.2.4",
|
"react-dom": "^19.2.4",
|
||||||
|
"recharts": "^3.8.0",
|
||||||
"tailwindcss": "^3.4.19",
|
"tailwindcss": "^3.4.19",
|
||||||
"typescript": "^5.9.3"
|
"typescript": "^5.9.3"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/bcryptjs": "^2.4.6",
|
"@types/bcryptjs": "^2.4.6",
|
||||||
"@types/pg": "^8.18.0",
|
"@types/pg": "^8.18.0",
|
||||||
"prisma": "^7.4.2"
|
"prisma": "^7.4.2",
|
||||||
|
"tsx": "^4.21.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "User" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"email" TEXT NOT NULL,
|
||||||
|
"password" TEXT NOT NULL,
|
||||||
|
"name" TEXT,
|
||||||
|
"role" TEXT NOT NULL DEFAULT 'member',
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "User_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "TikTokToken" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"userId" TEXT NOT NULL,
|
||||||
|
"openId" TEXT NOT NULL,
|
||||||
|
"accessToken" TEXT NOT NULL,
|
||||||
|
"refreshToken" TEXT NOT NULL,
|
||||||
|
"expiresAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "TikTokToken_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "TrackedAccount" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"platform" TEXT NOT NULL,
|
||||||
|
"username" TEXT NOT NULL,
|
||||||
|
"accountId" TEXT NOT NULL,
|
||||||
|
"userId" TEXT NOT NULL,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "TrackedAccount_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "Snapshot" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"accountId" TEXT NOT NULL,
|
||||||
|
"followers" INTEGER NOT NULL,
|
||||||
|
"views" INTEGER NOT NULL,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "Snapshot_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "TikTokToken_userId_key" ON "TikTokToken"("userId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "TikTokToken_openId_key" ON "TikTokToken"("openId");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "TikTokToken" ADD CONSTRAINT "TikTokToken_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "TrackedAccount" ADD CONSTRAINT "TrackedAccount_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "Snapshot" ADD CONSTRAINT "Snapshot_accountId_fkey" FOREIGN KEY ("accountId") REFERENCES "TrackedAccount"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "TikTokPKCE" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"state" TEXT NOT NULL,
|
||||||
|
"codeVerifier" TEXT NOT NULL,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "TikTokPKCE_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "TikTokPKCE_state_key" ON "TikTokPKCE"("state");
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
/*
|
||||||
|
Warnings:
|
||||||
|
|
||||||
|
- Added the required column `userId` to the `TikTokPKCE` table without a default value. This is not possible if the table is not empty.
|
||||||
|
|
||||||
|
*/
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "TikTokPKCE" ADD COLUMN "userId" TEXT NOT NULL;
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
-- DropIndex
|
||||||
|
DROP INDEX "TikTokToken_openId_key";
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "Snapshot" ADD COLUMN "likes" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
ADD COLUMN "videoCount" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
ALTER COLUMN "views" SET DEFAULT 0;
|
||||||
|
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "User" ADD COLUMN "plan" TEXT NOT NULL DEFAULT 'free';
|
||||||
3
prisma/migrations/migration_lock.toml
Normal file
3
prisma/migrations/migration_lock.toml
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# Please do not edit this file manually
|
||||||
|
# It should be added in your version-control system (e.g., Git)
|
||||||
|
provider = "postgresql"
|
||||||
@@ -13,9 +13,31 @@ model User {
|
|||||||
password String
|
password String
|
||||||
name String?
|
name String?
|
||||||
role String @default("member")
|
role String @default("member")
|
||||||
|
plan String @default("free")
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
accounts TrackedAccount[]
|
accounts TrackedAccount[]
|
||||||
|
tiktokToken TikTokToken?
|
||||||
|
}
|
||||||
|
|
||||||
|
model TikTokToken {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
userId String @unique
|
||||||
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
|
openId String
|
||||||
|
accessToken String
|
||||||
|
refreshToken String
|
||||||
|
expiresAt DateTime
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
}
|
||||||
|
|
||||||
|
model TikTokPKCE {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
state String @unique
|
||||||
|
codeVerifier String
|
||||||
|
userId String
|
||||||
|
createdAt DateTime @default(now())
|
||||||
}
|
}
|
||||||
|
|
||||||
model TrackedAccount {
|
model TrackedAccount {
|
||||||
@@ -34,6 +56,8 @@ model Snapshot {
|
|||||||
accountId String
|
accountId String
|
||||||
account TrackedAccount @relation(fields: [accountId], references: [id], onDelete: Cascade)
|
account TrackedAccount @relation(fields: [accountId], references: [id], onDelete: Cascade)
|
||||||
followers Int
|
followers Int
|
||||||
views Int
|
likes Int @default(0)
|
||||||
|
videoCount Int @default(0)
|
||||||
|
views Int @default(0)
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
}
|
}
|
||||||
@@ -1,11 +1,28 @@
|
|||||||
/** @type {import('tailwindcss').Config} */
|
/** @type {import('tailwindcss').Config} */
|
||||||
module.exports = {
|
module.exports = {
|
||||||
|
darkMode: "class",
|
||||||
content: [
|
content: [
|
||||||
"./app/**/*.{ts,tsx}",
|
"./app/**/*.{ts,tsx}",
|
||||||
"./components/**/*.{ts,tsx}",
|
"./components/**/*.{ts,tsx}",
|
||||||
],
|
],
|
||||||
theme: {
|
theme: {
|
||||||
extend: {},
|
extend: {
|
||||||
|
colors: {
|
||||||
|
"acid-green": "#4aff8c",
|
||||||
|
"rathian-dark": "#0a8a3a",
|
||||||
|
"wy-dark": "#0d1117",
|
||||||
|
"wy-surface": "#161b22",
|
||||||
|
"wy-border": "#30363d",
|
||||||
|
"wy-text-primary": "#c9d1d9",
|
||||||
|
"wy-text-secondary": "#8b949e",
|
||||||
|
// Light theme
|
||||||
|
"wy-light-bg": "#f0f6ff",
|
||||||
|
"wy-light-surface": "#ffffff",
|
||||||
|
"wy-light-border": "#d0d7de",
|
||||||
|
"wy-light-text-primary": "#1c2128",
|
||||||
|
"wy-light-text-secondary": "#57606a",
|
||||||
|
},
|
||||||
|
},
|
||||||
},
|
},
|
||||||
plugins: [],
|
plugins: [],
|
||||||
}
|
}
|
||||||
19
worker/Dockerfile
Normal file
19
worker/Dockerfile
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
FROM node:20-alpine
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY package*.json ./
|
||||||
|
COPY prisma.config.ts ./
|
||||||
|
COPY prisma ./prisma/
|
||||||
|
COPY tsconfig.json ./
|
||||||
|
|
||||||
|
RUN npm ci
|
||||||
|
|
||||||
|
RUN npx prisma generate
|
||||||
|
|
||||||
|
COPY worker ./worker/
|
||||||
|
COPY app/generated ./app/generated/
|
||||||
|
|
||||||
|
RUN npm install -g tsx
|
||||||
|
|
||||||
|
CMD ["tsx", "worker/snapshot-worker.ts"]
|
||||||
225
worker/snapshot-worker.ts
Normal file
225
worker/snapshot-worker.ts
Normal file
@@ -0,0 +1,225 @@
|
|||||||
|
/**
|
||||||
|
* Snapshot Worker
|
||||||
|
* Tourne toutes les heures, indépendamment de Next.js.
|
||||||
|
* Pour chaque user avec un token TikTok valide :
|
||||||
|
* 1. Rafraîchit le token si nécessaire
|
||||||
|
* 2. Récupère les stats TikTok
|
||||||
|
* 3. Sauvegarde un snapshot en base (max 1 par heure par compte)
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { PrismaClient } from "../app/generated/prisma/client";
|
||||||
|
import { PrismaPg } from "@prisma/adapter-pg";
|
||||||
|
import { Pool } from "pg";
|
||||||
|
|
||||||
|
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
|
||||||
|
const adapter = new PrismaPg(pool);
|
||||||
|
const prisma = new PrismaClient({ adapter });
|
||||||
|
|
||||||
|
const TIKTOK_TOKEN_URL = "https://open.tiktokapis.com/v2/oauth/token/";
|
||||||
|
const TIKTOK_USER_INFO_URL = "https://open.tiktokapis.com/v2/user/info/";
|
||||||
|
const TIKTOK_VIDEO_LIST_URL = "https://open.tiktokapis.com/v2/video/list/";
|
||||||
|
const CLIENT_KEY = process.env.TIKTOK_CLIENT_KEY!;
|
||||||
|
const CLIENT_SECRET = process.env.TIKTOK_CLIENT_SECRET!;
|
||||||
|
const INTERVAL_MS = 60 * 60 * 1000; // 1 heure
|
||||||
|
const DEDUP_WINDOW_MS = 55 * 60 * 1000; // 55 min — évite les doublons si restart
|
||||||
|
|
||||||
|
// ── Graceful shutdown ─────────────────────────────────────────
|
||||||
|
|
||||||
|
async function shutdown() {
|
||||||
|
console.log("[worker] arrêt propre...");
|
||||||
|
await prisma.$disconnect();
|
||||||
|
await pool.end();
|
||||||
|
process.exit(0);
|
||||||
|
}
|
||||||
|
process.on("SIGTERM", shutdown);
|
||||||
|
process.on("SIGINT", shutdown);
|
||||||
|
|
||||||
|
// ── TikTok helpers ────────────────────────────────────────────
|
||||||
|
|
||||||
|
async function refreshTikTokToken(refreshTokenStr: string) {
|
||||||
|
const body = new URLSearchParams({
|
||||||
|
client_key: CLIENT_KEY,
|
||||||
|
client_secret: CLIENT_SECRET,
|
||||||
|
grant_type: "refresh_token",
|
||||||
|
refresh_token: refreshTokenStr,
|
||||||
|
});
|
||||||
|
|
||||||
|
const res = await fetch(TIKTOK_TOKEN_URL, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||||
|
body: body.toString(),
|
||||||
|
});
|
||||||
|
const data = await res.json();
|
||||||
|
|
||||||
|
if (!res.ok || data.error) {
|
||||||
|
throw new Error(data.error_description ?? data.error ?? "Refresh failed");
|
||||||
|
}
|
||||||
|
return data as { access_token: string; refresh_token: string; expires_in: number };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchTikTokStats(accessToken: string) {
|
||||||
|
const fields = "follower_count,likes_count,video_count,video_view_count,display_name";
|
||||||
|
const res = await fetch(`${TIKTOK_USER_INFO_URL}?fields=${fields}`, {
|
||||||
|
headers: { Authorization: `Bearer ${accessToken}` },
|
||||||
|
});
|
||||||
|
const data = await res.json();
|
||||||
|
|
||||||
|
if (!res.ok || data.error?.code !== "ok") {
|
||||||
|
throw new Error(data.error?.message ?? "Stats fetch failed");
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = data.data?.user ?? {};
|
||||||
|
let views = (user.video_view_count ?? user.profile_view_count ?? 0) as number;
|
||||||
|
|
||||||
|
if (user.video_view_count == null) {
|
||||||
|
try {
|
||||||
|
views = await fetchTotalVideoViews(accessToken);
|
||||||
|
} catch (err) {
|
||||||
|
console.warn("[worker] fallback views failed:", err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
followers: (user.follower_count ?? 0) as number,
|
||||||
|
likes: (user.likes_count ?? 0) as number,
|
||||||
|
videoCount: (user.video_count ?? 0) as number,
|
||||||
|
views,
|
||||||
|
displayName: (user.display_name ?? "") as string,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchTotalVideoViews(accessToken: string): Promise<number> {
|
||||||
|
const fields = "id,view_count";
|
||||||
|
let cursor = 0;
|
||||||
|
let totalViews = 0;
|
||||||
|
|
||||||
|
for (let page = 0; page < 50; page++) {
|
||||||
|
const res = await fetch(`${TIKTOK_VIDEO_LIST_URL}?fields=${fields}`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${accessToken}`,
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ max_count: 20, cursor }),
|
||||||
|
});
|
||||||
|
const data = await res.json();
|
||||||
|
|
||||||
|
if (!res.ok || data.error?.code !== "ok") {
|
||||||
|
throw new Error(data.error?.message ?? "Video list fetch failed");
|
||||||
|
}
|
||||||
|
|
||||||
|
const videos = Array.isArray(data.data?.videos) ? data.data.videos : [];
|
||||||
|
for (const video of videos) {
|
||||||
|
totalViews += Number(video?.view_count ?? 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
const hasMore = Boolean(data.data?.has_more);
|
||||||
|
if (!hasMore) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
const nextCursor = Number(data.data?.cursor ?? cursor + videos.length);
|
||||||
|
if (!Number.isFinite(nextCursor) || nextCursor <= cursor) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
cursor = nextCursor;
|
||||||
|
}
|
||||||
|
|
||||||
|
return totalViews;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Core job ──────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async function runSnapshots() {
|
||||||
|
console.log(`[worker] ${new Date().toISOString()} — début du run`);
|
||||||
|
|
||||||
|
const tokens = await prisma.tikTokToken.findMany({
|
||||||
|
include: { user: { include: { accounts: { where: { platform: "tiktok" } } } } },
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log(`[worker] ${tokens.length} compte(s) TikTok à traiter`);
|
||||||
|
|
||||||
|
for (const token of tokens) {
|
||||||
|
const { userId, openId } = token;
|
||||||
|
let { accessToken, refreshToken: rt, expiresAt } = token;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 1. Refresh si nécessaire
|
||||||
|
if (expiresAt.getTime() - Date.now() < 60_000) {
|
||||||
|
console.log(`[worker] refresh token userId=${userId}`);
|
||||||
|
const refreshed = await refreshTikTokToken(rt);
|
||||||
|
await prisma.tikTokToken.update({
|
||||||
|
where: { userId },
|
||||||
|
data: {
|
||||||
|
accessToken: refreshed.access_token,
|
||||||
|
refreshToken: refreshed.refresh_token,
|
||||||
|
expiresAt: new Date(Date.now() + refreshed.expires_in * 1000),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
accessToken = refreshed.access_token;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Upsert TrackedAccount
|
||||||
|
let account = token.user.accounts[0] ?? null;
|
||||||
|
if (!account) {
|
||||||
|
const stats0 = await fetchTikTokStats(accessToken);
|
||||||
|
account = await prisma.trackedAccount.create({
|
||||||
|
data: { userId, platform: "tiktok", username: stats0.displayName || openId, accountId: openId },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Déduplication — skip si snapshot < 55 min
|
||||||
|
const lastSnapshot = await prisma.snapshot.findFirst({
|
||||||
|
where: { accountId: account.id },
|
||||||
|
orderBy: { createdAt: "desc" },
|
||||||
|
});
|
||||||
|
if (lastSnapshot && Date.now() - lastSnapshot.createdAt.getTime() < DEDUP_WINDOW_MS) {
|
||||||
|
console.log(`[worker] skip userId=${userId} — snapshot trop récent (${Math.round((Date.now() - lastSnapshot.createdAt.getTime()) / 60_000)}min)`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Fetch stats
|
||||||
|
const stats = await fetchTikTokStats(accessToken);
|
||||||
|
|
||||||
|
// 5. Sauvegarde snapshot
|
||||||
|
await prisma.snapshot.create({
|
||||||
|
data: {
|
||||||
|
accountId: account.id,
|
||||||
|
followers: stats.followers,
|
||||||
|
likes: stats.likes,
|
||||||
|
videoCount: stats.videoCount,
|
||||||
|
views: stats.views,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log(`[worker] ✓ userId=${userId} — followers=${stats.followers} likes=${stats.likes} videos=${stats.videoCount} views=${stats.views}`);
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
console.error(`[worker] ✗ erreur userId=${userId}:`, err);
|
||||||
|
// Non bloquant — on continue avec le user suivant
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`[worker] ${new Date().toISOString()} — run terminé`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Loop principale ───────────────────────────────────────────
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
console.log(`[worker] démarrage — intervalle ${INTERVAL_MS / 60_000}min`);
|
||||||
|
|
||||||
|
// Run immédiat au démarrage
|
||||||
|
await runSnapshots().catch(err => console.error("[worker] erreur:", err));
|
||||||
|
|
||||||
|
// Puis toutes les heures
|
||||||
|
setInterval(() => {
|
||||||
|
runSnapshots().catch(err => console.error("[worker] erreur:", err));
|
||||||
|
}, INTERVAL_MS);
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch(err => {
|
||||||
|
console.error("[worker] crash fatal:", err);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
|
|
||||||
Reference in New Issue
Block a user