Files
EpicNext-Cms/src/lib/services/habbofurni.ts
T
openhands 1acace49d0
Deploy / release (push) Skipped
Deploy / deploy (push) Failing after 8s
refactor: full codebase overhaul — dead code removal, env validation, logger migration, date consolidation, Prisma schema cleanup, button consistency, useEffect deps, test coverage
- env.ts: added 10 missing Zod-validated env vars (imager, paypal currency, argon2/bcrypt params)
- Migrated 6 modules from process.env to validated env.* (auth, proxy-auth, paypal, password, redis, imager, moderation, alert, logger)
- Replaced console.warn/error with pino logger in 9 server-side modules
- Removed 50+ dead exports (SWF wrappers, coalesceHotelName, signIn, isStaff re-export, formatTimestamp, Skeleton/SkeletonCard, 4 unused housekeeping sections)
- Consolidated date formatting: 28 files migrated to shared formatDate() from @/lib/format-date
- Wired 4 radio/settings API routes through cached siteSettings service instead of raw Prisma queries
- Added getMany()/getAll() helpers to SiteSettings service
- Removed 88 dead Prisma model definitions (schema 2763→1846 lines)
- Created admin action-helper.ts with wrapAction() for standardized error handling
- Fixed useEffect dependency arrays in 4 data-heavy components
- Replaced raw btn CSS classes with shadcn Button component across admin pages
- Stripped dead i18n namespaces (common, pages.client) from all 22 translation files
- Removed 2 dead scripts (create-release.sh, check-local-imports.ts)
- Fixed knip.json configuration
- Added 7 new test suites: format-date, paypal, moderation, alert, webhook, action-helper, and fixed password.test.ts for env mocking
- All 358 tests passing across 72 test files
- TypeScript: 0 errors
2026-07-25 17:33:06 +02:00

166 lines
4.9 KiB
TypeScript

/**
* Furniture search & listing — powered by official Habbo furnidata.
*
* Hotel locale comes from CMS setting `habbo_gamedata_hotel`.
* No third-party APIs (habbofurni.com) needed.
*/
import { logger } from "@/lib/logger";
import type { FurniListResult, HabboFurniItem } from "@/types/furni";
import { getHabboItFurnidata } from "./habbo-furnidata-cache";
export type { FurniListResult, HabboFurniItem };
// ── List / Browse endpoint ────────────────────────────────────────
/**
* List furniture from official Habbo furnidata with optional search and pagination.
* Data comes from the configured hotel furnidata_json (cached 30 min).
*/
export async function listFurniture(
options: {
search?: string;
page?: number;
perPage?: number;
/**
* Optional set of already-imported classnames. When provided, non-imported
* items are sorted to the top so the user finds them on page 1 instead of
* paging through 15+ pages of already-imported newest items.
*/
importedSet?: Set<string>;
} = {},
): Promise<FurniListResult> {
const empty: FurniListResult = {
items: [],
meta: { currentPage: 1, lastPage: 1, total: 0, perPage: 50 },
};
const perPage = Math.min(options.perPage || 50, 100);
const page = options.page || 1;
const search = options.search?.toLowerCase().trim() || "";
const importedSet = options.importedSet;
try {
const map = await getHabboItFurnidata();
if (map.size === 0) return empty;
// Convert to array and optionally filter by search
let items = Array.from(map.values());
if (search) {
items = items.filter(
(item) =>
item.classname.toLowerCase().includes(search) ||
item.name.toLowerCase().includes(search) ||
item.description.toLowerCase().includes(search),
);
}
if (importedSet) {
// Non-imported first (id desc), then imported (id desc).
items.sort((a, b) => {
const aImp = importedSet.has(a.classname) ? 1 : 0;
const bImp = importedSet.has(b.classname) ? 1 : 0;
if (aImp !== bImp) return aImp - bImp;
return b.id - a.id;
});
} else {
// Sort by id descending (newest first)
items.sort((a, b) => b.id - a.id);
}
const total = items.length;
const lastPage = Math.max(Math.ceil(total / perPage), 1);
const start = (page - 1) * perPage;
const pageItems = items.slice(start, start + perPage);
return {
items: pageItems.map((item) => ({
id: item.id,
classname: item.classname,
name: item.name || item.classname,
description: item.description || "",
type: item.itemType === "i" ? "wallitem" : "flooritem",
revision: item.revision,
category: item.category || item.furniline || "",
})),
meta: { currentPage: page, lastPage, total, perPage },
};
} catch (err) {
logger.warn("[furni] List error", { error: (err as Error).message });
return empty;
}
}
// ── Search endpoint ────────────────────────────────────────────────
/**
* Search furniture by query string.
*/
export async function searchFurniture(
query: string,
perPage = 50,
): Promise<HabboFurniItem[]> {
const result = await listFurniture({ search: query, perPage });
return result.items;
}
// ── Direct lookup by classname ─────────────────────────────────────
/**
* Get a single furniture item by classname.
* Uses the cached habbo.it furnidata.
*/
export async function getFurnitureByClassname(
classname: string,
): Promise<HabboFurniItem | null> {
const map = await getHabboItFurnidata();
// Try exact match
let entry = map.get(classname);
// Try without color variant
if (!entry && classname.includes("*")) {
const base = classname.split("*")[0];
entry = map.get(`${base}*0`) || map.get(base);
}
// Try with *0
if (!entry && !classname.includes("*")) {
entry = map.get(`${classname}*0`);
}
if (!entry) return null;
return {
id: entry.id,
classname: entry.classname,
name: entry.name || entry.classname,
description: entry.description || "",
type: entry.itemType === "i" ? "wallitem" : "flooritem",
revision: entry.revision,
category: entry.category || entry.furniline || "",
};
}
// ── Batch lookup ───────────────────────────────────────────────────
/**
* Batch lookup: get data for a list of classnames.
* Much faster than the old habbofurni.com API — single cache lookup, no network.
*/
export async function batchLookupByClassnames(
classnames: string[],
): Promise<Map<string, HabboFurniItem>> {
const result = new Map<string, HabboFurniItem>();
if (classnames.length === 0) return result;
for (const cn of classnames) {
const item = await getFurnitureByClassname(cn);
if (item?.name) {
result.set(cn, item);
}
}
return result;
}