Initial reader-api backend extracted from reader
This commit is contained in:
@@ -0,0 +1,174 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { getServerSession } from "next-auth/next"
|
||||
import { authOptions } from "@/lib/auth"
|
||||
import { prisma } from "@/lib/prisma"
|
||||
|
||||
type EnrichedItem = {
|
||||
id: string
|
||||
title: string
|
||||
originalTitle: string
|
||||
authorName: string
|
||||
originalAuthorName: string
|
||||
description: string
|
||||
coverUrl?: string
|
||||
status: "Đang ra" | "Hoàn thành" | "Tạm ngưng"
|
||||
genresSuggested: string[]
|
||||
firstPublishYear?: number
|
||||
confidence: number
|
||||
source: string
|
||||
sourceUrl?: string
|
||||
}
|
||||
|
||||
function normalizeText(value: string): string {
|
||||
return value
|
||||
.normalize("NFD")
|
||||
.replace(/[\u0300-\u036f]/g, "")
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9\s]/g, " ")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim()
|
||||
}
|
||||
|
||||
function trimText(value: string, maxLength: number): string {
|
||||
if (value.length <= maxLength) return value
|
||||
return `${value.slice(0, maxLength - 1).trimEnd()}...`
|
||||
}
|
||||
|
||||
function buildBatchPrompt(novels: any[]) {
|
||||
const itemsText = novels.map(n => {
|
||||
const shortDesc = trimText(n.description || "", 1500)
|
||||
return `[ID: ${n.id}]\nTên: ${n.title}\nTên gốc: ${n.originalTitle || ""}\nTác giả: ${n.authorName}\nTác giả gốc: ${n.originalAuthorName || ""}\nThể loại: ${(n.genres || []).map((g: any) => g.genre.name).join(", ")}\nMô tả: ${shortDesc}`
|
||||
}).join("\n\n---\n\n")
|
||||
|
||||
return [
|
||||
"Bạn là biên tập viên truyện dịch tiếng Trung.",
|
||||
"Nhiệm vụ: bổ sung thông tin bị thiếu (Tên gốc, Tác giả gốc, Mô tả, Thể loại) cho danh sách tác phẩm sau bằng cách tìm kiếm trên Qidian, JJWXC, v.v...",
|
||||
"Trường 'description': Nếu mô tả gốc đã chi tiết, chỉ cần sửa chính tả. Nếu trống/ngắn, hãy viết mới 1 đoạn giới thiệu dài chi tiết bám sát nội dung gốc (KHÔNG tóm tắt kiểu chung chung).",
|
||||
"Trạng thái (status) phải luôn là: Đang ra, Hoàn thành, hoặc Tạm ngưng.",
|
||||
"Kết quả BẮT BUỘC là 1 JSON Object chứa mảng 'results'. Mỗi item trong mảng phải có key 'id' khớp với báo cáo.",
|
||||
`Schema: {"results":[{"id":"","title":"","originalTitle":"","authorName":"","originalAuthorName":"","description":"","coverUrl":"","status":"Đang ra|Hoàn thành|Tạm ngưng","genresSuggested":[],"firstPublishYear":2020,"confidence":80,"source":"","sourceUrl":""}]}`,
|
||||
"Dưới đây là danh sách truyện cần xử lý:\n",
|
||||
itemsText
|
||||
].join("\n")
|
||||
}
|
||||
|
||||
function extractJsonCandidate(text: string): string {
|
||||
const trimmed = text.trim()
|
||||
if (!trimmed) return ""
|
||||
const fenced = trimmed.match(/```(?:json)?\s*([\s\S]*?)```/i)
|
||||
if (fenced?.[1]) return fenced[1].trim()
|
||||
const firstBrace = trimmed.indexOf("{")
|
||||
const lastBrace = trimmed.lastIndexOf("}")
|
||||
if (firstBrace >= 0 && lastBrace > firstBrace) {
|
||||
return trimmed.slice(firstBrace, lastBrace + 1)
|
||||
}
|
||||
return trimmed
|
||||
}
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const session = await getServerSession(authOptions)
|
||||
if (!session || (session.user.role !== "MOD" && session.user.role !== "ADMIN")) {
|
||||
return NextResponse.json({ error: "Không có quyền truy cập" }, { status: 401 })
|
||||
}
|
||||
|
||||
const { novelIds } = await req.json()
|
||||
if (!Array.isArray(novelIds) || novelIds.length === 0 || novelIds.length > 20) {
|
||||
return NextResponse.json({ error: "novelIds không hợp lệ hoặc quá lớn (tối đa 20)" }, { status: 400 })
|
||||
}
|
||||
|
||||
const accessWhere = session.user.role === "ADMIN"
|
||||
? { id: { in: novelIds } }
|
||||
: {
|
||||
id: { in: novelIds },
|
||||
OR: [
|
||||
{ uploaderId: session.user.id },
|
||||
{ uploaderId: null },
|
||||
],
|
||||
}
|
||||
|
||||
const novels = await prisma.novel.findMany({
|
||||
where: accessWhere,
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
originalTitle: true,
|
||||
authorName: true,
|
||||
originalAuthorName: true,
|
||||
description: true,
|
||||
coverUrl: true,
|
||||
status: true,
|
||||
genres: { select: { genre: { select: { name: true } } } },
|
||||
}
|
||||
})
|
||||
|
||||
if (novels.length === 0) {
|
||||
return NextResponse.json({ error: "Không tìm thấy truyện nào hợp lệ" }, { status: 404 })
|
||||
}
|
||||
|
||||
const apiKey = process.env.DEEKSEEK_KEY?.trim() || process.env.DEEPSEEK_KEY?.trim()
|
||||
const model = process.env.DEEPSEEK_MODEL?.trim() || "deepseek-chat"
|
||||
|
||||
if (!apiKey) {
|
||||
return NextResponse.json({ error: "Thiếu DEEPSEEK_KEY" }, { status: 400 })
|
||||
}
|
||||
|
||||
const prompt = buildBatchPrompt(novels)
|
||||
|
||||
const controller = new AbortController()
|
||||
const timeout = setTimeout(() => controller.abort(), 90000) // 90 seconds for batch
|
||||
const startedAt = Date.now()
|
||||
|
||||
try {
|
||||
const res = await fetch("https://api.deepseek.com/v1/chat/completions", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model,
|
||||
temperature: 0.2,
|
||||
max_tokens: 2500,
|
||||
response_format: { type: "json_object" },
|
||||
messages: [
|
||||
{ role: "system", content: "You are a helpful assistant. You must output only valid standard JSON object following the prompt schema, without markdown formatting." },
|
||||
{ role: "user", content: prompt },
|
||||
],
|
||||
}),
|
||||
signal: controller.signal,
|
||||
})
|
||||
|
||||
clearTimeout(timeout)
|
||||
|
||||
if (!res.ok) {
|
||||
const errorText = await res.text().catch(() => "")
|
||||
throw new Error(`HTTP ${res.status}: ${errorText.slice(0, 200)}`)
|
||||
}
|
||||
|
||||
const data = await res.json()
|
||||
const text = data.choices?.[0]?.message?.content?.trim() || ""
|
||||
const jsonText = extractJsonCandidate(text)
|
||||
|
||||
let parsed: any = null
|
||||
try {
|
||||
parsed = JSON.parse(jsonText)
|
||||
} catch {
|
||||
throw new Error("Phản hồi JSON bị hỏng")
|
||||
}
|
||||
|
||||
const results = Array.isArray(parsed?.results) ? parsed.results : []
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
latencyMs: Date.now() - startedAt,
|
||||
model,
|
||||
count: results.length,
|
||||
results,
|
||||
sourceNovels: novels,
|
||||
})
|
||||
|
||||
} catch (error: any) {
|
||||
clearTimeout(timeout)
|
||||
return NextResponse.json({ error: `DeepSeek Error: ${error.message}` }, { status: 500 })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,689 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { getServerSession } from "next-auth/next"
|
||||
import { authOptions } from "@/lib/auth"
|
||||
import { prisma } from "@/lib/prisma"
|
||||
|
||||
type EnrichedItem = {
|
||||
title: string
|
||||
originalTitle: string
|
||||
authorName: string
|
||||
originalAuthorName: string
|
||||
description: string
|
||||
coverUrl?: string
|
||||
status: "Đang ra" | "Hoàn thành" | "Tạm ngưng"
|
||||
genresSuggested: string[]
|
||||
firstPublishYear?: number
|
||||
confidence: number
|
||||
source: string
|
||||
sourceUrl?: string
|
||||
}
|
||||
|
||||
type AttemptStatus = {
|
||||
provider: "google" | "openrouter" | "deepseek"
|
||||
model: string
|
||||
status: "success" | "failed" | "skipped"
|
||||
message?: string
|
||||
latencyMs?: number
|
||||
}
|
||||
|
||||
type ProviderResult = {
|
||||
provider: "google" | "openrouter" | "deepseek"
|
||||
model: string
|
||||
results: EnrichedItem[]
|
||||
}
|
||||
|
||||
type GeminiResponse = {
|
||||
candidates?: Array<{
|
||||
content?: {
|
||||
parts?: Array<{ text?: string }>
|
||||
}
|
||||
}>
|
||||
}
|
||||
|
||||
type ChatResponse = {
|
||||
choices?: Array<{
|
||||
message?: {
|
||||
content?: string
|
||||
}
|
||||
}>
|
||||
}
|
||||
|
||||
type OpenRouterModelsResponse = {
|
||||
data?: Array<{
|
||||
id?: string
|
||||
}>
|
||||
}
|
||||
|
||||
const OPENROUTER_PAUSED = (process.env.OPENROUTER_PAUSED ?? "true").toLowerCase() !== "false"
|
||||
|
||||
function hasMeaningfulDescription(value: string): boolean {
|
||||
const normalized = normalizeText(value)
|
||||
if (!normalized || normalized.length < 40) return false
|
||||
|
||||
const placeholders = [
|
||||
"chua co gioi thieu",
|
||||
"khong co gioi thieu",
|
||||
"dang cap nhat",
|
||||
"dang update",
|
||||
"updating",
|
||||
"no description",
|
||||
"khong ro",
|
||||
"chua ro",
|
||||
]
|
||||
|
||||
return !placeholders.some((item) => normalized.includes(item))
|
||||
}
|
||||
|
||||
function buildGeneratedDescription(
|
||||
title: string,
|
||||
authorName: string,
|
||||
genres: string[],
|
||||
status: "Đang ra" | "Hoàn thành" | "Tạm ngưng"
|
||||
): string {
|
||||
const genreText = genres.length > 0 ? genres.slice(0, 3).join(", ") : "tiểu thuyết mạng"
|
||||
const statusText = status === "Đang ra" ? "đang ra" : status === "Hoàn thành" ? "đã hoàn thành" : "tạm ngưng"
|
||||
|
||||
return trimText(
|
||||
`${title} là một tác phẩm ${genreText} của ${authorName}. Câu chuyện được hệ thống tóm lược lại từ những thông tin đã tìm thấy trên web và hiện ở trạng thái ${statusText}. Đây là đoạn mô tả thay thế được tạo tự động khi mô hình chưa trả về phần giới thiệu đủ chi tiết, giúp biên tập viên có sẵn nội dung để rà soát và chỉnh sửa tiếp.`,
|
||||
1200
|
||||
)
|
||||
}
|
||||
|
||||
function normalizeText(value: string): string {
|
||||
return value
|
||||
.normalize("NFD")
|
||||
.replace(/[\u0300-\u036f]/g, "")
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9\s]/g, " ")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim()
|
||||
}
|
||||
|
||||
function trimText(value: string, maxLength: number): string {
|
||||
if (value.length <= maxLength) return value
|
||||
return `${value.slice(0, maxLength - 1).trimEnd()}...`
|
||||
}
|
||||
|
||||
function inferStatus(subjects: string[], description: string): "Đang ra" | "Hoàn thành" | "Tạm ngưng" {
|
||||
const haystack = normalizeText(`${subjects.join(" ")} ${description}`)
|
||||
|
||||
if (haystack.includes("completed") || haystack.includes("finished") || haystack.includes("full text")) {
|
||||
return "Hoàn thành"
|
||||
}
|
||||
|
||||
if (haystack.includes("hiatus") || haystack.includes("on hold") || haystack.includes("paused")) {
|
||||
return "Tạm ngưng"
|
||||
}
|
||||
|
||||
return "Đang ra"
|
||||
}
|
||||
|
||||
function clampNumber(value: unknown, min: number, max: number, fallback: number): number {
|
||||
const num = typeof value === "number" ? value : Number(value)
|
||||
if (!Number.isFinite(num)) return fallback
|
||||
return Math.max(min, Math.min(max, num))
|
||||
}
|
||||
|
||||
function toOptionalUrl(value: unknown): string | undefined {
|
||||
if (typeof value !== "string") return undefined
|
||||
const trimmed = value.trim()
|
||||
if (!trimmed) return undefined
|
||||
if (!/^https?:\/\//i.test(trimmed)) return undefined
|
||||
return trimmed
|
||||
}
|
||||
|
||||
function coerceStatus(value: unknown, genres: string[], description: string): "Đang ra" | "Hoàn thành" | "Tạm ngưng" {
|
||||
if (typeof value === "string") {
|
||||
const normalized = normalizeText(value)
|
||||
if (normalized.includes("hoan thanh") || normalized.includes("completed") || normalized.includes("finished")) {
|
||||
return "Hoàn thành"
|
||||
}
|
||||
if (normalized.includes("tam") || normalized.includes("ngung") || normalized.includes("hiatus") || normalized.includes("paused")) {
|
||||
return "Tạm ngưng"
|
||||
}
|
||||
if (normalized.includes("dang") || normalized.includes("ongoing")) {
|
||||
return "Đang ra"
|
||||
}
|
||||
}
|
||||
|
||||
return inferStatus(genres, description)
|
||||
}
|
||||
|
||||
function extractJsonCandidate(text: string): string {
|
||||
const trimmed = text.trim()
|
||||
if (!trimmed) return ""
|
||||
|
||||
const fenced = trimmed.match(/```(?:json)?\s*([\s\S]*?)```/i)
|
||||
if (fenced?.[1]) return fenced[1].trim()
|
||||
|
||||
const firstBrace = trimmed.indexOf("{")
|
||||
const lastBrace = trimmed.lastIndexOf("}")
|
||||
if (firstBrace >= 0 && lastBrace > firstBrace) {
|
||||
return trimmed.slice(firstBrace, lastBrace + 1)
|
||||
}
|
||||
|
||||
return trimmed
|
||||
}
|
||||
|
||||
function toItem(raw: any, novelTitle: string): EnrichedItem | null {
|
||||
const title = typeof raw?.title === "string" ? raw.title.trim() : ""
|
||||
if (!title) return null
|
||||
|
||||
const originalTitle = typeof raw?.originalTitle === "string" && raw.originalTitle.trim()
|
||||
? raw.originalTitle.trim()
|
||||
: title
|
||||
|
||||
const authorName = typeof raw?.authorName === "string" && raw.authorName.trim()
|
||||
? raw.authorName.trim()
|
||||
: "Chưa rõ"
|
||||
|
||||
const originalAuthorName = typeof raw?.originalAuthorName === "string" && raw.originalAuthorName.trim()
|
||||
? raw.originalAuthorName.trim()
|
||||
: authorName
|
||||
|
||||
const genres = Array.isArray(raw?.genresSuggested)
|
||||
? raw.genresSuggested
|
||||
.map((g: unknown) => (typeof g === "string" ? g.trim() : ""))
|
||||
.filter(Boolean)
|
||||
.slice(0, 10)
|
||||
: []
|
||||
|
||||
const status = coerceStatus(raw?.status, genres, typeof raw?.description === "string" ? raw.description.trim() : "")
|
||||
|
||||
const descriptionInput = typeof raw?.description === "string" ? raw.description.trim() : ""
|
||||
const description = trimText(
|
||||
hasMeaningfulDescription(descriptionInput)
|
||||
? descriptionInput
|
||||
: buildGeneratedDescription(title || novelTitle, authorName, genres, status),
|
||||
1200
|
||||
)
|
||||
|
||||
const year = Number(raw?.firstPublishYear)
|
||||
const firstPublishYear = Number.isFinite(year) && year >= 1000 && year <= 2100 ? year : undefined
|
||||
|
||||
return {
|
||||
title,
|
||||
originalTitle,
|
||||
authorName,
|
||||
originalAuthorName,
|
||||
description,
|
||||
coverUrl: toOptionalUrl(raw?.coverUrl),
|
||||
status,
|
||||
genresSuggested: genres,
|
||||
firstPublishYear,
|
||||
confidence: clampNumber(raw?.confidence, 1, 99, 65),
|
||||
source: typeof raw?.source === "string" && raw.source.trim() ? raw.source.trim() : "LLM Web Search",
|
||||
sourceUrl: toOptionalUrl(raw?.sourceUrl),
|
||||
}
|
||||
}
|
||||
|
||||
function parseResultsFromText(text: string, novelTitle: string): EnrichedItem[] {
|
||||
const jsonText = extractJsonCandidate(text)
|
||||
if (!jsonText) return []
|
||||
|
||||
let parsed: any = null
|
||||
try {
|
||||
parsed = JSON.parse(jsonText)
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
|
||||
const rows = Array.isArray(parsed?.results) ? parsed.results : []
|
||||
return rows
|
||||
.map((row: any) => toItem(row, novelTitle))
|
||||
.filter((row: EnrichedItem | null): row is EnrichedItem => Boolean(row))
|
||||
.slice(0, 6)
|
||||
}
|
||||
|
||||
function buildFallbackResult(novelTitle: string): EnrichedItem {
|
||||
return {
|
||||
title: novelTitle,
|
||||
originalTitle: novelTitle,
|
||||
authorName: "Chưa rõ",
|
||||
originalAuthorName: "Chưa rõ",
|
||||
description: buildGeneratedDescription(novelTitle, "Chưa rõ", [], "Đang ra"),
|
||||
coverUrl: undefined,
|
||||
status: "Đang ra",
|
||||
genresSuggested: [],
|
||||
firstPublishYear: undefined,
|
||||
confidence: 30,
|
||||
source: "Fallback",
|
||||
sourceUrl: undefined,
|
||||
}
|
||||
}
|
||||
|
||||
function buildPrompt(novel: {
|
||||
title: string
|
||||
originalTitle?: string | null
|
||||
authorName: string
|
||||
originalAuthorName?: string | null
|
||||
description: string
|
||||
genres: string[]
|
||||
}) {
|
||||
const shortDescription = trimText(novel.description || "", 1500)
|
||||
|
||||
return [
|
||||
"Bạn là trợ lý biên tập truyện dịch từ truyện mạng Trung Quốc.",
|
||||
"Hãy tìm thông tin trên web, ưu tiên các nguồn như Qidian, JJWXC, NovelUpdates, wiki fan và nhà xuất bản.",
|
||||
"Trả về JSON thuần, không markdown, không giải thích thêm.",
|
||||
"Bắt buộc viết các trường title, authorName, description, genresSuggested bằng tiếng Việt có dấu nếu đó là tên hoặc khái niệm đã có bản Việt hóa phổ biến.",
|
||||
"Riêng originalTitle và originalAuthorName hãy giữ theo nguyên tác nếu tìm được.",
|
||||
"Trường description là bắt buộc. Nếu 'Mô tả hiện tại' (dưới đây) đã dài và chi tiết, hãy giữ nguyên ý chính gốc và chỉ chỉnh sửa văn phong, bố cục cho mượt mà hoặc hấp dẫn hơn. TUYỆT ĐỐI KHÔNG tóm tắt ngắn đi nếu bản gốc đang đầy đủ.",
|
||||
"Nếu 'Mô tả hiện tại' chống không hoặc quá sơ sài, hãy tìm kiếm nội dung về cốt truyện gốc trên mạng và viết một bài giới thiệu dài, chi tiết, bám sát các sự kiện thực tế trong truyện. KHÔNG viết chung chung kiểu 'đầy chông gai và thử thách'.",
|
||||
"Trạng thái (status) phải luôn là 1 trong 3 giá trị: Đang ra, Hoàn thành, Tạm ngưng. Mảng genresSuggested chứa tối đa 10 thể loại phù hợp.",
|
||||
`Schema: {"results":[{"title":"","originalTitle":"","authorName":"","originalAuthorName":"","description":"","coverUrl":"","status":"Đang ra|Hoàn thành|Tạm ngưng","genresSuggested":[],"firstPublishYear":2020,"confidence":80,"source":"","sourceUrl":""}]}`,
|
||||
"Tối đa 3 kết quả, ưu tiên kết quả gần nhất với truyện hiện tại.",
|
||||
`Tên hiện tại: ${novel.title}`,
|
||||
`Tên gốc hiện tại: ${novel.originalTitle || ""}`,
|
||||
`Tác giả hiện tại: ${novel.authorName}`,
|
||||
`Tác giả gốc hiện tại: ${novel.originalAuthorName || ""}`,
|
||||
`Thể loại hiện tại: ${novel.genres.join(", ")}`,
|
||||
`Mô tả hiện tại: ${shortDescription}`,
|
||||
].join(" ")
|
||||
}
|
||||
|
||||
async function fetchJsonWithTimeout<T>(url: string, init: RequestInit, timeoutMs = 25000): Promise<T> {
|
||||
const controller = new AbortController()
|
||||
const timeout = setTimeout(() => controller.abort(), timeoutMs)
|
||||
|
||||
try {
|
||||
const res = await fetch(url, { ...init, signal: controller.signal, cache: "no-store" })
|
||||
if (!res.ok) {
|
||||
const text = await res.text().catch(() => "")
|
||||
throw new Error(`HTTP ${res.status}: ${text.slice(0, 220)}`)
|
||||
}
|
||||
return (await res.json()) as T
|
||||
} finally {
|
||||
clearTimeout(timeout)
|
||||
}
|
||||
}
|
||||
|
||||
function summarizeError(error: unknown): string {
|
||||
if (!(error instanceof Error)) return "Lỗi không xác định"
|
||||
return error.message.slice(0, 220)
|
||||
}
|
||||
|
||||
async function tryGoogle(prompt: string, novelTitle: string, attempts: AttemptStatus[]): Promise<ProviderResult | null> {
|
||||
const apiKey = process.env.GOOGLE_AI_KEY?.trim()
|
||||
const model = process.env.GOOGLE_AI_MODEL?.trim() || "gemini-2.0-flash"
|
||||
|
||||
if (!apiKey) {
|
||||
attempts.push({ provider: "google", model, status: "skipped", message: "Thiếu GOOGLE_AI_KEY" })
|
||||
return null
|
||||
}
|
||||
|
||||
const startedAt = Date.now()
|
||||
try {
|
||||
const data = await fetchJsonWithTimeout<GeminiResponse>(
|
||||
`https://generativelanguage.googleapis.com/v1beta/models/${encodeURIComponent(model)}:generateContent?key=${encodeURIComponent(apiKey)}`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
contents: [{ role: "user", parts: [{ text: prompt }] }],
|
||||
tools: [{ googleSearch: {} }],
|
||||
generationConfig: {
|
||||
temperature: 0.2,
|
||||
maxOutputTokens: 1400,
|
||||
},
|
||||
}),
|
||||
},
|
||||
22000
|
||||
)
|
||||
|
||||
const text = (data.candidates || [])
|
||||
.flatMap((candidate) => candidate.content?.parts || [])
|
||||
.map((part) => part.text || "")
|
||||
.join("\n")
|
||||
.trim()
|
||||
|
||||
const results = parseResultsFromText(text, novelTitle)
|
||||
if (results.length === 0) {
|
||||
console.log("Google parsing failed. Raw text:", text)
|
||||
throw new Error("Không có kết quả JSON hợp lệ")
|
||||
}
|
||||
|
||||
attempts.push({
|
||||
provider: "google",
|
||||
model,
|
||||
status: "success",
|
||||
message: `${results.length} kết quả`,
|
||||
latencyMs: Date.now() - startedAt,
|
||||
})
|
||||
|
||||
return { provider: "google", model, results }
|
||||
} catch (error) {
|
||||
console.log("Google fetch error:", error)
|
||||
attempts.push({
|
||||
provider: "google",
|
||||
model,
|
||||
status: "failed",
|
||||
message: summarizeError(error),
|
||||
latencyMs: Date.now() - startedAt,
|
||||
})
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveOpenRouterFreeModels(apiKey: string): Promise<string[]> {
|
||||
const envModels = (process.env.OPENROUTER_FREE_MODELS || "")
|
||||
.split(",")
|
||||
.map((s) => s.trim())
|
||||
.filter((s) => s.endsWith(":free"))
|
||||
|
||||
const dynamicModels: string[] = []
|
||||
|
||||
try {
|
||||
const data = await fetchJsonWithTimeout<OpenRouterModelsResponse>(
|
||||
"https://openrouter.ai/api/v1/models",
|
||||
{
|
||||
method: "GET",
|
||||
headers: {
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
},
|
||||
},
|
||||
12000
|
||||
)
|
||||
|
||||
for (const row of data.data || []) {
|
||||
const id = (row.id || "").trim()
|
||||
if (!id || !id.endsWith(":free")) continue
|
||||
dynamicModels.push(id)
|
||||
}
|
||||
} catch {
|
||||
// Ignore model-list errors and keep env list fallback.
|
||||
}
|
||||
|
||||
const merged = Array.from(new Set([...envModels, ...dynamicModels]))
|
||||
|
||||
const preferredOrder = [
|
||||
"google/gemma-2-9b-it:free",
|
||||
"meta-llama/llama-3.1-8b-instruct:free",
|
||||
"qwen/qwen2.5-7b-instruct:free",
|
||||
]
|
||||
|
||||
merged.sort((a, b) => {
|
||||
const ai = preferredOrder.findIndex((item) => item === a)
|
||||
const bi = preferredOrder.findIndex((item) => item === b)
|
||||
const ar = ai === -1 ? 999 : ai
|
||||
const br = bi === -1 ? 999 : bi
|
||||
if (ar !== br) return ar - br
|
||||
return a.localeCompare(b)
|
||||
})
|
||||
|
||||
return merged.slice(0, 10)
|
||||
}
|
||||
|
||||
async function tryOpenRouter(prompt: string, novelTitle: string, attempts: AttemptStatus[]): Promise<ProviderResult | null> {
|
||||
const apiKey = process.env.OPENROUTER_KEY?.trim()
|
||||
if (!apiKey) {
|
||||
attempts.push({ provider: "openrouter", model: "free-chain", status: "skipped", message: "Thiếu OPENROUTER_KEY" })
|
||||
return null
|
||||
}
|
||||
|
||||
const freeModels = await resolveOpenRouterFreeModels(apiKey)
|
||||
if (freeModels.length === 0) {
|
||||
attempts.push({ provider: "openrouter", model: "free-chain", status: "skipped", message: "Không có model free khả dụng" })
|
||||
return null
|
||||
}
|
||||
|
||||
for (const model of freeModels) {
|
||||
const startedAt = Date.now()
|
||||
try {
|
||||
const data = await fetchJsonWithTimeout<ChatResponse>(
|
||||
"https://openrouter.ai/api/v1/chat/completions",
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
"HTTP-Referer": "http://localhost:3000",
|
||||
"X-Title": "reader-mod-ai-tool",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model,
|
||||
temperature: 0.2,
|
||||
max_tokens: 1400,
|
||||
messages: [
|
||||
{ role: "system", content: "Return only valid JSON." },
|
||||
{ role: "user", content: prompt },
|
||||
],
|
||||
}),
|
||||
},
|
||||
22000
|
||||
)
|
||||
|
||||
const text = data.choices?.[0]?.message?.content?.trim() || ""
|
||||
const results = parseResultsFromText(text, novelTitle)
|
||||
if (results.length === 0) {
|
||||
console.log("OpenRouter parsing failed. Raw text:", text)
|
||||
throw new Error("Không có kết quả JSON hợp lệ")
|
||||
}
|
||||
|
||||
attempts.push({
|
||||
provider: "openrouter",
|
||||
model,
|
||||
status: "success",
|
||||
message: `${results.length} kết quả`,
|
||||
latencyMs: Date.now() - startedAt,
|
||||
})
|
||||
|
||||
return { provider: "openrouter", model, results }
|
||||
} catch (error) {
|
||||
console.log("OpenRouter fetch error:", error)
|
||||
attempts.push({
|
||||
provider: "openrouter",
|
||||
model,
|
||||
status: "failed",
|
||||
message: summarizeError(error),
|
||||
latencyMs: Date.now() - startedAt,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
async function tryDeepSeek(prompt: string, novelTitle: string, attempts: AttemptStatus[]): Promise<ProviderResult | null> {
|
||||
const apiKey = process.env.DEEKSEEK_KEY?.trim() || process.env.DEEPSEEK_KEY?.trim()
|
||||
const model = process.env.DEEPSEEK_MODEL?.trim() || "deepseek-chat"
|
||||
|
||||
if (!apiKey) {
|
||||
attempts.push({ provider: "deepseek", model, status: "skipped", message: "Thiếu DEEKSEEK_KEY/DEEPSEEK_KEY" })
|
||||
return null
|
||||
}
|
||||
|
||||
const profiles = [
|
||||
{ maxTokens: 1300, timeoutMs: 60000 },
|
||||
{ maxTokens: 900, timeoutMs: 45000 },
|
||||
]
|
||||
|
||||
for (const profile of profiles) {
|
||||
const startedAt = Date.now()
|
||||
try {
|
||||
const data = await fetchJsonWithTimeout<ChatResponse>(
|
||||
"https://api.deepseek.com/v1/chat/completions",
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model,
|
||||
temperature: 0.2,
|
||||
max_tokens: profile.maxTokens,
|
||||
response_format: { type: "json_object" },
|
||||
messages: [
|
||||
{ role: "system", content: "You are a helpful assistant. You must output only valid standard JSON object following the prompt schema, without markdown formatting." },
|
||||
{ role: "user", content: prompt },
|
||||
],
|
||||
}),
|
||||
},
|
||||
profile.timeoutMs
|
||||
)
|
||||
|
||||
const text = data.choices?.[0]?.message?.content?.trim() || ""
|
||||
const results = parseResultsFromText(text, novelTitle)
|
||||
if (results.length === 0) {
|
||||
console.log("DeepSeek parsing failed. Raw text:", text)
|
||||
throw new Error("Không có kết quả JSON hợp lệ")
|
||||
}
|
||||
|
||||
attempts.push({
|
||||
provider: "deepseek",
|
||||
model,
|
||||
status: "success",
|
||||
message: `${results.length} kết quả`,
|
||||
latencyMs: Date.now() - startedAt,
|
||||
})
|
||||
|
||||
return { provider: "deepseek", model, results }
|
||||
} catch (error) {
|
||||
console.log("DeepSeek fetch error:", error)
|
||||
attempts.push({
|
||||
provider: "deepseek",
|
||||
model,
|
||||
status: "failed",
|
||||
message: summarizeError(error),
|
||||
latencyMs: Date.now() - startedAt,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export async function GET(req: Request) {
|
||||
const session = await getServerSession(authOptions)
|
||||
if (!session || (session.user.role !== "MOD" && session.user.role !== "ADMIN")) {
|
||||
return NextResponse.json({ error: "Không có quyền truy cập" }, { status: 401 })
|
||||
}
|
||||
|
||||
const { searchParams } = new URL(req.url)
|
||||
const novelId = searchParams.get("novelId")?.trim() || ""
|
||||
|
||||
if (!novelId) {
|
||||
return NextResponse.json({ error: "Thiếu novelId" }, { status: 400 })
|
||||
}
|
||||
|
||||
const accessWhere = session.user.role === "ADMIN"
|
||||
? { id: novelId }
|
||||
: {
|
||||
id: novelId,
|
||||
OR: [
|
||||
{ uploaderId: session.user.id },
|
||||
{ uploaderId: null },
|
||||
],
|
||||
}
|
||||
|
||||
const novel = await prisma.novel.findFirst({
|
||||
where: accessWhere,
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
originalTitle: true,
|
||||
slug: true,
|
||||
authorName: true,
|
||||
originalAuthorName: true,
|
||||
description: true,
|
||||
coverUrl: true,
|
||||
status: true,
|
||||
updatedAt: true,
|
||||
genres: {
|
||||
select: {
|
||||
genre: {
|
||||
select: {
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if (!novel) {
|
||||
return NextResponse.json({ error: "Không tìm thấy truyện hoặc bạn không có quyền truy cập" }, { status: 404 })
|
||||
}
|
||||
|
||||
const attempts: AttemptStatus[] = []
|
||||
const currentNovel = {
|
||||
id: novel.id,
|
||||
title: novel.title,
|
||||
originalTitle: novel.originalTitle,
|
||||
slug: novel.slug,
|
||||
authorName: novel.authorName,
|
||||
originalAuthorName: novel.originalAuthorName,
|
||||
description: novel.description,
|
||||
coverUrl: novel.coverUrl,
|
||||
status: novel.status,
|
||||
updatedAt: novel.updatedAt,
|
||||
genres: (novel.genres || []).map((row) => row.genre.name),
|
||||
}
|
||||
|
||||
const prompt = buildPrompt(currentNovel)
|
||||
|
||||
// Tạm thời bỏ qua Google Gemini theo yêu cầu của user
|
||||
attempts.push({
|
||||
provider: "google",
|
||||
model: "gemini-2.0-flash",
|
||||
status: "skipped",
|
||||
message: "Tạm bỏ qua theo yêu cầu người dùng.",
|
||||
})
|
||||
/*
|
||||
const google = await tryGoogle(prompt, currentNovel.title, attempts)
|
||||
if (google) {
|
||||
return NextResponse.json({
|
||||
novel: currentNovel,
|
||||
provider: google.provider,
|
||||
model: google.model,
|
||||
attempts,
|
||||
count: google.results.length,
|
||||
results: google.results,
|
||||
})
|
||||
}
|
||||
*/
|
||||
|
||||
const deepseek = await tryDeepSeek(prompt, currentNovel.title, attempts)
|
||||
if (deepseek) {
|
||||
return NextResponse.json({
|
||||
novel: currentNovel,
|
||||
provider: deepseek.provider,
|
||||
model: deepseek.model,
|
||||
attempts,
|
||||
count: deepseek.results.length,
|
||||
results: deepseek.results,
|
||||
})
|
||||
}
|
||||
|
||||
if (OPENROUTER_PAUSED) {
|
||||
attempts.push({
|
||||
provider: "openrouter",
|
||||
model: "free-chain",
|
||||
status: "skipped",
|
||||
message: "Tạm dừng OpenRouter theo cấu hình",
|
||||
})
|
||||
} else {
|
||||
const openrouter = await tryOpenRouter(prompt, currentNovel.title, attempts)
|
||||
if (openrouter) {
|
||||
return NextResponse.json({
|
||||
novel: currentNovel,
|
||||
provider: openrouter.provider,
|
||||
model: openrouter.model,
|
||||
attempts,
|
||||
count: openrouter.results.length,
|
||||
results: openrouter.results,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
novel: currentNovel,
|
||||
provider: "fallback",
|
||||
model: "none",
|
||||
attempts,
|
||||
count: 1,
|
||||
results: [buildFallbackResult(currentNovel.title)],
|
||||
warning: "Google AI và DeepSeek đều thất bại",
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { getServerSession } from "next-auth/next"
|
||||
import { authOptions } from "@/lib/auth"
|
||||
import { prisma } from "@/lib/prisma"
|
||||
|
||||
export async function GET(req: Request) {
|
||||
const session = await getServerSession(authOptions)
|
||||
if (!session || (session.user.role !== "MOD" && session.user.role !== "ADMIN")) {
|
||||
return NextResponse.json({ error: "Không có quyền truy cập" }, { status: 401 })
|
||||
}
|
||||
|
||||
const { searchParams } = new URL(req.url)
|
||||
const q = (searchParams.get("q") || "").trim()
|
||||
const page = parseInt(searchParams.get("page") || "1", 10)
|
||||
const take = 24
|
||||
const skip = (Math.max(1, page) - 1) * take
|
||||
|
||||
const whereScope = session.user.role === "ADMIN"
|
||||
? {}
|
||||
: {
|
||||
OR: [
|
||||
{ uploaderId: session.user.id },
|
||||
{ uploaderId: null },
|
||||
],
|
||||
}
|
||||
|
||||
const isMissingFilter = searchParams.get("missing") === "true"
|
||||
const baseWhereOptions: any[] = [whereScope]
|
||||
|
||||
if (q.length > 0) {
|
||||
baseWhereOptions.push({
|
||||
OR: [
|
||||
{ title: { contains: q, mode: "insensitive" } },
|
||||
{ originalTitle: { contains: q, mode: "insensitive" } },
|
||||
{ authorName: { contains: q, mode: "insensitive" } },
|
||||
{ originalAuthorName: { contains: q, mode: "insensitive" } },
|
||||
{ slug: { contains: q, mode: "insensitive" } },
|
||||
],
|
||||
})
|
||||
} else if (!isMissingFilter) {
|
||||
return NextResponse.json({ novels: [], hasMore: false })
|
||||
}
|
||||
|
||||
if (isMissingFilter) {
|
||||
baseWhereOptions.push({
|
||||
OR: [
|
||||
{ authorName: { in: ["", "Chưa rõ"] } },
|
||||
{ description: "" },
|
||||
{ description: { in: ["Chưa có giới thiệu", "Không có giới thiệu", "chưa có giới thiệu", "không có", "chưa rõ", "đang cập nhật"] } }
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
const rows = await prisma.novel.findMany({
|
||||
where: {
|
||||
AND: baseWhereOptions,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
originalTitle: true,
|
||||
slug: true,
|
||||
authorName: true,
|
||||
originalAuthorName: true,
|
||||
description: true,
|
||||
coverUrl: true,
|
||||
status: true,
|
||||
updatedAt: true,
|
||||
},
|
||||
orderBy: [{ updatedAt: "desc" }],
|
||||
take: take + 1, // Fetch one extra to know if there's a next page
|
||||
skip,
|
||||
})
|
||||
|
||||
const hasMore = rows.length > take
|
||||
const returnRows = hasMore ? rows.slice(0, take) : rows
|
||||
|
||||
return NextResponse.json({ novels: returnRows, hasMore })
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { getServerSession } from "next-auth/next"
|
||||
import { authOptions } from "@/lib/auth"
|
||||
|
||||
export async function GET() {
|
||||
const session = await getServerSession(authOptions)
|
||||
if (!session || (session.user.role !== "MOD" && session.user.role !== "ADMIN")) {
|
||||
return NextResponse.json({ error: "Không có quyền truy cập" }, { status: 401 })
|
||||
}
|
||||
|
||||
const apiKey = process.env.DEEKSEEK_KEY?.trim() || process.env.DEEPSEEK_KEY?.trim()
|
||||
const model = process.env.DEEPSEEK_MODEL?.trim() || "deepseek-chat"
|
||||
|
||||
if (!apiKey) {
|
||||
return NextResponse.json({ error: "Chưa cấu hình API Key cho DeepSeek (DEEKSEEK_KEY / DEEPSEEK_KEY)" }, { status: 400 })
|
||||
}
|
||||
|
||||
const startedAt = Date.now()
|
||||
try {
|
||||
const controller = new AbortController()
|
||||
const timeout = setTimeout(() => controller.abort(), 15000)
|
||||
|
||||
const res = await fetch("https://api.deepseek.com/v1/chat/completions", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model,
|
||||
temperature: 0.1,
|
||||
max_tokens: 10,
|
||||
messages: [{ role: "user", content: "Ping! Please reply with 'pong'." }],
|
||||
}),
|
||||
signal: controller.signal,
|
||||
})
|
||||
|
||||
clearTimeout(timeout)
|
||||
|
||||
if (!res.ok) {
|
||||
const text = await res.text().catch(() => "")
|
||||
throw new Error(`HTTP ${res.status}: ${text.slice(0, 100)}`)
|
||||
}
|
||||
|
||||
const data = await res.json()
|
||||
const text = data.choices?.[0]?.message?.content?.trim() || ""
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: `DeepSeek phản hồi thành công: "${text}"`,
|
||||
latencyMs: Date.now() - startedAt,
|
||||
model
|
||||
})
|
||||
} catch (error: any) {
|
||||
return NextResponse.json({
|
||||
error: `Kết nối DeepSeek thất bại: ${error.message}`
|
||||
}, { status: 500 })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { getServerSession } from "next-auth/next"
|
||||
import { authOptions } from "@/lib/auth"
|
||||
import connectToMongoDB from "@/lib/mongoose"
|
||||
import { Chapter } from "@/lib/models/chapter"
|
||||
import { prisma } from "@/lib/prisma"
|
||||
|
||||
export async function GET(
|
||||
req: Request,
|
||||
context: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const { id } = await context.params
|
||||
const session = await getServerSession(authOptions)
|
||||
if (!session || (session.user.role !== "MOD" && session.user.role !== "ADMIN")) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
||||
}
|
||||
|
||||
try {
|
||||
await connectToMongoDB()
|
||||
// console.log("Fetching chapter with ID:", id)
|
||||
|
||||
const chapter = await Chapter.findById(id)
|
||||
|
||||
if (!chapter) {
|
||||
// console.log("Chapter not found in DB")
|
||||
return NextResponse.json({ error: "Chapter not found" }, { status: 404 })
|
||||
}
|
||||
|
||||
// Verify the moderator owns the related novel (or is an ADMIN)
|
||||
let novelQuery: any = { id: chapter.novelId }
|
||||
if (session.user.role !== "ADMIN") {
|
||||
novelQuery.uploaderId = session.user.id
|
||||
}
|
||||
|
||||
const novel = await prisma.novel.findFirst({
|
||||
where: novelQuery
|
||||
})
|
||||
|
||||
if (!novel) {
|
||||
console.log("Novel not found or unauthorized:", {
|
||||
chapterNovelId: chapter.novelId,
|
||||
userId: session.user.id,
|
||||
role: session.user.role
|
||||
})
|
||||
return NextResponse.json({ error: "Unauthorized access to this chapter" }, { status: 403 })
|
||||
}
|
||||
|
||||
return NextResponse.json(chapter)
|
||||
} catch (error) {
|
||||
console.error("GET Chapter error:", error)
|
||||
return NextResponse.json({ error: "Failed to fetch chapter details" }, { status: 500 })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { getServerSession } from "next-auth/next"
|
||||
import { authOptions } from "@/lib/auth"
|
||||
import { prisma } from "@/lib/prisma"
|
||||
import connectToMongoDB from "@/lib/mongoose"
|
||||
import { Chapter } from "@/lib/models/chapter"
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const session = await getServerSession(authOptions)
|
||||
if (!session || (session.user.role !== "MOD" && session.user.role !== "ADMIN")) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
||||
}
|
||||
|
||||
try {
|
||||
const data = await req.json()
|
||||
const { novelId, fromNumber, toNumber } = data
|
||||
|
||||
if (!novelId || typeof fromNumber !== "number" || typeof toNumber !== "number") {
|
||||
return NextResponse.json({ error: "Dữ liệu không hợp lệ" }, { status: 400 })
|
||||
}
|
||||
|
||||
if (fromNumber > toNumber) {
|
||||
return NextResponse.json({ error: "Chương bắt đầu không được lớn hơn chương kết thúc" }, { status: 400 })
|
||||
}
|
||||
|
||||
// Xác minh truyện thuộc về Mod này (hoặc Admin)
|
||||
const novel = await prisma.novel.findUnique({
|
||||
where: { id: novelId }
|
||||
})
|
||||
|
||||
if (!novel) {
|
||||
return NextResponse.json({ error: "Truyện không tồn tại" }, { status: 404 })
|
||||
}
|
||||
|
||||
if (session.user.role !== "ADMIN" && novel.uploaderId !== session.user.id) {
|
||||
return NextResponse.json({ error: "Bạn không có quyền thao tác trên truyện này" }, { status: 403 })
|
||||
}
|
||||
|
||||
await connectToMongoDB()
|
||||
|
||||
// Xóa các chương trong khoảng
|
||||
const deleteResult = await Chapter.deleteMany({
|
||||
novelId,
|
||||
number: { $gte: fromNumber, $lte: toNumber }
|
||||
})
|
||||
|
||||
// Cập nhật lại số lượng chương
|
||||
const totalChapters = await Chapter.countDocuments({ novelId })
|
||||
await prisma.novel.update({
|
||||
where: { id: novelId },
|
||||
data: { totalChapters },
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
deletedCount: deleteResult.deletedCount,
|
||||
totalChapters
|
||||
})
|
||||
} catch (error: any) {
|
||||
console.error("Bulk Delete Chapters Error:", error)
|
||||
return NextResponse.json({ error: "Lỗi hệ thống khi xóa chương: " + error.message }, { status: 500 })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { getServerSession } from "next-auth/next"
|
||||
import { authOptions } from "@/lib/auth"
|
||||
import connectToMongoDB from "@/lib/mongoose"
|
||||
import { Chapter } from "@/lib/models/chapter"
|
||||
import { prisma } from "@/lib/prisma"
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const session = await getServerSession(authOptions)
|
||||
if (!session || (session.user.role !== "MOD" && session.user.role !== "ADMIN")) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await req.json()
|
||||
const { novelId, action = "replace", findText, replaceText, matchCase = false, trashWords = "", preview = false } = body
|
||||
|
||||
if (!novelId) {
|
||||
return NextResponse.json({ error: "novelId is required" }, { status: 400 })
|
||||
}
|
||||
|
||||
// Verify that the novel belongs to the uploader
|
||||
let novelQuery: any = { id: novelId }
|
||||
if (session.user.role !== "ADMIN") {
|
||||
novelQuery.uploaderId = session.user.id
|
||||
}
|
||||
|
||||
const novel = await prisma.novel.findFirst({
|
||||
where: novelQuery,
|
||||
})
|
||||
|
||||
if (!novel) {
|
||||
return NextResponse.json({ error: "Truyện không tồn tại hoặc không đủ quyền" }, { status: 403 })
|
||||
}
|
||||
|
||||
await connectToMongoDB()
|
||||
|
||||
let patterns: { regex: RegExp, replaceWith: string }[] = []
|
||||
|
||||
if (action === "replace") {
|
||||
if (!findText) return NextResponse.json({ error: "findText is required for replace action" }, { status: 400 })
|
||||
const flags = matchCase ? "g" : "gi"
|
||||
const safeFindText = findText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||||
patterns.push({ regex: new RegExp(safeFindText, flags), replaceWith: replaceText || "" })
|
||||
} else if (action === "trash") {
|
||||
let words: string[] = []
|
||||
if (Array.isArray(trashWords)) {
|
||||
words = trashWords
|
||||
} else if (typeof trashWords === "string") {
|
||||
words = trashWords.split(',').map((w: string) => w.trim()).filter((w: string) => w.length > 0)
|
||||
}
|
||||
|
||||
if (words.length === 0) return NextResponse.json({ error: "No valid words provided" }, { status: 400 })
|
||||
|
||||
words.forEach((word: string) => {
|
||||
const safeWord = word.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||||
patterns.push({ regex: new RegExp(safeWord, 'gi'), replaceWith: "" })
|
||||
})
|
||||
} else {
|
||||
return NextResponse.json({ error: "Invalid action" }, { status: 400 })
|
||||
}
|
||||
|
||||
// Find all chapters for the novel
|
||||
const chapters = await Chapter.find({ novelId }).sort({ number: 1 })
|
||||
let updatedCount = 0
|
||||
let previewResults: any[] = []
|
||||
|
||||
for (const chap of chapters) {
|
||||
let originalContent = chap.content || ""
|
||||
let newContent = originalContent
|
||||
let modified = false
|
||||
|
||||
patterns.forEach(({ regex, replaceWith }) => {
|
||||
if (regex.test(newContent)) {
|
||||
modified = true
|
||||
newContent = newContent.replace(regex, replaceWith)
|
||||
}
|
||||
})
|
||||
|
||||
if (modified) {
|
||||
if (preview && previewResults.length < 5) { // Limit previews to 5 chapters to save payload size
|
||||
// Capture a small text snippet from the first pattern match
|
||||
let snippet = ""
|
||||
if (patterns.length > 0) {
|
||||
const match = patterns[0].regex.exec(originalContent)
|
||||
if (match) {
|
||||
const matchIndex = match.index
|
||||
const start = Math.max(0, matchIndex - 30)
|
||||
const end = Math.min(originalContent.length, matchIndex + match[0].length + 30)
|
||||
snippet = "..." + originalContent.substring(start, end).replace(/\n/g, ' ') + "..."
|
||||
}
|
||||
}
|
||||
|
||||
previewResults.push({
|
||||
chapterId: chap._id,
|
||||
number: chap.number,
|
||||
title: chap.title,
|
||||
snippet
|
||||
})
|
||||
}
|
||||
|
||||
if (!preview) {
|
||||
chap.content = newContent
|
||||
await chap.save()
|
||||
}
|
||||
|
||||
updatedCount++
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
message: preview ? "Preview generated" : "Success",
|
||||
updatedChapters: updatedCount,
|
||||
previews: previewResults
|
||||
}, { status: 200 })
|
||||
|
||||
} catch (error) {
|
||||
console.error("Global Replace Error:", error)
|
||||
return NextResponse.json({ error: "Failed to perform global replacement" }, { status: 500 })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { getServerSession } from "next-auth/next"
|
||||
import { authOptions } from "@/lib/auth"
|
||||
import connectToMongoDB from "@/lib/mongoose"
|
||||
import { Chapter } from "@/lib/models/chapter"
|
||||
import { prisma } from "@/lib/prisma"
|
||||
|
||||
export async function PUT(req: Request) {
|
||||
const session = await getServerSession(authOptions)
|
||||
if (!session || (session.user.role !== "MOD" && session.user.role !== "ADMIN")) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await req.json()
|
||||
const { novelId, updates } = body
|
||||
|
||||
if (!novelId || !updates || !Array.isArray(updates)) {
|
||||
return NextResponse.json({ error: "Tham số không hợp lệ" }, { status: 400 })
|
||||
}
|
||||
|
||||
const novel = await prisma.novel.findUnique({
|
||||
where: { id: novelId },
|
||||
select: { id: true, uploaderId: true }
|
||||
})
|
||||
|
||||
if (!novel) {
|
||||
return NextResponse.json({ error: "Không tìm thấy truyện" }, { status: 404 })
|
||||
}
|
||||
|
||||
if (session.user.role !== "ADMIN" && novel.uploaderId !== session.user.id) {
|
||||
return NextResponse.json({ error: "Forbidden" }, { status: 403 })
|
||||
}
|
||||
|
||||
const validUpdates = updates.filter((update: any) =>
|
||||
update &&
|
||||
typeof update.id === "string" &&
|
||||
typeof update.number === "number" &&
|
||||
typeof update.title === "string"
|
||||
)
|
||||
|
||||
if (validUpdates.length === 0) {
|
||||
return NextResponse.json({ message: "Không có thay đổi nào" }, { status: 200 })
|
||||
}
|
||||
|
||||
await connectToMongoDB()
|
||||
|
||||
// Prepare bulk operations for mongoose
|
||||
const bulkOps = validUpdates.map((update: any) => ({
|
||||
updateOne: {
|
||||
filter: { _id: update.id, novelId: novelId },
|
||||
update: {
|
||||
$set: {
|
||||
number: update.number,
|
||||
title: update.title
|
||||
}
|
||||
}
|
||||
}
|
||||
}))
|
||||
|
||||
if (bulkOps.length === 0) {
|
||||
return NextResponse.json({ message: "Không có thay đổi nào" }, { status: 200 })
|
||||
}
|
||||
|
||||
const result = await Chapter.bulkWrite(bulkOps)
|
||||
|
||||
return NextResponse.json({
|
||||
message: "Cập nhật thành công",
|
||||
matchedCount: result.matchedCount,
|
||||
modifiedCount: result.modifiedCount
|
||||
}, { status: 200 })
|
||||
|
||||
} catch (error: any) {
|
||||
console.error("Bulk optimize error:", error)
|
||||
return NextResponse.json({ error: "Lỗi cập nhật hàng loạt", details: error.message }, { status: 500 })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { getServerSession } from "next-auth/next"
|
||||
import { authOptions } from "@/lib/auth"
|
||||
import connectToMongoDB from "@/lib/mongoose"
|
||||
import { Chapter } from "@/lib/models/chapter"
|
||||
import { prisma } from "@/lib/prisma"
|
||||
|
||||
function toNullableNumber(value: any): number | null {
|
||||
if (value === null || value === undefined || value === "") return null
|
||||
const parsed = Number(value)
|
||||
return Number.isFinite(parsed) ? parsed : null
|
||||
}
|
||||
|
||||
export async function GET(req: Request) {
|
||||
const { searchParams } = new URL(req.url)
|
||||
const novelId = searchParams.get("novelId")
|
||||
const page = parseInt(searchParams.get("page") || "1")
|
||||
const limit = parseInt(searchParams.get("limit") || "20")
|
||||
|
||||
if (!novelId) {
|
||||
return NextResponse.json({ error: "novelId is required" }, { status: 400 })
|
||||
}
|
||||
|
||||
try {
|
||||
await connectToMongoDB()
|
||||
const skip = (page - 1) * limit
|
||||
|
||||
const [chapters, totalChapters] = await Promise.all([
|
||||
Chapter.find({ novelId })
|
||||
.sort({ number: 1 })
|
||||
.skip(skip)
|
||||
.limit(limit)
|
||||
.select("-content"),
|
||||
Chapter.countDocuments({ novelId })
|
||||
])
|
||||
|
||||
return NextResponse.json({
|
||||
chapters,
|
||||
totalChapters,
|
||||
totalPages: Math.ceil(totalChapters / limit),
|
||||
currentPage: page
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("GET Chapter Error:", error)
|
||||
return NextResponse.json({ error: "Failed to fetch chapters" }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const session = await getServerSession(authOptions)
|
||||
if (!session || (session.user.role !== "MOD" && session.user.role !== "ADMIN")) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
||||
}
|
||||
|
||||
try {
|
||||
const data = await req.json()
|
||||
const { novelId, number, title, content, volumeNumber, volumeTitle, volumeChapterNumber } = data
|
||||
|
||||
// Xác minh truyện thuộc về Mod này
|
||||
const novel = await prisma.novel.findFirst({
|
||||
where: { id: novelId, uploaderId: session.user.id },
|
||||
})
|
||||
|
||||
if (!novel) {
|
||||
return NextResponse.json({ error: "Truyện không tồn tại hoặc không đủ quyền" }, { status: 403 })
|
||||
}
|
||||
|
||||
await connectToMongoDB()
|
||||
|
||||
// Kiểm tra chương đã tồn tại
|
||||
const existingChapter = await Chapter.findOne({ novelId, number })
|
||||
if (existingChapter) {
|
||||
return NextResponse.json({ error: "Chương này đã tồn tại" }, { status: 400 })
|
||||
}
|
||||
|
||||
const newChapter = await Chapter.create({
|
||||
novelId,
|
||||
number,
|
||||
volumeNumber: toNullableNumber(volumeNumber),
|
||||
volumeTitle: typeof volumeTitle === "string" && volumeTitle.trim().length > 0 ? volumeTitle.trim() : null,
|
||||
volumeChapterNumber: toNullableNumber(volumeChapterNumber),
|
||||
title,
|
||||
content,
|
||||
})
|
||||
|
||||
// Cập nhật số chương trong table PostgreSQL, tự động đếm lại
|
||||
const totalChapters = await Chapter.countDocuments({ novelId })
|
||||
await prisma.novel.update({
|
||||
where: { id: novelId },
|
||||
data: { totalChapters },
|
||||
})
|
||||
|
||||
return NextResponse.json(newChapter, { status: 201 })
|
||||
} catch (error) {
|
||||
console.error("POST Chapter Error:", error)
|
||||
return NextResponse.json({ error: "Failed to create chapter" }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
export async function PUT(req: Request) {
|
||||
const session = await getServerSession(authOptions)
|
||||
if (!session || (session.user.role !== "MOD" && session.user.role !== "ADMIN")) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
||||
}
|
||||
|
||||
try {
|
||||
const data = await req.json()
|
||||
const { id, novelId, number, title, content, volumeNumber, volumeTitle, volumeChapterNumber } = data
|
||||
|
||||
// Xác minh truyện thuộc về Mod này
|
||||
const novel = await prisma.novel.findFirst({
|
||||
where: { id: novelId, uploaderId: session.user.id },
|
||||
})
|
||||
|
||||
if (!novel) {
|
||||
return NextResponse.json({ error: "Truyện không tồn tại hoặc không đủ quyền" }, { status: 403 })
|
||||
}
|
||||
|
||||
await connectToMongoDB()
|
||||
|
||||
const updatedChapter = await Chapter.findOneAndUpdate(
|
||||
{ _id: id, novelId },
|
||||
{
|
||||
number,
|
||||
title,
|
||||
content,
|
||||
volumeNumber: toNullableNumber(volumeNumber),
|
||||
volumeTitle: typeof volumeTitle === "string" && volumeTitle.trim().length > 0 ? volumeTitle.trim() : null,
|
||||
volumeChapterNumber: toNullableNumber(volumeChapterNumber),
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
|
||||
if (!updatedChapter) {
|
||||
return NextResponse.json({ error: "Không tìm thấy chương" }, { status: 404 })
|
||||
}
|
||||
|
||||
return NextResponse.json(updatedChapter)
|
||||
} catch (error) {
|
||||
console.error("PUT Chapter Error:", error)
|
||||
return NextResponse.json({ error: "Failed to update chapter" }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(req: Request) {
|
||||
const session = await getServerSession(authOptions)
|
||||
if (!session || (session.user.role !== "MOD" && session.user.role !== "ADMIN")) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
||||
}
|
||||
|
||||
try {
|
||||
const url = new URL(req.url)
|
||||
const id = url.searchParams.get("id")
|
||||
const novelId = url.searchParams.get("novelId")
|
||||
|
||||
if (!id || !novelId) {
|
||||
return NextResponse.json({ error: "Thiếu ID chương hoặc ID truyện" }, { status: 400 })
|
||||
}
|
||||
|
||||
// Xác minh truyện thuộc về Mod này
|
||||
const novel = await prisma.novel.findFirst({
|
||||
where: { id: novelId, uploaderId: session.user.id },
|
||||
})
|
||||
|
||||
if (!novel) {
|
||||
return NextResponse.json({ error: "Truyện không tồn tại hoặc không đủ quyền" }, { status: 403 })
|
||||
}
|
||||
|
||||
await connectToMongoDB()
|
||||
|
||||
const deletedChapter = await Chapter.findOneAndDelete({ _id: id, novelId })
|
||||
|
||||
if (!deletedChapter) {
|
||||
return NextResponse.json({ error: "Không tìm thấy chương" }, { status: 404 })
|
||||
}
|
||||
|
||||
// Cập nhật lại số lượng chương trong Postgres
|
||||
const totalChapters = await Chapter.countDocuments({ novelId })
|
||||
await prisma.novel.update({
|
||||
where: { id: novelId },
|
||||
data: { totalChapters },
|
||||
})
|
||||
|
||||
return NextResponse.json({ message: "Đã xóa chương thành công" })
|
||||
} catch (error) {
|
||||
console.error("DELETE Chapter Error:", error)
|
||||
return NextResponse.json({ error: "Failed to delete chapter" }, { status: 500 })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { getServerSession } from "next-auth/next"
|
||||
import { authOptions } from "@/lib/auth"
|
||||
import { prisma } from "@/lib/prisma"
|
||||
import connectToMongoDB from "@/lib/mongoose"
|
||||
import { EditorRecommendation } from "@/lib/models/editor-recommendation"
|
||||
|
||||
const MAX_RECOMMENDATIONS_PER_EDITOR = 5
|
||||
|
||||
function normalizeText(value: any): string {
|
||||
return typeof value === "string" ? value.trim() : ""
|
||||
}
|
||||
|
||||
function isAllowedModerator(role: string) {
|
||||
return role === "MOD" || role === "ADMIN"
|
||||
}
|
||||
|
||||
export async function GET(req: Request) {
|
||||
const session = await getServerSession(authOptions)
|
||||
if (!session || !isAllowedModerator(session.user.role)) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
||||
}
|
||||
|
||||
try {
|
||||
const url = new URL(req.url)
|
||||
const q = normalizeText(url.searchParams.get("q"))
|
||||
|
||||
await connectToMongoDB()
|
||||
|
||||
const docs = (await EditorRecommendation.find({})
|
||||
.sort({ createdAt: -1 })
|
||||
.limit(1000)
|
||||
.lean()) as Array<{
|
||||
_id: any
|
||||
novelId: string
|
||||
editorId: string
|
||||
createdAt?: Date
|
||||
}>
|
||||
|
||||
const novelIds = Array.from(new Set(docs.map((doc) => doc.novelId).filter(Boolean)))
|
||||
const editorIds = Array.from(new Set(docs.map((doc) => doc.editorId).filter(Boolean)))
|
||||
|
||||
const [novels, editors] = await Promise.all([
|
||||
novelIds.length > 0
|
||||
? prisma.novel.findMany({
|
||||
where: { id: { in: novelIds } },
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
slug: true,
|
||||
authorName: true,
|
||||
coverUrl: true,
|
||||
status: true,
|
||||
totalChapters: true,
|
||||
},
|
||||
})
|
||||
: Promise.resolve([]),
|
||||
editorIds.length > 0
|
||||
? prisma.user.findMany({
|
||||
where: { id: { in: editorIds } },
|
||||
select: { id: true, name: true },
|
||||
})
|
||||
: Promise.resolve([]),
|
||||
])
|
||||
|
||||
const novelMap = new Map(novels.map((novel) => [novel.id, novel]))
|
||||
const editorMap = new Map(editors.map((editor) => [editor.id, editor]))
|
||||
|
||||
const recommendationCountMap = new Map<string, number>()
|
||||
for (const doc of docs) {
|
||||
recommendationCountMap.set(doc.novelId, (recommendationCountMap.get(doc.novelId) || 0) + 1)
|
||||
}
|
||||
|
||||
const items = docs
|
||||
.map((doc) => {
|
||||
const novel = novelMap.get(doc.novelId)
|
||||
if (!novel) return null
|
||||
|
||||
const editor = editorMap.get(doc.editorId)
|
||||
return {
|
||||
id: String(doc._id),
|
||||
createdAt: doc.createdAt || null,
|
||||
recommendCount: recommendationCountMap.get(doc.novelId) || 0,
|
||||
novel,
|
||||
editor: {
|
||||
id: doc.editorId,
|
||||
name: editor?.name || "Biên tập viên",
|
||||
},
|
||||
}
|
||||
})
|
||||
.filter((item): item is NonNullable<typeof item> => Boolean(item))
|
||||
|
||||
const summary = Array.from(recommendationCountMap.entries())
|
||||
.map(([novelId, recommendCount]) => {
|
||||
const novel = novelMap.get(novelId)
|
||||
if (!novel) return null
|
||||
return { novel, recommendCount }
|
||||
})
|
||||
.filter((item): item is NonNullable<typeof item> => Boolean(item))
|
||||
.sort((a, b) => b.recommendCount - a.recommendCount)
|
||||
|
||||
const myNovelIdSet = new Set(
|
||||
docs.filter((doc) => doc.editorId === session.user.id).map((doc) => doc.novelId)
|
||||
)
|
||||
const myRecommendationCount = myNovelIdSet.size
|
||||
|
||||
const candidates = q
|
||||
? await prisma.novel.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ title: { contains: q, mode: "insensitive" } },
|
||||
{ slug: { contains: q, mode: "insensitive" } },
|
||||
{ authorName: { contains: q, mode: "insensitive" } },
|
||||
],
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
slug: true,
|
||||
authorName: true,
|
||||
coverUrl: true,
|
||||
status: true,
|
||||
totalChapters: true,
|
||||
},
|
||||
take: 20,
|
||||
orderBy: [{ updatedAt: "desc" }],
|
||||
})
|
||||
: []
|
||||
|
||||
const candidateRows = candidates.map((novel) => ({
|
||||
...novel,
|
||||
alreadyRecommended: myNovelIdSet.has(novel.id),
|
||||
recommendCount: recommendationCountMap.get(novel.id) || 0,
|
||||
}))
|
||||
|
||||
return NextResponse.json({
|
||||
items,
|
||||
summary,
|
||||
candidates: candidateRows,
|
||||
myNovelIds: Array.from(myNovelIdSet),
|
||||
currentUser: {
|
||||
id: session.user.id,
|
||||
role: session.user.role,
|
||||
recommendationCount: myRecommendationCount,
|
||||
maxRecommendationCount: MAX_RECOMMENDATIONS_PER_EDITOR,
|
||||
},
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch editor recommendations", error)
|
||||
return NextResponse.json({ error: "Failed to fetch recommendations" }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const session = await getServerSession(authOptions)
|
||||
if (!session || !isAllowedModerator(session.user.role)) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await req.json()
|
||||
const novelId = normalizeText(body?.novelId)
|
||||
|
||||
if (!novelId) {
|
||||
return NextResponse.json({ error: "Thiếu ID truyện" }, { status: 400 })
|
||||
}
|
||||
|
||||
const existedNovel = await prisma.novel.findUnique({
|
||||
where: { id: novelId },
|
||||
select: { id: true },
|
||||
})
|
||||
|
||||
if (!existedNovel) {
|
||||
return NextResponse.json({ error: "Truyện không tồn tại" }, { status: 404 })
|
||||
}
|
||||
|
||||
await connectToMongoDB()
|
||||
|
||||
const existing = (await EditorRecommendation.findOne({
|
||||
novelId,
|
||||
editorId: session.user.id,
|
||||
})
|
||||
.select({ _id: 1 })
|
||||
.lean()) as { _id: any } | null
|
||||
|
||||
if (existing) {
|
||||
return NextResponse.json({ error: "Bạn đã đề cử truyện này rồi" }, { status: 409 })
|
||||
}
|
||||
|
||||
const myRecommendationCount = await EditorRecommendation.countDocuments({
|
||||
editorId: session.user.id,
|
||||
})
|
||||
|
||||
if (myRecommendationCount >= MAX_RECOMMENDATIONS_PER_EDITOR) {
|
||||
return NextResponse.json(
|
||||
{ error: `Mỗi biên tập viên chỉ được đề cử tối đa ${MAX_RECOMMENDATIONS_PER_EDITOR} truyện` },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
try {
|
||||
const created = await EditorRecommendation.create({
|
||||
novelId,
|
||||
editorId: session.user.id,
|
||||
})
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
id: String(created._id),
|
||||
novelId,
|
||||
editorId: session.user.id,
|
||||
},
|
||||
{ status: 201 }
|
||||
)
|
||||
} catch (error: any) {
|
||||
if (error?.code === 11000) {
|
||||
return NextResponse.json({ error: "Bạn đã đề cử truyện này rồi" }, { status: 409 })
|
||||
}
|
||||
throw error
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to create editor recommendation", error)
|
||||
return NextResponse.json({ error: "Failed to create recommendation" }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(req: Request) {
|
||||
const session = await getServerSession(authOptions)
|
||||
if (!session || !isAllowedModerator(session.user.role)) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
||||
}
|
||||
|
||||
try {
|
||||
const url = new URL(req.url)
|
||||
const id = normalizeText(url.searchParams.get("id"))
|
||||
|
||||
if (!id) {
|
||||
return NextResponse.json({ error: "Thiếu ID đề cử" }, { status: 400 })
|
||||
}
|
||||
|
||||
await connectToMongoDB()
|
||||
|
||||
const existed = (await EditorRecommendation.findById(id).lean()) as {
|
||||
_id: any
|
||||
editorId: string
|
||||
} | null
|
||||
|
||||
if (!existed) {
|
||||
return NextResponse.json({ error: "Đề cử không tồn tại" }, { status: 404 })
|
||||
}
|
||||
|
||||
if (session.user.role !== "ADMIN" && existed.editorId !== session.user.id) {
|
||||
return NextResponse.json({ error: "Bạn không thể xóa đề cử của người khác" }, { status: 403 })
|
||||
}
|
||||
|
||||
await EditorRecommendation.deleteOne({ _id: id })
|
||||
return NextResponse.json({ success: true })
|
||||
} catch (error) {
|
||||
console.error("Failed to delete editor recommendation", error)
|
||||
return NextResponse.json({ error: "Failed to delete recommendation" }, { status: 500 })
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,200 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { getServerSession } from "next-auth/next"
|
||||
import { authOptions } from "@/lib/auth"
|
||||
import { prisma } from "@/lib/prisma"
|
||||
import { slugify } from "@/lib/utils"
|
||||
|
||||
function normalizeText(value: any): string {
|
||||
return typeof value === "string" ? value.trim() : ""
|
||||
}
|
||||
|
||||
async function resolveEditableSeries(
|
||||
id: string,
|
||||
session: { user: { role: "USER" | "MOD" | "ADMIN"; id: string } }
|
||||
) {
|
||||
return prisma.series.findFirst({
|
||||
where: session.user.role === "ADMIN"
|
||||
? { id }
|
||||
: {
|
||||
id,
|
||||
OR: [
|
||||
{ novels: { some: { uploaderId: session.user.id } } },
|
||||
{ novels: { some: { uploaderId: null } } },
|
||||
{ novels: { none: {} } },
|
||||
],
|
||||
},
|
||||
select: { id: true },
|
||||
})
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
const session = await getServerSession(authOptions)
|
||||
if (!session || (session.user.role !== "MOD" && session.user.role !== "ADMIN")) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
||||
}
|
||||
|
||||
try {
|
||||
const series = await prisma.series.findMany({
|
||||
where: session.user.role === "ADMIN"
|
||||
? undefined
|
||||
: {
|
||||
OR: [
|
||||
{ novels: { some: { uploaderId: session.user.id } } },
|
||||
{ novels: { some: { uploaderId: null } } },
|
||||
{ novels: { none: {} } },
|
||||
],
|
||||
},
|
||||
orderBy: { updatedAt: "desc" },
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
slug: true,
|
||||
description: true,
|
||||
_count: { select: { novels: true } },
|
||||
},
|
||||
})
|
||||
|
||||
return NextResponse.json(series)
|
||||
} catch {
|
||||
return NextResponse.json({ error: "Failed to fetch series" }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const session = await getServerSession(authOptions)
|
||||
if (!session || (session.user.role !== "MOD" && session.user.role !== "ADMIN")) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await req.json()
|
||||
const name = normalizeText(body?.name)
|
||||
const description = normalizeText(body?.description)
|
||||
|
||||
if (!name) {
|
||||
return NextResponse.json({ error: "Tên series không được để trống" }, { status: 400 })
|
||||
}
|
||||
|
||||
const existing = await prisma.series.findFirst({
|
||||
where: { name: { equals: name, mode: "insensitive" } },
|
||||
select: { id: true, name: true, slug: true, description: true },
|
||||
})
|
||||
|
||||
if (existing) {
|
||||
return NextResponse.json(existing)
|
||||
}
|
||||
|
||||
const baseSlug = slugify(name)
|
||||
let slug = baseSlug
|
||||
let counter = 1
|
||||
|
||||
while (await prisma.series.findUnique({ where: { slug } })) {
|
||||
slug = `${baseSlug}-${counter}`
|
||||
counter += 1
|
||||
}
|
||||
|
||||
const created = await prisma.series.create({
|
||||
data: { name, slug, description: description || null },
|
||||
select: { id: true, name: true, slug: true, description: true },
|
||||
})
|
||||
|
||||
return NextResponse.json(created, { status: 201 })
|
||||
} catch {
|
||||
return NextResponse.json({ error: "Failed to create series" }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
export async function PUT(req: Request) {
|
||||
const session = await getServerSession(authOptions)
|
||||
if (!session || (session.user.role !== "MOD" && session.user.role !== "ADMIN")) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await req.json()
|
||||
const id = normalizeText(body?.id)
|
||||
const name = normalizeText(body?.name)
|
||||
const description = normalizeText(body?.description)
|
||||
|
||||
if (!id || !name) {
|
||||
return NextResponse.json({ error: "Thiếu thông tin series" }, { status: 400 })
|
||||
}
|
||||
|
||||
const target = await resolveEditableSeries(id, session as any)
|
||||
if (!target) {
|
||||
return NextResponse.json({ error: "Không tìm thấy series hoặc không đủ quyền" }, { status: 404 })
|
||||
}
|
||||
|
||||
const duplicated = await prisma.series.findFirst({
|
||||
where: {
|
||||
id: { not: id },
|
||||
name: { equals: name, mode: "insensitive" },
|
||||
},
|
||||
select: { id: true },
|
||||
})
|
||||
|
||||
if (duplicated) {
|
||||
return NextResponse.json({ error: "Tên series đã tồn tại" }, { status: 409 })
|
||||
}
|
||||
|
||||
const baseSlug = slugify(name)
|
||||
let slug = baseSlug
|
||||
let counter = 1
|
||||
|
||||
while (await prisma.series.findFirst({ where: { slug, id: { not: id } }, select: { id: true } })) {
|
||||
slug = `${baseSlug}-${counter}`
|
||||
counter += 1
|
||||
}
|
||||
|
||||
const updated = await prisma.series.update({
|
||||
where: { id },
|
||||
data: {
|
||||
name,
|
||||
slug,
|
||||
description: description || null,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
slug: true,
|
||||
description: true,
|
||||
_count: { select: { novels: true } },
|
||||
},
|
||||
})
|
||||
|
||||
return NextResponse.json(updated)
|
||||
} catch {
|
||||
return NextResponse.json({ error: "Failed to update series" }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(req: Request) {
|
||||
const session = await getServerSession(authOptions)
|
||||
if (!session || (session.user.role !== "MOD" && session.user.role !== "ADMIN")) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
||||
}
|
||||
|
||||
try {
|
||||
const url = new URL(req.url)
|
||||
const id = normalizeText(url.searchParams.get("id"))
|
||||
|
||||
if (!id) {
|
||||
return NextResponse.json({ error: "Thiếu id series" }, { status: 400 })
|
||||
}
|
||||
|
||||
const target = await resolveEditableSeries(id, session as any)
|
||||
if (!target) {
|
||||
return NextResponse.json({ error: "Không tìm thấy series hoặc không đủ quyền" }, { status: 404 })
|
||||
}
|
||||
|
||||
const usedCount = await prisma.novel.count({ where: { seriesId: id } })
|
||||
if (usedCount > 0) {
|
||||
return NextResponse.json({ error: "Series đang chứa truyện, không thể xóa" }, { status: 409 })
|
||||
}
|
||||
|
||||
await prisma.series.delete({ where: { id } })
|
||||
return NextResponse.json({ success: true })
|
||||
} catch {
|
||||
return NextResponse.json({ error: "Failed to delete series" }, { status: 500 })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { getServerSession } from "next-auth/next"
|
||||
import { authOptions } from "@/lib/auth"
|
||||
import { prisma } from "@/lib/prisma"
|
||||
import { slugify } from "@/lib/utils"
|
||||
|
||||
// Get all genres
|
||||
export async function GET() {
|
||||
try {
|
||||
const genres = await prisma.genre.findMany({
|
||||
orderBy: { name: "asc" }
|
||||
})
|
||||
return NextResponse.json(genres)
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: "Failed to fetch genres" }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
// Admins/Mods can add new genres
|
||||
export async function POST(req: Request) {
|
||||
const session = await getServerSession(authOptions)
|
||||
if (!session || (session.user.role !== "MOD" && session.user.role !== "ADMIN")) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
||||
}
|
||||
|
||||
try {
|
||||
const data = await req.json()
|
||||
const { name, description } = data
|
||||
|
||||
if (!name) {
|
||||
return NextResponse.json({ error: "Genre name is required" }, { status: 400 })
|
||||
}
|
||||
|
||||
const slug = slugify(name)
|
||||
|
||||
const newGenre = await prisma.genre.create({
|
||||
data: { name, slug, description }
|
||||
})
|
||||
|
||||
return NextResponse.json(newGenre, { status: 201 })
|
||||
} catch (error: any) {
|
||||
if (error.code === 'P2002') {
|
||||
return NextResponse.json({ error: "Thể loại này đã tồn tại" }, { status: 400 })
|
||||
}
|
||||
return NextResponse.json({ error: "Failed to create genre" }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(req: Request) {
|
||||
const session = await getServerSession(authOptions)
|
||||
if (!session || (session.user.role !== "MOD" && session.user.role !== "ADMIN")) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
||||
}
|
||||
|
||||
try {
|
||||
const url = new URL(req.url)
|
||||
const id = url.searchParams.get("id")
|
||||
|
||||
if (!id) {
|
||||
return NextResponse.json({ error: "Thiếu ID thể loại" }, { status: 400 })
|
||||
}
|
||||
|
||||
await prisma.genre.delete({
|
||||
where: { id }
|
||||
})
|
||||
|
||||
return NextResponse.json({ message: "Đã xóa thể loại thành công" })
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: "Lỗi khi xóa thể loại" }, { status: 500 })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { getServerSession } from "next-auth/next"
|
||||
import { authOptions } from "@/lib/auth"
|
||||
import { prisma } from "@/lib/prisma"
|
||||
|
||||
export async function GET(
|
||||
req: Request,
|
||||
context: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const { id } = await context.params
|
||||
const session = await getServerSession(authOptions)
|
||||
if (!session || (session.user.role !== "MOD" && session.user.role !== "ADMIN")) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
||||
}
|
||||
|
||||
try {
|
||||
const novel = await prisma.novel.findFirst({
|
||||
where: session.user.role === "ADMIN"
|
||||
? { id }
|
||||
: {
|
||||
id,
|
||||
OR: [
|
||||
{ uploaderId: session.user.id },
|
||||
{ uploaderId: null },
|
||||
],
|
||||
},
|
||||
include: {
|
||||
series: true,
|
||||
genres: {
|
||||
include: {
|
||||
genre: true
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
if (!novel) {
|
||||
return NextResponse.json({ error: "Novel not found" }, { status: 404 })
|
||||
}
|
||||
|
||||
return NextResponse.json(novel)
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: "Failed to fetch novel details" }, { status: 500 })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { getServerSession } from "next-auth/next"
|
||||
import { authOptions } from "@/lib/auth"
|
||||
import { prisma } from "@/lib/prisma"
|
||||
|
||||
export async function GET(req: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||
const session = await getServerSession(authOptions)
|
||||
if (!session || (session.user.role !== "MOD" && session.user.role !== "ADMIN")) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
||||
}
|
||||
|
||||
const { id: novelId } = await params
|
||||
|
||||
try {
|
||||
const novel = await prisma.novel.findUnique({
|
||||
where: { id: novelId },
|
||||
select: { trashWords: true, uploaderId: true }
|
||||
})
|
||||
|
||||
if (!novel) {
|
||||
return NextResponse.json({ error: "Not found" }, { status: 404 })
|
||||
}
|
||||
|
||||
if (session.user.role !== "ADMIN" && novel.uploaderId !== session.user.id) {
|
||||
return NextResponse.json({ error: "Forbidden" }, { status: 403 })
|
||||
}
|
||||
|
||||
return NextResponse.json({ trashWords: novel.trashWords })
|
||||
} catch (error) {
|
||||
console.error("GET Trash Words Error:", error)
|
||||
return NextResponse.json({ error: "Lỗi Server" }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
export async function PUT(req: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||
const session = await getServerSession(authOptions)
|
||||
if (!session || (session.user.role !== "MOD" && session.user.role !== "ADMIN")) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
||||
}
|
||||
|
||||
const { id: novelId } = await params
|
||||
|
||||
try {
|
||||
const novel = await prisma.novel.findUnique({
|
||||
where: { id: novelId },
|
||||
select: { id: true, uploaderId: true }
|
||||
})
|
||||
|
||||
if (!novel) return NextResponse.json({ error: "Not found" }, { status: 404 })
|
||||
|
||||
if (session.user.role !== "ADMIN" && novel.uploaderId !== session.user.id) {
|
||||
return NextResponse.json({ error: "Forbidden" }, { status: 403 })
|
||||
}
|
||||
|
||||
const body = await req.json()
|
||||
const { trashWords } = body
|
||||
|
||||
if (!Array.isArray(trashWords)) {
|
||||
return NextResponse.json({ error: "Mảng từ rác không hợp lệ" }, { status: 400 })
|
||||
}
|
||||
|
||||
const updated = await prisma.novel.update({
|
||||
where: { id: novelId },
|
||||
data: { trashWords }
|
||||
})
|
||||
|
||||
return NextResponse.json({ success: true, trashWords: updated.trashWords })
|
||||
} catch (error) {
|
||||
console.error("PUT Trash Words Error:", error)
|
||||
return NextResponse.json({ error: "Lỗi Server" }, { status: 500 })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { getServerSession } from "next-auth/next"
|
||||
import { authOptions } from "@/lib/auth"
|
||||
import { prisma } from "@/lib/prisma"
|
||||
import connectToMongoDB from "@/lib/mongoose"
|
||||
import { Chapter } from "@/lib/models/chapter"
|
||||
import { deleteR2ObjectByUrl } from "@/lib/r2"
|
||||
|
||||
function normalizeIds(value: any): string[] {
|
||||
if (!Array.isArray(value)) return []
|
||||
return value.filter((item) => typeof item === "string" && item.trim()).map((item) => item.trim())
|
||||
}
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const session = await getServerSession(authOptions)
|
||||
if (!session || (session.user.role !== "MOD" && session.user.role !== "ADMIN")) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await req.json()
|
||||
const action = typeof body?.action === "string" ? body.action : ""
|
||||
const ids = normalizeIds(body?.ids)
|
||||
|
||||
if (ids.length === 0) {
|
||||
return NextResponse.json({ error: "Danh sách truyện trống" }, { status: 400 })
|
||||
}
|
||||
|
||||
const accessibleNovels = await prisma.novel.findMany({
|
||||
where: session.user.role === "ADMIN"
|
||||
? { id: { in: ids } }
|
||||
: {
|
||||
id: { in: ids },
|
||||
OR: [
|
||||
{ uploaderId: session.user.id },
|
||||
{ uploaderId: null },
|
||||
],
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
coverUrl: true,
|
||||
},
|
||||
})
|
||||
|
||||
if (accessibleNovels.length === 0) {
|
||||
return NextResponse.json({ error: "Không có truyện hợp lệ để thao tác" }, { status: 404 })
|
||||
}
|
||||
|
||||
const accessibleIds = accessibleNovels.map((novel) => novel.id)
|
||||
|
||||
if (action === "delete") {
|
||||
await connectToMongoDB()
|
||||
await Chapter.deleteMany({ novelId: { $in: accessibleIds } })
|
||||
|
||||
await prisma.novel.deleteMany({
|
||||
where: { id: { in: accessibleIds } },
|
||||
})
|
||||
|
||||
await Promise.all(
|
||||
accessibleNovels.map((novel) => deleteR2ObjectByUrl(novel.coverUrl).catch(() => {}))
|
||||
)
|
||||
|
||||
return NextResponse.json({ success: true, deletedCount: accessibleIds.length })
|
||||
}
|
||||
|
||||
return NextResponse.json({ error: "Chỉ hỗ trợ xóa hàng loạt" }, { status: 400 })
|
||||
} catch {
|
||||
return NextResponse.json({ error: "Bulk operation failed" }, { status: 500 })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { getServerSession } from "next-auth/next"
|
||||
import { authOptions } from "@/lib/auth"
|
||||
import { prisma } from "@/lib/prisma"
|
||||
|
||||
type MissingKey = "author" | "cover" | "description" | "genres"
|
||||
|
||||
const ALL_MISSING_KEYS: MissingKey[] = ["author", "cover", "description", "genres"]
|
||||
|
||||
function getScopeWhere(session: { user: { role: string; id: string } }) {
|
||||
if (session.user.role === "ADMIN") {
|
||||
return {}
|
||||
}
|
||||
|
||||
return {
|
||||
OR: [
|
||||
{ uploaderId: session.user.id },
|
||||
{ uploaderId: null },
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
function parseMissingKeys(raw: string | null): MissingKey[] {
|
||||
if (!raw || !raw.trim()) return ALL_MISSING_KEYS
|
||||
|
||||
const parsed = raw
|
||||
.split(",")
|
||||
.map((item) => item.trim().toLowerCase())
|
||||
.filter((item): item is MissingKey => ALL_MISSING_KEYS.includes(item as MissingKey))
|
||||
|
||||
if (parsed.length === 0) return ALL_MISSING_KEYS
|
||||
return Array.from(new Set(parsed))
|
||||
}
|
||||
|
||||
function buildMissingWhereForKey(key: MissingKey) {
|
||||
switch (key) {
|
||||
case "author":
|
||||
return { authorName: { equals: "" } }
|
||||
case "cover":
|
||||
return {
|
||||
OR: [
|
||||
{ coverUrl: null },
|
||||
{ coverUrl: { equals: "" } },
|
||||
],
|
||||
}
|
||||
case "description":
|
||||
return { description: { equals: "" } }
|
||||
case "genres":
|
||||
return { genres: { none: {} } }
|
||||
default:
|
||||
return {}
|
||||
}
|
||||
}
|
||||
|
||||
function computeMissingStatus(novel: {
|
||||
authorName: string
|
||||
coverUrl: string | null
|
||||
description: string
|
||||
genres: Array<{ genre: { id: string; name: string } }>
|
||||
}) {
|
||||
const authorMissing = novel.authorName.trim().length === 0
|
||||
const coverMissing = !novel.coverUrl || novel.coverUrl.trim().length === 0
|
||||
const descriptionMissing = novel.description.trim().length === 0
|
||||
const genresMissing = novel.genres.length === 0
|
||||
|
||||
return {
|
||||
author: authorMissing,
|
||||
cover: coverMissing,
|
||||
description: descriptionMissing,
|
||||
genres: genresMissing,
|
||||
}
|
||||
}
|
||||
|
||||
function hasSelectedMissing(missingStatus: Record<MissingKey, boolean>, selected: MissingKey[]) {
|
||||
return selected.some((key) => missingStatus[key])
|
||||
}
|
||||
|
||||
export async function GET(req: Request) {
|
||||
const session = await getServerSession(authOptions)
|
||||
if (!session || (session.user.role !== "MOD" && session.user.role !== "ADMIN")) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
||||
}
|
||||
|
||||
try {
|
||||
const url = new URL(req.url)
|
||||
const q = (url.searchParams.get("q") || "").trim()
|
||||
const selectedMissing = parseMissingKeys(url.searchParams.get("missing"))
|
||||
|
||||
const andWhere: any[] = [getScopeWhere(session)]
|
||||
|
||||
if (q) {
|
||||
andWhere.push({
|
||||
OR: [
|
||||
{ title: { contains: q, mode: "insensitive" } },
|
||||
{ slug: { contains: q, mode: "insensitive" } },
|
||||
{ authorName: { contains: q, mode: "insensitive" } },
|
||||
{ series: { name: { contains: q, mode: "insensitive" } } },
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
if (selectedMissing.length > 0) {
|
||||
andWhere.push({
|
||||
OR: selectedMissing.map((key) => buildMissingWhereForKey(key)),
|
||||
})
|
||||
}
|
||||
|
||||
const novels = await (prisma as any).novel.findMany({
|
||||
where: { AND: andWhere },
|
||||
orderBy: [{ updatedAt: "desc" }],
|
||||
take: 600,
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
slug: true,
|
||||
authorName: true,
|
||||
coverUrl: true,
|
||||
description: true,
|
||||
totalChapters: true,
|
||||
updatedAt: true,
|
||||
series: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
slug: true,
|
||||
},
|
||||
},
|
||||
genres: {
|
||||
select: {
|
||||
genre: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const items = novels
|
||||
.map((novel: any) => {
|
||||
const missing = computeMissingStatus(novel)
|
||||
|
||||
return {
|
||||
id: novel.id,
|
||||
title: novel.title,
|
||||
slug: novel.slug,
|
||||
authorName: novel.authorName,
|
||||
coverUrl: novel.coverUrl,
|
||||
description: novel.description,
|
||||
totalChapters: novel.totalChapters,
|
||||
updatedAt: novel.updatedAt,
|
||||
series: novel.series,
|
||||
genres: novel.genres.map((item: any) => item.genre),
|
||||
missing,
|
||||
}
|
||||
})
|
||||
.filter((item: any) => hasSelectedMissing(item.missing, selectedMissing))
|
||||
|
||||
return NextResponse.json({
|
||||
items,
|
||||
total: items.length,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch novels with missing fields", error)
|
||||
return NextResponse.json({ error: "Failed to fetch missing-field novels" }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
export async function PATCH(req: Request) {
|
||||
const session = await getServerSession(authOptions)
|
||||
if (!session || (session.user.role !== "MOD" && session.user.role !== "ADMIN")) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await req.json()
|
||||
const updates = Array.isArray(body?.updates) ? body.updates : []
|
||||
|
||||
if (updates.length === 0) {
|
||||
return NextResponse.json({ error: "Thiếu danh sách cập nhật" }, { status: 400 })
|
||||
}
|
||||
|
||||
if (updates.length > 200) {
|
||||
return NextResponse.json({ error: "Chỉ hỗ trợ tối đa 200 bản ghi mỗi lần" }, { status: 400 })
|
||||
}
|
||||
|
||||
const ids = updates
|
||||
.map((item: any) => (typeof item?.id === "string" ? item.id : ""))
|
||||
.filter(Boolean)
|
||||
|
||||
if (ids.length === 0) {
|
||||
return NextResponse.json({ error: "Danh sách ID không hợp lệ" }, { status: 400 })
|
||||
}
|
||||
|
||||
const allowedRows = await (prisma as any).novel.findMany({
|
||||
where: {
|
||||
AND: [
|
||||
getScopeWhere(session),
|
||||
{ id: { in: ids } },
|
||||
],
|
||||
},
|
||||
select: { id: true },
|
||||
})
|
||||
|
||||
const allowedSet = new Set(allowedRows.map((row: any) => row.id))
|
||||
|
||||
let updatedCount = 0
|
||||
let skippedCount = 0
|
||||
const failures: Array<{ id: string; error: string }> = []
|
||||
|
||||
for (const raw of updates) {
|
||||
const id = typeof raw?.id === "string" ? raw.id : ""
|
||||
if (!id) {
|
||||
skippedCount += 1
|
||||
continue
|
||||
}
|
||||
|
||||
if (!allowedSet.has(id)) {
|
||||
failures.push({ id, error: "Không có quyền cập nhật truyện này" })
|
||||
continue
|
||||
}
|
||||
|
||||
const data: Record<string, any> = {}
|
||||
|
||||
if (typeof raw.authorName === "string") {
|
||||
data.authorName = raw.authorName.trim()
|
||||
}
|
||||
|
||||
if (typeof raw.coverUrl === "string") {
|
||||
const normalizedCover = raw.coverUrl.trim()
|
||||
data.coverUrl = normalizedCover.length > 0 ? normalizedCover : null
|
||||
} else if (raw.coverUrl === null) {
|
||||
data.coverUrl = null
|
||||
}
|
||||
|
||||
if (typeof raw.description === "string") {
|
||||
data.description = raw.description.trim()
|
||||
}
|
||||
|
||||
const hasGenreUpdate = Array.isArray(raw.genreIds)
|
||||
const genreIds: string[] = hasGenreUpdate
|
||||
? Array.from(new Set((raw.genreIds as unknown[]).filter((item): item is string => typeof item === "string" && item.trim().length > 0)))
|
||||
: []
|
||||
|
||||
if (Object.keys(data).length === 0 && !hasGenreUpdate) {
|
||||
skippedCount += 1
|
||||
continue
|
||||
}
|
||||
|
||||
try {
|
||||
await prisma.$transaction(async (tx) => {
|
||||
if (Object.keys(data).length > 0) {
|
||||
await (tx as any).novel.update({
|
||||
where: { id },
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
if (hasGenreUpdate) {
|
||||
await (tx as any).novelGenre.deleteMany({ where: { novelId: id } })
|
||||
|
||||
if (genreIds.length > 0) {
|
||||
await (tx as any).novelGenre.createMany({
|
||||
data: genreIds.map((genreId) => ({ novelId: id, genreId })),
|
||||
skipDuplicates: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
updatedCount += 1
|
||||
} catch (error: any) {
|
||||
failures.push({ id, error: error?.message || "Cập nhật thất bại" })
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
updatedCount,
|
||||
skippedCount,
|
||||
failureCount: failures.length,
|
||||
failures,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Failed to patch missing-field novels", error)
|
||||
return NextResponse.json({ error: "Failed to update novels" }, { status: 500 })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { getServerSession } from "next-auth/next"
|
||||
import { authOptions } from "@/lib/auth"
|
||||
import { prisma } from "@/lib/prisma"
|
||||
import { slugify } from "@/lib/utils"
|
||||
import connectToMongoDB from "@/lib/mongoose"
|
||||
import { Chapter } from "@/lib/models/chapter"
|
||||
import { deleteR2ObjectByUrl } from "@/lib/r2"
|
||||
|
||||
function normalizeOptionalText(value: any): string {
|
||||
return typeof value === "string" ? value.trim() : ""
|
||||
}
|
||||
|
||||
async function resolveSeriesIdForWrite(
|
||||
seriesIdInput: any,
|
||||
seriesNameInput: any,
|
||||
userRole: "USER" | "MOD" | "ADMIN",
|
||||
userId: string
|
||||
): Promise<string | null> {
|
||||
const seriesId = normalizeOptionalText(seriesIdInput)
|
||||
const seriesName = normalizeOptionalText(seriesNameInput)
|
||||
|
||||
if (seriesId) {
|
||||
const series = await prisma.series.findFirst({
|
||||
where: userRole === "ADMIN"
|
||||
? { id: seriesId }
|
||||
: {
|
||||
id: seriesId,
|
||||
OR: [
|
||||
{ novels: { some: { uploaderId: userId } } },
|
||||
{ novels: { some: { uploaderId: null } } },
|
||||
{ novels: { none: {} } },
|
||||
],
|
||||
},
|
||||
select: { id: true },
|
||||
})
|
||||
|
||||
if (!series) {
|
||||
throw new Error("Series không tồn tại hoặc bạn không có quyền sử dụng")
|
||||
}
|
||||
|
||||
return series.id
|
||||
}
|
||||
|
||||
if (!seriesName) return null
|
||||
|
||||
const existingSeries = await prisma.series.findFirst({
|
||||
where: { name: { equals: seriesName, mode: "insensitive" } },
|
||||
select: { id: true },
|
||||
})
|
||||
|
||||
if (existingSeries) {
|
||||
return existingSeries.id
|
||||
}
|
||||
|
||||
const baseSlug = slugify(seriesName)
|
||||
let slug = baseSlug
|
||||
let counter = 1
|
||||
|
||||
while (await prisma.series.findUnique({ where: { slug } })) {
|
||||
slug = `${baseSlug}-${counter}`
|
||||
counter += 1
|
||||
}
|
||||
|
||||
const createdSeries = await prisma.series.create({
|
||||
data: {
|
||||
name: seriesName,
|
||||
slug,
|
||||
},
|
||||
select: { id: true },
|
||||
})
|
||||
|
||||
return createdSeries.id
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
const session = await getServerSession(authOptions)
|
||||
if (!session || (session.user.role !== "MOD" && session.user.role !== "ADMIN")) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
||||
}
|
||||
|
||||
try {
|
||||
const novels = await prisma.novel.findMany({
|
||||
where: session.user.role === "ADMIN"
|
||||
? undefined
|
||||
: {
|
||||
OR: [
|
||||
{ uploaderId: session.user.id },
|
||||
{ uploaderId: null },
|
||||
],
|
||||
},
|
||||
include: {
|
||||
series: {
|
||||
select: { id: true, name: true, slug: true }
|
||||
}
|
||||
},
|
||||
orderBy: { updatedAt: "desc" },
|
||||
})
|
||||
return NextResponse.json(novels)
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: "Failed to fetch novels" }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const session = await getServerSession(authOptions)
|
||||
if (!session || (session.user.role !== "MOD" && session.user.role !== "ADMIN")) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
||||
}
|
||||
|
||||
try {
|
||||
const data = await req.json()
|
||||
const { title, originalTitle, authorName, originalAuthorName, description, coverUrl, genreIds = [] } = data
|
||||
const seriesId = await resolveSeriesIdForWrite(data?.seriesId, data?.seriesName, session.user.role, session.user.id)
|
||||
// Tạo slug từ title
|
||||
const slug = slugify(title)
|
||||
|
||||
const newNovel = await prisma.novel.create({
|
||||
data: {
|
||||
title,
|
||||
originalTitle,
|
||||
slug: slug,
|
||||
authorName,
|
||||
originalAuthorName,
|
||||
description,
|
||||
coverUrl,
|
||||
seriesId,
|
||||
uploaderId: session.user.id,
|
||||
genres: {
|
||||
create: genreIds.map((id: string) => ({
|
||||
genre: { connect: { id } }
|
||||
}))
|
||||
}
|
||||
},
|
||||
})
|
||||
return NextResponse.json(newNovel, { status: 201 })
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: "Failed to create novel" }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
export async function PUT(req: Request) {
|
||||
const session = await getServerSession(authOptions)
|
||||
if (!session || (session.user.role !== "MOD" && session.user.role !== "ADMIN")) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
||||
}
|
||||
|
||||
try {
|
||||
const data = await req.json()
|
||||
const { id, title, originalTitle, authorName, originalAuthorName, description, coverUrl, status, genreIds } = data
|
||||
|
||||
if (!id) {
|
||||
return NextResponse.json({ error: "Thiếu ID truyện" }, { status: 400 })
|
||||
}
|
||||
|
||||
const hasField = (field: string) => Object.prototype.hasOwnProperty.call(data, field)
|
||||
|
||||
const targetNovel = await prisma.novel.findFirst({
|
||||
where: session.user.role === "ADMIN"
|
||||
? { id }
|
||||
: {
|
||||
id,
|
||||
OR: [
|
||||
{ uploaderId: session.user.id },
|
||||
{ uploaderId: null },
|
||||
],
|
||||
},
|
||||
select: { id: true, seriesId: true },
|
||||
})
|
||||
|
||||
if (!targetNovel) {
|
||||
return NextResponse.json({ error: "Truyện không tồn tại hoặc không đủ quyền" }, { status: 404 })
|
||||
}
|
||||
|
||||
// Disable editing series relation from novel edit form: keep current seriesId.
|
||||
const fixedSeriesId = targetNovel.seriesId
|
||||
|
||||
if (fixedSeriesId) {
|
||||
const sharedData: Record<string, unknown> = {}
|
||||
if (hasField("originalTitle")) sharedData.originalTitle = originalTitle
|
||||
if (hasField("authorName")) sharedData.authorName = authorName
|
||||
if (hasField("originalAuthorName")) sharedData.originalAuthorName = originalAuthorName
|
||||
if (hasField("description")) sharedData.description = description
|
||||
if (hasField("status")) sharedData.status = status
|
||||
|
||||
const ownData: Record<string, unknown> = {}
|
||||
if (hasField("title")) ownData.title = title
|
||||
if (hasField("coverUrl")) ownData.coverUrl = coverUrl
|
||||
if (session.user.role === "MOD") ownData.uploaderId = session.user.id
|
||||
|
||||
const seriesNovels = await prisma.novel.findMany({
|
||||
where: { seriesId: fixedSeriesId },
|
||||
select: { id: true },
|
||||
})
|
||||
const seriesNovelIds = seriesNovels.map((novel) => novel.id)
|
||||
|
||||
const updatedNovel = await prisma.$transaction(async (tx) => {
|
||||
// Sync shared metadata for all novels in the same series.
|
||||
if (Object.keys(sharedData).length > 0) {
|
||||
await tx.novel.updateMany({
|
||||
where: { id: { in: seriesNovelIds } },
|
||||
data: sharedData,
|
||||
})
|
||||
}
|
||||
|
||||
if (genreIds !== undefined) {
|
||||
await tx.novelGenre.deleteMany({
|
||||
where: { novelId: { in: seriesNovelIds } },
|
||||
})
|
||||
|
||||
if (genreIds.length > 0) {
|
||||
await tx.novelGenre.createMany({
|
||||
data: seriesNovelIds.flatMap((novelId) =>
|
||||
genreIds.map((genreId: string) => ({ novelId, genreId }))
|
||||
),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Only current novel keeps its own title and cover.
|
||||
if (Object.keys(ownData).length === 0) {
|
||||
return tx.novel.findUnique({ where: { id } })
|
||||
}
|
||||
|
||||
return tx.novel.update({
|
||||
where: { id },
|
||||
data: ownData,
|
||||
})
|
||||
})
|
||||
|
||||
return NextResponse.json(updatedNovel)
|
||||
}
|
||||
|
||||
const updateData: Record<string, unknown> = {
|
||||
seriesId: fixedSeriesId,
|
||||
...(session.user.role === "MOD" && { uploaderId: session.user.id }),
|
||||
}
|
||||
|
||||
if (hasField("title")) updateData.title = title
|
||||
if (hasField("originalTitle")) updateData.originalTitle = originalTitle
|
||||
if (hasField("authorName")) updateData.authorName = authorName
|
||||
if (hasField("originalAuthorName")) updateData.originalAuthorName = originalAuthorName
|
||||
if (hasField("description")) updateData.description = description
|
||||
if (hasField("coverUrl")) updateData.coverUrl = coverUrl
|
||||
if (hasField("status")) updateData.status = status
|
||||
|
||||
const updatedNovel = await prisma.novel.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...updateData,
|
||||
...(genreIds !== undefined && {
|
||||
genres: {
|
||||
deleteMany: {},
|
||||
create: genreIds.map((gId: string) => ({
|
||||
genre: { connect: { id: gId } }
|
||||
}))
|
||||
}
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
return NextResponse.json(updatedNovel)
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: "Failed to update novel" }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(req: Request) {
|
||||
const session = await getServerSession(authOptions)
|
||||
if (!session || (session.user.role !== "MOD" && session.user.role !== "ADMIN")) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
||||
}
|
||||
|
||||
try {
|
||||
const url = new URL(req.url)
|
||||
const id = url.searchParams.get("id")
|
||||
|
||||
if (!id) return NextResponse.json({ error: "Thiếu ID truyện" }, { status: 400 })
|
||||
|
||||
const novel = await prisma.novel.findFirst({
|
||||
where: session.user.role === "ADMIN"
|
||||
? { id }
|
||||
: {
|
||||
id,
|
||||
OR: [
|
||||
{ uploaderId: session.user.id },
|
||||
{ uploaderId: null },
|
||||
],
|
||||
},
|
||||
select: { id: true, coverUrl: true, seriesId: true }
|
||||
})
|
||||
|
||||
if (!novel) {
|
||||
return NextResponse.json({ error: "Truyện không tồn tại hoặc không đủ quyền" }, { status: 404 })
|
||||
}
|
||||
|
||||
await connectToMongoDB()
|
||||
const chapterDeleteResult = await Chapter.deleteMany({ novelId: id })
|
||||
|
||||
await prisma.novel.delete({
|
||||
where: { id },
|
||||
})
|
||||
|
||||
await deleteR2ObjectByUrl(novel.coverUrl).catch(() => { })
|
||||
|
||||
if (novel.seriesId) {
|
||||
const remainingSeriesNovels = await prisma.novel.count({ where: { seriesId: novel.seriesId } })
|
||||
if (remainingSeriesNovels === 0) {
|
||||
await prisma.series.delete({ where: { id: novel.seriesId } }).catch(() => { })
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
message: "Đã xóa truyện và toàn bộ chương thành công",
|
||||
deletedChapters: chapterDeleteResult.deletedCount || 0
|
||||
})
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: "Failed to delete novel" }, { status: 500 })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { getServerSession } from "next-auth/next"
|
||||
import { authOptions } from "@/lib/auth"
|
||||
import { uploadBufferToR2 } from "@/lib/r2"
|
||||
|
||||
export async function POST(req: Request) {
|
||||
try {
|
||||
const session = await getServerSession(authOptions)
|
||||
if (!session || (session.user.role !== "MOD" && session.user.role !== "ADMIN")) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
||||
}
|
||||
|
||||
const formData = await req.formData()
|
||||
const file = formData.get("file") as File | null
|
||||
|
||||
if (!file) {
|
||||
return NextResponse.json({ error: "No file uploaded" }, { status: 400 })
|
||||
}
|
||||
|
||||
if (!file.type.startsWith("image/")) {
|
||||
return NextResponse.json({ error: "Only image files are allowed" }, { status: 400 })
|
||||
}
|
||||
|
||||
const bytes = await file.arrayBuffer()
|
||||
const buffer = Buffer.from(bytes)
|
||||
|
||||
const url = await uploadBufferToR2({
|
||||
buffer,
|
||||
contentType: file.type,
|
||||
keyPrefix: "covers/manual",
|
||||
fileNameHint: file.name,
|
||||
})
|
||||
|
||||
return NextResponse.json({ url })
|
||||
} catch (error: any) {
|
||||
console.error("Cover upload error:", error)
|
||||
return NextResponse.json({ error: error.message || "Failed to upload cover" }, { status: 500 })
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user