refactor(db): migrate app pages and APIs from Prisma facade to Drizzle (2)

Co-authored-by: Cursor <[email protected]>
This commit is contained in:
SimoandCursor committed 2026-08-01 14:15:28 +02:00
1 parent 7c39aef5d9
commit 2cd0863cb8
40 files changed
+1069 -726

No files matched your search

+16 -9
View File
@@ -1,9 +1,10 @@
import { asc, eq } from "drizzle-orm";
import { ChevronRight } from "lucide-react";
import Link from "next/link";
import { notFound, redirect } from "next/navigation";
import { Fragment } from "react";
import { CatalogPages, db } from "@/lib/db";
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
import { prisma } from "@/lib/prisma";
import { loadCatalogItemsData } from "@/lib/services/catalog-items-loader";
import { getAncestors } from "@/lib/services/catalog-tree";
import { CatalogDetailTabs } from "./catalog-detail-tabs";
@@ -22,18 +23,24 @@ export default async function CatalogEditPage({
const pageId = parseInt(id, 10);
if (Number.isNaN(pageId)) notFound();
const catalogPage = await prisma.catalogPages.findUnique({
where: { id: pageId },
});
const [catalogPage] = await db
.select()
.from(CatalogPages)
.where(eq(CatalogPages.id, pageId))
.limit(1);
if (!catalogPage) notFound();
const [children, itemsData, ancestors] = await Promise.all([
prisma.catalogPages.findMany({
where: { parentId: pageId },
orderBy: { orderNum: "asc" },
select: { id: true, caption: true, enabled: true },
}),
db
.select({
id: CatalogPages.id,
caption: CatalogPages.caption,
enabled: CatalogPages.enabled,
})
.from(CatalogPages)
.where(eq(CatalogPages.parentId, pageId))
.orderBy(asc(CatalogPages.orderNum)),
loadCatalogItemsData(pageId),
getAncestors(catalogPage.parentId),
]);
@@ -1,6 +1,7 @@
import { asc, eq } from "drizzle-orm";
import { notFound, redirect } from "next/navigation";
import { CatalogItemsBc, CatalogPagesBc, db } from "@/lib/db";
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
import { prisma } from "@/lib/prisma";
import { BcPageDetail } from "../bc-manager";
export default async function BcPageDetailPage({
@@ -19,13 +20,18 @@ export default async function BcPageDetailPage({
const canEdit = canAccess(permissions, PERMS.CATALOG_EDIT, session.user.rank);
const bcPage = await prisma.catalogPagesBc.findUnique({ where: { id } });
const [bcPage] = await db
.select()
.from(CatalogPagesBc)
.where(eq(CatalogPagesBc.id, id))
.limit(1);
if (!bcPage) notFound();
const bcItems = await prisma.catalogItemsBc.findMany({
where: { pageId: id },
orderBy: { orderNumber: "asc" },
});
const bcItems = await db
.select()
.from(CatalogItemsBc)
.where(eq(CatalogItemsBc.pageId, id))
.orderBy(asc(CatalogItemsBc.orderNumber));
return (
<BcPageDetail
+184 -106
View File
@@ -1,16 +1,41 @@
import {
and,
asc,
count,
desc,
eq,
inArray,
like,
or,
type SQL,
sql,
} from "drizzle-orm";
import type { AnyMySqlColumn } from "drizzle-orm/mysql-core";
import { Store } from "lucide-react";
import { redirect } from "next/navigation";
import { getTranslations } from "next-intl/server";
import { AdminPageShell } from "@/components/admin/admin-page-shell";
import { CatalogTree } from "@/components/admin/catalog-tree";
import { calcPagination, parseListParams } from "@/lib/admin-helpers";
import {
CatalogItems,
CatalogItemsBc,
CatalogPages,
CatalogPagesBc,
db,
} from "@/lib/db";
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
import { Prisma, prisma } from "@/lib/prisma";
import { getCatalogItemCounts } from "@/lib/services/catalog-tree";
import { CatalogActions } from "./catalog-actions";
import { CatalogManagerDialog } from "./catalog-manager-dialog-wrapper";
import { CatalogTable } from "./catalog-table";
import { CatalogViewToggle } from "./catalog-view-toggle";
async function rawRows<T>(query: ReturnType<typeof sql>): Promise<T[]> {
const [rows] = (await db.execute(query)) as unknown as [T[], unknown];
return rows ?? [];
}
export default async function CatalogPagesPage({
params: paramsPromise,
searchParams,
@@ -33,7 +58,6 @@ export default async function CatalogPagesPage({
const viewMode = sp.get("view") || "tree";
const catalogType = sp.get("catalog") || "normal";
// ── Builder Club mode ──────────────────────────────────────────
type TreeNodeShape = {
id: number;
caption: string;
@@ -48,41 +72,56 @@ export default async function CatalogPagesPage({
};
if (catalogType === "bc") {
const [totalBcPages, totalBcItems, enabledBcPages] = await Promise.all([
prisma.catalogPagesBc.count(),
prisma.catalogItemsBc.count(),
prisma.catalogPagesBc.count({ where: { enabled: "1" } }),
]);
const [totalBcPagesRows, totalBcItemsRows, enabledBcPagesRows] =
await Promise.all([
db.select({ total: count() }).from(CatalogPagesBc),
db.select({ total: count() }).from(CatalogItemsBc),
db
.select({ total: count() })
.from(CatalogPagesBc)
.where(eq(CatalogPagesBc.enabled, "1")),
]);
const totalBcPages = Number(totalBcPagesRows[0]?.total ?? 0);
const totalBcItems = Number(totalBcItemsRows[0]?.total ?? 0);
const enabledBcPages = Number(enabledBcPagesRows[0]?.total ?? 0);
// ── BC tree view ──────────────────────────────────────────────
let bcRootPages: TreeNodeShape[] = [];
if (viewMode === "tree") {
const bcRootRaw = await prisma.catalogPagesBc.findMany({
where: { OR: [{ parentId: -1 }, { parentId: 0 }] },
orderBy: { orderNum: "asc" },
});
const bcRootRaw = await db
.select()
.from(CatalogPagesBc)
.where(
or(eq(CatalogPagesBc.parentId, -1), eq(CatalogPagesBc.parentId, 0)),
)
.orderBy(asc(CatalogPagesBc.orderNum));
const bcRootIds = bcRootRaw.map((p) => p.id);
const [bcChildCounts, bcItemCounts] = await Promise.all([
bcRootIds.length > 0
? prisma.catalogPagesBc.groupBy({
by: ["parentId"],
where: { parentId: { in: bcRootIds } },
_count: true,
})
? db
.select({
parentId: CatalogPagesBc.parentId,
total: count(),
})
.from(CatalogPagesBc)
.where(inArray(CatalogPagesBc.parentId, bcRootIds))
.groupBy(CatalogPagesBc.parentId)
: [],
bcRootIds.length > 0
? prisma.catalogItemsBc.groupBy({
by: ["pageId"],
where: { pageId: { in: bcRootIds } },
_count: true,
})
? db
.select({
pageId: CatalogItemsBc.pageId,
total: count(),
})
.from(CatalogItemsBc)
.where(inArray(CatalogItemsBc.pageId, bcRootIds))
.groupBy(CatalogItemsBc.pageId)
: [],
]);
const bcChildMap = Object.fromEntries(
bcChildCounts.map((c) => [c.parentId, c._count]),
bcChildCounts.map((c) => [c.parentId, Number(c.total)]),
);
const bcItemMap = Object.fromEntries(
bcItemCounts.map((c) => [c.pageId, c._count]),
bcItemCounts.map((c) => [c.pageId, Number(c.total)]),
);
bcRootPages = bcRootRaw.map((p) => ({
id: p.id,
@@ -98,7 +137,6 @@ export default async function CatalogPagesPage({
}));
}
// ── BC table view ─────────────────────────────────────────────
let bcRows: {
id: number;
caption: string;
@@ -119,32 +157,38 @@ export default async function CatalogPagesPage({
const parentId =
parentFilter !== null ? parseInt(parentFilter, 10) : undefined;
const where: Record<string, unknown> = {};
const conditions: SQL[] = [];
const hasParent = parentId !== undefined && !Number.isNaN(parentId);
if (search) {
const pattern = { contains: search };
where.OR = [{ caption: pattern }];
conditions.push(like(CatalogPagesBc.caption, `%${search}%`));
}
if (hasParent) where.parentId = parentId;
if (hasParent) conditions.push(eq(CatalogPagesBc.parentId, parentId));
const where = conditions.length > 0 ? and(...conditions) : undefined;
// Prisma sort key is snake_case for BC model. Translate known keys.
const sortKeyMap: Record<string, string> = {
parentId: "parentId",
pageLayout: "pageLayout",
orderNum: "orderNum",
const sortKeyMap: Record<string, AnyMySqlColumn> = {
parentId: CatalogPagesBc.parentId,
pageLayout: CatalogPagesBc.pageLayout,
orderNum: CatalogPagesBc.orderNum,
caption: CatalogPagesBc.caption,
id: CatalogPagesBc.id,
};
const sortKey = sort ? (sortKeyMap[sort] ?? sort) : "orderNum";
const orderBy = { [sortKey]: sort ? order : "asc" };
const sortCol = sort
? (sortKeyMap[sort] ?? CatalogPagesBc.orderNum)
: CatalogPagesBc.orderNum;
const orderBy =
(sort ? order : "asc") === "desc" ? desc(sortCol) : asc(sortCol);
const [pages, total] = await Promise.all([
prisma.catalogPagesBc.findMany({
where,
orderBy,
skip: (page - 1) * perPage,
take: perPage,
}),
prisma.catalogPagesBc.count({ where }),
const [pages, totalRows] = await Promise.all([
db
.select()
.from(CatalogPagesBc)
.where(where)
.orderBy(orderBy)
.limit(perPage)
.offset((page - 1) * perPage),
db.select({ total: count() }).from(CatalogPagesBc).where(where),
]);
const total = Number(totalRows[0]?.total ?? 0);
bcPagination = calcPagination(total, page, perPage);
@@ -154,31 +198,40 @@ export default async function CatalogPagesPage({
];
const [childCounts, itemCounts, parentPages] = await Promise.all([
pageIds.length > 0
? prisma.catalogPagesBc.groupBy({
by: ["parentId"],
where: { parentId: { in: pageIds } },
_count: true,
})
? db
.select({
parentId: CatalogPagesBc.parentId,
total: count(),
})
.from(CatalogPagesBc)
.where(inArray(CatalogPagesBc.parentId, pageIds))
.groupBy(CatalogPagesBc.parentId)
: [],
pageIds.length > 0
? prisma.catalogItemsBc.groupBy({
by: ["pageId"],
where: { pageId: { in: pageIds } },
_count: true,
})
? db
.select({
pageId: CatalogItemsBc.pageId,
total: count(),
})
.from(CatalogItemsBc)
.where(inArray(CatalogItemsBc.pageId, pageIds))
.groupBy(CatalogItemsBc.pageId)
: [],
parentIds.length > 0
? prisma.catalogPagesBc.findMany({
where: { id: { in: parentIds } },
select: { id: true, caption: true },
})
? db
.select({
id: CatalogPagesBc.id,
caption: CatalogPagesBc.caption,
})
.from(CatalogPagesBc)
.where(inArray(CatalogPagesBc.id, parentIds))
: [],
]);
const childCountMap = Object.fromEntries(
childCounts.map((c) => [c.parentId, c._count]),
childCounts.map((c) => [c.parentId, Number(c.total)]),
);
const itemCountMap = Object.fromEntries(
itemCounts.map((c) => [c.pageId, c._count]),
itemCounts.map((c) => [c.pageId, Number(c.total)]),
);
const parentNameMap = Object.fromEntries(
parentPages.map((p) => [p.id, p.caption]),
@@ -195,7 +248,7 @@ export default async function CatalogPagesPage({
pageLayout: String(p.pageLayout),
enabled: String(p.enabled),
visible: String(p.visible),
minRank: 0, // BC pages have no min rank column
minRank: 0,
orderNum: p.orderNum,
itemCount: itemCountMap[p.id] ?? 0,
childCount: childCountMap[p.id] ?? 0,
@@ -252,33 +305,39 @@ export default async function CatalogPagesPage({
);
}
// ── Normal catalog mode ────────────────────────────────────────
// Global stats (lightweight counts)
const [totalPages, totalItems, enabledPages] = await Promise.all([
prisma.catalogPages.count(),
prisma.catalogItems.count(),
prisma.catalogPages.count({ where: { enabled: "1" } }),
const [totalPagesRows, totalItemsRows, enabledPagesRows] = await Promise.all([
db.select({ total: count() }).from(CatalogPages),
db.select({ total: count() }).from(CatalogItems),
db
.select({ total: count() })
.from(CatalogPages)
.where(eq(CatalogPages.enabled, "1")),
]);
const totalPages = Number(totalPagesRows[0]?.total ?? 0);
const totalItems = Number(totalItemsRows[0]?.total ?? 0);
const enabledPages = Number(enabledPagesRows[0]?.total ?? 0);
// ── Root pages (tree view + Visual Manager seed) ────────────────
const rootPagesRaw = await prisma.catalogPages.findMany({
where: { OR: [{ parentId: -1 }, { parentId: 0 }] },
orderBy: { orderNum: "asc" },
});
const rootPagesRaw = await db
.select()
.from(CatalogPages)
.where(or(eq(CatalogPages.parentId, -1), eq(CatalogPages.parentId, 0)))
.orderBy(asc(CatalogPages.orderNum));
const rootIds = rootPagesRaw.map((p) => p.id);
const [rootChildCounts, rootItemCountMap] = await Promise.all([
rootIds.length > 0
? prisma.catalogPages.groupBy({
by: ["parentId"],
where: { parentId: { in: rootIds } },
_count: true,
})
? db
.select({
parentId: CatalogPages.parentId,
total: count(),
})
.from(CatalogPages)
.where(inArray(CatalogPages.parentId, rootIds))
.groupBy(CatalogPages.parentId)
: [],
getCatalogItemCounts(rootIds),
]);
const rootChildMap = Object.fromEntries(
rootChildCounts.map((c) => [c.parentId, c._count]),
rootChildCounts.map((c) => [c.parentId, Number(c.total)]),
);
const rootItemMap = Object.fromEntries(rootItemCountMap);
const rootPages: TreeNodeShape[] = rootPagesRaw.map((p) => ({
@@ -294,7 +353,6 @@ export default async function CatalogPagesPage({
itemCount: rootItemMap[p.id] ?? 0,
}));
// ── Table view data (skip if tree) ────────────────────────────
let rows: {
id: number;
caption: string;
@@ -315,15 +373,15 @@ export default async function CatalogPagesPage({
const parentId =
parentFilter !== null ? parseInt(parentFilter, 10) : undefined;
const where: Record<string, unknown> = {};
const conditions: SQL[] = [];
const hasParent = parentId !== undefined && !Number.isNaN(parentId);
if (search) {
const searchPattern = `%${search}%`;
const parentClause = hasParent
? Prisma.sql`AND cp.parent_id = ${parentId}`
: Prisma.empty;
? sql`AND cp.parent_id = ${parentId}`
: sql``;
const matchedIds = await prisma.$queryRaw<{ id: number }[]>(Prisma.sql`
const matchedIds = await rawRows<{ id: number }>(sql`
SELECT DISTINCT cp.id FROM catalog_pages cp
LEFT JOIN catalog_items ci ON CAST(ci.page_id AS CHAR) = CAST(cp.id AS CHAR)
LEFT JOIN items_base ib ON FIND_IN_SET(ib.id, REPLACE(ci.item_ids, ';', ','))
@@ -334,48 +392,68 @@ export default async function CatalogPagesPage({
OR ib.item_name LIKE ${searchPattern})
${parentClause}
`);
where.id = { in: matchedIds.map((r) => r.id) };
const ids = matchedIds.map((r) => r.id);
if (ids.length > 0) conditions.push(inArray(CatalogPages.id, ids));
else conditions.push(sql`1 = 0`);
} else if (hasParent) {
where.parentId = parentId;
conditions.push(eq(CatalogPages.parentId, parentId));
}
const orderBy = sort ? { [sort]: order } : { orderNum: "asc" as const };
const where = conditions.length > 0 ? and(...conditions) : undefined;
const sortColMap: Record<string, AnyMySqlColumn> = {
caption: CatalogPages.caption,
parentId: CatalogPages.parentId,
pageLayout: CatalogPages.pageLayout,
enabled: CatalogPages.enabled,
orderNum: CatalogPages.orderNum,
id: CatalogPages.id,
minRank: CatalogPages.minRank,
};
const sortCol = sort
? (sortColMap[sort] ?? CatalogPages.orderNum)
: CatalogPages.orderNum;
const orderBy =
(sort ? order : "asc") === "desc" ? desc(sortCol) : asc(sortCol);
const [pages, total] = await Promise.all([
prisma.catalogPages.findMany({
where,
orderBy,
skip: (page - 1) * perPage,
take: perPage,
}),
prisma.catalogPages.count({ where }),
const [pages, totalRows] = await Promise.all([
db
.select()
.from(CatalogPages)
.where(where)
.orderBy(orderBy)
.limit(perPage)
.offset((page - 1) * perPage),
db.select({ total: count() }).from(CatalogPages).where(where),
]);
const total = Number(totalRows[0]?.total ?? 0);
pagination = calcPagination(total, page, perPage);
// Count children and items per page, and resolve parent names in parallel
const pageIds = pages.map((p) => p.id);
const parentIds = [
...new Set(pages.map((p) => p.parentId).filter((id) => id > 0)),
];
const [childCounts, itemCountMapRaw, parentPages] = await Promise.all([
pageIds.length > 0
? prisma.catalogPages.groupBy({
by: ["parentId"],
where: { parentId: { in: pageIds } },
_count: true,
})
? db
.select({
parentId: CatalogPages.parentId,
total: count(),
})
.from(CatalogPages)
.where(inArray(CatalogPages.parentId, pageIds))
.groupBy(CatalogPages.parentId)
: [],
getCatalogItemCounts(pageIds),
parentIds.length > 0
? prisma.catalogPages.findMany({
where: { id: { in: parentIds } },
select: { id: true, caption: true },
})
? db
.select({ id: CatalogPages.id, caption: CatalogPages.caption })
.from(CatalogPages)
.where(inArray(CatalogPages.id, parentIds))
: [],
]);
const childCountMap = Object.fromEntries(
childCounts.map((c) => [c.parentId, c._count]),
childCounts.map((c) => [c.parentId, Number(c.total)]),
);
const itemCountMap = Object.fromEntries(itemCountMapRaw);
const parentNameMap = Object.fromEntries(