feat(admin): centralize subscriptions under /admin?tab=subscriptions
Replaced the dedicated /admin/subscriptions page with a redirect to the central admin panel’s subscriptions tab. Removed session checks, imports, and the AdminSubscriptionDashboard since routing and access are now handled centrally. This streamlines admin UX and keeps access control unified.
This commit is contained in:
1 parent
d8e7d5d7e6
commit
62ab5b2608
19 files changed
+3091
-357
No files matched your search
@@ -0,0 +1,267 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { prisma } from "@/lib/prisma/app";
|
||||
import { secureLogger } from "@/lib/secure-logger";
|
||||
|
||||
export interface ImportStats {
|
||||
processedTables: number;
|
||||
processedItems: number;
|
||||
inserted: number;
|
||||
skipped: number;
|
||||
}
|
||||
|
||||
const PT_TO_EN_CATEGORY_MAP: Record<string, string> = {
|
||||
espadas: "weapon",
|
||||
armaduras: "armor",
|
||||
capacetes: "helmet",
|
||||
calcas: "legs",
|
||||
botas: "boots",
|
||||
escudos: "shield",
|
||||
amuletos: "amulet",
|
||||
aneis: "ring",
|
||||
runas: "rune",
|
||||
ferramentas: "tool",
|
||||
municao: "ammunition",
|
||||
};
|
||||
|
||||
const SQLITE_EXTRA_FIELDS = [
|
||||
"voc",
|
||||
"volume",
|
||||
"bonus_de_skill",
|
||||
"protecao",
|
||||
"dropa_de",
|
||||
"npc_price",
|
||||
"dropped_by",
|
||||
"tipo",
|
||||
"classe",
|
||||
"atributos",
|
||||
"descricao",
|
||||
"descricao_curta",
|
||||
"descricao_longa",
|
||||
"description",
|
||||
] as const;
|
||||
|
||||
const SQL_CHUNK_SIZE = 250;
|
||||
|
||||
let seedPromise: Promise<ImportStats | null> | null = null;
|
||||
let seedLogged = false;
|
||||
|
||||
function loadBetterSqlite(): any | null {
|
||||
try {
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
return require("better-sqlite3");
|
||||
} catch (error) {
|
||||
secureLogger.warn("better-sqlite3 não está disponível. Importação automática será ignorada.", {
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function openSQLiteDatabase(Database: any) {
|
||||
const dbPath = path.join(process.cwd(), "data", "tibiawiki.db");
|
||||
if (!fs.existsSync(dbPath)) {
|
||||
secureLogger.warn("Base SQLite não encontrada em data/tibiawiki.db. Importação ignorada.");
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return new Database(dbPath, { readonly: true, fileMustExist: true });
|
||||
} catch (error) {
|
||||
secureLogger.error("Falha ao abrir base SQLite", error instanceof Error ? error.message : error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function toNullableInt(value: unknown): number | null {
|
||||
if (value === null || value === undefined || value === "") return null;
|
||||
const parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : null;
|
||||
}
|
||||
|
||||
function toNullableDecimal(value: unknown): Prisma.Decimal | null {
|
||||
if (value === null || value === undefined || value === "") return null;
|
||||
const parsed = Number(value);
|
||||
if (!Number.isFinite(parsed)) return null;
|
||||
return new Prisma.Decimal(parsed);
|
||||
}
|
||||
|
||||
function collectMetadata(row: Record<string, unknown>): Record<string, unknown> {
|
||||
const metadata: Record<string, unknown> = {};
|
||||
|
||||
for (const field of SQLITE_EXTRA_FIELDS) {
|
||||
if (row[field] !== undefined && row[field] !== null && row[field] !== "") {
|
||||
metadata[field] = row[field];
|
||||
}
|
||||
}
|
||||
|
||||
const description =
|
||||
(row.descricao as unknown as string | undefined) ??
|
||||
(row.descricao_longa as unknown as string | undefined) ??
|
||||
(row.description as unknown as string | undefined);
|
||||
|
||||
if (description) {
|
||||
metadata.description = description;
|
||||
}
|
||||
|
||||
return metadata;
|
||||
}
|
||||
|
||||
function normalizeCategory(tableName: string): string {
|
||||
return PT_TO_EN_CATEGORY_MAP[tableName] ?? tableName;
|
||||
}
|
||||
|
||||
export async function importItemsFromSQLite(): Promise<ImportStats> {
|
||||
const Database = loadBetterSqlite();
|
||||
if (!Database) {
|
||||
return { processedTables: 0, processedItems: 0, inserted: 0, skipped: 0 };
|
||||
}
|
||||
|
||||
const db = openSQLiteDatabase(Database);
|
||||
if (!db) {
|
||||
return { processedTables: 0, processedItems: 0, inserted: 0, skipped: 0 };
|
||||
}
|
||||
|
||||
try {
|
||||
const tables = db
|
||||
.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")
|
||||
.all() as { name: string }[];
|
||||
|
||||
let processedTables = 0;
|
||||
let processedItems = 0;
|
||||
let inserted = 0;
|
||||
let skipped = 0;
|
||||
|
||||
const batch: Prisma.ItemCreateManyInput[] = [];
|
||||
|
||||
for (const { name: tableName } of tables) {
|
||||
const pragma = db.prepare(`PRAGMA table_info(${tableName})`).all() as Array<{
|
||||
name: string;
|
||||
}>;
|
||||
const colNames = new Set(pragma.map((col) => col.name.toLowerCase()));
|
||||
|
||||
const hasId = colNames.has("id");
|
||||
const hasNome = colNames.has("nome") || colNames.has("name");
|
||||
|
||||
if (!hasId || !hasNome) {
|
||||
continue;
|
||||
}
|
||||
|
||||
processedTables += 1;
|
||||
const rows = db.prepare(`SELECT * FROM ${tableName}`).all() as Record<string, unknown>[];
|
||||
|
||||
for (const row of rows) {
|
||||
processedItems += 1;
|
||||
|
||||
const rawId = row.id ?? row.item_id;
|
||||
const numericId = toNullableInt(rawId);
|
||||
if (!numericId) {
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const nameField = (row.nome ?? row.name ?? "") as string;
|
||||
const itemName = typeof nameField === "string" ? nameField.trim() : "";
|
||||
if (!itemName) {
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const imageUrl = (row.image_url ?? row.image ?? null) as string | null;
|
||||
const imageLocalPath = (row.image_local_path ?? row.image_local ?? null) as string | null;
|
||||
const rarity =
|
||||
(row.rarity ?? row.raridade ?? row.rareza ?? null) !== null
|
||||
? String(row.rarity ?? row.raridade ?? row.rareza)
|
||||
: null;
|
||||
const level = toNullableInt(row.lvl ?? row.nivel ?? row.level);
|
||||
const weight = toNullableDecimal(row.peso ?? row.peso_em_oz ?? row.weight);
|
||||
const slots = toNullableInt(row.slots ?? row.slot);
|
||||
const skill =
|
||||
row.skill_para_usar ?? row.skill_required ?? row.skill ?? null
|
||||
? String(row.skill_para_usar ?? row.skill_required ?? row.skill)
|
||||
: null;
|
||||
|
||||
const metadata = collectMetadata(row);
|
||||
const metadataPayload = metadata as Prisma.InputJsonValue;
|
||||
|
||||
batch.push({
|
||||
source_table_id: numericId,
|
||||
source_table_name: tableName,
|
||||
item_name: itemName,
|
||||
category: normalizeCategory(tableName),
|
||||
image_local_path: imageLocalPath,
|
||||
image_url: imageUrl,
|
||||
rarity,
|
||||
level,
|
||||
weight,
|
||||
slots,
|
||||
skill,
|
||||
metadata: metadataPayload,
|
||||
});
|
||||
|
||||
if (batch.length >= SQL_CHUNK_SIZE) {
|
||||
const { count } = await prisma.item.createMany({
|
||||
data: batch,
|
||||
skipDuplicates: true,
|
||||
});
|
||||
inserted += count;
|
||||
skipped += batch.length - count;
|
||||
batch.length = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (batch.length > 0) {
|
||||
const { count } = await prisma.item.createMany({
|
||||
data: batch,
|
||||
skipDuplicates: true,
|
||||
});
|
||||
inserted += count;
|
||||
skipped += batch.length - count;
|
||||
}
|
||||
|
||||
return { processedTables, processedItems, inserted, skipped };
|
||||
} finally {
|
||||
try {
|
||||
db.close();
|
||||
} catch {
|
||||
// ignore close errors
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function ensureItemsSeeded(): Promise<ImportStats | null> {
|
||||
if (seedPromise) {
|
||||
return seedPromise;
|
||||
}
|
||||
|
||||
seedPromise = (async () => {
|
||||
const currentCount = await prisma.item.count();
|
||||
if (!seedLogged) {
|
||||
seedLogged = true;
|
||||
secureLogger.info("Verificação da tabela items concluída", { existing: currentCount });
|
||||
}
|
||||
|
||||
if (currentCount > 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
secureLogger.info("Tabela items vazia. Iniciando importação automática a partir do SQLite.");
|
||||
try {
|
||||
const stats = await importItemsFromSQLite();
|
||||
secureLogger.info("Importação de itens concluída", stats);
|
||||
return stats;
|
||||
} catch (error) {
|
||||
secureLogger.error("Falha na importação automática de itens", error);
|
||||
throw error;
|
||||
}
|
||||
})();
|
||||
|
||||
try {
|
||||
return await seedPromise;
|
||||
} finally {
|
||||
seedPromise = null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
export type SQLiteColumnType = "TEXT" | "INTEGER" | "REAL" | "BOOLEAN";
|
||||
|
||||
export interface SQLiteColumnDefinition {
|
||||
name: string;
|
||||
type: SQLiteColumnType;
|
||||
notNull?: boolean;
|
||||
defaultValue?: string | number | null;
|
||||
editable?: boolean;
|
||||
primaryKey?: boolean;
|
||||
}
|
||||
|
||||
export interface CategoryTemplate {
|
||||
name: string;
|
||||
columns: SQLiteColumnDefinition[];
|
||||
imagePath: string;
|
||||
}
|
||||
|
||||
const BASE_COLUMNS: SQLiteColumnDefinition[] = [
|
||||
{ name: "id", type: "INTEGER", primaryKey: true, notNull: true, editable: false },
|
||||
{ name: "nome", type: "TEXT", notNull: true, editable: true },
|
||||
{ name: "image_url", type: "TEXT", editable: true },
|
||||
{ name: "image_local_path", type: "TEXT", editable: true },
|
||||
];
|
||||
|
||||
const SQLITE_DB_PATH = path.join(process.cwd(), "data", "tibiawiki.db");
|
||||
const IMAGES_ROOT = path.join(process.cwd(), "data", "images");
|
||||
|
||||
let cachedDatabase: any | null = null;
|
||||
|
||||
function loadBetterSqlite(): any {
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
const Database = require("better-sqlite3");
|
||||
return Database;
|
||||
}
|
||||
|
||||
function getDatabase(): any {
|
||||
if (cachedDatabase) {
|
||||
return cachedDatabase;
|
||||
}
|
||||
|
||||
if (!fs.existsSync(SQLITE_DB_PATH)) {
|
||||
throw new Error("Banco SQLite tibiawiki.db não encontrado em data/");
|
||||
}
|
||||
|
||||
const Database = loadBetterSqlite();
|
||||
cachedDatabase = new Database(SQLITE_DB_PATH, { fileMustExist: true });
|
||||
return cachedDatabase;
|
||||
}
|
||||
|
||||
function normalizeColumnType(type: SQLiteColumnType | string): SQLiteColumnType {
|
||||
const upper = type.toUpperCase();
|
||||
switch (upper) {
|
||||
case "INTEGER":
|
||||
case "INT":
|
||||
return "INTEGER";
|
||||
case "REAL":
|
||||
case "FLOAT":
|
||||
case "DOUBLE":
|
||||
return "REAL";
|
||||
case "BOOLEAN":
|
||||
return "BOOLEAN";
|
||||
default:
|
||||
return "TEXT";
|
||||
}
|
||||
}
|
||||
|
||||
function sqliteTypeFromColumn(column: SQLiteColumnDefinition): string {
|
||||
const type = normalizeColumnType(column.type);
|
||||
if (type === "BOOLEAN") {
|
||||
return "INTEGER";
|
||||
}
|
||||
return type;
|
||||
}
|
||||
|
||||
function ensureImageDirectory(category: string) {
|
||||
const dir = path.join(IMAGES_ROOT, category);
|
||||
if (!fs.existsSync(dir)) {
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
}
|
||||
}
|
||||
|
||||
function mapPragmaColumns(columns: Array<{ name: string; type: string; notnull: number; pk: number }>): SQLiteColumnDefinition[] {
|
||||
const mapped = columns.map((column) => {
|
||||
const baseMatch = BASE_COLUMNS.find((base) => base.name === column.name);
|
||||
return {
|
||||
name: column.name,
|
||||
type: normalizeColumnType(column.type as SQLiteColumnType),
|
||||
notNull: column.notnull === 1,
|
||||
primaryKey: column.pk === 1,
|
||||
editable: baseMatch ? baseMatch.editable : column.pk !== 1,
|
||||
} satisfies SQLiteColumnDefinition;
|
||||
});
|
||||
|
||||
return mapped;
|
||||
}
|
||||
|
||||
export function listCategoryTemplates(): CategoryTemplate[] {
|
||||
const db = getDatabase();
|
||||
const tables = db
|
||||
.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")
|
||||
.all() as Array<{ name: string }>;
|
||||
|
||||
return tables.map((table) => {
|
||||
const pragma = db.prepare(`PRAGMA table_info(${table.name})`).all() as Array<{
|
||||
name: string;
|
||||
type: string;
|
||||
notnull: number;
|
||||
pk: number;
|
||||
}>;
|
||||
|
||||
const columns = mapPragmaColumns(pragma);
|
||||
ensureImageDirectory(table.name);
|
||||
|
||||
return {
|
||||
name: table.name,
|
||||
columns,
|
||||
imagePath: path.join("data", "images", table.name),
|
||||
} satisfies CategoryTemplate;
|
||||
});
|
||||
}
|
||||
|
||||
function validateCategoryName(name: string) {
|
||||
if (!/^[a-z0-9_]+$/i.test(name)) {
|
||||
throw new Error("Nome da categoria deve conter apenas letras, números ou sublinhado.");
|
||||
}
|
||||
}
|
||||
|
||||
export interface CreateCategoryInput {
|
||||
name: string;
|
||||
columns?: SQLiteColumnDefinition[];
|
||||
}
|
||||
|
||||
export function createCategoryTemplate(input: CreateCategoryInput): CategoryTemplate {
|
||||
const db = getDatabase();
|
||||
const name = input.name.trim().toLowerCase();
|
||||
validateCategoryName(name);
|
||||
|
||||
const existing = db
|
||||
.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name = ?")
|
||||
.get(name) as { name: string } | undefined;
|
||||
|
||||
if (existing) {
|
||||
throw new Error("Categoria já existe.");
|
||||
}
|
||||
|
||||
const userColumns = (input.columns ?? []).map((column) => ({
|
||||
...column,
|
||||
type: normalizeColumnType(column.type),
|
||||
}));
|
||||
|
||||
const columnsSql = [
|
||||
...BASE_COLUMNS.map((column) => {
|
||||
const pieces = [column.name, sqliteTypeFromColumn(column)];
|
||||
if (column.primaryKey) pieces.push("PRIMARY KEY AUTOINCREMENT");
|
||||
if (column.notNull) pieces.push("NOT NULL");
|
||||
return pieces.join(" ");
|
||||
}),
|
||||
...userColumns.map((column) => {
|
||||
const pieces = [column.name, sqliteTypeFromColumn(column)];
|
||||
if (column.notNull) pieces.push("NOT NULL");
|
||||
if (column.defaultValue !== undefined && column.defaultValue !== null) {
|
||||
pieces.push(`DEFAULT ${JSON.stringify(column.defaultValue)}`);
|
||||
}
|
||||
return pieces.join(" ");
|
||||
}),
|
||||
];
|
||||
|
||||
const createSql = `CREATE TABLE ${name} (${columnsSql.join(", ")})`;
|
||||
db.prepare(createSql).run();
|
||||
ensureImageDirectory(name);
|
||||
|
||||
return {
|
||||
name,
|
||||
columns: [...BASE_COLUMNS, ...userColumns],
|
||||
imagePath: path.join("data", "images", name),
|
||||
} satisfies CategoryTemplate;
|
||||
}
|
||||
|
||||
export interface AddColumnInput {
|
||||
category: string;
|
||||
column: SQLiteColumnDefinition;
|
||||
}
|
||||
|
||||
export function addColumnToCategory(input: AddColumnInput): SQLiteColumnDefinition {
|
||||
const db = getDatabase();
|
||||
const name = input.category.trim().toLowerCase();
|
||||
validateCategoryName(name);
|
||||
|
||||
const column = {
|
||||
...input.column,
|
||||
type: normalizeColumnType(input.column.type),
|
||||
} satisfies SQLiteColumnDefinition;
|
||||
|
||||
const columnSqlParts = [column.name, sqliteTypeFromColumn(column)];
|
||||
if (column.notNull) columnSqlParts.push("NOT NULL");
|
||||
if (column.defaultValue !== undefined && column.defaultValue !== null) {
|
||||
columnSqlParts.push(`DEFAULT ${JSON.stringify(column.defaultValue)}`);
|
||||
}
|
||||
|
||||
const sql = `ALTER TABLE ${name} ADD COLUMN ${columnSqlParts.join(" ")}`;
|
||||
db.prepare(sql).run();
|
||||
|
||||
return column;
|
||||
}
|
||||
|
||||
export interface UpsertItemInput {
|
||||
category: string;
|
||||
data: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export function insertCategoryItem(input: UpsertItemInput): number {
|
||||
const db = getDatabase();
|
||||
const category = input.category.trim().toLowerCase();
|
||||
validateCategoryName(category);
|
||||
|
||||
const data = { ...input.data };
|
||||
delete data.id;
|
||||
|
||||
const keys = Object.keys(data);
|
||||
const placeholders = keys.map(() => "?").join(", ");
|
||||
const sql = `INSERT INTO ${category} (${keys.join(", ")}) VALUES (${placeholders})`;
|
||||
|
||||
const values = keys.map((key) => {
|
||||
const value = data[key];
|
||||
if (typeof value === "boolean") {
|
||||
return value ? 1 : 0;
|
||||
}
|
||||
return value;
|
||||
});
|
||||
|
||||
const result = db.prepare(sql).run(...values);
|
||||
return Number(result.lastInsertRowid);
|
||||
}
|
||||
|
||||
export function updateCategoryItem(category: string, id: number, data: Record<string, unknown>) {
|
||||
const db = getDatabase();
|
||||
const normalized = category.trim().toLowerCase();
|
||||
validateCategoryName(normalized);
|
||||
|
||||
const payload = { ...data };
|
||||
delete payload.id;
|
||||
|
||||
const keys = Object.keys(payload);
|
||||
const assignments = keys.map((key) => `${key} = ?`).join(", ");
|
||||
const sql = `UPDATE ${normalized} SET ${assignments} WHERE id = ?`;
|
||||
const values = keys.map((key) => {
|
||||
const value = payload[key];
|
||||
if (typeof value === "boolean") return value ? 1 : 0;
|
||||
return value;
|
||||
});
|
||||
|
||||
db.prepare(sql).run(...values, id);
|
||||
}
|
||||
|
||||
export function getCategoryItem(category: string, id: number): Record<string, unknown> | null {
|
||||
const db = getDatabase();
|
||||
const normalized = category.trim().toLowerCase();
|
||||
validateCategoryName(normalized);
|
||||
|
||||
const row = db.prepare(`SELECT * FROM ${normalized} WHERE id = ?`).get(id);
|
||||
if (!row) return null;
|
||||
|
||||
const result: Record<string, unknown> = { ...row };
|
||||
for (const [key, value] of Object.entries(result)) {
|
||||
if (typeof value === "number") {
|
||||
const template = BASE_COLUMNS.find((column) => column.name === key);
|
||||
if (!template) {
|
||||
// Heuristic: columns stored as BOOLEAN use 0/1
|
||||
// If column type is INTEGER but values only 0/1, mantain numeric to allow consumer decide.
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
Reference in new issue
Block a user