Compare commits
76
Commits
458972fdfd
...
v1.0.3
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
52459c0b74 | ||
|
|
a640e40a5d | ||
|
|
649e2f0663 | ||
|
|
1a9b361420 | ||
|
|
3e0ba73d1c | ||
|
|
bef1775dea | ||
|
|
c5284e0b79 | ||
|
|
539e6d3fad | ||
|
|
7033d65846 | ||
|
|
35d0f3ee01 | ||
|
|
93a7e9a7c2 | ||
|
|
08321df2aa | ||
|
|
55a47949f1 | ||
|
|
0bedc04692 | ||
|
|
814d8650be | ||
|
|
193b6686a9 | ||
|
|
16f35568f5 | ||
|
|
3f2f2c6ed1 | ||
|
|
75dc84d9f1 | ||
|
|
fea8023ac6 | ||
|
|
d1003bb89b | ||
|
|
9b0ea2fb16 | ||
|
|
ef94646d60 | ||
|
|
96234075f8 | ||
|
|
a070004e7b | ||
|
|
35f66d879f | ||
|
|
9dc9d1fa4b | ||
|
|
251738fdda | ||
|
|
b5dcadb67b | ||
|
|
7c1f109a9d | ||
|
|
85a6df162b | ||
|
|
2840ef5d9d | ||
|
|
31691c1c7d | ||
|
|
6146995758 | ||
|
|
9ae03056e2 | ||
|
|
9bc0834bbb | ||
|
|
8c12fc6c60 | ||
|
|
b12e405b34 | ||
|
|
8b59bd1d2d | ||
|
|
180129699c | ||
|
|
51d1284950 | ||
|
|
85facd349a | ||
|
|
fdbb143558 | ||
|
|
226d280c22 | ||
|
|
667637f8da | ||
|
|
98b0009206 | ||
|
|
816e3875c2 | ||
|
|
c6b919c01d | ||
|
|
e17346ab9f | ||
|
|
3ae4f21217 | ||
|
|
570f3dde44 | ||
|
|
3c24df9b1d | ||
|
|
dcb5f46eed | ||
|
|
cd75361b9f | ||
|
|
08b0b5021e | ||
|
|
2619bec165 | ||
|
|
775d14f861 | ||
|
|
2d14e02a68 | ||
|
|
33b6d1520e | ||
|
|
f0dcbee162 | ||
|
|
159b1f7d1b | ||
|
|
8c1efae296 | ||
|
|
8a919f85b2 | ||
|
|
7880d5d5df | ||
|
|
a78d8256e0 | ||
|
|
9dc6b8a261 | ||
|
|
9f791ba284 | ||
|
|
26f071117b | ||
|
|
2578bf6a09 | ||
|
|
bf126fd825 | ||
|
|
bfdf4def0f | ||
|
|
b6d866b087 | ||
|
|
c0c6926309 | ||
|
|
9ec9ab31ad | ||
|
|
bfbf244141 | ||
|
|
4795ed4f8f |
No files matched your search
Whitespace-only changes.
@@ -7,6 +7,12 @@ storage
|
|||||||
prod.log
|
prod.log
|
||||||
update.log
|
update.log
|
||||||
.pm2
|
.pm2
|
||||||
|
# Only the pnpm lockfile is used. Ignore other lockfile formats and stray
|
||||||
|
# package managers so they never taint the build context by accident.
|
||||||
|
package-lock.json
|
||||||
|
yarn.lock
|
||||||
|
bun.lockb
|
||||||
|
.npmrc.bak
|
||||||
# NOTE: .env is intentionally NOT ignored here — the build loads it (only inside
|
# NOTE: .env is intentionally NOT ignored here — the build loads it (only inside
|
||||||
# a build RUN layer) to produce NEXT_PUBLIC_* + validated build-time values.
|
# a build RUN layer) to produce NEXT_PUBLIC_* + validated build-time values.
|
||||||
# It is not copied into the runtime image (the runner stage copies only
|
# It is not copied into the runtime image (the runner stage copies only
|
||||||
|
|||||||
@@ -76,3 +76,8 @@ LOG_LEVEL=error
|
|||||||
|
|
||||||
# --- FLARESOLVERR (Cloudflare bypass for clone sources) ---
|
# --- FLARESOLVERR (Cloudflare bypass for clone sources) ---
|
||||||
FLARESOLVERR_URL=http://localhost:8191
|
FLARESOLVERR_URL=http://localhost:8191
|
||||||
|
|
||||||
|
# Catalog Studio export: dedicated clean clone on Beta-3 with Git push credentials.
|
||||||
|
CATALOG_GIT_CHECKOUT=
|
||||||
|
# Persistent directory shared by CMS and worker, outside the catalog clone.
|
||||||
|
CATALOG_GIT_STATE_DIR=
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
.husky/* text eol=lf
|
||||||
|
*.sh text eol=lf
|
||||||
+15
-119
@@ -31,9 +31,15 @@ jobs:
|
|||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: pnpm install --frozen-lockfile
|
run: pnpm install --frozen-lockfile
|
||||||
|
|
||||||
|
- name: Dependency security audit
|
||||||
|
run: pnpm deps:audit
|
||||||
|
|
||||||
- name: Lint
|
- name: Lint
|
||||||
run: pnpm biome:lint
|
run: pnpm biome:lint
|
||||||
|
|
||||||
|
- name: CMS translation contracts
|
||||||
|
run: pnpm i18n:check
|
||||||
|
|
||||||
- name: Typecheck
|
- name: Typecheck
|
||||||
run: pnpm typecheck
|
run: pnpm typecheck
|
||||||
|
|
||||||
@@ -45,7 +51,12 @@ jobs:
|
|||||||
REDIS_URL: "redis://127.0.0.1:6379?connect_timeout=2"
|
REDIS_URL: "redis://127.0.0.1:6379?connect_timeout=2"
|
||||||
AUTH_SECRET: "ci-test-secret-key-that-is-long-enough"
|
AUTH_SECRET: "ci-test-secret-key-that-is-long-enough"
|
||||||
BCRYPT_ROUNDS: 4
|
BCRYPT_ROUNDS: 4
|
||||||
run: pnpm test --maxWorkers=1
|
run: |
|
||||||
|
if [ -x /usr/bin/time ]; then
|
||||||
|
/usr/bin/time -f 'Tests: %e seconds; peak process RSS: %M KiB' pnpm test --maxWorkers=2
|
||||||
|
else
|
||||||
|
time pnpm test --maxWorkers=2
|
||||||
|
fi
|
||||||
|
|
||||||
- name: Knip (unused files/exports)
|
- name: Knip (unused files/exports)
|
||||||
run: pnpm knip
|
run: pnpm knip
|
||||||
@@ -66,123 +77,8 @@ jobs:
|
|||||||
repository: ${{ gitea.repository }}
|
repository: ${{ gitea.repository }}
|
||||||
token: ${{ gitea.token }}
|
token: ${{ gitea.token }}
|
||||||
|
|
||||||
- name: Provide production env for build
|
- name: Build, deploy and smoke test
|
||||||
run: |
|
|
||||||
# De Next.js-build bakt NEXT_PUBLIC_* in de client-bundle en
|
|
||||||
# valideert DATABASE_URL/HOTEL_NAME (zie src/env.ts — validatie
|
|
||||||
# overslaan is verboden voor productie). .env staat niet in git,
|
|
||||||
# dus kopieer de productie-.env van de host in de build-context.
|
|
||||||
# Hij belandt alleen in de wegwerp-builder-stage, niet in de
|
|
||||||
# runtime-image (die krijgt env via -e flags bij docker run).
|
|
||||||
cp /var/www/atom-nexst/.env .env
|
|
||||||
|
|
||||||
- name: Build image
|
|
||||||
run: |
|
|
||||||
# --network=host is vereist: deze host heeft Docker iptables
|
|
||||||
# uitgeschakeld, dus build-containers op het bridge-netwerk
|
|
||||||
# hebben geen outbound internet (npm/pnpm zouden hangen).
|
|
||||||
DOCKER_BUILDKIT=1 docker build \
|
|
||||||
--network=host \
|
|
||||||
--build-arg NODE_OPTIONS="--max-old-space-size=1536" \
|
|
||||||
--cache-from epicnext-cms:latest \
|
|
||||||
-t epicnext-cms:latest .
|
|
||||||
|
|
||||||
- name: Run migrations
|
|
||||||
run: |
|
|
||||||
# Draai DB-migraties van deze commit op de host (de slimme
|
|
||||||
# runtime-image heeft geen source/tsx, zie docker-compose.yml).
|
|
||||||
# Idempotent: al toegepaste migraties worden overgeslagen.
|
|
||||||
# Gebruikt .env uit de eerdere stap (productie-DB). Vóór het
|
|
||||||
# vervangen van de container, zodat het schema klaarstaat.
|
|
||||||
pnpm install --frozen-lockfile
|
|
||||||
pnpm db:migrate
|
|
||||||
|
|
||||||
- name: Deploy container
|
|
||||||
shell: bash
|
shell: bash
|
||||||
run: |
|
|
||||||
# Maak poort 3002 vrij: stop zowel de vorige CI-container als de
|
|
||||||
# compose-container (beide draaien op het host-netwerk).
|
|
||||||
docker stop epicnext-cms-app 2>/dev/null || true
|
|
||||||
docker rm epicnext-cms-app 2>/dev/null || true
|
|
||||||
docker stop epicnext-cms 2>/dev/null || true
|
|
||||||
docker rm epicnext-cms 2>/dev/null || true
|
|
||||||
|
|
||||||
# Geef de productie-env 1-op-1 door. GEEN env-file-flag: `docker run`
|
|
||||||
# behoudt letterlijke quotes uit het bestand (DATABASE_URL="..." →
|
|
||||||
# ongeldige URL en crash), terwijl de shell ze correct stript.
|
|
||||||
# Sourcen + elke sleutel met -e doorgeven geeft de container exact
|
|
||||||
# dezelfde waarden als waarmee de image gebouwd is.
|
|
||||||
set -a
|
|
||||||
# shellcheck disable=SC1091
|
|
||||||
. /var/www/atom-nexst/.env
|
|
||||||
set +a
|
|
||||||
ENV_ARGS=()
|
|
||||||
while IFS='=' read -r key _; do
|
|
||||||
case "$key" in
|
|
||||||
''|'#'*|*[!A-Za-z0-9_]* ) continue ;;
|
|
||||||
esac
|
|
||||||
ENV_ARGS+=(-e "$key")
|
|
||||||
done < /var/www/atom-nexst/.env
|
|
||||||
|
|
||||||
# Zelfde env + volumes als docker-compose.yml, zodat de CI-container
|
|
||||||
# functioneel gelijk is aan de compose-container die hij vervangt.
|
|
||||||
docker run -d \
|
|
||||||
--name epicnext-cms-app \
|
|
||||||
--restart always \
|
|
||||||
--net=host \
|
|
||||||
"${ENV_ARGS[@]}" \
|
|
||||||
-v /var/www/atom-nexst/public/nitro-assets:/app/public/nitro-assets \
|
|
||||||
-v /var/www/atom-nexst/public/swf:/app/public/swf \
|
|
||||||
-v /var/www/atom-nexst/storage:/app/storage \
|
|
||||||
-v /var/www/Gamedata:/var/www/Gamedata \
|
|
||||||
epicnext-cms:latest
|
|
||||||
|
|
||||||
docker image prune -f
|
|
||||||
|
|
||||||
- name: Health check
|
|
||||||
run: |
|
|
||||||
for i in $(seq 1 30); do
|
|
||||||
if curl -sf --max-time 5 http://127.0.0.1:3002/api/health \
|
|
||||||
| grep -q '"database":true'; then
|
|
||||||
echo "Deploy OK"
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
echo "Waiting... ($i/30)"
|
|
||||||
sleep 3
|
|
||||||
done
|
|
||||||
|
|
||||||
echo "ERROR: Health check failed" >&2
|
|
||||||
docker logs epicnext-cms-app --tail 50 >&2 || true
|
|
||||||
echo "Rolling back to compose container..." >&2
|
|
||||||
docker stop epicnext-cms-app 2>/dev/null || true
|
|
||||||
docker rm epicnext-cms-app 2>/dev/null || true
|
|
||||||
docker compose -f /var/www/atom-nexst/docker-compose.yml up -d --no-build 2>&1 || true
|
|
||||||
exit 1
|
|
||||||
|
|
||||||
# ─────────────────────────────────────────────
|
|
||||||
# E2E smoke against the freshly deployed container.
|
|
||||||
# Runs after a successful deploy on main/master only
|
|
||||||
# (on PRs the deploy job is skipped, so this is skipped too).
|
|
||||||
# Public read-only endpoints only — safe against production.
|
|
||||||
# ─────────────────────────────────────────────
|
|
||||||
e2e:
|
|
||||||
needs: deploy
|
|
||||||
if: gitea.event_name == 'push' && (gitea.ref_name == 'main' || gitea.ref_name == 'master')
|
|
||||||
runs-on: self-hosted
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
repository: ${{ gitea.repository }}
|
|
||||||
token: ${{ gitea.token }}
|
|
||||||
|
|
||||||
- name: Install dependencies
|
|
||||||
run: pnpm install --frozen-lockfile
|
|
||||||
|
|
||||||
- name: Install Playwright browser
|
|
||||||
run: pnpm exec playwright install chromium
|
|
||||||
|
|
||||||
- name: Smoke test deployed app
|
|
||||||
env:
|
env:
|
||||||
PLAYWRIGHT_BASE_URL: "http://127.0.0.1:3002"
|
DEPLOY_BRANCH: ${{ gitea.ref_name }}
|
||||||
run: pnpm test:e2e
|
run: bash scripts/ci-deploy.sh
|
||||||
@@ -39,3 +39,5 @@ test-results/
|
|||||||
playwright-report/
|
playwright-report/
|
||||||
blob-report/
|
blob-report/
|
||||||
.aider*
|
.aider*
|
||||||
|
|
||||||
|
/public/vendor/tinymce/
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
# Catalog Studio repository export
|
||||||
|
|
||||||
|
Studio mutations automatically queue an export to
|
||||||
|
`https://gitlab.epicnabbo.nl/remco/Epicnabbo-Catalogus-Updated-Daily.git`, branch
|
||||||
|
`Beta-3`. The jobs worker processes pending exports every minute. Streaming
|
||||||
|
imports stay active until their stream completes. Server actions for catalog
|
||||||
|
pages, offers, deletion and maintenance are covered as well.
|
||||||
|
|
||||||
|
## Server setup
|
||||||
|
|
||||||
|
1. Create a **dedicated clean clone** of the repository on `Beta-3`, outside the
|
||||||
|
CMS directory. Configure non-interactive Git push authentication for the
|
||||||
|
worker OS account using its credential helper. Do not put tokens in URLs.
|
||||||
|
2. Set `CATALOG_GIT_CHECKOUT` to that absolute clone directory in the CMS and
|
||||||
|
worker environments. Set `CATALOG_GIT_STATE_DIR` to a persistent, writable
|
||||||
|
directory outside the clone, shared by both processes on the same host.
|
||||||
|
3. Run `pnpm jobs:worker` alongside the CMS under your process supervisor.
|
||||||
|
Both processes must have access to the configured asset directories and DB.
|
||||||
|
The worker command enables the React server condition for server-only modules.
|
||||||
|
4. Restart the CMS after setting the environment. In **Studio → Sync**, use
|
||||||
|
**Export now / retry** for the initial export. Subsequent mutations queue
|
||||||
|
automatically. Status shows pending/active operations and the last commit.
|
||||||
|
|
||||||
|
Leaving `CATALOG_GIT_CHECKOUT` empty disables export. No credentials are shipped.
|
||||||
|
This source change alone does not configure or deploy the production service.
|
||||||
|
|
||||||
|
## Exported content
|
||||||
|
|
||||||
|
| Source | Repository destination |
|
||||||
|
| --- | --- |
|
||||||
|
| Configured Nitro bundles, including furniture, figures, effects and pets | `Gamedata/bundled` |
|
||||||
|
| Configured furni icons | `Gamedata/icons` |
|
||||||
|
| Existing badge/catalog images | `Gamedata/c_images` |
|
||||||
|
| FurnitureData and supported public game-data JSON files | `Gamedata/config` |
|
||||||
|
| Existing localized FurnitureData files | `catalogue version 2 ( Final (Dev)/langs furnidata` |
|
||||||
|
| `items_base`, `catalog_pages`, `catalog_items` | `catalogue version 2 ( Final (Dev)/sqls` |
|
||||||
|
| `catalog_pages_bc`, `catalog_items_bc`, when present | Same SQL directory |
|
||||||
|
|
||||||
|
SQL is read in one consistent, read-only InnoDB transaction. Dumps contain table
|
||||||
|
definitions and deterministic upserts with hexadecimal UTF-8 string literals.
|
||||||
|
Import `items_base.sql`, then `catalog_pages.sql`, then `catalog_items.sql`.
|
||||||
|
Existing schemas are not migrated by these dumps. Rows absent from the source
|
||||||
|
are omitted; importing an upsert dump into another existing database does not
|
||||||
|
delete that database's extra rows. No user, session or credential tables are exported.
|
||||||
|
|
||||||
|
Only existing local assets are exported. Translation generation follows Studio's
|
||||||
|
existing setting; export does not generate missing languages or download assets.
|
||||||
|
Public JSON is explicitly allowlisted so translation caches and private runtime
|
||||||
|
files cannot enter the repository. Invalid JSON or concurrent Studio changes
|
||||||
|
prevent publication of that snapshot.
|
||||||
|
|
||||||
|
## Failure and concurrency behavior
|
||||||
|
|
||||||
|
- Pending events survive process restarts; events added during publication remain
|
||||||
|
pending for the next run. Partial imports are exported as their settled local
|
||||||
|
state, including successful items from a batch containing failures.
|
||||||
|
- A single filesystem lock serializes the worker. Dead local process markers are
|
||||||
|
recovered on the next run. For an unreadable marker or a marker from another
|
||||||
|
host, stop the CMS and worker before repairing the queue directory.
|
||||||
|
- A failed push retains the local commit and pending events for retry. Concurrent
|
||||||
|
upstream commits are rebased; a conflict aborts the rebase and leaves the event
|
||||||
|
pending. Resolve conflicts in the dedicated clone, then retry.
|
||||||
|
- The checkout must be clean before each run. Unrelated files are preserved and
|
||||||
|
no force push is used. Missing local files do not cause remote deletions.
|
||||||
|
- Status errors omit raw Git output to avoid exposing authentication material.
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
Run the `catalog-git-*` service tests and `src/lib/catalog-export-api.test.ts` with
|
||||||
|
Vitest. The integration test creates a temporary bare remote and verifies push,
|
||||||
|
failed-push recovery, no-op export and preservation of unrelated files. SQL
|
||||||
|
snapshot tests mock the database; production DB import and production push need
|
||||||
|
verification in the deployed environment.
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
# CMS translation audit and editor
|
||||||
|
|
||||||
|
The CMS editor at `/admin/translations/cms` now uses the same bundled catalogs as the request-time translator. Runtime changes are stored separately in `storage/cms-translations/<locale>.json`, inside the existing persistent `/app/storage` mount. No source-file write, environment-variable change or rebuild is required to apply an edit.
|
||||||
|
|
||||||
|
Only overrides are saved. Unchanged messages continue to receive updates from Git. Saves use a file lock, an atomic replacement and a revision check; a stale editor cannot overwrite another operator's changes. ICU syntax, argument names, rich-text tags and allowed keys are checked server-side. Invalid or obsolete overrides are excluded when reading a new release. Storage read errors are reported to the CMS error monitor and public pages fall back to bundled text.
|
||||||
|
|
||||||
|
The page starts in the operator's language. It shows all English reference keys, including missing translations, and supports search by key, translated text or English source. Filters separate missing, identical and modified text. Drafts survive language switches and failed saves. Users without `SETTINGS_EDIT` can review and export but cannot save.
|
||||||
|
|
||||||
|
## Audit outcome, 6 September 2026
|
||||||
|
|
||||||
|
- Scanned 25 JSON catalogs; 22 languages are selectable. The small Arabic, Finnish and Japanese catalogs are legacy files and remain outside the supported locale list.
|
||||||
|
- Repaired 66 malformed ICU messages across the 22 active catalogs, including HTML fragments and unescaped JSON examples.
|
||||||
|
- Added 199 missing English reference keys used by page components, with Italian translations, and fixed the incorrect navigation namespace in the admin error page.
|
||||||
|
- Completed the 31 previously missing Italian reference keys.
|
||||||
|
- Repaired missing `count` and `preset` variables in other locales.
|
||||||
|
- Final checks: zero malformed messages, zero argument/tag mismatches and zero missing references among the statically resolved translation calls.
|
||||||
|
- English contains 3,423 reference keys. Italian covers all of them; 629 values match English. Dutch is missing 524 reference keys and has 618 identical values. Matching English can be intentional for names and technical labels; this is not proof of translation quality.
|
||||||
|
- Found 1,577 literal JSX text candidates outside translation calls. These include labels, technical strings and names; they are an editorial inventory, not 1,577 confirmed bugs. The largest concentrations are the catalog item table (118), Studio main component (79), import audit (53), sound management (50) and permission editor (42).
|
||||||
|
|
||||||
|
## Repeatable checks
|
||||||
|
|
||||||
|
- `pnpm i18n:check`: fails on malformed messages, incompatible variables/tags, empty messages, source parsing errors or missing statically referenced keys. Runs in Gitea CI.
|
||||||
|
- `pnpm i18n:audit`: prints coverage and findings.
|
||||||
|
- `node scripts/audit-cms-translations.mjs --json`: full machine-readable inventory, including file and line references for literal JSX candidates.
|
||||||
|
|
||||||
|
Static analysis resolves literal translator namespaces and literal message keys. Dynamic key construction, prose embedded in arbitrary JavaScript strings, and the linguistic accuracy of all 22 translations still require targeted review. English fallback remains explicit; copying English into other catalogs would hide untranslated entries and is intentionally avoided.
|
||||||
|
|
||||||
|
## Validation
|
||||||
|
|
||||||
|
Automated tests exercise message syntax, actual translator output, persistent overrides, invalid-message rejection, revision conflicts and reset behavior. A browser fixture mounts the real editor and verifies missing-key editing, validation, failed-save preservation, language switching, successful saves, read-only access and mobile layout. Server actions are simulated in that fixture; authenticated production editing requires a staff session.
|
||||||
+43
-105
@@ -1,110 +1,48 @@
|
|||||||
# ==============================================================================
|
# syntax=docker/dockerfile:1
|
||||||
# EpicNext-CMS — Docker image (Node 26.8.1, multi-package-manager, Next.js standalone)
|
# node:alpine = latest Node within the supported LTS major (tracks the newest
|
||||||
# ==============================================================================
|
# patch automatically; currently v26.x, which satisfies package.json's
|
||||||
# Supports pnpm (default), npm, and yarn. The build stage detects which package
|
# engines ">=26.8.1 <27").
|
||||||
# manager lockfile is present and uses it automatically.
|
FROM node:alpine AS builder
|
||||||
# ==============================================================================
|
|
||||||
|
|
||||||
# --- Builder stage ---
|
|
||||||
FROM node:26.8.1-bookworm-slim AS builder
|
|
||||||
|
|
||||||
# git is needed by next.config.ts (git rev-parse for deploymentId) and
|
|
||||||
# ca-certificates by package registries. Build runs on host network (see
|
|
||||||
# compose: iptables is disabled), so apt has registry access here.
|
|
||||||
RUN apt-get update && apt-get install -y --no-install-recommends git ca-certificates \
|
|
||||||
&& rm -rf /var/lib/apt/lists/*
|
|
||||||
|
|
||||||
# Install all three package managers so the build can pick whichever lockfile exists.
|
|
||||||
RUN npm install -g [email protected] yarn
|
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
ENV NEXT_TELEMETRY_DISABLED=1
|
||||||
# First copy only the manifests so dependency layers are cached when using pnpm.
|
# Real release id supplied by CI (ci-deploy.sh) so next.config.ts skips git
|
||||||
# For npm/yarn the full context is copied below before install.
|
# entirely (there is no .git in the build context). Defaults to "unknown".
|
||||||
COPY package.json pnpm-workspace.yaml .npmrc ./
|
ARG NEXT_DEPLOYMENT_ID="unknown"
|
||||||
|
ENV NEXT_DEPLOYMENT_ID="$NEXT_DEPLOYMENT_ID"
|
||||||
# Copy the rest of the source (brings in whichever lockfile your project uses).
|
# pnpm install is always pinned to the version in package.json's
|
||||||
|
# `packageManager` field (pnpm auto-selects it on install), so this global
|
||||||
|
# install only needs to exist as a bootstrap and follows the active major.
|
||||||
|
RUN apk add --no-cache git \
|
||||||
|
&& npm install -g pnpm@latest
|
||||||
|
# pnpm-workspace.yaml + .npmrc must be present too: the lockfile records the
|
||||||
|
# overrides from pnpm-workspace.yaml, and --frozen-lockfile rejects a build
|
||||||
|
# where the workspace config is absent (ERR_PNPM_LOCKFILE_CONFIG_MISMATCH).
|
||||||
|
COPY package.json pnpm-lock.yaml* pnpm-workspace.yaml* .npmrc* ./
|
||||||
|
# pnpm fetch: download all deps into $PNPM_STORE first, so only the lockfile
|
||||||
|
# change (not source changes) invalidates the network-heavy download layer.
|
||||||
|
RUN pnpm fetch --ignore-scripts
|
||||||
|
RUN pnpm install --frozen-lockfile --ignore-scripts --offline
|
||||||
COPY . .
|
COPY . .
|
||||||
|
RUN pnpm run build
|
||||||
|
|
||||||
# --- Detect package manager & install dependencies ---
|
FROM node:alpine AS runner
|
||||||
# Priority: pnpm > yarn > npm
|
|
||||||
# Build arg lets the user force a manager; otherwise it is auto-detected.
|
|
||||||
ARG PACKAGE_MANAGER=
|
|
||||||
|
|
||||||
RUN if [ "$PACKAGE_MANAGER" = "pnpm" ] || { [ -z "$PACKAGE_MANAGER" ] && [ -f pnpm-lock.yaml ]; }; then \
|
|
||||||
echo ">> Using pnpm" && \
|
|
||||||
pnpm install --frozen-lockfile --ignore-scripts; \
|
|
||||||
elif [ "$PACKAGE_MANAGER" = "yarn" ] || { [ -z "$PACKAGE_MANAGER" ] && [ -f yarn.lock ]; }; then \
|
|
||||||
echo ">> Using yarn" && \
|
|
||||||
yarn install --frozen-lockfile --ignore-scripts; \
|
|
||||||
elif [ "$PACKAGE_MANAGER" = "npm" ] || { [ -z "$PACKAGE_MANAGER" ] && [ -f package-lock.json ]; }; then \
|
|
||||||
echo ">> Using npm" && \
|
|
||||||
npm ci --ignore-scripts; \
|
|
||||||
else \
|
|
||||||
echo "!! No lockfile found — falling back to npm install" && \
|
|
||||||
npm install --ignore-scripts; \
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Build the production bundle.
|
|
||||||
# The .env file is loaded ONLY inside this RUN layer (not persisted as ENV, so no
|
|
||||||
# secrets end up in the image) — Next.js needs NEXT_PUBLIC_* + validated build-time
|
|
||||||
# values (HOTEL_NAME, DATABASE_URL, AUTH_SECRET, ...) at build time.
|
|
||||||
ENV NODE_ENV=production
|
|
||||||
RUN if [ -f .env ]; then set -a && . ./.env && set +a; fi && \
|
|
||||||
if [ "$PACKAGE_MANAGER" = "yarn" ] || { [ -z "$PACKAGE_MANAGER" ] && [ -f yarn.lock ]; }; then \
|
|
||||||
yarn build; \
|
|
||||||
elif [ "$PACKAGE_MANAGER" = "npm" ] || { [ -z "$PACKAGE_MANAGER" ] && [ -f package-lock.json ]; }; then \
|
|
||||||
npm run build; \
|
|
||||||
else \
|
|
||||||
pnpm build; \
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Prune dev dependencies for the runtime image.
|
|
||||||
RUN if [ "$PACKAGE_MANAGER" = "yarn" ] || { [ -z "$PACKAGE_MANAGER" ] && [ -f yarn.lock ]; }; then \
|
|
||||||
yarn install --production --ignore-scripts && rm -rf node_modules/.cache; \
|
|
||||||
elif [ "$PACKAGE_MANAGER" = "npm" ] || { [ -z "$PACKAGE_MANAGER" ] && [ -f package-lock.json ]; }; then \
|
|
||||||
npm prune --production; \
|
|
||||||
else \
|
|
||||||
pnpm prune --prod; \
|
|
||||||
fi
|
|
||||||
|
|
||||||
# --- Runtime stage ---
|
|
||||||
FROM node:26.8.1-bookworm-slim AS runner
|
|
||||||
|
|
||||||
# The CMS writes to bind-mounted host directories (/var/www/Gamedata is owned by
|
|
||||||
# the host's www-data user, UID/GID 33). The node base image already ships a
|
|
||||||
# www-data user with UID/GID 33, which matches that ownership — so we run as
|
|
||||||
# www-data and can write to the shared gamedata directory. If your host owner
|
|
||||||
# differs, override via --build-arg RUN_USER (e.g. --build-arg RUN_USER=1000).
|
|
||||||
ARG RUN_USER=www-data
|
|
||||||
|
|
||||||
ENV NODE_ENV=production
|
|
||||||
ENV PORT=3002
|
|
||||||
ENV HOSTNAME=0.0.0.0
|
|
||||||
|
|
||||||
EXPOSE 3002
|
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
ENV NODE_ENV=production \
|
||||||
# Storage directory for runtime uploaded media (persistent volume).
|
NEXT_TELEMETRY_DISABLED=1 \
|
||||||
# Also create the hardcoded gamedata mount point (/var/www/Gamedata is
|
PORT=3002 \
|
||||||
# bind-mounted at runtime so the CMS can read + write imported assets there).
|
HOSTNAME=0.0.0.0
|
||||||
RUN mkdir -p /app/storage \
|
RUN apk add --no-cache tini \
|
||||||
/app/public/nitro-assets \
|
&& addgroup -g 33 -S nextjs && adduser -u 33 -S -G nextjs nextjs \
|
||||||
/app/public/swf \
|
&& mkdir -p /app/storage /app/public/nitro-assets /app/public/swf /var/www/Gamedata \
|
||||||
/var/www/Gamedata \
|
&& chown -R 33:33 /app/storage /app/public /var/www/Gamedata
|
||||||
&& chown -R ${RUN_USER} /app /var/www/Gamedata
|
COPY --from=builder --chown=nextjs:nextjs /app/public ./public
|
||||||
|
COPY --from=builder --chown=nextjs:nextjs /app/.next/standalone ./
|
||||||
# Copy standalone Next.js output (includes a minimal node_modules).
|
COPY --from=builder --chown=nextjs:nextjs /app/.next/static ./.next/static
|
||||||
COPY --from=builder --chown=${RUN_USER} /app/.next/standalone ./
|
USER nextjs
|
||||||
# Copy static assets (public files served directly).
|
EXPOSE 3002
|
||||||
COPY --from=builder --chown=${RUN_USER} /app/public ./public
|
# Self-contained healthcheck so `docker run` (ci-deploy) also gets Docker-level
|
||||||
# Copy the server-side static build output.
|
# health; docker-compose overrides this with its own probe if needed.
|
||||||
COPY --from=builder --chown=${RUN_USER} /app/.next/static ./.next/static
|
HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 \
|
||||||
|
CMD ["node", "-e", "fetch('http://127.0.0.1:'+(process.env.PORT||'3002')+'/api/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"]
|
||||||
# Client assets + runtime uploads live outside the image (mounted volumes).
|
ENTRYPOINT ["/sbin/tini", "--"]
|
||||||
VOLUME ["/app/public/nitro-assets", "/app/public/swf", "/app/storage"]
|
|
||||||
|
|
||||||
USER ${RUN_USER}
|
|
||||||
|
|
||||||
CMD ["node", "server.js"]
|
CMD ["node", "server.js"]
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
# EpicNext-CMS v1.0.1
|
# EpicNext-CMS v1.0.3
|
||||||
|
|
||||||
A modern, high-performance content management system for Habbo hotel emulators, built on **Next.js 16** (App Router) with **Drizzle ORM** and **React 19**. Designed to integrate seamlessly with Polaris / Arcturus Morningstar MySQL/MariaDB databases.
|
A modern, high-performance content management system for Habbo hotel emulators, built on **Next.js 16** (App Router) with **Drizzle ORM** and **React 19**. Designed to integrate seamlessly with Polaris / Arcturus Morningstar MySQL/MariaDB databases.
|
||||||
|
|
||||||
@@ -112,7 +112,7 @@ Open `http://localhost:3002` in your browser.
|
|||||||
|
|
||||||
## Docker Deployment
|
## Docker Deployment
|
||||||
|
|
||||||
The CMS ships with a multi-stage Dockerfile that automatically detects your package manager (pnpm, npm, or yarn) based on which lockfile is present. Only the **CMS** runs in Docker; the Nitro/Octane client and its renderer stay outside and are served by nginx on the host.
|
The CMS ships with a multi-stage Dockerfile that automatically detects your package manager (pnpm, npm, or yarn) based on which lockfile is present. The **CMS** runs in Docker; the Nitro/Octane client stays outside and is served by nginx on the host. The server-side **avatar imager** also runs in its own Docker container (`avatar-imaging-pixinode`, port 8082) — see [Avatar Imaging](#avatar-imaging).
|
||||||
|
|
||||||
### Prerequisites
|
### Prerequisites
|
||||||
|
|
||||||
@@ -196,6 +196,7 @@ an exit of 0 means the CMS is healthy on the new commit.
|
|||||||
| `docker compose pull && docker compose up -d --build` | Update and redeploy |
|
| `docker compose pull && docker compose up -d --build` | Update and redeploy |
|
||||||
| `pnpm db:migrate` (on the **host**) | Run database migrations (slim image has no source) |
|
| `pnpm db:migrate` (on the **host**) | Run database migrations (slim image has no source) |
|
||||||
| `./scripts/docker-update.sh` | Full automated update (manual or cron) |
|
| `./scripts/docker-update.sh` | Full automated update (manual or cron) |
|
||||||
|
| `pnpm db:up` / `pnpm db:down` | Start / stop the `mariadb-turbo` bulk-load container |
|
||||||
|
|
||||||
### How Package Manager Detection Works
|
### How Package Manager Detection Works
|
||||||
|
|
||||||
@@ -212,7 +213,7 @@ This means you can use any package manager on your host machine — the Docker b
|
|||||||
|
|
||||||
### Volumes
|
### Volumes
|
||||||
|
|
||||||
Only the CMS runs in Docker. The heavy client assets and gamedata stay on the host and are shared into the container so imports and uploads persist:
|
Only the CMS (and the optional avatar imager container, see [Avatar Imaging](#avatar-imaging)) run in Docker. The heavy client assets and gamedata stay on the host and are shared into the container so imports and uploads persist:
|
||||||
|
|
||||||
| Container Path | Host Path | Mode | Purpose |
|
| Container Path | Host Path | Mode | Purpose |
|
||||||
| -------------------------- | -------------------------- | ---- | ------------------------------------ |
|
| -------------------------- | -------------------------- | ---- | ------------------------------------ |
|
||||||
@@ -228,7 +229,7 @@ Only the CMS runs in Docker. The heavy client assets and gamedata stay on the ho
|
|||||||
| Component | Host path | How it's served |
|
| Component | Host path | How it's served |
|
||||||
| -------------------- | ----------------------- | ---------------------------------------------------------------------- |
|
| -------------------- | ----------------------- | ---------------------------------------------------------------------- |
|
||||||
| Nitro/Octane client | `/var/www/Octane/dist` | nginx `location ^~ /client/` and `/nitro-client/` alias |
|
| Nitro/Octane client | `/var/www/Octane/dist` | nginx `location ^~ /client/` and `/nitro-client/` alias |
|
||||||
| Octane-Renderer | `/var/www/Octane-Renderer` | Optional. Run separately (or as the commented-out `imager` service) proxied by nginx `/imaging` |
|
| Avatar imager | `/docker/Polaris-imager`| Docker container `avatar-imaging-pixinode` on port `8082` — see [Avatar Imaging](#avatar-imaging) |
|
||||||
| Camera uploads | `/var/www/Camera` | nginx `/camera/` alias |
|
| Camera uploads | `/var/www/Camera` | nginx `/camera/` alias |
|
||||||
|
|
||||||
**Container user & write permissions:** the CMS container runs as `www-data` (UID/GID 33) by default to match the host owner of `/var/www/Gamedata`. Ensure the other write volumes (`./public/nitro-assets`, `./public/swf`, `./storage`) are also owned by `www-data` on the host:
|
**Container user & write permissions:** the CMS container runs as `www-data` (UID/GID 33) by default to match the host owner of `/var/www/Gamedata`. Ensure the other write volumes (`./public/nitro-assets`, `./public/swf`, `./storage`) are also owned by `www-data` on the host:
|
||||||
@@ -258,6 +259,45 @@ The container includes a health check that hits `/api/health` on port 3002 every
|
|||||||
docker inspect --format='{{.State.Health.Status}}' epicnext-cms
|
docker inspect --format='{{.State.Health.Status}}' epicnext-cms
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### MariaDB Turbo (bulk loads)
|
||||||
|
|
||||||
|
`docker-compose.yml` ships an opt-in **`mariadb-turbo`** service — a dedicated MariaDB 11 container tuned for loading >50 MB JSON dumps (furnidata, external texts, etc.). It configures itself via mysqld flags on the `command:`, so no external `.cnf` file has to be mounted or kept in sync:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pnpm db:up # docker compose --profile db up -d (starts mariadb-turbo)
|
||||||
|
```
|
||||||
|
|
||||||
|
Key settings (see the `command:` block in `docker-compose.yml`):
|
||||||
|
|
||||||
|
- `max_allowed_packet = 512M` — 50 MB JSON batches no longer hit the 16 MB packet ceiling.
|
||||||
|
- `innodb_flush_log_at_trx_commit = 2` + `innodb_doublewrite = 0` — durability relaxed for bulk writes.
|
||||||
|
- `innodb_buffer_pool_size = 2G`, `innodb_log_file_size = 1G`, `bulk_insert_buffer_size = 512M`.
|
||||||
|
- `net_read_timeout` / `net_write_timeout = 600`, `wait_timeout = 3600` — fixes the `drizzle-kit` **"Pulling schema from database..."** hang by never starving introspection/DDL sessions behind a long import.
|
||||||
|
- `performance_schema = OFF` — saves ~1-2 GB RAM.
|
||||||
|
|
||||||
|
The datadir lives in a **named volume** (`mariadb-turbo-data`), never a host bind-mount: shared-filesystem sync trashes InnoDB files the same way it corrupts pnpm's `node_modules`. Named volumes stay inside the container filesystem, so 50 MB of JSON writes never cross a host-sync boundary.
|
||||||
|
|
||||||
|
> **Port note:** the service uses `network_mode: host` and binds `127.0.0.1:3306` — stop the host MariaDB first, otherwise the port collides with the standalone `.env` `DATABASE_URL` (`localhost:3306`).
|
||||||
|
|
||||||
|
#### node_modules & host-sync corruption
|
||||||
|
|
||||||
|
pnpm's store is hard-linked and its `.bin` shims are symlinks, so **node_modules must never be a host bind-mount** (Docker Desktop gRPC-FUSE/VirtioFS, Unison and Syncthing all corrupt it). The production build bakes `node_modules` into the image at build time; it is never bind-mounted. For local dev, mount a *named volume* (`node_modules:/app/node_modules`) instead of the host directory, and keep `node_modules` / the pnpm store out of any shared-filesystem bind.
|
||||||
|
|
||||||
|
#### Loading a 50 MB JSON dump
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Habbo furnidata (auto-detects roomitemtypes / wallitemtypes / effecttypes)
|
||||||
|
pnpm db:bulk --file=/var/www/Gamedata/config/FurnitureData.json
|
||||||
|
|
||||||
|
# Flat array of documents → generic JSON store
|
||||||
|
pnpm db:bulk --file=/data/products.json --table=docs --category=furni
|
||||||
|
|
||||||
|
# Key/value texts
|
||||||
|
pnpm db:bulk --file=/data/external_texts.json --table=texts --category=default
|
||||||
|
```
|
||||||
|
|
||||||
|
The importer (`scripts/bulk-import-json.ts`) maps rows onto `src/db/schema-gamedata.ts`, batches them into **2000-row multi-row INSERTs** (one statement per chunk), uses `ON DUPLICATE KEY UPDATE` so re-runs are idempotent and interrupted loads resume, and prints rows/s + ETA. See ["ORM Setup & Type Generation"](#orm-setup--type-generation) → *Bulk JSON storage* for the design.
|
||||||
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -284,10 +324,41 @@ const found = await db.select()
|
|||||||
| `pnpm db:generate` | Draft SQL from Drizzle schema into `drizzle/drafts/` (review + copy) |
|
| `pnpm db:generate` | Draft SQL from Drizzle schema into `drizzle/drafts/` (review + copy) |
|
||||||
| `pnpm db:studio` | Open Drizzle Studio (dev only) |
|
| `pnpm db:studio` | Open Drizzle Studio (dev only) |
|
||||||
| `pnpm db:introspect` | Reverse-engineer an existing DB into a Drizzle schema draft |
|
| `pnpm db:introspect` | Reverse-engineer an existing DB into a Drizzle schema draft |
|
||||||
|
| `pnpm db:bulk` | Batch-import >50 MB JSON (2000-row chunks, resumable) via `scripts/bulk-import-json.ts` |
|
||||||
| `pnpm db:schema:generate` | Regen committed `src/db/schema.ts` from previous schema + live DB |
|
| `pnpm db:schema:generate` | Regen committed `src/db/schema.ts` from previous schema + live DB |
|
||||||
|
|
||||||
> The CMS does **not** use `drizzle-kit push` or `drizzle-kit migrate` — the database is shared with the emulator. Apply CMS DDL only via `pnpm db:migrate`.
|
> The CMS does **not** use `drizzle-kit push` or `drizzle-kit migrate` — the database is shared with the emulator. Apply CMS DDL only via `pnpm db:migrate`.
|
||||||
|
|
||||||
|
#### Bulk JSON storage (MariaDB)
|
||||||
|
|
||||||
|
Emulator/hotel JSON dumps (furnidata, external texts, product data) are often >50 MB. MariaDB's `JSON` type is an alias for `LONGTEXT` and can **never be indexed directly**, so `src/db/schema-gamedata.ts` follows the "promote + index" pattern:
|
||||||
|
|
||||||
|
- The raw JSON document stays intact in a `longtext` / `mediumtext` column (`payload`, `value`).
|
||||||
|
- The fields you actually `WHERE` / `ORDER BY` on are promoted into real columns (`sprite_id`, `class_name`, `kind`, `title`, `text_key`) and indexed.
|
||||||
|
- Optional **VIRTUAL generated columns** extract indexed fields from the payload with `JSON_EXTRACT` (MariaDB supports secondary indexes on virtual columns, 10.2+), so no duplicate data has to be written by the importer.
|
||||||
|
|
||||||
|
Three tables are exported:
|
||||||
|
|
||||||
|
| Table | Purpose | Unique key |
|
||||||
|
| -------------------- | ---------------------------------------------- | --------------------------- |
|
||||||
|
| `gamedata_furnidata` | One row per furni/clothing item (habbo furnidata_json shape) | `(source, sprite_id)` |
|
||||||
|
| `gamedata_docs` | Generic JSON document store (per-key documents) | `(category, doc_key)` |
|
||||||
|
| `gamedata_texts` | External-texts style key/value pairs | `(category, text_key)` |
|
||||||
|
|
||||||
|
The bulk importer (`scripts/bulk-import-json.ts`, run via `pnpm db:bulk`) is DB-driven and fast precisely because each chunk is a *single* multi-row `INSERT … VALUES () ()… ON DUPLICATE KEY UPDATE`, so a 50 MB dump is a few dozen statements instead of hundreds of thousands of round-trips. Flags:
|
||||||
|
|
||||||
|
| Flag | Default | Description |
|
||||||
|
| -------------------- | ----------- | ------------------------------------------------- |
|
||||||
|
| `--file=<path>` | — (required)| JSON file (habbo furnidata_json or flat array) |
|
||||||
|
| `--table=<name>` | `furnidata` | One of `furnidata` \| `docs` \| `texts` |
|
||||||
|
| `--source=<x>` | `habbo` | `source` value for `furnidata` |
|
||||||
|
| `--category=<x>` | `default` | `category` value for `docs` / `texts` |
|
||||||
|
| `--chunk-size=N` | `2000` | Rows per multi-row INSERT |
|
||||||
|
| `--limit=N` | `0` | Stop after N rows (dry-test) |
|
||||||
|
| `--truncate` | off | DELETE rows for this source/category first |
|
||||||
|
|
||||||
|
The script sets `FOREIGN_KEY_CHECKS=0` for the session and is safe to interrupt: each chunk commits on its own, and `ON DUPLICATE KEY UPDATE` makes re-runs overwrite instead of appending.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## DragonflyDB (Caching, Rate Limiting, SSE)
|
## DragonflyDB (Caching, Rate Limiting, SSE)
|
||||||
@@ -386,9 +457,11 @@ server {
|
|||||||
add_header Cache-Control "public, max-age=31536000, immutable";
|
add_header Cache-Control "public, max-age=31536000, immutable";
|
||||||
}
|
}
|
||||||
|
|
||||||
location /imaging {
|
location /imaging/ {
|
||||||
proxy_pass http://127.0.0.1:3030;
|
proxy_pass http://127.0.0.1:8082/;
|
||||||
add_header Cache-Control "public, max-age=3600, s-maxage=86400";
|
proxy_set_header Connection "";
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
add_header Cache-Control "public, max-age=300";
|
||||||
}
|
}
|
||||||
|
|
||||||
location /health {
|
location /health {
|
||||||
@@ -399,6 +472,124 @@ server {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
> **`/imaging` trailing-slash gotcha:** `location /imaging` (no trailing slash) combined with `proxy_pass http://…8082/;` rewrites `/imaging/avatarimage` into `//avatarimage` and 404s. Always use `location /imaging/` + a trailing-slash `proxy_pass` so `/imaging/avatarimage` reaches the imager's `/avatarimage` route.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Avatar Imaging
|
||||||
|
|
||||||
|
Avatar images (profile figures, chat badges, forum avatars, admin previews) are rendered server-side by **Polaris-imager** ([duckietm/Polaris-imager](https://github.com/duckietm/Polaris-imager)) — a headless Nitro/Octane renderer that runs `@pixi/node` (real WebGL via `gl` + Xvfb) inside a Docker container named **`avatar-imaging-pixinode`**. It serves `GET /avatarimage?figure=…` on port **8082** and can emit PNG/APNG/GIF, gestures, actions, scenes and more.
|
||||||
|
|
||||||
|
### Request flow
|
||||||
|
|
||||||
|
```
|
||||||
|
browser → Cloudflare → (page rule /origin for /imaging/*) → host:8082
|
||||||
|
browser → nginx origin → location /imaging/ → 127.0.0.1:8082/avatarimage
|
||||||
|
```
|
||||||
|
|
||||||
|
URLs look like `https://<hotel>/imaging/avatarimage?figure=hd-180-1.ch-210-66&img_format=png&size=l&direction=4`. The public `NEXT_PUBLIC_IMAGER_URL` points at that endpoint (see `src/lib/imager.ts`). Responses carry `Cache-Control: public, max-age=300`, so browsers and Cloudflare reuse a render for 5 minutes.
|
||||||
|
|
||||||
|
### Requirements (host)
|
||||||
|
|
||||||
|
- Docker (daemon with `build.network: host`, same as the CMS build — this host disables Docker iptables).
|
||||||
|
- An nginx that serves `/gamedata/` (FigureData/FigureMap/EffectMap…) and `/gamedata/bundled` (`.nitro` assets) over HTTP so the renderer can fetch them. The compose file points at `host.docker.internal:8081`.
|
||||||
|
|
||||||
|
### Configuration — `/docker/Polaris-imager/.env`
|
||||||
|
|
||||||
|
```dotenv
|
||||||
|
NITRO_GAMEDATA_URL=http://host.docker.internal:8081/gamedata/config
|
||||||
|
NITRO_ASSET_URL=http://host.docker.internal:8081/gamedata/bundled
|
||||||
|
AVATAR_IMAGING_FPS=12
|
||||||
|
AVATAR_IMAGING_MAX_FRAMES=60
|
||||||
|
AVATAR_IMAGING_HOST=0.0.0.0
|
||||||
|
AVATAR_IMAGING_PORT=8082
|
||||||
|
AVATAR_IMAGING_RATELIMIT_MAX=600
|
||||||
|
AVATAR_IMAGING_SCENE=1
|
||||||
|
AVATAR_IMAGING_WARDROBE=1
|
||||||
|
AVATAR_IMAGING_HABBO_FONTS=1
|
||||||
|
AVATAR_IMAGING_CHAT_BUBBLES=1
|
||||||
|
AVATAR_IMAGING_HOTEL_URL=https://<hotel>
|
||||||
|
AVATAR_IMAGING_HOTEL_NAME=<hotel>
|
||||||
|
```
|
||||||
|
|
||||||
|
### Build & start
|
||||||
|
|
||||||
|
The image is self-contained — the `Dockerfile` clones the pinned Nitro/Octane renderer and runs the full `yarn`/`vite` bundle at build time, then produces a slim Debian runtime with Xvfb + Mesa software rendering:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd /docker/Polaris-imager
|
||||||
|
docker compose build
|
||||||
|
docker compose up -d # container: avatar-imaging-pixinode
|
||||||
|
docker logs -f avatar-imaging-pixinode # expect: "listening on http://0.0.0.0:8082"
|
||||||
|
```
|
||||||
|
|
||||||
|
The container runs `restart: unless-stopped` and ships a healthcheck that probes `/health` (reports `{ "ready": true }` once the headless renderer has booted). Verify a render:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -o avatar.png 'http://127.0.0.1:8082/avatarimage?figure=hr-893-45.hd-600-1.ch-255-66.lg-280-110.sh-295-62&img_format=png&size=l'
|
||||||
|
```
|
||||||
|
|
||||||
|
A production issue that this section documents: **the `avatar-imaging-pixinode` image can be removed by a `docker image prune`**, which takes the whole site's avatars offline (502 on `/imaging/*`). Keep the image tagged and re-build it via the commands above if it ever disappears (`docker compose build && docker compose up -d`).
|
||||||
|
|
||||||
|
### Figure string validation (`src/app/api/imaging/avatar/route.ts`)
|
||||||
|
|
||||||
|
The CMS-side route re-validates the incoming figure against `/^[a-z]{2}-\d+(-\d+)?(\.[a-z]{2}-\d+(-\d+)?)*$/i`. Real Habbo figure strings use `type-id-color` parts separated by dots (`hd-180-1.ch-210-66`), so each part allows an optional second number. Invalid input is rejected with `400` before any render happens.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Performance Tuning (production)
|
||||||
|
|
||||||
|
The CMS shares its MySQL/MariaDB database with the emulator, so the hot wins come from caching, asset serving and database knob-tuning — not from a storage-engine migration.
|
||||||
|
|
||||||
|
### 1. gzip_static pre-compression of gamedata JSON
|
||||||
|
|
||||||
|
The client downloads `FurnitureData.json` (~48 MB, one file per supported language) plus other large JSON from `/gamedata/`. nginx has `gzip` and `gzip_static on` (see `/etc/nginx/nginx.conf`), but with no pre-built `.gz` file it re-compressed the 48 MB **on every request** (~0.25–0.30 s of CPU per miss).
|
||||||
|
|
||||||
|
`scripts/compress-gamedata.mjs` pre-compresses every JSON >1 MB in `<Gamedata>/config` and `<Gamedata>/bundled/config` once (gzip level 9): `FurnitureData*.json` go from ~48 MB to ~2.4 MB (~95 % smaller). It is idempotent — a file is only re-compressed when the source mtime is newer than its `.gz` (e.g. after a Studio catalog export).
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pnpm gamedata:compress # manual run
|
||||||
|
```
|
||||||
|
|
||||||
|
Once the `.gz` exists, nginx `gzip_static` serves it straight from disk with `Content-Encoding: gzip` and effectively zero CPU. **Measured result on the production origin: 0.25–0.30 s → ~0.005 s per file.**
|
||||||
|
|
||||||
|
The production host runs the script on a cron so newly exported catalogs are compressed shortly after they land:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
crontab -e
|
||||||
|
# */15 * * * * node /var/www/atom-nexst/scripts/compress-gamedata.mjs >> /var/www/atom-nexst/logs/gamedata-compress.log 2>&1
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. MariaDB tuning
|
||||||
|
|
||||||
|
The whole `habbo` datadir is roughly 0.5 GB; the default InnoDB buffer pool (128 MB) pushed index/row reads to disk. The pool is raised to **4 GB** and the slow-query log is enabled (threshold 2 s), both live (`SET GLOBAL …`) and persisted for boot in `/etc/mysql/mariadb.conf.d/zz-cms-performance.cnf`:
|
||||||
|
|
||||||
|
```ini
|
||||||
|
[mysqld]
|
||||||
|
innodb_buffer_pool_size = 4G
|
||||||
|
slow_query_log = 1
|
||||||
|
long_query_time = 2
|
||||||
|
slow_query_log_file = /var/log/mysql/mariadb-slow.log
|
||||||
|
```
|
||||||
|
|
||||||
|
The slow-query log surfaces hot-spot SQL for a follow-up index/query audit. The CMS connection pool itself is already tuned (pool size 25, `connection_limit` in `DATABASE_URL`).
|
||||||
|
|
||||||
|
For bulk-written tables (game-data JSON, imports) a containerized **`mariadb-turbo`** variant is available — see [MariaDB Turbo](#mariadb-turbo-bulk-loads).
|
||||||
|
|
||||||
|
### 3. Asset caching headers
|
||||||
|
|
||||||
|
| Path | Cache-Control |
|
||||||
|
| ------------------------------ | -------------------------------------------------------------- |
|
||||||
|
| `/swf/**`, `/nitro-assets/**` | `public, max-age=604800, stale-while-revalidate=2592000` |
|
||||||
|
| `/gamedata/**`, `/client/**` | `public` + `expires 7–30 d` (nginx) |
|
||||||
|
| `/imaging/*` | `public, max-age=300` |
|
||||||
|
| `/camera/**` | `public, max-age=31536000, immutable` |
|
||||||
|
| `/_next/static/**` | `public, max-age=31536000, immutable` |
|
||||||
|
|
||||||
|
### 4. Cache layers (Redis + CDN)
|
||||||
|
|
||||||
|
The CMS caches through `cached()` / `cachedQuery()` (`src/lib/cache.ts`): an in-memory fast path with a Redis (DragonflyDB-compatible) fallback and single-flight protection against cache stampedes. Public API routes (home, leaderboard, online count, radio, photos, …) fill Redis keys per route; verify with `redis-cli DBSIZE`. With Cloudflare in front, static and `/imaging/*` responses are additionally cached edge-side (`cf-cache-status`), cutting origin load further.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Production Deployment (PM2)
|
## Production Deployment (PM2)
|
||||||
@@ -435,6 +626,9 @@ pm2 restart next
|
|||||||
| `pnpm db:generate` | Draft SQL via drizzle-kit → `drizzle/drafts/` |
|
| `pnpm db:generate` | Draft SQL via drizzle-kit → `drizzle/drafts/` |
|
||||||
| `pnpm db:studio` | Drizzle Studio (dev) |
|
| `pnpm db:studio` | Drizzle Studio (dev) |
|
||||||
| `pnpm db:introspect` | drizzle-kit introspect (draft) |
|
| `pnpm db:introspect` | drizzle-kit introspect (draft) |
|
||||||
|
| `pnpm db:bulk` | Batch-import >50 MB JSON via `scripts/bulk-import-json.ts` |
|
||||||
|
| `pnpm db:up` / `pnpm db:down` | Start / stop the `mariadb-turbo` container |
|
||||||
|
| `pnpm gamedata:compress` | Pre-compress large gamedata JSON to `.gz` (gzip_static) |
|
||||||
| `pnpm analyze` | Build + open bundle analyzer |
|
| `pnpm analyze` | Build + open bundle analyzer |
|
||||||
| `pnpm jobs:worker` | Start background task worker |
|
| `pnpm jobs:worker` | Start background task worker |
|
||||||
| `pnpm biome:check` | Lint and format code |
|
| `pnpm biome:check` | Lint and format code |
|
||||||
@@ -456,6 +650,7 @@ pm2 restart next
|
|||||||
| **Streaming & Suspense** | Next.js App Router streaming for fast page loads |
|
| **Streaming & Suspense** | Next.js App Router streaming for fast page loads |
|
||||||
| **Automatic Image Optimization** | `next/image` with Sharp for resizing and WebP/AVIF |
|
| **Automatic Image Optimization** | `next/image` with Sharp for resizing and WebP/AVIF |
|
||||||
| **Compression** | Gzip compression enabled on all responses |
|
| **Compression** | Gzip compression enabled on all responses |
|
||||||
|
| **gzip_static (gamedata)** | 48 MB FurnitureData JSON served from pre-built `.gz` — no per-request CPU |
|
||||||
| **PWA** | Service worker with skip-waiting, stale CSS chunk recovery |
|
| **PWA** | Service worker with skip-waiting, stale CSS chunk recovery |
|
||||||
| **Biome** | Fast linting and formatting (replaces ESLint + Prettier) |
|
| **Biome** | Fast linting and formatting (replaces ESLint + Prettier) |
|
||||||
|
|
||||||
@@ -469,11 +664,14 @@ pm2 restart next
|
|||||||
│ └── drafts/ # drizzle-kit generate output (never auto-applied)
|
│ └── drafts/ # drizzle-kit generate output (never auto-applied)
|
||||||
├── scripts/
|
├── scripts/
|
||||||
│ ├── apply-migrations.ts # SQL migration runner (apply + status)
|
│ ├── apply-migrations.ts # SQL migration runner (apply + status)
|
||||||
|
│ ├── bulk-import-json.ts # 50 MB+ JSON importer (2000-row chunks, UPSERT)
|
||||||
│ ├── jobs-worker.ts # Background task scheduler
|
│ ├── jobs-worker.ts # Background task scheduler
|
||||||
│ └── generate-drizzle-schema.mjs # Regen src/db/schema.ts from schema + live DB
|
│ ├── generate-drizzle-schema.mjs # Regen src/db/schema.ts from schema + live DB
|
||||||
|
│ └── compress-gamedata.mjs # Pre-compress large gamedata JSON (gzip_static)
|
||||||
├── src/
|
├── src/
|
||||||
│ ├── db/
|
│ ├── db/
|
||||||
│ │ ├── schema.ts # Drizzle ORM schema (committed — runtime data layer)
|
│ │ ├── schema.ts # Drizzle ORM schema (committed — runtime data layer)
|
||||||
|
│ │ ├── schema-gamedata.ts # Large-JSON storage schema (furnidata/docs/texts)
|
||||||
│ │ └── relations.ts # Drizzle relations
|
│ │ └── relations.ts # Drizzle relations
|
||||||
│ ├── app/ # Next.js App Router (pages & API routes)
|
│ ├── app/ # Next.js App Router (pages & API routes)
|
||||||
│ ├── actions/ # Server Actions
|
│ ├── actions/ # Server Actions
|
||||||
@@ -577,4 +775,3 @@ pnpm biome:check # Lint and format
|
|||||||
## License
|
## License
|
||||||
|
|
||||||
CC BY-NC-SA 4.0. See `LICENSE` for details.
|
CC BY-NC-SA 4.0. See `LICENSE` for details.
|
||||||
Test aanpassing voor Gitea Actions
|
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,205 @@
|
|||||||
|
[
|
||||||
|
{
|
||||||
|
"id": 132,
|
||||||
|
"sprite_id": 132,
|
||||||
|
"item_name": "floortile",
|
||||||
|
"public_name": "Floor Tile",
|
||||||
|
"type": "s",
|
||||||
|
"width": 1,
|
||||||
|
"length": 1,
|
||||||
|
"stack_height": 0,
|
||||||
|
"allow_stack": 1,
|
||||||
|
"allow_sit": 0,
|
||||||
|
"allow_lay": 0,
|
||||||
|
"allow_walk": 1,
|
||||||
|
"allow_gift": 1,
|
||||||
|
"allow_trade": 1,
|
||||||
|
"allow_recycle": 0,
|
||||||
|
"allow_marketplace_sell": 0,
|
||||||
|
"allow_inventory_stack": 1,
|
||||||
|
"interaction_type": "default",
|
||||||
|
"interaction_modes_count": 0,
|
||||||
|
"vending_ids": "0",
|
||||||
|
"multiheight": "",
|
||||||
|
"customparams": "",
|
||||||
|
"effect_id_male": 0,
|
||||||
|
"effect_id_female": 0,
|
||||||
|
"clothing_on_walk": "",
|
||||||
|
"page_id": "429",
|
||||||
|
"rare": "0"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 420,
|
||||||
|
"sprite_id": 420,
|
||||||
|
"item_name": "soft_jaggara_norja",
|
||||||
|
"public_name": "Norja-pehmojakkara",
|
||||||
|
"type": "s",
|
||||||
|
"width": 1,
|
||||||
|
"length": 3,
|
||||||
|
"stack_height": 1.7,
|
||||||
|
"allow_stack": 1,
|
||||||
|
"allow_sit": 1,
|
||||||
|
"allow_lay": 0,
|
||||||
|
"allow_walk": 0,
|
||||||
|
"allow_gift": 1,
|
||||||
|
"allow_trade": 1,
|
||||||
|
"allow_recycle": 0,
|
||||||
|
"allow_marketplace_sell": 0,
|
||||||
|
"allow_inventory_stack": 1,
|
||||||
|
"interaction_type": "default",
|
||||||
|
"interaction_modes_count": 1,
|
||||||
|
"vending_ids": "0",
|
||||||
|
"multiheight": "",
|
||||||
|
"customparams": "",
|
||||||
|
"effect_id_male": 0,
|
||||||
|
"effect_id_female": 0,
|
||||||
|
"clothing_on_walk": "",
|
||||||
|
"page_id": "429",
|
||||||
|
"rare": "0"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 1001,
|
||||||
|
"sprite_id": 1001,
|
||||||
|
"item_name": "Chess",
|
||||||
|
"public_name": "",
|
||||||
|
"type": "i",
|
||||||
|
"width": 1,
|
||||||
|
"length": 1,
|
||||||
|
"stack_height": 1,
|
||||||
|
"allow_stack": 1,
|
||||||
|
"allow_sit": 0,
|
||||||
|
"allow_lay": 0,
|
||||||
|
"allow_walk": 0,
|
||||||
|
"allow_gift": 1,
|
||||||
|
"allow_trade": 1,
|
||||||
|
"allow_recycle": 0,
|
||||||
|
"allow_marketplace_sell": 0,
|
||||||
|
"allow_inventory_stack": 1,
|
||||||
|
"interaction_type": "default",
|
||||||
|
"interaction_modes_count": 0,
|
||||||
|
"vending_ids": "0",
|
||||||
|
"multiheight": "",
|
||||||
|
"customparams": "",
|
||||||
|
"effect_id_male": 0,
|
||||||
|
"effect_id_female": 0,
|
||||||
|
"clothing_on_walk": "",
|
||||||
|
"page_id": "429",
|
||||||
|
"rare": "0"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 1011,
|
||||||
|
"sprite_id": 1011,
|
||||||
|
"item_name": "TicTacToe",
|
||||||
|
"public_name": "",
|
||||||
|
"type": "i",
|
||||||
|
"width": 1,
|
||||||
|
"length": 1,
|
||||||
|
"stack_height": 1,
|
||||||
|
"allow_stack": 1,
|
||||||
|
"allow_sit": 0,
|
||||||
|
"allow_lay": 0,
|
||||||
|
"allow_walk": 0,
|
||||||
|
"allow_gift": 1,
|
||||||
|
"allow_trade": 1,
|
||||||
|
"allow_recycle": 0,
|
||||||
|
"allow_marketplace_sell": 0,
|
||||||
|
"allow_inventory_stack": 1,
|
||||||
|
"interaction_type": "default",
|
||||||
|
"interaction_modes_count": 0,
|
||||||
|
"vending_ids": "0",
|
||||||
|
"multiheight": "",
|
||||||
|
"customparams": "",
|
||||||
|
"effect_id_male": 0,
|
||||||
|
"effect_id_female": 0,
|
||||||
|
"clothing_on_walk": "",
|
||||||
|
"page_id": "429",
|
||||||
|
"rare": "0"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 1021,
|
||||||
|
"sprite_id": 1021,
|
||||||
|
"item_name": "BattleShip",
|
||||||
|
"public_name": "",
|
||||||
|
"type": "i",
|
||||||
|
"width": 1,
|
||||||
|
"length": 1,
|
||||||
|
"stack_height": 1,
|
||||||
|
"allow_stack": 1,
|
||||||
|
"allow_sit": 0,
|
||||||
|
"allow_lay": 0,
|
||||||
|
"allow_walk": 0,
|
||||||
|
"allow_gift": 1,
|
||||||
|
"allow_trade": 1,
|
||||||
|
"allow_recycle": 0,
|
||||||
|
"allow_marketplace_sell": 0,
|
||||||
|
"allow_inventory_stack": 1,
|
||||||
|
"interaction_type": "default",
|
||||||
|
"interaction_modes_count": 0,
|
||||||
|
"vending_ids": "0",
|
||||||
|
"multiheight": "",
|
||||||
|
"customparams": "",
|
||||||
|
"effect_id_male": 0,
|
||||||
|
"effect_id_female": 0,
|
||||||
|
"clothing_on_walk": "",
|
||||||
|
"page_id": "429",
|
||||||
|
"rare": "0"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 1659,
|
||||||
|
"sprite_id": 1659,
|
||||||
|
"item_name": "ticket",
|
||||||
|
"public_name": "Big Ticket Bundle",
|
||||||
|
"type": "s",
|
||||||
|
"width": 1,
|
||||||
|
"length": 1,
|
||||||
|
"stack_height": 1,
|
||||||
|
"allow_stack": 1,
|
||||||
|
"allow_sit": 0,
|
||||||
|
"allow_lay": 0,
|
||||||
|
"allow_walk": 0,
|
||||||
|
"allow_gift": 1,
|
||||||
|
"allow_trade": 1,
|
||||||
|
"allow_recycle": 0,
|
||||||
|
"allow_marketplace_sell": 0,
|
||||||
|
"allow_inventory_stack": 1,
|
||||||
|
"interaction_type": "default",
|
||||||
|
"interaction_modes_count": 0,
|
||||||
|
"vending_ids": "0",
|
||||||
|
"multiheight": "",
|
||||||
|
"customparams": "",
|
||||||
|
"effect_id_male": 0,
|
||||||
|
"effect_id_female": 0,
|
||||||
|
"clothing_on_walk": "",
|
||||||
|
"page_id": "429",
|
||||||
|
"rare": "0"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 10056,
|
||||||
|
"sprite_id": 10056,
|
||||||
|
"item_name": "Vacuum",
|
||||||
|
"public_name": "laundry_r18_vacuum",
|
||||||
|
"type": "s",
|
||||||
|
"width": 1,
|
||||||
|
"length": 1,
|
||||||
|
"stack_height": 0,
|
||||||
|
"allow_stack": 0,
|
||||||
|
"allow_sit": 0,
|
||||||
|
"allow_lay": 0,
|
||||||
|
"allow_walk": 0,
|
||||||
|
"allow_gift": 1,
|
||||||
|
"allow_trade": 1,
|
||||||
|
"allow_recycle": 0,
|
||||||
|
"allow_marketplace_sell": 0,
|
||||||
|
"allow_inventory_stack": 1,
|
||||||
|
"interaction_type": "default",
|
||||||
|
"interaction_modes_count": 0,
|
||||||
|
"vending_ids": "0",
|
||||||
|
"multiheight": "",
|
||||||
|
"customparams": "",
|
||||||
|
"effect_id_male": 0,
|
||||||
|
"effect_id_female": 0,
|
||||||
|
"clothing_on_walk": "",
|
||||||
|
"page_id": "9966",
|
||||||
|
"rare": "0"
|
||||||
|
}
|
||||||
|
]
|
||||||
+119
-5
@@ -7,11 +7,6 @@ services:
|
|||||||
# build containers on the bridge network have no outbound NAT/DNS. Build on
|
# build containers on the bridge network have no outbound NAT/DNS. Build on
|
||||||
# the host network instead so pnpm/npm/yarn can reach the registry.
|
# the host network instead so pnpm/npm/yarn can reach the registry.
|
||||||
network: host
|
network: host
|
||||||
args:
|
|
||||||
# Run as the host owner (www-data = UID/GID 33, already present in the
|
|
||||||
# node base image) of /var/www/Gamedata so the container can read + write
|
|
||||||
# the shared gamedata directory.
|
|
||||||
RUN_USER: "www-data"
|
|
||||||
container_name: epicnext-cms
|
container_name: epicnext-cms
|
||||||
# Runs on the host network so existing 127.0.0.1 refs in .env keep working:
|
# Runs on the host network so existing 127.0.0.1 refs in .env keep working:
|
||||||
# MariaDB (3306), DragonflyDB/Redis (6379), emulator RCON (3003) + API (3001),
|
# MariaDB (3306), DragonflyDB/Redis (6379), emulator RCON (3003) + API (3001),
|
||||||
@@ -22,6 +17,8 @@ services:
|
|||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
env_file:
|
env_file:
|
||||||
- .env
|
- .env
|
||||||
|
environment:
|
||||||
|
- HOSTNAME=0.0.0.0
|
||||||
volumes:
|
volumes:
|
||||||
# ── Write targets (runtime imports/uploads, persistent on the host) ──
|
# ── Write targets (runtime imports/uploads, persistent on the host) ──
|
||||||
# The CMS writes imported furni/figures/pets/effects here (see
|
# The CMS writes imported furni/figures/pets/effects here (see
|
||||||
@@ -39,6 +36,16 @@ services:
|
|||||||
# same directory, so mount it into the container at the same absolute path.
|
# same directory, so mount it into the container at the same absolute path.
|
||||||
# Must be RW so furniture/badge imports can write mirrors to it.
|
# Must be RW so furniture/badge imports can write mirrors to it.
|
||||||
- /var/www/Gamedata:/var/www/Gamedata
|
- /var/www/Gamedata:/var/www/Gamedata
|
||||||
|
#
|
||||||
|
# ── node_modules corruption (§ host-sync) ──
|
||||||
|
# pnpm node_modules must NEVER be a host bind-mount: shared-filesystem
|
||||||
|
# sync (Docker Desktop gRPC-FUSE/VirtioFS, Unison, Syncthing) corrupts
|
||||||
|
# pnpm's hardlinked store and .bin shims. The production image already
|
||||||
|
# bakes node_modules in at build time and is NOT bind-mounted here.
|
||||||
|
# For local dev use a *named volume* instead of a host bind:
|
||||||
|
# - node_modules:/app/node_modules
|
||||||
|
# and never share `node_modules` / `pnpm store` via the Docker bind.
|
||||||
|
# On macOS add `:cached`/`:delegated` consistency labels per mount.
|
||||||
|
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test: ["CMD", "node", "-e", "fetch('http://localhost:3002/api/health').then(r=>{if(!r.ok)process.exit(1)}).catch(()=>process.exit(1))"]
|
test: ["CMD", "node", "-e", "fetch('http://localhost:3002/api/health').then(r=>{if(!r.ok)process.exit(1)}).catch(()=>process.exit(1))"]
|
||||||
@@ -48,6 +55,27 @@ services:
|
|||||||
start_period: 40s
|
start_period: 40s
|
||||||
mem_limit: 2g
|
mem_limit: 2g
|
||||||
|
|
||||||
|
# ── FlareSolverr (Cloudflare bypass for clone sources) ──
|
||||||
|
# Solves Cloudflare/TLS-fingerprint blocks via a headless Chrome browser.
|
||||||
|
# The CMS calls this on http://localhost:8191 for sources that block Node's
|
||||||
|
# TLS fingerprint (e.g. Leet.city). Used by src/lib/services/flare-solver.ts.
|
||||||
|
flaresolverr:
|
||||||
|
image: ghcr.io/flaresolverr/flaresolverr:latest
|
||||||
|
container_name: flaresolverr
|
||||||
|
network_mode: host
|
||||||
|
restart: unless-stopped
|
||||||
|
environment:
|
||||||
|
- LOG_LEVEL=info
|
||||||
|
- BROWSER_TIMEOUT=60000
|
||||||
|
- BROWSER_WORKERS=1
|
||||||
|
mem_limit: 2g
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "curl", "-sf", "http://localhost:8191/health"]
|
||||||
|
interval: 30s
|
||||||
|
timeout: 10s
|
||||||
|
retries: 3
|
||||||
|
start_period: 30s
|
||||||
|
|
||||||
# ── Opt-in: Octane-Renderer (Habbo avatar imager) ──
|
# ── Opt-in: Octane-Renderer (Habbo avatar imager) ──
|
||||||
# Serves /imaging on port 3030 (the CMS proxies /imaging to it). Renders
|
# Serves /imaging on port 3030 (the CMS proxies /imaging to it). Renders
|
||||||
# avatars into /var/www/Gamedata/habbo-imaging, so it needs RW access.
|
# avatars into /var/www/Gamedata/habbo-imaging, so it needs RW access.
|
||||||
@@ -61,3 +89,89 @@ services:
|
|||||||
# restart: unless-stopped
|
# restart: unless-stopped
|
||||||
# volumes:
|
# volumes:
|
||||||
# - /var/www/Gamedata:/var/www/Gamedata
|
# - /var/www/Gamedata:/var/www/Gamedata
|
||||||
|
|
||||||
|
# ── MariaDB "Turbo" (heavy JSON / bulk-loads) ──
|
||||||
|
# Dedicated MariaDB tuned for >50 MB JSON imports. All tuning lives inline
|
||||||
|
# in the service `command:` (bulk_insert_buffer_size,
|
||||||
|
# innodb_flush_log_at_trx_commit=2, max_allowed_packet=512M, ...) so the
|
||||||
|
# container configures itself — no external .cnf to mount or keep in sync.
|
||||||
|
# Opt-in via profile so `docker compose up` keeps running the standalone
|
||||||
|
# stack as today.
|
||||||
|
#
|
||||||
|
# Start: docker compose --profile db up -d (= pnpm db:up)
|
||||||
|
# Note: host networking binds 127.0.0.1:3306 → STOP the host MariaDB
|
||||||
|
# first (the app's .env DATABASE_URL points at localhost:3306).
|
||||||
|
# Fixes the "Pulling schema from database..." hang: raise
|
||||||
|
# net_read/net_write_timeout (done above) + stop imports while
|
||||||
|
# running `pnpm db:generate` / drizzle-kit introspection.
|
||||||
|
mariadb-turbo:
|
||||||
|
image: mariadb:11
|
||||||
|
container_name: mariadb-turbo
|
||||||
|
profiles: ["db"]
|
||||||
|
network_mode: host
|
||||||
|
restart: unless-stopped
|
||||||
|
environment:
|
||||||
|
# mariadb:11 uses MARIADB_*; MYSQL_* also works but is deprecated there.
|
||||||
|
- MARIADB_ROOT_PASSWORD=${MARIADB_ROOT_PASSWORD:-root}
|
||||||
|
- MARIADB_DATABASE=${MARIADB_DATABASE:-habbo}
|
||||||
|
- MARIADB_USER=${MARIADB_USER:-cms}
|
||||||
|
- MARIADB_PASSWORD=${MARIADB_PASSWORD:-cms}
|
||||||
|
- MARIADB_AUTO_UPGRADE=1
|
||||||
|
# MariaDB tunes itself — the Official image appends these flags to mysqld,
|
||||||
|
# no external .cnf file needed.
|
||||||
|
command: [
|
||||||
|
# Charset
|
||||||
|
"--character-set-server=utf8mb4",
|
||||||
|
"--collation-server=utf8mb4_unicode_ci",
|
||||||
|
# 50 MB JSON batches: raise the 16 MB default packet ceiling.
|
||||||
|
"--max-allowed-packet=512M",
|
||||||
|
"--net-buffer-length=1M",
|
||||||
|
# Timeouts — fixes the "Pulling schema from database..." hang
|
||||||
|
# (drizzle-kit introspection no longer starves behind big imports).
|
||||||
|
"--connect-timeout=30",
|
||||||
|
"--wait-timeout=3600",
|
||||||
|
"--interactive-timeout=3600",
|
||||||
|
"--net-read-timeout=600",
|
||||||
|
"--net-write-timeout=600",
|
||||||
|
# InnoDB: durability/performance trade-off for bulk writes.
|
||||||
|
"--innodb-flush-log-at-trx-commit=2",
|
||||||
|
"--innodb-buffer-pool-size=2G",
|
||||||
|
"--innodb-buffer-pool-instances=4",
|
||||||
|
"--innodb-log-file-size=1G",
|
||||||
|
"--innodb-log-buffer-size=64M",
|
||||||
|
"--innodb-flush-method=O_DIRECT",
|
||||||
|
"--innodb-autoextend-increment=512",
|
||||||
|
"--innodb-max-dirty-pages-pct=90",
|
||||||
|
"--bulk-insert-buffer-size=512M",
|
||||||
|
# Raise so the engine nearly never double-writes during a 50 MB load.
|
||||||
|
"--innodb-doublewrite=0",
|
||||||
|
# libaio/native_aio misbehaves in some containers; io_uring path is fine.
|
||||||
|
"--innodb-use-native-aio=0",
|
||||||
|
# Temp tables used when MariaDB scans JSON blobs cannot be indexed.
|
||||||
|
"--tmp-table-size=256M",
|
||||||
|
"--max-heap-table-size=256M",
|
||||||
|
"--read-buffer-size=4M",
|
||||||
|
"--read-rnd-buffer-size=16M",
|
||||||
|
# Save ~1-2 GB RAM; bulk loads don't need the instrumentation.
|
||||||
|
"--performance-schema=OFF",
|
||||||
|
"--skip-name-resolve",
|
||||||
|
]
|
||||||
|
volumes:
|
||||||
|
# Named volume, NOT a host bind — shared-filesystem sync trashes InnoDB
|
||||||
|
# files the same way it trashes pnpm's node_modules. Named volumes live
|
||||||
|
# inside the container filesystem, so 50 MB of JSON writes never cross a
|
||||||
|
# host-sync boundary.
|
||||||
|
- mariadb-turbo-data:/var/lib/mysql
|
||||||
|
healthcheck:
|
||||||
|
# healthcheck.sh ships in the official mariadb image.
|
||||||
|
test: ["CMD-SHELL", "healthcheck.sh --connect --innodb_initialized || mariadb-admin ping --silent"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
start_period: 30s
|
||||||
|
mem_limit: 4g
|
||||||
|
|
||||||
|
# Named volumes declared once; used by the MariaDB service above.
|
||||||
|
volumes:
|
||||||
|
mariadb-turbo-data:
|
||||||
|
driver: local
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
# Refactor del catalogo HK — analisi e programma
|
||||||
|
|
||||||
|
Data: 6 settembre 2026. Base verificata: main, commit 9b0ea2fb. Documento di proposta, non implementazione approvata. Il sito /admin/catalog reindirizza al login senza sessione staff: nessuna prova delle mutazioni sul database di produzione. Le criticità indicate sono percorsi verificati nel codice; gli effetti concorrenti richiedono riproduzione controllata.
|
||||||
|
|
||||||
|
## Obiettivo e perimetro
|
||||||
|
|
||||||
|
Un catalogo HK con un solo ambiente di lavoro, regole coerenti e operazioni recuperabili. Conservare stile HK, icone reali, salvataggio diretto, catalogo normale e Builder Club. Nessun ritorno dei Preferiti.
|
||||||
|
|
||||||
|
Inclusi: albero, categorie, offerte, prezzi, bundle, disponibilità, proprietà condivise dei furni, traduzioni, ricerca, anteprima, operazioni massive, manutenzione, collegamenti a Catalog Studio e sincronizzazione Git/hotel.
|
||||||
|
|
||||||
|
Catalog Studio conserva la responsabilità di importare, convertire e riparare .nitro, icone e furnidata. Il refactor collega questi strumenti alla selezione del catalogo; non comporta riscrivere il convertitore, cambiare protocollo dell'emulatore o sostituire il sistema Git/Gitea già esistente.
|
||||||
|
|
||||||
|
## Inventario verificato
|
||||||
|
|
||||||
|
Sono già presenti virtualizzazione dell'albero, trascinamento, multiselezione, griglia/tabella, editor dei prezzi, anteprima negozio, import massivo, traduzioni, manutenzione e coda di export Git. Vanno riutilizzati.
|
||||||
|
|
||||||
|
| File | Righe attuali | Responsabilità da separare |
|
||||||
|
|---|---:|---|
|
||||||
|
| src/app/admin/catalog/[id]/catalog-items-table/catalog-items-table.tsx | 2342 | Rendering, selezione, editor offerta/furno, prezzi massivi, drag and drop, dialoghi |
|
||||||
|
| src/components/admin/catalog-manager/sortable-tree.tsx | 1135 | Lettura albero, mutazioni, ricerca, trascinamento, comandi |
|
||||||
|
| src/components/admin/catalog-manager/inline-editor.tsx | 775 | Fetch, stato modifiche, schede, salvataggio, anteprima |
|
||||||
|
| src/app/admin/catalog/[id]/catalog-page-form.tsx | 738 | Campi, layout, media, salvataggio |
|
||||||
|
| src/app/admin/catalog/[id]/catalog-translate-tab.tsx | 617 | Selezione, proposta traduzioni, applicazione |
|
||||||
|
| src/app/admin/catalog/builder-club/bc-manager.tsx | 608 | Gestione parallela BC |
|
||||||
|
| src/app/admin/catalog/page.tsx | 526 | Query, conteggi, varianti normale/BC, composizione UI |
|
||||||
|
|
||||||
|
Le dimensioni aiutano a trovare i punti di intervento: l'obiettivo non è un limite arbitrario di righe, ma responsabilità verificabili e riutilizzabili.
|
||||||
|
|
||||||
|
## Problemi e interventi
|
||||||
|
|
||||||
|
| Priorità | Evidenza | Intervento |
|
||||||
|
|---|---|---|
|
||||||
|
| P0 | sortable-tree.tsx invia il riordino dei fratelli con Promise.allSettled, una action per riga; catalog.ts aggiorna RCON per ciascuna | Un comando batch con lista completa, validazione, transazione e un solo evento di aggiornamento |
|
||||||
|
| P0 | catalog-items.ts riordina le offerte con update sequenziali fuori transazione | Stesso contratto atomico per l'ordine delle offerte |
|
||||||
|
| P0 | updateCatalogPage accetta parentId direttamente; il controllo cicli è separato in movePage | Validazione comune per creazione, form, spostamento e API; controllare destinazioni inesistenti e concorrenza |
|
||||||
|
| P0 | deletePage normale sposta figli, elimina offerte e pagina separatamente | Transazione, analisi dell'impatto e snapshot ripristinabile |
|
||||||
|
| P0 | updateCatalogItem modifica pagina, offerta e items_base con scritture separate | Transazione e verifica che il furno appartenga all'offerta; scope distinto per proprietà condivise |
|
||||||
|
| P1 | cascadeDelete non mantiene un insieme di nodi visitati; il calcolo profondità BC è ricorsivo senza guardia ai cicli | Lettura tollerante di dati incoerenti, diagnostica e arresto sicuro delle traversate |
|
||||||
|
| P1 | handleEditTab modifica lo stato prima della conferma; chiusura X bypassa la protezione | Un unico controllo delle modifiche per cambio pagina, offerta, scheda, uscita e navigazione |
|
||||||
|
| P1 | loadPage/loadItemsData non annullano o identificano la richiesta precedente | AbortController e identità della selezione; solo la risposta corrente può aggiornare l'editor |
|
||||||
|
| P1 | Il salvataggio ignora il booleano restituito da RCON; Git opera in coda | Distinguere DB salvato, invio hotel riuscito/fallito e stato Git; retry senza risalvare i dati |
|
||||||
|
| P1 | loadCatalogItemsData usa Number(value) || fallback per order_number, offer_id e amount | Definire semantica di zero/null per campo e testare il round trip prima di cambiare i fallback |
|
||||||
|
| P2 | Tutte le offerte e metadati sono caricati insieme; filtro con CAST(page_id AS CHAR) | Misurare query/payload, separare elenco e dettagli, paginazione e adapter compatibile INT/VARCHAR |
|
||||||
|
| P2 | Editor normale/BC e form condividono solo parte delle regole; testi anche letterali | Contratti comuni, differenze BC esplicite, traduzioni e permessi coerenti |
|
||||||
|
|
||||||
|
Riferimenti principali: src/actions/catalog.ts, src/actions/catalog-items.ts, src/actions/catalog-bc.ts, src/lib/services/catalog-tree.ts, src/lib/services/catalog-items-loader.ts, src/app/api/admin/catalog/tree/route.ts, src/components/admin/catalog-manager/catalog-manager-dialog.tsx, src/components/admin/catalog-manager/inline-editor.tsx.
|
||||||
|
|
||||||
|
## Alternative
|
||||||
|
|
||||||
|
1. **Pulizia dei file mantenendo tutti gli editor:** rischio iniziale basso, ma conserva duplicazioni e differenze operative. Utile solo come passaggio iniziale.
|
||||||
|
2. **Refactor progressivo con un editor principale — consigliato:** servizi comuni prima, poi promozione del Visual Manager a pagina. Permette piccoli rilasci e confronti tra vecchio e nuovo percorso.
|
||||||
|
3. **Riscrittura completa:** libertà maggiore, ma più rischio di perdere casi speciali, compatibilità DB e funzioni già presenti. Non giustificata dall'inventario attuale.
|
||||||
|
|
||||||
|
## Architettura proposta
|
||||||
|
|
||||||
|
Modulo src/features/catalog con confini chiari:
|
||||||
|
|
||||||
|
- domain/: tipi Page, Offer, FurnitureReference, CatalogKind; validazione gerarchie, prezzi, bundle e disponibilità; nessuna dipendenza React/DB.
|
||||||
|
- server/queries/: letture albero, elenco offerte, dettaglio e ricerca; output serializzabile esplicito.
|
||||||
|
- server/commands/: create/update/move/reorder/delete; autorizzazione, validazione, transazioni, controllo revisione e audit.
|
||||||
|
- server/repositories/: accesso Drizzle e compatibilità delle colonne; adapter normale/BC senza fingere che tutti i campi coincidano.
|
||||||
|
- client/: stato selezione, modifiche locali, operazioni in corso, caricamento e gestione conflitti.
|
||||||
|
- components/: albero, elenco offerte, editor categoria, editor offerta, dettagli furno, diagnostica, stato sincronizzazione.
|
||||||
|
|
||||||
|
Le route e le action attuali rimangono inizialmente adapter sottili. Un unico risultato di operazione include ID operazione, revisione, elementi modificati, eventuali errori di campo e stato sincronizzazione. Non introdurre nuove librerie prima di verificare i limiti degli strumenti già installati.
|
||||||
|
|
||||||
|
Flusso di scrittura: permesso → validazione → verifica revisione → transazione DB con audit → risposta di salvataggio → aggiornamento hotel/export Git. La durabilità del passaggio DB→coda va garantita con un evento persistito nella transazione o meccanismo equivalente verificato. Un fallimento Git/RCON non deve far ripetere una creazione già committata. Riutilizzare il worker e la coda esistenti, aggiungendo idempotenza dove manca.
|
||||||
|
|
||||||
|
## UX proposta
|
||||||
|
|
||||||
|
Pagina /admin/catalog con barra: Normale/BC, ricerca, nuova categoria, aggiungi furni, stato operazioni. Sotto: categorie a sinistra, offerte al centro, dettagli a destra. Il pannello dettagli si richiude; su schermi piccoli diventa una vista dedicata. Un solo scorrimento per ciascuna area, azioni di salvataggio sempre raggiungibili.
|
||||||
|
|
||||||
|
La URL conserva catalogo, categoria, offerta, vista e ricerca; i campi non salvati restano nello stato locale. Indietro/avanti e ricaricamento devono riaprire il contesto corretto. I vecchi URL dei dettagli continuano a funzionare.
|
||||||
|
|
||||||
|
Tre oggetti riconoscibili:
|
||||||
|
|
||||||
|
- Categoria: percorso, titolo, icona, layout, visibilità e requisiti.
|
||||||
|
- Offerta: prezzo, valuta, quantità, componenti bundle, disponibilità e ordine.
|
||||||
|
- Furno condiviso: classname, sprite, dimensioni e interazioni; mostrare quante offerte lo referenziano prima di una modifica globale.
|
||||||
|
|
||||||
|
Idee operative:
|
||||||
|
|
||||||
|
- Ricerca trasversale per nome, classname, ID pagina/offerta/furno e sprite ID, con percorso nei risultati.
|
||||||
|
- Selettore visuale di categoria e layout; proprietà tecniche nelle Avanzate.
|
||||||
|
- Prezzi con icone reali delle valute; mostrare il prima/dopo delle operazioni massive, arrotondamenti ed elementi esclusi.
|
||||||
|
- Multiselezione con riepilogo di spostamento/eliminazione; dopo un errore mantenere selezionati i falliti.
|
||||||
|
- Anteprima del negozio già esistente integrata nel contesto; non presentarla come prova completa del comportamento del client hotel.
|
||||||
|
- Diagnostica su richiesta: offerta, SQL, furnidata, Nitro e icona separati. Collegamento a Catalog Studio sul furno esatto; nessuna scansione pesante a ogni apertura.
|
||||||
|
- Storico di chi/cosa/quando con differenze e ripristino. Il ripristino controlla revisioni successive: non sovrascrive in silenzio modifiche di altri operatori e non annulla acquisti già avvenuti.
|
||||||
|
- Riepilogo visibile: salvato, invio hotel, Git. Gli errori hanno riferimento al monitor CMS.
|
||||||
|
- Stati vuoti, errori, caricamento e sola lettura distinti; traduzioni complete e uso da tastiera.
|
||||||
|
|
||||||
|
## Programma di lavoro e criteri di uscita
|
||||||
|
|
||||||
|
| Lotto | Consegna | Criterio per proseguire |
|
||||||
|
|---|---|---|
|
||||||
|
| 1. Baseline | Matrice funzioni/route/permessi normale e BC; fixture con bundle, LTD, offerte speciali, zeri/null, alberi incoerenti; misure query e rete | Tutti i flussi esistenti hanno una destinazione nel piano, senza omissioni |
|
||||||
|
| 2. Integrità | Validatori, transazioni di riordino/spostamento/eliminazione, gerarchie sicure, revisioni | Un fallimento intermedio non lascia dati parziali; due operatori non si sovrascrivono |
|
||||||
|
| 3. Servizi condivisi | Query/command/repository e risultato comune; vecchie route come adapter | Vecchie UI superano le stesse prove con il nuovo backend |
|
||||||
|
| 4. Stato editor | Unica gestione delle modifiche, richieste annullabili, risposta coerente con selezione | Annullare l'uscita conserva tutto; cambi rapidi mostrano sempre l'ultima selezione |
|
||||||
|
| 5. Pagina unificata | Visual Manager nella pagina, griglia/tabella condivise, URL, layout adattivo | Parità normale/BC e vecchi link conservati; niente perdita di scroll o azioni nascoste |
|
||||||
|
| 6. Operazioni avanzate | Ricerca, editor bundle, prezzi massivi con differenze, storico e diagnosi contestuale | Gli effetti sono spiegati prima dell'applicazione; retry applica solo ciò che manca |
|
||||||
|
| 7. Sincronizzazione | Stato DB/hotel/Git, operazioni persistenti, retry/idempotenza | Guasto dopo commit e riavvio worker non duplicano né perdono l'operazione |
|
||||||
|
| 8. Prestazioni e rimozione duplicati | Paginazione, caricamento progressivo, accessibilità, eliminazione vecchi componenti | Confronto misurato e prove finali; nessuna route o funzione rimasta senza equivalente |
|
||||||
|
|
||||||
|
I lotti 2 e 7 condividono il contratto delle operazioni: progettare subito evento persistente e idempotenza, anche se la UI di stato arriva dopo. Nessuna stima in giorni finché non sono note dimensioni reali del catalogo, varianti DB e casi speciali attivi. Ogni lotto può richiedere più PR piccole; niente sostituzione monolitica.
|
||||||
|
|
||||||
|
## Verifica e rilascio
|
||||||
|
|
||||||
|
Test unitari delle regole; integrazione su MariaDB per rollback, concorrenza e varianti INT/VARCHAR; browser con permessi lettura/modifica, desktop e schermo ridotto. Simulare doppio submit, timeout, risposta fuori ordine, fallimento RCON, Git non raggiungibile, riavvio dopo commit. Conservare test e componenti esistenti finché la parità non è dimostrata.
|
||||||
|
|
||||||
|
Registrare baseline e risultati per categorie grandi/piccole: richieste per riordino, tempo DB, payload, tempo fino a editor utilizzabile, risposte fallite. Non promettere percentuali senza dati.
|
||||||
|
|
||||||
|
Rilascio progressivo con selezione reversibile del nuovo editor. Il ritorno alla UI precedente deve usare gli stessi servizi corretti. Migrazioni additive e compatibili; il rollback dell'app non deve richiedere la cancellazione di dati. Eliminare le vecchie UI solo dopo parità verificata. Confermare CI, deploy, health e prove staff prima di dichiarare risolto il flusso live.
|
||||||
|
|
||||||
|
## Primo passo consigliato
|
||||||
|
|
||||||
|
Lotti 1 e 2: inventario di compatibilità e correzione delle operazioni a rischio, mantenendo inizialmente l'aspetto corrente. Poi estrarre i servizi e unificare l'editor. È la sequenza che permette di migliorare UX senza portare avanti gli stessi difetti dentro una nuova schermata.
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
# CMS error center and dependency maintenance
|
||||||
|
|
||||||
|
Open **HK > DevOps > CMS error center** (`/admin/devops/cms-errors`).
|
||||||
|
The previous `/admin/devops/errors` page still displays emulator errors.
|
||||||
|
|
||||||
|
## Access and workflow
|
||||||
|
|
||||||
|
- Read: existing `admin.devops.view` permission, checked on the server.
|
||||||
|
- Mark resolved: `admin.devops.edit`, checked again in the server action; recorded in the staff audit log.
|
||||||
|
- Search by event reference, Next.js digest, route, message or deployment version.
|
||||||
|
- Expand a group for its latest stack, sanitized context and occurrence references.
|
||||||
|
- Marking a group resolved does not delete evidence. A later occurrence reopens it.
|
||||||
|
- Refresh is manual so inspecting an expanded error is not interrupted by polling.
|
||||||
|
|
||||||
|
## What is collected
|
||||||
|
|
||||||
|
Pino `logger.error`, `logServerError`, unexpected action errors, Next.js request
|
||||||
|
failures, React error boundaries, uncaught browser errors and unhandled browser
|
||||||
|
promise rejections. API wrapper failures return an `errorId`; Next.js boundary
|
||||||
|
errors can be correlated by their digest. Release identifiers come from the build.
|
||||||
|
Browser reports retain their own client release separately from the receiving server.
|
||||||
|
|
||||||
|
Reports are stored in `storage/cms-errors`, using the existing persistent storage
|
||||||
|
mount. No third-party service, token or new database table is required.
|
||||||
|
Storage does not depend on database availability; viewing the HK and its permission
|
||||||
|
checks still require authentication/database availability. Server console logs
|
||||||
|
remain the fallback when the CMS itself cannot serve requests.
|
||||||
|
|
||||||
|
Retention: seven days; approximately 10 MB/day, 100 queued server writes, and the
|
||||||
|
latest 1,000 events in the viewer. Limits are per CMS process/storage volume;
|
||||||
|
this is intended for the existing single-instance deployment. Daily expiry runs
|
||||||
|
on the next write. The browser endpoint is same-origin, body-size bounded and
|
||||||
|
rate-limited. Browser reports are untrusted observations and cannot grant access.
|
||||||
|
Known credential patterns and URL parameters are redacted; arbitrary object
|
||||||
|
metadata and request bodies are excluded. Avoid putting personal data in error
|
||||||
|
messages: this is pattern-based redaction, not a universal data-loss filter.
|
||||||
|
|
||||||
|
This does not collect historical console logs, process crashes before framework
|
||||||
|
startup, nginx failures, all `console.error` calls, or every handled business
|
||||||
|
validation error. A browser stack may point at minified chunks; private source-map
|
||||||
|
symbolication and distributed traces are not part of this local viewer. A recorded
|
||||||
|
stack is diagnostic evidence, not an automatic root-cause determination.
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
|
||||||
|
`pnpm install --frozen-lockfile`, `pnpm deps:audit`, `pnpm typecheck`, `pnpm test`,
|
||||||
|
`pnpm knip`, `pnpm biome:lint`, and `pnpm build` are the verification sequence.
|
||||||
|
`pnpm analyze --output` writes a Next.js bundle analysis (not an application build).
|
||||||
|
|
||||||
|
TinyMCE 8.9 is pinned in pnpm. `pnpm assets:editor` copies its runtime files and
|
||||||
|
license notices to ignored `public/vendor/tinymce`; dev/build run this first.
|
||||||
|
The Docker build includes the generated assets. The editor retains its existing
|
||||||
|
HTML fields and toolbar; validate saved content and preview when upgrading it.
|
||||||
|
|
||||||
|
Lenis has been removed; the public site now uses native scrolling. Other used
|
||||||
|
runtime libraries remain. Vitest and its coverage provider are upgraded together;
|
||||||
|
`clearMocks: false` preserves initialization-time permission contract assertions.
|
||||||
|
|
||||||
|
Renovate uses separate development/UI/Vitest groups with manual merge and a
|
||||||
|
three-day release age. The existing external Gitea bot configuration is retained.
|
||||||
|
Node/pnpm upgrades remain coordinated with Docker and the runner toolchain.
|
||||||
|
Obsolete global overrides were removed; a scoped esbuild override remains because
|
||||||
|
Drizzle Kit's loader still resolves a vulnerable legacy development-server build.
|
||||||
|
The two deprecated esbuild-kit packages remain upstream dependencies of Drizzle
|
||||||
|
Kit; replacing the ORM is not warranted for this tooling issue.
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
# Catalog operations upgrade plan
|
||||||
|
|
||||||
|
User approved bulk editing and complete category duplication, keeping Visual Manager in its button-opened modal.
|
||||||
|
|
||||||
|
Use subagent-driven-development for the independent duplication task; root owns bulk operations and final review.
|
||||||
|
|
||||||
|
- [x] Duplicate category subtree and offers atomically for normal/BC; preview counts, destination/name, fresh IDs, preserve furniture references; fail on stale source, invalid destination, cycles and insert failure. Shared permissions, single export/RCON outcome. UI in Visual Manager.
|
||||||
|
- [x] Extend selected-offer operations to preview and atomically apply prices, currency, and destination. Visibility belongs to categories, so expose it separately with exact affected categories; no fictitious per-offer flag. Preserve unselected and unrelated fields; conflicts prevent overwriting concurrent changes.
|
||||||
|
- [x] Meaningful domain/transaction/action tests, browser fixtures for modal preview/confirm, typecheck/Biome/i18n/Knip; review limits and commit exact scope.
|
||||||
|
|
||||||
|
No production data mutations, added dependencies or schema migrations. Full category duplication shares existing items_base definitions and asset files. Repeated confirmations must be disabled while saving. Preview should be revalidated under locks before write. Existing direct save and permissions remain.
|
||||||
|
|
||||||
|
## Implementation notes
|
||||||
|
|
||||||
|
Bulk editing now works from selected normal-catalog offers and from selection across global searches. Only explicitly chosen prices/currency/destination fields change. Prices support set/add/percentage with integer rounding and range validation; 500 selected offers per transaction. Preview binds rows, changes and category names; concurrent changes reject confirmation. Category visibility remains on the existing category controls, not a fabricated offer property. BC has no offer pricing and does not expose that editor.
|
||||||
|
|
||||||
|
Duplication copies up to 500 categories and 5000 offers, preserving bundle and asset references. New root starts disabled and hidden. Includes and internal offer IDs are remapped. Explicit normal offer IDs use the existing allocator and do not require AUTO_INCREMENT; database collisions roll back the whole copy. Preview binds destination siblings as well as source data so confirmed preview replay is rejected. Dirty editor state blocks copying saved data until drafts are saved/reset.
|
||||||
|
|
||||||
|
No database migration or dependency added. Database transaction tests use mocks and do not prove live MariaDB locking behavior. Browser fixtures use real components with mocked actions, not production writes. Existing allocator is process-local; competing external imports may cause a safe rollback requiring a fresh preview. No automatic retry of uncertain copy commits.
|
||||||
|
|
||||||
|
Verification complete: 1339 unit tests passed, 5 skipped. Typecheck/Knip/i18n and changed-file Biome checked. Real-component browser fixtures passed bulk selection, preview, conflicts, pending guards, mobile bounds and table refresh without phantom drafts; duplication nested inside actual manager verified menus, picker, preview and dirty-state guards. Fixed manager portal layering and invalid menu-label nesting uncovered by those tests. Browser actions are mocked; no live data written or deployment claimed.
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
# Catalog refactor implementation plan
|
||||||
|
|
||||||
|
> For agentic workers: use superpowers:subagent-driven-development for independent changes and review each deliverable.
|
||||||
|
|
||||||
|
Goal: deliver the approved progressive catalog refactor while preserving current features.
|
||||||
|
Architecture: shared domain validation and transactional commands behind existing action contracts; unified editor reuses current views and tools.
|
||||||
|
Stack: Next, React, Drizzle/MariaDB, Zod, Vitest, Playwright; no added dependencies.
|
||||||
|
Spec: docs/CATALOG_REFACTOR_PLAN.md
|
||||||
|
Constraints: preserve normal/BC differences, direct save, real icons, permissions, existing routes, no favorites. No production data mutations for testing.
|
||||||
|
|
||||||
|
- [x] Characterize compatibility and command rules with tests; capture baseline source map.
|
||||||
|
- [x] Domain hierarchy/reorder validation and transactional page commands (normal/BC), deterministic locking, common updates/deletion.
|
||||||
|
- [x] Offer update/reorder atomicity and safe numeric normalization, shared mutation contracts.
|
||||||
|
- [x] Editor cancellation/dirty state protection (agent catalog_editor_state), review and browser verification.
|
||||||
|
- [x] Promote editor as an in-page view with reversible classic view, URL context, responsive panels and coherent tool access.
|
||||||
|
- [ ] Sync outcomes/diagnostics/history integration; safe retry and explicit limits.
|
||||||
|
- [ ] Verify unit tests, database integration if runtime available, browser, typecheck, lint/i18n, full suite; review final scope and remaining environment-only checks.
|
||||||
|
|
||||||
|
Execution notes: changes are progressive, no destructive migration. Existing UI adapters stay until functional parity is tested. Whole-program completion must not be claimed from the first deliverable.
|
||||||
|
|
||||||
|
## First implementation delivery (2026-09-06)
|
||||||
|
|
||||||
|
Completed: shared normal/BC page and offer commands; transactional page reorder/delete/move and offer create/update/reorder; hierarchy validation and optimistic page-save checks; embedded default manager with classic views retained; request cancellation, editor unsaved-change guards and URL selection; bounded global category/offer/furniture search; separate hotel/Git status and hotel retry; export-finalization failures no longer mask committed server actions. Existing permissions and direct-save behavior retained. No added dependency or DB migration.
|
||||||
|
|
||||||
|
Verification: full unit suite 1308 passed / 5 skipped before final retry-classification regression; final focused catalog suite 96 passed. TypeScript, i18n static validation, Knip and Biome on all 54 changed source files pass. Browser fixtures cover editor loading races, retry failures, unsaved changes, URL history, read-only, normal/BC, search and 375px layout. Database calls and mutations are mocked in those fixtures. Full-repository formatter check reports pre-existing Windows CRLF formatting differences; unrelated files were not reformatted.
|
||||||
|
|
||||||
|
Remaining roadmap: per-operation durable dispatch/outbox, category/offer snapshot history and conflict-aware undo, contextual maintenance diagnosis, pagination/performance measurement against representative real data, further decomposition of retained legacy views. Existing coarse audit/export infrastructure remains; the new status file is not a durable outbox and RCON socket success does not prove client application. External furni importer mutation internals remain outside shared editor commands.
|
||||||
|
|
||||||
|
Environment checks still required: real MariaDB locking/rollback integration, staff-authenticated end-to-end smoke test and pipeline/deployment health. No production mutations performed; no production deployment claimed.
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
-- Existing articles remain published. Preserve any publication settings already present.
|
||||||
|
ALTER TABLE website_articles
|
||||||
|
ADD COLUMN IF NOT EXISTS status VARCHAR(20) NOT NULL DEFAULT 'published',
|
||||||
|
ADD COLUMN IF NOT EXISTS publish_at TIMESTAMP NULL DEFAULT NULL,
|
||||||
|
ADD COLUMN IF NOT EXISTS published_at TIMESTAMP NULL DEFAULT NULL;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_website_articles_publication
|
||||||
|
ON website_articles (status, publish_at, created_at);
|
||||||
@@ -12,6 +12,6 @@
|
|||||||
"scripts/furni-diagnose-now.ts"
|
"scripts/furni-diagnose-now.ts"
|
||||||
],
|
],
|
||||||
"project": ["src/**/*.{ts,tsx,css}", "scripts/**/*.{ts,js}"],
|
"project": ["src/**/*.{ts,tsx,css}", "scripts/**/*.{ts,js}"],
|
||||||
"ignoreDependencies": ["@sentry/nextjs", "pino-pretty", "husky"],
|
"ignoreDependencies": ["pino-pretty"],
|
||||||
"ignoreBinaries": ["sendmail"]
|
"ignoreBinaries": ["sendmail"]
|
||||||
}
|
}
|
||||||
@@ -27,6 +27,10 @@ const securityHeaders = [
|
|||||||
|
|
||||||
const nextConfig: NextConfig = {
|
const nextConfig: NextConfig = {
|
||||||
output: "standalone",
|
output: "standalone",
|
||||||
|
env: {
|
||||||
|
NEXT_PUBLIC_CMS_RELEASE:
|
||||||
|
process.env.NEXT_DEPLOYMENT_ID?.trim() || getGitCommit() || "unknown",
|
||||||
|
},
|
||||||
deploymentId: process.env.NEXT_DEPLOYMENT_ID?.trim() || getGitCommit(),
|
deploymentId: process.env.NEXT_DEPLOYMENT_ID?.trim() || getGitCommit(),
|
||||||
distDir: process.env.NEXT_DIST_DIR?.trim() || ".next",
|
distDir: process.env.NEXT_DIST_DIR?.trim() || ".next",
|
||||||
reactStrictMode: true,
|
reactStrictMode: true,
|
||||||
|
|||||||
+32
-18
@@ -7,8 +7,8 @@
|
|||||||
},
|
},
|
||||||
"packageManager": "[email protected]+sha512.5cde925b4f075f725eb71fbae18a42ffe784524789f19b61c731cb8721ec28aaee160e01a8d5af4fedb2a42cdbf300efe23db356b0d4a17b4d63e11f8ab7c956",
|
"packageManager": "[email protected]+sha512.5cde925b4f075f725eb71fbae18a42ffe784524789f19b61c731cb8721ec28aaee160e01a8d5af4fedb2a42cdbf300efe23db356b0d4a17b4d63e11f8ab7c956",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "next dev",
|
"dev": "pnpm assets:editor && next dev",
|
||||||
"build": "next build",
|
"build": "pnpm assets:editor && next build",
|
||||||
"start": "next start",
|
"start": "next start",
|
||||||
"toolchain:check": "node scripts/check-node-toolchain.mjs",
|
"toolchain:check": "node scripts/check-node-toolchain.mjs",
|
||||||
"lint": "biome check .",
|
"lint": "biome check .",
|
||||||
@@ -16,26 +16,39 @@
|
|||||||
"format": "biome format --write .",
|
"format": "biome format --write .",
|
||||||
"knip": "knip --include files,dependencies,devDependencies,unlisted,binaries",
|
"knip": "knip --include files,dependencies,devDependencies,unlisted,binaries",
|
||||||
"diag:permissions": "tsx scripts/diagnose-permission-page.ts",
|
"diag:permissions": "tsx scripts/diagnose-permission-page.ts",
|
||||||
"jobs:worker": "tsx scripts/jobs-worker.ts",
|
"jobs:worker": "node --conditions=react-server --import tsx scripts/jobs-worker.ts",
|
||||||
"test": "vitest run",
|
"test": "vitest run",
|
||||||
"test:e2e": "playwright test",
|
"test:e2e": "playwright test",
|
||||||
"typecheck": "tsc --noEmit",
|
"typecheck": "tsc --noEmit",
|
||||||
"db:generate": "drizzle-kit generate",
|
"db:generate": "drizzle-kit generate",
|
||||||
|
"db:introspect": "drizzle-kit introspect",
|
||||||
|
"db:bulk": "tsx scripts/bulk-import-json.ts",
|
||||||
|
"db:up": "docker compose --profile db up -d mariadb-turbo",
|
||||||
|
"db:down": "docker compose --profile db stop mariadb-turbo",
|
||||||
|
"db:schema:generate": "node scripts/generate-drizzle-schema.mjs",
|
||||||
"db:migrate": "tsx scripts/apply-migrations.ts",
|
"db:migrate": "tsx scripts/apply-migrations.ts",
|
||||||
"db:migrate:status": "tsx scripts/apply-migrations.ts --status",
|
"db:migrate:status": "tsx scripts/apply-migrations.ts --status",
|
||||||
"db:studio": "drizzle-kit studio",
|
"db:studio": "drizzle-kit studio",
|
||||||
|
"gamedata:compress": "node scripts/compress-gamedata.mjs",
|
||||||
"hk:matrix:check": "tsx scripts/verify-housekeeping-matrix.ts",
|
"hk:matrix:check": "tsx scripts/verify-housekeeping-matrix.ts",
|
||||||
"test:housekeeping": "vitest run --coverage.enabled=false src/features/housekeeping src/lib/admin-theme-source-audit.test.ts src/lib/admin/authorization-contract.test.ts"
|
"test:housekeeping": "vitest run --coverage.enabled=false src/features/housekeeping src/lib/admin-theme-source-audit.test.ts src/lib/admin/authorization-contract.test.ts",
|
||||||
|
"prepare": "node scripts/prepare-hooks.mjs",
|
||||||
|
"assets:editor": "node scripts/copy-editor-assets.mjs",
|
||||||
|
"deps:audit": "pnpm audit --audit-level=high",
|
||||||
|
"analyze": "next experimental-analyze",
|
||||||
|
"i18n:check": "node scripts/audit-cms-translations.mjs --check",
|
||||||
|
"i18n:audit": "node scripts/audit-cms-translations.mjs"
|
||||||
},
|
},
|
||||||
"lint-staged": {
|
"lint-staged": {
|
||||||
"*.{js,ts,jsx,tsx,json}": "biome check --write --no-errors-on-unmatched",
|
"*.{js,ts,jsx,tsx,json}": "biome check --write --no-errors-on-unmatched",
|
||||||
"*.{ts,tsx}": "node scripts/check-admin-colors.mjs"
|
"*.{ts,tsx}": "node scripts/check-admin-colors.mjs"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@base-ui/react": "1.7.0",
|
"@base-ui/react": "1.8.0",
|
||||||
"@dnd-kit/core": "6.3.1",
|
"@dnd-kit/core": "6.3.1",
|
||||||
"@dnd-kit/sortable": "10.0.0",
|
"@dnd-kit/sortable": "10.0.0",
|
||||||
"@dnd-kit/utilities": "3.2.2",
|
"@dnd-kit/utilities": "3.2.2",
|
||||||
|
"@formatjs/icu-messageformat-parser": "3.5.17",
|
||||||
"@hookform/resolvers": "5.9.1",
|
"@hookform/resolvers": "5.9.1",
|
||||||
"@tanstack/react-virtual": "3.14.10",
|
"@tanstack/react-virtual": "3.14.10",
|
||||||
"class-variance-authority": "0.7.1",
|
"class-variance-authority": "0.7.1",
|
||||||
@@ -49,46 +62,47 @@
|
|||||||
"jpeg-js": "0.4.4",
|
"jpeg-js": "0.4.4",
|
||||||
"jsonc-parser": "3.3.1",
|
"jsonc-parser": "3.3.1",
|
||||||
"jszip": "3.10.1",
|
"jszip": "3.10.1",
|
||||||
"lenis": "1.3.26",
|
"lucide-react": "1.41.0",
|
||||||
"lucide-react": "1.38.0",
|
|
||||||
"lzma-wasm": "1.0.7",
|
"lzma-wasm": "1.0.7",
|
||||||
"motion": "13.1.1",
|
"motion": "13.2.0",
|
||||||
"music-metadata": "11.15.0",
|
"music-metadata": "11.15.0",
|
||||||
"mysql2": "3.24.2",
|
"mysql2": "3.24.3",
|
||||||
"next": "16.3.4",
|
"next": "16.3.4",
|
||||||
"next-auth": "5.0.0-beta.32",
|
"next-auth": "5.0.0-beta.32",
|
||||||
"next-intl": "4.14.1",
|
"next-intl": "4.14.2",
|
||||||
"otplib": "13.5.0",
|
"otplib": "13.5.0",
|
||||||
"pino": "10.3.1",
|
"pino": "10.3.1",
|
||||||
"react": "19.2.8",
|
"react": "19.2.8",
|
||||||
"react-dom": "19.2.8",
|
"react-dom": "19.2.8",
|
||||||
"react-hook-form": "7.87.0",
|
"react-hook-form": "7.87.0",
|
||||||
"resend": "6.25.0",
|
"resend": "6.26.0",
|
||||||
"server-only": "0.0.1",
|
"server-only": "0.0.1",
|
||||||
"sharp": "^0.35.4",
|
"sharp": "^0.35.4",
|
||||||
"sonner": "2.0.8",
|
"sonner": "2.0.8",
|
||||||
"tailwind-merge": "3.6.0",
|
"tailwind-merge": "3.6.0",
|
||||||
|
"tinymce": "8.9.0",
|
||||||
"zod": "4.5.4"
|
"zod": "4.5.4"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@biomejs/biome": "2.5.11",
|
"@babel/parser": "7.29.8",
|
||||||
|
"@biomejs/biome": "2.5.12",
|
||||||
"@playwright/test": "^1.62.1",
|
"@playwright/test": "^1.62.1",
|
||||||
"@tailwindcss/forms": "0.5.11",
|
"@tailwindcss/forms": "0.5.11",
|
||||||
"@tailwindcss/postcss": "4.3.3",
|
"@tailwindcss/postcss": "4.3.3",
|
||||||
"@tailwindcss/typography": "0.5.20",
|
"@tailwindcss/typography": "0.5.20",
|
||||||
"@types/node": "26.4.0",
|
"@types/node": "26.4.1",
|
||||||
"@types/react": "19.2.18",
|
"@types/react": "19.2.18",
|
||||||
"@types/react-dom": "19.2.5",
|
"@types/react-dom": "19.2.7",
|
||||||
"@vitest/coverage-v8": "4.1.11",
|
"@vitest/coverage-v8": "5.0.0",
|
||||||
"drizzle-kit": "0.31.10",
|
"drizzle-kit": "0.31.10",
|
||||||
"husky": "9.1.7",
|
"husky": "9.1.7",
|
||||||
"knip": "6.33.0",
|
"knip": "6.34.0",
|
||||||
"lint-staged": "17.4.1",
|
"lint-staged": "17.4.1",
|
||||||
"pino-pretty": "13.1.3",
|
"pino-pretty": "13.1.3",
|
||||||
"postcss": "^8.5.26",
|
"postcss": "8.5.28",
|
||||||
"tailwindcss": "4.3.3",
|
"tailwindcss": "4.3.3",
|
||||||
"tsx": "4.23.13",
|
"tsx": "4.23.13",
|
||||||
"typescript": "7.0.2",
|
"typescript": "7.0.2",
|
||||||
"vitest": "4.1.11"
|
"vitest": "5.0.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Generated
+542
-356
File diff suppressed because it is too large.
Load diff
+4
-71
@@ -1,80 +1,13 @@
|
|||||||
# pnpm-workspace.yaml
|
|
||||||
|
|
||||||
allowBuilds:
|
allowBuilds:
|
||||||
esbuild: true
|
esbuild: true
|
||||||
sharp: true
|
sharp: true
|
||||||
"@parcel/watcher": true
|
"@parcel/watcher": true
|
||||||
"@swc/core": true
|
"@swc/core": true
|
||||||
bcrypt: true
|
|
||||||
|
|
||||||
minimumReleaseAgeExclude:
|
minimumReleaseAge: 1440
|
||||||
- "@base-ui/[email protected]"
|
|
||||||
- "@base-ui/[email protected]"
|
|
||||||
- "@biomejs/[email protected]"
|
|
||||||
- "@biomejs/[email protected]"
|
|
||||||
- "@biomejs/[email protected]"
|
|
||||||
- "@biomejs/[email protected]"
|
|
||||||
- "@biomejs/[email protected]"
|
|
||||||
- "@biomejs/[email protected]"
|
|
||||||
- "@biomejs/[email protected]"
|
|
||||||
- "@biomejs/[email protected]"
|
|
||||||
- "@biomejs/[email protected]"
|
|
||||||
- "@hookform/[email protected]"
|
|
||||||
- "@next/[email protected]"
|
|
||||||
- "@next/[email protected]"
|
|
||||||
- "@next/[email protected]"
|
|
||||||
- "@next/[email protected]"
|
|
||||||
- "@next/[email protected]"
|
|
||||||
- "@next/[email protected]"
|
|
||||||
- "@next/[email protected]"
|
|
||||||
- "@next/[email protected]"
|
|
||||||
- "@next/[email protected]"
|
|
||||||
- "@next/[email protected]"
|
|
||||||
- "@next/[email protected]"
|
|
||||||
- "@next/[email protected]"
|
|
||||||
- "@next/[email protected]"
|
|
||||||
- "@next/[email protected]"
|
|
||||||
- "@next/[email protected]"
|
|
||||||
- "@next/[email protected]"
|
|
||||||
- "@next/[email protected]"
|
|
||||||
- "@next/[email protected]"
|
|
||||||
- "@next/[email protected]"
|
|
||||||
- "@next/[email protected]"
|
|
||||||
- "[email protected]"
|
|
||||||
- "[email protected]"
|
|
||||||
- "[email protected]"
|
|
||||||
- "[email protected]"
|
|
||||||
- "[email protected]"
|
|
||||||
- "[email protected]"
|
|
||||||
- "[email protected]"
|
|
||||||
- "[email protected]"
|
|
||||||
- "[email protected]"
|
|
||||||
|
|
||||||
overrides:
|
overrides:
|
||||||
glob: "^11.0.3"
|
# drizzle-kit still uses an obsolete development-server dependency.
|
||||||
rimraf: "^6.0.1"
|
"@esbuild-kit/core-utils>esbuild": "^0.25.9"
|
||||||
uuid: "^11.1.0"
|
|
||||||
fast-uri: "^3.1.3"
|
|
||||||
"@hono/node-server": "^1.19.13"
|
|
||||||
postcss: "^8.5.26"
|
|
||||||
tmp: "^0.2.6"
|
|
||||||
sharp: "^0.35.4"
|
|
||||||
brace-expansion: "^5.0.8"
|
|
||||||
"@types/react": "19.2.18"
|
"@types/react": "19.2.18"
|
||||||
"@types/react-dom": "19.2.5"
|
"@types/react-dom": "19.2.7"
|
||||||
# Tijdelijke mitigatie voor drizzle-kit audit
|
|
||||||
esbuild: "^0.25.9"
|
|
||||||
|
|
||||||
allowedDeprecatedVersions:
|
|
||||||
"@esbuild-kit/esm-loader": "*"
|
|
||||||
"@esbuild-kit/core-utils": "*"
|
|
||||||
|
|
||||||
ignoredBuiltDependencies:
|
|
||||||
- "@prisma/engines"
|
|
||||||
- "prisma"
|
|
||||||
|
|
||||||
peerDependencyRules:
|
|
||||||
allowedVersions:
|
|
||||||
nodemailer: "9.0.3"
|
|
||||||
ignoreMissing:
|
|
||||||
- nodemailer
|
|
||||||
+24
-17
@@ -14,29 +14,36 @@
|
|||||||
"prConcurrentLimit": 5,
|
"prConcurrentLimit": 5,
|
||||||
"packageRules": [
|
"packageRules": [
|
||||||
{
|
{
|
||||||
"description": "Group all dependency updates into a single PR",
|
"matchDepTypes": ["devDependencies"],
|
||||||
"matchPackagePatterns": ["*"],
|
"matchUpdateTypes": ["minor", "patch"],
|
||||||
"groupName": "All dependencies",
|
"groupName": "Development tools",
|
||||||
"groupSlug": "all",
|
"automerge": false
|
||||||
"automerge": true
|
},
|
||||||
|
{
|
||||||
|
"matchPackageNames": [
|
||||||
|
"@base-ui/react",
|
||||||
|
"lucide-react",
|
||||||
|
"motion",
|
||||||
|
"@dnd-kit/**"
|
||||||
|
],
|
||||||
|
"matchUpdateTypes": ["minor", "patch"],
|
||||||
|
"groupName": "Interface libraries",
|
||||||
|
"automerge": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"matchPackageNames": ["vitest", "@vitest/coverage-v8"],
|
||||||
|
"groupName": "Vitest",
|
||||||
|
"automerge": false
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"description": "Major updates need manual review",
|
|
||||||
"matchUpdateTypes": ["major"],
|
"matchUpdateTypes": ["major"],
|
||||||
"labels": ["dependencies", "major"],
|
"automerge": false
|
||||||
"automerge": false,
|
|
||||||
"assignees": [],
|
|
||||||
"reviewers": []
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"description": "Disable updates for engine pins",
|
|
||||||
"matchPackageNames": ["node", "pnpm"],
|
"matchPackageNames": ["node", "pnpm"],
|
||||||
"enabled": false
|
"enabled": false
|
||||||
},
|
|
||||||
{
|
|
||||||
"description": "Disable server-only (abandoned, pinned at 0.0.1)",
|
|
||||||
"matchPackageNames": ["server-only"],
|
|
||||||
"enabled": false
|
|
||||||
}
|
}
|
||||||
]
|
],
|
||||||
|
"minimumReleaseAge": "3 days",
|
||||||
|
"automerge": false
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
import fs from "node:fs";
|
||||||
|
import path from "node:path";
|
||||||
|
import * as babel from "@babel/parser";
|
||||||
|
import { parse } from "@formatjs/icu-messageformat-parser";
|
||||||
|
|
||||||
|
const flat = (obj, p = "", r = {}) => {
|
||||||
|
for (const [k, v] of Object.entries(obj)) {
|
||||||
|
const key = p ? `${p}.${k}` : k;
|
||||||
|
if (v && typeof v === "object") flat(v, key, r);
|
||||||
|
else r[key] = v;
|
||||||
|
}
|
||||||
|
return r;
|
||||||
|
};
|
||||||
|
const messages = Object.fromEntries(
|
||||||
|
fs
|
||||||
|
.readdirSync("src/messages")
|
||||||
|
.filter((n) => n.endsWith(".json"))
|
||||||
|
.map((n) => [
|
||||||
|
n.slice(0, -5),
|
||||||
|
flat(JSON.parse(fs.readFileSync(`src/messages/${n}`, "utf8"))),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
const base = messages.en,
|
||||||
|
invalid = [],
|
||||||
|
mismatches = [];
|
||||||
|
function vars(ast, r = new Set()) {
|
||||||
|
for (const n of ast) {
|
||||||
|
if ([1, 2, 3, 4, 5, 6, 8].includes(n.type)) r.add(n.value);
|
||||||
|
if (n.options) for (const o of Object.values(n.options)) vars(o.value, r);
|
||||||
|
if (n.children) vars(n.children, r);
|
||||||
|
}
|
||||||
|
return [...r].sort().join(",");
|
||||||
|
}
|
||||||
|
const signatures = {};
|
||||||
|
for (const [k, v] of Object.entries(base)) {
|
||||||
|
try {
|
||||||
|
signatures[k] = vars(parse(v));
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
const locales = Object.entries(messages).map(([locale, m]) => {
|
||||||
|
for (const [k, v] of Object.entries(m)) {
|
||||||
|
try {
|
||||||
|
const sig = vars(parse(v));
|
||||||
|
if (k in signatures && sig !== signatures[k])
|
||||||
|
mismatches.push({
|
||||||
|
locale,
|
||||||
|
key: k,
|
||||||
|
expected: signatures[k],
|
||||||
|
actual: sig,
|
||||||
|
value: v,
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
invalid.push({ locale, key: k, value: v, error: e.message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
locale,
|
||||||
|
total: Object.keys(m).length,
|
||||||
|
missing: Object.keys(base).filter((k) => !(k in m)).length,
|
||||||
|
empty: Object.values(m).filter((v) => !v?.trim()).length,
|
||||||
|
sameAsEnglish: Object.keys(base).filter((k) => m[k] === base[k]).length,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
const missingCalls = [],
|
||||||
|
hardcoded = [],
|
||||||
|
unparsedFiles = [];
|
||||||
|
function walk(n, fn) {
|
||||||
|
if (!n || typeof n !== "object") return;
|
||||||
|
fn(n);
|
||||||
|
for (const [k, v] of Object.entries(n)) {
|
||||||
|
if (k === "loc" || k === "extra") continue;
|
||||||
|
if (Array.isArray(v))
|
||||||
|
v.forEach((x) => {
|
||||||
|
walk(x, fn);
|
||||||
|
});
|
||||||
|
else if (v && typeof v === "object") walk(v, fn);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const f of fs
|
||||||
|
.readdirSync("src", { recursive: true })
|
||||||
|
.filter((f) => /\.(tsx|ts)$/.test(f) && !f.includes(".test."))) {
|
||||||
|
let ast;
|
||||||
|
try {
|
||||||
|
ast = babel.parse(fs.readFileSync(path.join("src", f), "utf8"), {
|
||||||
|
sourceType: "module",
|
||||||
|
plugins: ["typescript", "jsx"],
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
unparsedFiles.push({ file: f, error: error.message });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const bindings = {};
|
||||||
|
walk(ast, (n) => {
|
||||||
|
if (n.type === "VariableDeclarator" && n.id.type === "Identifier") {
|
||||||
|
let c = n.init;
|
||||||
|
if (c?.type === "AwaitExpression") c = c.argument;
|
||||||
|
if (
|
||||||
|
c?.type === "CallExpression" &&
|
||||||
|
["useTranslations", "getTranslations"].includes(c.callee.name)
|
||||||
|
) {
|
||||||
|
const arg = c.arguments[0];
|
||||||
|
const ns =
|
||||||
|
arg?.type === "StringLiteral"
|
||||||
|
? arg.value
|
||||||
|
: arg?.type === "ObjectExpression"
|
||||||
|
? arg.properties.find((p) => p.key?.name === "namespace")?.value
|
||||||
|
?.value
|
||||||
|
: arg
|
||||||
|
? null
|
||||||
|
: "";
|
||||||
|
if (ns !== null) {
|
||||||
|
bindings[n.id.name] ??= new Set();
|
||||||
|
bindings[n.id.name].add(ns);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
walk(ast, (n) => {
|
||||||
|
if (n.type === "CallExpression") {
|
||||||
|
const name = n.callee.name ?? n.callee.object?.name;
|
||||||
|
const ns = bindings[name];
|
||||||
|
const k = n.arguments[0];
|
||||||
|
if (ns?.size === 1 && k?.type === "StringLiteral") {
|
||||||
|
const full = [...ns][0] ? `${[...ns][0]}.${k.value}` : k.value;
|
||||||
|
if (
|
||||||
|
!(full in base) &&
|
||||||
|
!Object.keys(base).some((b) => b.startsWith(`${full}.`))
|
||||||
|
)
|
||||||
|
missingCalls.push({ file: f, line: n.loc.start.line, key: full });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (n.type === "JSXText" && /[A-Za-z]{3}/.test(n.value.trim()))
|
||||||
|
hardcoded.push({
|
||||||
|
file: f,
|
||||||
|
line: n.loc.start.line,
|
||||||
|
text: n.value.trim().replace(/\s+/g, " "),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const result = {
|
||||||
|
locales,
|
||||||
|
invalid,
|
||||||
|
mismatches,
|
||||||
|
missingCalls,
|
||||||
|
hardcoded,
|
||||||
|
unparsedFiles,
|
||||||
|
};
|
||||||
|
if (process.argv.includes("--json"))
|
||||||
|
console.log(JSON.stringify(result, null, 2));
|
||||||
|
else {
|
||||||
|
console.table(locales);
|
||||||
|
console.log(
|
||||||
|
"Invalid ICU:",
|
||||||
|
invalid.length,
|
||||||
|
"Variable mismatches:",
|
||||||
|
mismatches.length,
|
||||||
|
"Missing static message references:",
|
||||||
|
missingCalls.length,
|
||||||
|
);
|
||||||
|
console.log(
|
||||||
|
"Literal JSX text candidates requiring editorial review:",
|
||||||
|
hardcoded.length,
|
||||||
|
);
|
||||||
|
console.log(
|
||||||
|
"Coverage checks static translator namespaces and literal keys; dynamic keys and semantic translation quality require review.",
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
invalid.length ||
|
||||||
|
mismatches.length ||
|
||||||
|
missingCalls.length ||
|
||||||
|
unparsedFiles.length
|
||||||
|
)
|
||||||
|
console.log(
|
||||||
|
JSON.stringify(
|
||||||
|
{ invalid, mismatches, missingCalls, unparsedFiles },
|
||||||
|
null,
|
||||||
|
2,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
process.argv.includes("--check") &&
|
||||||
|
(invalid.length ||
|
||||||
|
mismatches.length ||
|
||||||
|
missingCalls.length ||
|
||||||
|
unparsedFiles.length ||
|
||||||
|
locales.some((locale) => locale.empty > 0))
|
||||||
|
)
|
||||||
|
process.exitCode = 1;
|
||||||
@@ -0,0 +1,254 @@
|
|||||||
|
// Bulk-load >50 MB JSON into MariaDB in resumable chunks (2000 rows/batch).
|
||||||
|
//
|
||||||
|
// Drizzle multi-row INSERTs are wrapped in ONE statement per chunk, so a
|
||||||
|
// 50 MB dump becomes a few dozen statements instead of hundreds of thousands
|
||||||
|
// of round-trips — no connect/packet timeouts, no "Pulling schema from
|
||||||
|
// database..." freeze (that hang is introspection racing a saturated server).
|
||||||
|
//
|
||||||
|
// Usage (via pnpm, as required):
|
||||||
|
// pnpm exec tsx scripts/bulk-import-json.ts \
|
||||||
|
// --file=/var/www/Gamedata/.../FurnitureData.json [--chunk-size=2000]
|
||||||
|
//
|
||||||
|
// Input shapes supported automatically:
|
||||||
|
// A) habbo furnidata_json → { roomitemtypes:{furnitype:[…]}, wallitemtypes:{…} }
|
||||||
|
// B) flat array of objects → [ {…}, {…} ]
|
||||||
|
//
|
||||||
|
// Flags:
|
||||||
|
// --file=<path> JSON file to load (required)
|
||||||
|
// --table=<name> one of: furnidata | docs | texts (default: furnidata)
|
||||||
|
// --category=<x> category value for docs/texts tables
|
||||||
|
// --source=<x> source value for furnidata table (default: habbo)
|
||||||
|
// --chunk-size=N rows per multi-row INSERT (default: 2000)
|
||||||
|
// --limit=N stop after N rows (dry-test without loading everything)
|
||||||
|
// --truncate DELETE all rows for this table's source/category first
|
||||||
|
//
|
||||||
|
// Idempotent by default: rows re-import on their unique key with
|
||||||
|
// ON DUPLICATE KEY UPDATE, so interrupted runs resume safely.
|
||||||
|
|
||||||
|
import "./load-env";
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { resolve } from "node:path";
|
||||||
|
import { sql } from "drizzle-orm";
|
||||||
|
import { drizzle } from "drizzle-orm/mysql2";
|
||||||
|
import mysql from "mysql2/promise";
|
||||||
|
import {
|
||||||
|
GamedataDocs,
|
||||||
|
GamedataFurnidata,
|
||||||
|
GamedataTexts,
|
||||||
|
} from "@/db/schema-gamedata";
|
||||||
|
import { mysqlConnectionUrl } from "./db-url";
|
||||||
|
|
||||||
|
interface Args {
|
||||||
|
file: string;
|
||||||
|
table: "furnidata" | "docs" | "texts";
|
||||||
|
category: string;
|
||||||
|
source: string;
|
||||||
|
chunkSize: number;
|
||||||
|
limit: number;
|
||||||
|
truncate: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const FURNIDATA_SECTIONS = {
|
||||||
|
roomitemtypes: "s",
|
||||||
|
flooritemtypes: "s",
|
||||||
|
wallitemtypes: "i",
|
||||||
|
effecttypes: "e",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
function parseArgs(raw: string[]): Args {
|
||||||
|
const get = (name: string) => {
|
||||||
|
const hit = raw.find((a) => a.startsWith(`--${name}=`));
|
||||||
|
return hit?.slice(name.length + 3);
|
||||||
|
};
|
||||||
|
const has = (name: string) => raw.includes(`--${name}`);
|
||||||
|
const file = get("file");
|
||||||
|
if (!file) {
|
||||||
|
console.error(
|
||||||
|
"Usage: pnpm exec tsx scripts/bulk-import-json.ts --file=<path> [--table=furnidata|docs|texts] [--category=<x>] [--source=<x>] [--chunk-size=2000] [--limit=N] [--truncate]",
|
||||||
|
);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
const table = (get("table") ?? "furnidata") as Args["table"];
|
||||||
|
return {
|
||||||
|
file: resolve(file),
|
||||||
|
table,
|
||||||
|
category: get("category") ?? "default",
|
||||||
|
source: get("source") ?? "habbo",
|
||||||
|
chunkSize: Number(get("chunk-size") ?? "2000"),
|
||||||
|
limit: Number(get("limit") ?? "0"),
|
||||||
|
truncate: has("truncate"),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// A >50 MB file parses fine with a single JSON.parse (V8 string limit is far
|
||||||
|
// higher); streaming row-by-row would slow the seed down for no memory win.
|
||||||
|
async function readJsonFile(file: string): Promise<unknown> {
|
||||||
|
const { readFile } = await import("node:fs/promises");
|
||||||
|
return JSON.parse(await readFile(file, "utf8"));
|
||||||
|
}
|
||||||
|
|
||||||
|
interface NormalizedRow {
|
||||||
|
[key: string]: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Normalize any supported shape into a flat list of JSON documents.
|
||||||
|
function normalize(json: unknown, table: Args["table"]): NormalizedRow[] {
|
||||||
|
if (table !== "furnidata") {
|
||||||
|
if (Array.isArray(json)) return json as NormalizedRow[];
|
||||||
|
throw new Error(`Expected a top-level array for --table=${table}`);
|
||||||
|
}
|
||||||
|
if (Array.isArray(json)) return json as NormalizedRow[];
|
||||||
|
|
||||||
|
// habbo furnidata_json: { roomitemtypes: { furnitype: [...] }, ... }
|
||||||
|
if (json && typeof json === "object") {
|
||||||
|
const rows: NormalizedRow[] = [];
|
||||||
|
for (const [section, kind] of Object.entries(FURNIDATA_SECTIONS)) {
|
||||||
|
const block = (json as Record<string, unknown>)[section];
|
||||||
|
if (!block || typeof block !== "object") continue;
|
||||||
|
const list = (block as Record<string, unknown>).furnitype;
|
||||||
|
if (!Array.isArray(list)) continue;
|
||||||
|
for (const item of list) rows.push({ ...item, kind });
|
||||||
|
}
|
||||||
|
return rows;
|
||||||
|
}
|
||||||
|
throw new Error("Unsupported JSON shape: expected array or furnidata_json");
|
||||||
|
}
|
||||||
|
|
||||||
|
function toFurnidataRow(
|
||||||
|
row: NormalizedRow,
|
||||||
|
source: string,
|
||||||
|
): Record<string, unknown> {
|
||||||
|
return {
|
||||||
|
source,
|
||||||
|
kind: (row.kind as "s" | "i" | "e") ?? "s",
|
||||||
|
className: String(row.classname ?? row.className ?? ""),
|
||||||
|
publicName: String(row.public_name ?? row.publicName ?? ""),
|
||||||
|
spriteId: Number(row.id ?? 0),
|
||||||
|
payload: JSON.stringify(row),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function toDocsRow(
|
||||||
|
row: NormalizedRow,
|
||||||
|
category: string,
|
||||||
|
): Record<string, unknown> {
|
||||||
|
const payload = JSON.stringify(row);
|
||||||
|
return {
|
||||||
|
category,
|
||||||
|
docKey: String(row.key ?? row.docKey ?? row.id ?? ""),
|
||||||
|
payload,
|
||||||
|
payloadSha1: createHash("sha1").update(payload).digest("hex"),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function toTextsRow(
|
||||||
|
row: NormalizedRow,
|
||||||
|
category: string,
|
||||||
|
): Record<string, unknown> {
|
||||||
|
return {
|
||||||
|
category,
|
||||||
|
textKey: String(row.key ?? row.id ?? ""),
|
||||||
|
value: String(row.value ?? row.text ?? row),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const args = parseArgs(process.argv.slice(2));
|
||||||
|
const url = process.env.DATABASE_URL;
|
||||||
|
if (!url)
|
||||||
|
throw new Error("DATABASE_URL is required (load-env.ts loaded .env)");
|
||||||
|
|
||||||
|
const conn = await mysql.createConnection(mysqlConnectionUrl(url));
|
||||||
|
const db = drizzle(conn);
|
||||||
|
|
||||||
|
// Session bulk-load flags: worst case per chunk is a lost commit, not a
|
||||||
|
// corrupt table. FOREIGN_KEY_CHECKS off keeps each 50 MB chunk off FK
|
||||||
|
// validation work; UNIQUE_CHECK is a per-statement no-op vs ON DUPLICATE.
|
||||||
|
await conn.query("SET SESSION FOREIGN_KEY_CHECKS=0");
|
||||||
|
await conn.query("SET SESSION sql_mode='NO_ENGINE_SUBSTITUTION'");
|
||||||
|
|
||||||
|
const tableRef =
|
||||||
|
args.table === "furnidata"
|
||||||
|
? GamedataFurnidata
|
||||||
|
: args.table === "docs"
|
||||||
|
? GamedataDocs
|
||||||
|
: GamedataTexts;
|
||||||
|
const keyWhere =
|
||||||
|
args.table === "furnidata"
|
||||||
|
? sql`${GamedataFurnidata.source} = ${args.source}`
|
||||||
|
: args.table === "docs"
|
||||||
|
? sql`${GamedataDocs.category} = ${args.category}`
|
||||||
|
: sql`${GamedataTexts.category} = ${args.category}`;
|
||||||
|
|
||||||
|
if (args.truncate) {
|
||||||
|
await db.execute(sql`DELETE FROM ${tableRef} WHERE ${keyWhere}`);
|
||||||
|
console.log(`[bulk] truncated rows for ${args.table}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`[bulk] reading ${args.file} …`);
|
||||||
|
const json = await readJsonFile(args.file);
|
||||||
|
const rows = normalize(json, args.table);
|
||||||
|
console.log(`[bulk] parsed ${rows.length} documents (${args.table})`);
|
||||||
|
|
||||||
|
const mapper: (r: NormalizedRow) => Record<string, unknown> =
|
||||||
|
args.table === "furnidata"
|
||||||
|
? (r) => toFurnidataRow(r, args.source)
|
||||||
|
: args.table === "docs"
|
||||||
|
? (r) => toDocsRow(r, args.category)
|
||||||
|
: (r) => toTextsRow(r, args.category);
|
||||||
|
|
||||||
|
const values = rows
|
||||||
|
.slice(0, args.limit || rows.length)
|
||||||
|
.map<Record<string, unknown>>(mapper);
|
||||||
|
const total = values.length;
|
||||||
|
const chunkSize = args.chunkSize;
|
||||||
|
const started = Date.now();
|
||||||
|
let inserted = 0;
|
||||||
|
|
||||||
|
for (let i = 0; i < total; i += chunkSize) {
|
||||||
|
const chunk = values.slice(i, Math.min(i + chunkSize, total));
|
||||||
|
// `tableRef` is a 3-way union; drizzle's insert is typed per single
|
||||||
|
// table, so narrow through a custom shape here (runtime is unaffected).
|
||||||
|
const insert = db.insert(tableRef) as unknown as {
|
||||||
|
values: (rows: typeof chunk) => {
|
||||||
|
onDuplicateKeyUpdate: (opts: {
|
||||||
|
set: Record<string, unknown>;
|
||||||
|
}) => Promise<unknown>;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
await insert.values(chunk).onDuplicateKeyUpdate({
|
||||||
|
// MariaDB `VALUES(col)` = the incoming row value; re-runs overwrite.
|
||||||
|
set: Object.fromEntries(
|
||||||
|
Object.keys(chunk[0] ?? {}).map((k) => [
|
||||||
|
k,
|
||||||
|
sql.raw(`values(\`${k}\`)`),
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
});
|
||||||
|
|
||||||
|
inserted += chunk.length;
|
||||||
|
const remaining = total - i - chunk.length;
|
||||||
|
if (inserted % (chunkSize * 10) < chunkSize || remaining <= 0) {
|
||||||
|
const elapsedSec = (Date.now() - started) / 1000;
|
||||||
|
const rate = Math.round(inserted / Math.max(elapsedSec, 0.001));
|
||||||
|
const etaMin = Math.round(remaining / Math.max(rate, 1) / 60);
|
||||||
|
console.log(
|
||||||
|
`[bulk] ${inserted}/${total} (${Math.round((inserted / total) * 100)}%) ${rate} rows/s, ETA ~${etaMin}m`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const sec = ((Date.now() - started) / 1000).toFixed(1);
|
||||||
|
console.log(`[bulk] DONE: ${inserted}/${total} rows in ${sec}s`);
|
||||||
|
if (total === args.limit && args.limit > 0) {
|
||||||
|
console.log(
|
||||||
|
" NOTE: --limit was set; run again without it for the full dump.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
await conn.end();
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((err) => {
|
||||||
|
console.error("[bulk] FATAL:", err instanceof Error ? err.message : err);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# One lock covers build, migrations, cutover, health checks and smoke tests.
|
||||||
|
set -Eeuo pipefail
|
||||||
|
|
||||||
|
deploy_dir="${CMS_DEPLOY_DIR:-/var/www/atom-nexst}"
|
||||||
|
branch="${DEPLOY_BRANCH:-main}"
|
||||||
|
case "$branch" in main|master) ;; *) echo "Unsupported deployment branch" >&2; exit 1 ;; esac
|
||||||
|
exec 9>"$deploy_dir/.deploy.lock"
|
||||||
|
flock -w 1800 9
|
||||||
|
|
||||||
|
sha="$(git rev-parse HEAD)"
|
||||||
|
[[ "$sha" =~ ^[0-9a-f]{40}$ ]] || { echo "Invalid commit" >&2; exit 1; }
|
||||||
|
image="epicnext-cms:$sha"
|
||||||
|
previous_name=""
|
||||||
|
previous_image=""
|
||||||
|
backup_name="epicnext-cms-rollback"
|
||||||
|
cutover_started=0
|
||||||
|
candidate_attempted=0
|
||||||
|
backup_created=0
|
||||||
|
|
||||||
|
is_current() {
|
||||||
|
local head
|
||||||
|
head="$(git ls-remote --exit-code origin "refs/heads/$branch")" || return 2
|
||||||
|
head="${head%%[[:space:]]*}"
|
||||||
|
if [ "$head" != "$sha" ]; then
|
||||||
|
echo "Skipping superseded commit $sha (branch now at $head)"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
check_current() {
|
||||||
|
local status=0
|
||||||
|
is_current || status=$?
|
||||||
|
case "$status" in 0) ;; 1) exit 0 ;; *) echo "Cannot verify remote branch" >&2; exit 1 ;; esac
|
||||||
|
}
|
||||||
|
|
||||||
|
healthy() {
|
||||||
|
local attempt
|
||||||
|
for attempt in $(seq 1 30); do
|
||||||
|
if curl -sf --max-time 5 http://127.0.0.1:3002/api/health | grep -q '"database":true'; then return 0; fi
|
||||||
|
sleep 3
|
||||||
|
done
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
finish() {
|
||||||
|
local status=$?
|
||||||
|
trap - EXIT
|
||||||
|
if [ "$status" -ne 0 ] && [ "$cutover_started" -eq 1 ]; then
|
||||||
|
echo "Deployment failed; restoring previous container" >&2
|
||||||
|
docker logs epicnext-cms-app --tail 50 >&2 || true
|
||||||
|
if [ "$candidate_attempted" -eq 1 ]; then docker rm -f epicnext-cms-app || true; fi
|
||||||
|
if [ "$backup_created" -eq 1 ]; then docker rename "$backup_name" "$previous_name" || true; fi
|
||||||
|
if [ -n "$previous_name" ]; then
|
||||||
|
if docker start "$previous_name" && healthy; then
|
||||||
|
echo "Rollback verified: $previous_image"
|
||||||
|
else
|
||||||
|
echo "ERROR: previous container could not be restored to healthy state" >&2
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
echo "No previous container exists; rollback is unavailable" >&2
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
exit "$status"
|
||||||
|
}
|
||||||
|
trap finish EXIT
|
||||||
|
trap 'exit 130' INT
|
||||||
|
trap 'exit 143' TERM
|
||||||
|
|
||||||
|
check_current
|
||||||
|
cp "$deploy_dir/.env" .env
|
||||||
|
pnpm install --frozen-lockfile
|
||||||
|
# Prepare browser before cutover so installation failures cannot interrupt the site.
|
||||||
|
pnpm exec playwright install chromium
|
||||||
|
|
||||||
|
echo "Building $image"
|
||||||
|
# Throw away the previous build cache before each build so disk usage doesn't
|
||||||
|
# grow unbounded across deployments. The current release image (`epicnext-cms`)
|
||||||
|
# is still reused as a base layer via `--cache-from`; only the accumulated
|
||||||
|
# BuildKit intermediate cache is discarded.
|
||||||
|
docker builder prune -af --filter "until=1h" --keep-storage=0 2>/dev/null || true
|
||||||
|
DOCKER_BUILDKIT=1 docker build --network=host --progress=plain --cache-from epicnext-cms:latest \
|
||||||
|
--build-arg NEXT_DEPLOYMENT_ID="$sha" -t "$image" .
|
||||||
|
check_current
|
||||||
|
pnpm db:migrate
|
||||||
|
check_current
|
||||||
|
|
||||||
|
# Prefer the active CI container, or the active legacy compose container.
|
||||||
|
for name in epicnext-cms-app epicnext-cms; do
|
||||||
|
if [ "$(docker inspect --format '{{.State.Running}}' "$name" 2>/dev/null || true)" = true ]; then
|
||||||
|
previous_name="$name"
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
if [ -z "$previous_name" ]; then
|
||||||
|
for name in epicnext-cms-app epicnext-cms; do
|
||||||
|
if docker inspect "$name" >/dev/null 2>&1; then previous_name="$name"; break; fi
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
if docker inspect "$backup_name" >/dev/null 2>&1; then
|
||||||
|
echo "Unresolved rollback container exists; refusing to overwrite it" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
if [ -n "$previous_name" ]; then
|
||||||
|
previous_image="$(docker inspect --format '{{.Image}}' "$previous_name")"
|
||||||
|
docker tag "$previous_image" epicnext-cms:previous
|
||||||
|
fi
|
||||||
|
# Remove a stopped leftover CI container when the compose container is active.
|
||||||
|
if [ "$previous_name" != epicnext-cms-app ] && docker inspect epicnext-cms-app >/dev/null 2>&1; then
|
||||||
|
docker rm epicnext-cms-app
|
||||||
|
fi
|
||||||
|
|
||||||
|
cutover_started=1
|
||||||
|
if [ -n "$previous_name" ]; then
|
||||||
|
docker stop "$previous_name"
|
||||||
|
docker rename "$previous_name" "$backup_name"
|
||||||
|
backup_created=1
|
||||||
|
fi
|
||||||
|
candidate_attempted=1
|
||||||
|
(
|
||||||
|
set -a
|
||||||
|
# shellcheck disable=SC1091
|
||||||
|
. "$deploy_dir/.env"
|
||||||
|
set +a
|
||||||
|
ENV_ARGS=()
|
||||||
|
while IFS='=' read -r key _; do
|
||||||
|
case "$key" in ''|'#'*|*[!A-Za-z0-9_]* ) continue ;; esac
|
||||||
|
ENV_ARGS+=(-e "$key")
|
||||||
|
done < "$deploy_dir/.env"
|
||||||
|
docker run -d --name epicnext-cms-app --restart always --net=host \
|
||||||
|
"${ENV_ARGS[@]}" \
|
||||||
|
-v "$deploy_dir/public/nitro-assets:/app/public/nitro-assets" \
|
||||||
|
-v "$deploy_dir/public/swf:/app/public/swf" \
|
||||||
|
-v "$deploy_dir/storage:/app/storage" \
|
||||||
|
-v /var/www/Gamedata:/var/www/Gamedata \
|
||||||
|
"$image"
|
||||||
|
)
|
||||||
|
healthy
|
||||||
|
PLAYWRIGHT_BASE_URL=http://127.0.0.1:3002 pnpm test:e2e
|
||||||
|
# Publish the latest alias only after health and browser checks pass.
|
||||||
|
docker tag "$image" epicnext-cms:latest
|
||||||
|
cutover_started=0
|
||||||
|
if [ "$backup_created" -eq 1 ]; then docker rm "$backup_name" || true; fi
|
||||||
|
|
||||||
|
echo "Deployment verified: $sha"
|
||||||
|
# Retain the current and previous releases; do not remove arbitrary named tags.
|
||||||
|
while IFS= read -r tag; do
|
||||||
|
if [[ "$tag" =~ ^epicnext-cms:[0-9a-f]{40}$ ]] && [ "$tag" != "$image" ]; then
|
||||||
|
tagged_image="$(docker image inspect --format '{{.Id}}' "$tag" 2>/dev/null || true)"
|
||||||
|
if [ -n "$tagged_image" ] && [ "$tagged_image" != "$previous_image" ]; then docker image rm "$tag" || true; fi
|
||||||
|
fi
|
||||||
|
done < <(docker image ls --format '{{.Repository}}:{{.Tag}}' epicnext-cms)
|
||||||
|
docker builder prune -af --filter "until=72h" --keep-storage=2g || true
|
||||||
|
docker image prune -f --filter "until=168h" || true
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
/**
|
||||||
|
* Pre-compress large gamedata JSON files to .gz so nginx `gzip_static`
|
||||||
|
* serves them via sendfile instead of re-compressing up to 48 MB on every
|
||||||
|
* request (see /etc/nginx/nginx.conf: `gzip_static on`).
|
||||||
|
*
|
||||||
|
* Idempotent: a file is only re-compressed when its source mtime is newer
|
||||||
|
* than the existing .gz (e.g. after a Studio catalog export rewrites it).
|
||||||
|
*
|
||||||
|
* Usage: node scripts/compress-gamedata.mjs
|
||||||
|
* Env: GAMEDATA_ROOT (default /var/www/Gamedata)
|
||||||
|
* GAMEDATA_GZIP_MIN_BYTES (default 1048576)
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { createReadStream, createWriteStream, promises as fs } from "node:fs";
|
||||||
|
import { cpus } from "node:os";
|
||||||
|
import { join, relative } from "node:path";
|
||||||
|
import { pipeline } from "node:stream/promises";
|
||||||
|
import { createGzip } from "node:zlib";
|
||||||
|
|
||||||
|
const GAMEDATA_ROOT = process.env.GAMEDATA_ROOT ?? "/var/www/Gamedata";
|
||||||
|
const MIN_BYTES = Number(process.env.GAMEDATA_GZIP_MIN_BYTES ?? 1024 * 1024);
|
||||||
|
const GZIP_LEVEL = 9;
|
||||||
|
const TARGET_DIRS = ["config", "bundled/config"];
|
||||||
|
const CONCURRENCY = Math.max(1, Math.min(4, cpus().length));
|
||||||
|
|
||||||
|
function isCompressible(name) {
|
||||||
|
return (
|
||||||
|
name.endsWith(".json") &&
|
||||||
|
!name.endsWith(".gz") &&
|
||||||
|
!name.endsWith(".min.json")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function collectCandidates() {
|
||||||
|
const files = [];
|
||||||
|
for (const dir of TARGET_DIRS) {
|
||||||
|
const root = join(GAMEDATA_ROOT, dir);
|
||||||
|
let entries;
|
||||||
|
try {
|
||||||
|
entries = await fs.readdir(root, { withFileTypes: true });
|
||||||
|
} catch {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (const entry of entries) {
|
||||||
|
if (!entry.isFile() || !isCompressible(entry.name)) continue;
|
||||||
|
const full = join(root, entry.name);
|
||||||
|
const stat = await fs.stat(full);
|
||||||
|
if (stat.size < MIN_BYTES) continue;
|
||||||
|
files.push({ src: full, size: stat.size, mtimeMs: stat.mtimeMs });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return files;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function needsCompression({ src, mtimeMs }) {
|
||||||
|
const gz = `${src}.gz`;
|
||||||
|
try {
|
||||||
|
const stat = await fs.stat(gz);
|
||||||
|
return stat.mtimeMs < mtimeMs;
|
||||||
|
} catch {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function compressOne({ src }) {
|
||||||
|
const gz = `${src}.gz`;
|
||||||
|
const tmp = `${gz}.tmp-${process.pid}`;
|
||||||
|
await pipeline(
|
||||||
|
createReadStream(src),
|
||||||
|
createGzip({ level: GZIP_LEVEL }),
|
||||||
|
createWriteStream(tmp),
|
||||||
|
);
|
||||||
|
await fs.rename(tmp, gz);
|
||||||
|
try {
|
||||||
|
await fs.chmod(gz, 0o644);
|
||||||
|
} catch {
|
||||||
|
// Best-effort; ownership is up to the caller.
|
||||||
|
}
|
||||||
|
return gz;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const candidates = await collectCandidates();
|
||||||
|
const work = [];
|
||||||
|
const skipped = [];
|
||||||
|
for (const candidate of candidates) {
|
||||||
|
if (await needsCompression(candidate)) {
|
||||||
|
work.push(candidate);
|
||||||
|
} else {
|
||||||
|
skipped.push(candidate);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const results = [];
|
||||||
|
let idx = 0;
|
||||||
|
async function worker() {
|
||||||
|
while (idx < work.length) {
|
||||||
|
const item = work[idx++];
|
||||||
|
try {
|
||||||
|
const gz = await compressOne(item);
|
||||||
|
const stat = await fs.stat(gz);
|
||||||
|
results.push(
|
||||||
|
`compressed ${relative(GAMEDATA_ROOT, gz)} (${item.size} -> ${stat.size} bytes, ${Math.round((1 - stat.size / item.size) * 1000) / 10}% smaller)`,
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
results.push(
|
||||||
|
`FAILED ${relative(GAMEDATA_ROOT, item.src)}: ${err instanceof Error ? err.message : String(err)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const workers = Array.from(
|
||||||
|
{ length: Math.min(CONCURRENCY, work.length) },
|
||||||
|
() => worker(),
|
||||||
|
);
|
||||||
|
await Promise.all(workers);
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
`gamedata: ${work.length} to compress, ${skipped.length} up to date`,
|
||||||
|
);
|
||||||
|
for (const line of results) console.log(`gamedata: ${line}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((err) => {
|
||||||
|
console.error(
|
||||||
|
`gamedata: FATAL ${err instanceof Error ? err.message : String(err)}`,
|
||||||
|
);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { cp, mkdir } from "node:fs/promises";
|
||||||
|
import { createRequire } from "node:module";
|
||||||
|
import path from "node:path";
|
||||||
|
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
const source = path.dirname(require.resolve("tinymce/package.json"));
|
||||||
|
const target = path.resolve("public/vendor/tinymce");
|
||||||
|
await mkdir(target, { recursive: true });
|
||||||
|
for (const name of [
|
||||||
|
"tinymce.min.js",
|
||||||
|
"icons",
|
||||||
|
"models",
|
||||||
|
"plugins",
|
||||||
|
"skins",
|
||||||
|
"themes",
|
||||||
|
"license.md",
|
||||||
|
"notices.txt",
|
||||||
|
]) {
|
||||||
|
await cp(path.join(source, name), path.join(target, name), {
|
||||||
|
recursive: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
Executable
+139
@@ -0,0 +1,139 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# ==============================================================================
|
||||||
|
# docker-preflight.sh — Verify a VPS is ready to run the Dockerized EpicNext-CMS.
|
||||||
|
#
|
||||||
|
# Lets any supplied .env drive the checks. Checks (all idempotent, none mutating):
|
||||||
|
# 1. Docker + compose available and usable.
|
||||||
|
# 2. Required runtime dirs exist (RW for UID 33 where the CMS writes).
|
||||||
|
# 3. Volume owners are UID/GID 33 (www-data) on the host.
|
||||||
|
# 4. .env exists and required host-network services are reachable.
|
||||||
|
# 5. Port 3002 free (or the host CMS that must be stopped).
|
||||||
|
#
|
||||||
|
# Usage: ./scripts/docker-preflight.sh [--fix]
|
||||||
|
# --fix attempts to auto-correct permission/owner issues (chown).
|
||||||
|
#
|
||||||
|
# Exit codes: 0 ready, 1 not ready (or fixed nothing).
|
||||||
|
# ==============================================================================
|
||||||
|
|
||||||
|
set -uo pipefail
|
||||||
|
|
||||||
|
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||||
|
cd "$DIR" || exit 1
|
||||||
|
|
||||||
|
FIX=0
|
||||||
|
[ "${1:-}" = "--fix" ] && FIX=1
|
||||||
|
|
||||||
|
ENV_FILE="${ENV_FILE:-$DIR/.env}"
|
||||||
|
fail=0
|
||||||
|
warn=0
|
||||||
|
|
||||||
|
# Ports that are expected to be reachable ON THE HOST (network_mode: host).
|
||||||
|
# These mirror the defaults in .env / the emulator stack; override via env.
|
||||||
|
CMS_PORT="${CMS_PORT:-3002}"
|
||||||
|
MYSQL_PORT="${MYSQL_PORT:-3306}"
|
||||||
|
REDIS_PORT="${REDIS_PORT:-6379}"
|
||||||
|
RCON_PORT="${RCON_PORT:-3003}"
|
||||||
|
API_PORT="${API_PORT:-3001}"
|
||||||
|
IMAGER_PORT="${IMAGER_PORT:-8082}"
|
||||||
|
|
||||||
|
# Relative dirs the CMS writes to, plus the absolute shared gamedata root.
|
||||||
|
RW_DIRS=(
|
||||||
|
"$DIR/public/nitro-assets"
|
||||||
|
"$DIR/public/swf"
|
||||||
|
"$DIR/storage"
|
||||||
|
"/var/www/Gamedata"
|
||||||
|
)
|
||||||
|
|
||||||
|
say() { printf ' %s\n' "$*"; }
|
||||||
|
ok() { printf ' \033[32m[OK] \033[0m%s\n' "$*"; }
|
||||||
|
err() { printf ' \033[31m[FAIL]\033[0m %s\n' "$*"; fail=1; }
|
||||||
|
wrn() { printf ' \033[33m[WARN]\033[0m %s\n' "$*"; warn=1; }
|
||||||
|
doing(){ printf '\n\033[1m%s\033[0m\n' "$*"; }
|
||||||
|
|
||||||
|
doing "1. Docker engine + compose"
|
||||||
|
if command -v docker >/dev/null 2>&1; then
|
||||||
|
ok "docker binary present"
|
||||||
|
if docker info >/dev/null 2>&1; then ok "daemon reachable"; else err "daemon NOT reachable (is it running / does this user have access?)"; fi
|
||||||
|
else
|
||||||
|
err "docker binary missing"
|
||||||
|
fi
|
||||||
|
if docker compose version >/dev/null 2>&1; then
|
||||||
|
ok "docker compose plugin present"
|
||||||
|
else
|
||||||
|
err "docker compose plugin missing (install docker-compose-plugin)"
|
||||||
|
fi
|
||||||
|
|
||||||
|
doing "2. Runtime directories exist + RW for UID 33"
|
||||||
|
for d in "${RW_DIRS[@]}"; do
|
||||||
|
if [ ! -e "$d" ]; then
|
||||||
|
err "missing dir: $d"
|
||||||
|
if [ "$FIX" -eq 1 ]; then
|
||||||
|
mkdir -p "$d" && chown 33:33 "$d" && say " created + chown 33:33 $d" || err " could not create $d"
|
||||||
|
fi
|
||||||
|
continue
|
||||||
|
fi
|
||||||
|
if [ ! -d "$d" ]; then err "not a directory: $d"; continue; fi
|
||||||
|
# Test write as the target owner via a temp file drop (as root), then remove.
|
||||||
|
if [ "$(id -u)" -eq 0 ]; then
|
||||||
|
if touch "$d/.preflight-write-test" 2>/dev/null; then
|
||||||
|
rm -f "$d/.preflight-write-test"
|
||||||
|
ok "writable: $d"
|
||||||
|
else
|
||||||
|
err "not writable: $d (needs owner 33:33)"
|
||||||
|
[ "$FIX" -eq 1 ] && { chown -R 33:33 "$d" && say " chown -R 33:33 $d" || err " chown failed"; }
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
if [ -w "$d" ]; then ok "writable: $d"; else err "not writable: $d"; fi
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
doing "3. Volume ownership (UID/GID 33 = www-data)"
|
||||||
|
for d in "${RW_DIRS[@]}"; do
|
||||||
|
[ -e "$d" ] || continue
|
||||||
|
owner="$(stat -c '%u:%g' "$d" 2>/dev/null || true)"
|
||||||
|
if [ "$owner" = "33:33" ]; then
|
||||||
|
ok "owner 33:33: $d"
|
||||||
|
else
|
||||||
|
err "owner ${owner:-unknown} (want 33:33): $d"
|
||||||
|
[ "$FIX" -eq 1 ] && { chown 33:33 "$d" && say " chown 33:33 $d" || err " chown failed"; }
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
doing "4. Configuration + required services (.env, host network)"
|
||||||
|
if [ -f "$ENV_FILE" ]; then
|
||||||
|
ok ".env present: $ENV_FILE"
|
||||||
|
### shellcheck disable=SC1090
|
||||||
|
set -a; . "$ENV_FILE"; set +a
|
||||||
|
else
|
||||||
|
err ".env missing: $ENV_FILE (copy your production env here)"
|
||||||
|
fi
|
||||||
|
|
||||||
|
check_port() { # name port
|
||||||
|
if command -v nc >/dev/null 2>&1; then
|
||||||
|
if nc -z 127.0.0.1 "$2" >/dev/null 2>&1; then ok "reachable 127.0.0.1:$2 ($1)"; else err "NOT reachable 127.0.0.1:$2 ($1)"; fi
|
||||||
|
else
|
||||||
|
if (echo >/dev/tcp/127.0.0.1/"$2") >/dev/null 2>&1; then ok "reachable 127.0.0.1:$2 ($1)"; else err "NOT reachable 127.0.0.1:$2 ($1)"; fi
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
check_port "MariaDB" "$MYSQL_PORT"
|
||||||
|
check_port "Redis" "$REDIS_PORT"
|
||||||
|
check_dep() { # name
|
||||||
|
if command -v "$1" >/dev/null 2>&1; then ok "host binary: $1"; else wrn "host binary not found: $1 (may still work via container)"; fi
|
||||||
|
}
|
||||||
|
check_dep git
|
||||||
|
|
||||||
|
doing "5. Port 3002 state (host CMS clash)"
|
||||||
|
if (echo >/dev/tcp/127.0.0.1/"$CMS_PORT") >/dev/null 2>&1; then
|
||||||
|
err "port $CMS_PORT already in use on host — stop the host-side CMS (pm2 stop next) before starting the container"
|
||||||
|
else
|
||||||
|
ok "port $CMS_PORT free"
|
||||||
|
fi
|
||||||
|
|
||||||
|
printf '\n'
|
||||||
|
if [ "$fail" -eq 1 ]; then
|
||||||
|
printf '\033[31m=== NOT READY: %s issue(s) found%s ===\033[0m\n' "$fail" "$([ "$FIX" -eq 1 ] && echo ' after --fix' || echo ' (re-run with --fix to auto-correct)')"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
if [ "$warn" -eq 1 ]; then printf '\033[33m=== READY (with %s warning(s)) ===\033[0m\n' "$warn"; exit 0; fi
|
||||||
|
printf '\033[32m=== READY ===\033[0m\n'
|
||||||
|
exit 0
|
||||||
@@ -18,6 +18,10 @@ set -uo pipefail
|
|||||||
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||||
cd "$DIR" || exit 2
|
cd "$DIR" || exit 2
|
||||||
|
|
||||||
|
# Share the CI lock before pulling or touching the live application.
|
||||||
|
exec 9>"$DIR/.deploy.lock"
|
||||||
|
flock -w 1800 9 || exit 2
|
||||||
|
|
||||||
LOG_FILE="${LOG_FILE:-$DIR/logs/docker-update.log}"
|
LOG_FILE="${LOG_FILE:-$DIR/logs/docker-update.log}"
|
||||||
PM2_APP="${PM2_APP:-next}" # host-side CMS that must stay stopped (port 3002)
|
PM2_APP="${PM2_APP:-next}" # host-side CMS that must stay stopped (port 3002)
|
||||||
|
|
||||||
@@ -28,7 +32,13 @@ touch "$LOG_FILE"
|
|||||||
|
|
||||||
log "=== Start docker-update ==="
|
log "=== Start docker-update ==="
|
||||||
|
|
||||||
# --- 0. Guard: uncommitted changes would break git pull / taint deploys ---
|
# --- 0. Preflight: verify this VPS is ready (permissions, ports, deps) ---
|
||||||
|
if ! "$DIR/scripts/docker-preflight.sh"; then
|
||||||
|
die "preflight failed — fix issues first (see '--fix' flag)" 1
|
||||||
|
fi
|
||||||
|
log "preflight OK"
|
||||||
|
|
||||||
|
# --- 0b. Guard: uncommitted changes would break git pull / taint deploys ---
|
||||||
if ! { git diff --quiet --exit-code && git diff --cached --quiet --exit-code; }; then
|
if ! { git diff --quiet --exit-code && git diff --cached --quiet --exit-code; }; then
|
||||||
die "working tree has uncommitted changes; commit or stash first" 1
|
die "working tree has uncommitted changes; commit or stash first" 1
|
||||||
fi
|
fi
|
||||||
@@ -51,15 +61,35 @@ else
|
|||||||
fi
|
fi
|
||||||
log "db:migrate OK"
|
log "db:migrate OK"
|
||||||
|
|
||||||
# --- 3. Rebuild the image ---
|
# --- 3. Node major gate (patches auto, major upgrades need review) ---
|
||||||
|
# `node:alpine` floats within, then across, Node majors. Patches/minors are
|
||||||
|
# safe to apply silently; a NEW major (e.g. 26 -> 27) is a breaking risk for
|
||||||
|
# native addons / Next compatibility, so require an explicit review before it
|
||||||
|
# goes live. Compare the major of the deployed runtime image vs the floating
|
||||||
|
# tag; abort (not deploy) when they differ.
|
||||||
|
deployed_major="$(docker inspect --format '{{.Config.Image}}' epicnext-cms 2>/dev/null || true)"
|
||||||
|
# Resolve the currently-deployed Node major from its image.
|
||||||
|
if [ -n "$deployed_major" ] && docker image inspect "$deployed_major" >/dev/null 2>&1; then
|
||||||
|
deployed_major="$(docker run --rm --entrypoint sh "$deployed_major" -c 'node -p "process.versions.node.split(\".\")[0]"' 2>/dev/null || true)"
|
||||||
|
fi
|
||||||
|
float_major="$(docker run --rm --entrypoint sh node:alpine -c 'node -p "process.versions.node.split(\".\")[0]"' 2>/dev/null || true)"
|
||||||
|
if [ -n "$deployed_major" ] && [ -n "$float_major" ] && [ "$deployed_major" != "$float_major" ]; then
|
||||||
|
die "Node major change detected (deployed v$deployed_major, floating tag v$float_major). Major upgrades require review; update engines/Dockerfile deliberately first." 1
|
||||||
|
fi
|
||||||
|
log "Node major gate OK (major=${float_major:-?})"
|
||||||
|
|
||||||
|
# --- 4. Rebuild the image ---
|
||||||
|
# Reset the BuildKit cache first so the build doesn't accumulate unbounded
|
||||||
|
# layers on disk across daily rebuilds.
|
||||||
|
docker builder prune -af --filter "until=1h" --keep-storage=0 2>>"$LOG_FILE" || true
|
||||||
docker compose build >>"$LOG_FILE" 2>&1 || die "docker compose build failed" 2
|
docker compose build >>"$LOG_FILE" 2>&1 || die "docker compose build failed" 2
|
||||||
log "docker compose build OK"
|
log "docker compose build OK"
|
||||||
|
|
||||||
# --- 4. Recreate the container ---
|
# --- 5. Recreate the container ---
|
||||||
docker compose up -d >>"$LOG_FILE" 2>&1 || die "docker compose up failed" 2
|
docker compose up -d >>"$LOG_FILE" 2>&1 || die "docker compose up failed" 2
|
||||||
log "docker compose up OK"
|
log "docker compose up OK"
|
||||||
|
|
||||||
# --- 5. Wait for health (up to ~4 min) ---
|
# --- 6. Wait for health (up to ~4 min) ---
|
||||||
healthy=0
|
healthy=0
|
||||||
for i in $(seq 1 16); do
|
for i in $(seq 1 16); do
|
||||||
status="$(docker inspect --format='{{.State.Health.Status}}' epicnext-cms 2>/dev/null || true)"
|
status="$(docker inspect --format='{{.State.Health.Status}}' epicnext-cms 2>/dev/null || true)"
|
||||||
@@ -78,7 +108,7 @@ else
|
|||||||
exit 3
|
exit 3
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# --- 6. Make sure the stale host-side PM2 CMS stays stopped ---
|
# --- 7. Make sure the stale host-side PM2 CMS stays stopped ---
|
||||||
if command -v pm2 >/dev/null 2>&1 && pm2 jlist >/dev/null 2>&1; then
|
if command -v pm2 >/dev/null 2>&1 && pm2 jlist >/dev/null 2>&1; then
|
||||||
if pm2 list 2>/dev/null | grep -q "${PM2_APP}"; then
|
if pm2 list 2>/dev/null | grep -q "${PM2_APP}"; then
|
||||||
pm2 stop "$PM2_APP" >/dev/null 2>&1 && log "pm2 '${PM2_APP}' kept stopped (avoids port 3002 clash)"
|
pm2 stop "$PM2_APP" >/dev/null 2>&1 && log "pm2 '${PM2_APP}' kept stopped (avoids port 3002 clash)"
|
||||||
|
|||||||
+10
-5
@@ -11,6 +11,8 @@ import {
|
|||||||
import { logger } from "../src/lib/logger";
|
import { logger } from "../src/lib/logger";
|
||||||
import { redis } from "../src/lib/redis";
|
import { redis } from "../src/lib/redis";
|
||||||
import { emulatorOffline, healthDegraded } from "../src/lib/services/alert";
|
import { emulatorOffline, healthDegraded } from "../src/lib/services/alert";
|
||||||
|
import { runCatalogExport } from "../src/lib/services/catalog-git-export";
|
||||||
|
import { invalidateNewsCache } from "../src/lib/services/news-cache";
|
||||||
import { rcon } from "../src/lib/services/rcon";
|
import { rcon } from "../src/lib/services/rcon";
|
||||||
|
|
||||||
function captureWorkerError(err: unknown, context: string): void {
|
function captureWorkerError(err: unknown, context: string): void {
|
||||||
@@ -245,12 +247,10 @@ async function publishScheduledArticles(): Promise<void> {
|
|||||||
lte(WebsiteArticles.publishAt, now),
|
lte(WebsiteArticles.publishAt, now),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
const info = result as unknown as {
|
const [info] = result;
|
||||||
affectedRows?: number;
|
const published = info.affectedRows ?? 0;
|
||||||
rowsAffected?: number;
|
|
||||||
};
|
|
||||||
const published = info.affectedRows ?? info.rowsAffected ?? 0;
|
|
||||||
if (published > 0) {
|
if (published > 0) {
|
||||||
|
await invalidateNewsCache();
|
||||||
logger.info(`Published ${published} scheduled article(s)`, {
|
logger.info(`Published ${published} scheduled article(s)`, {
|
||||||
module: "jobs",
|
module: "jobs",
|
||||||
});
|
});
|
||||||
@@ -261,6 +261,11 @@ async function publishScheduledArticles(): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function main() {
|
async function main() {
|
||||||
|
new Cron("* * * * *", () => {
|
||||||
|
runCatalogExport().catch((e) =>
|
||||||
|
captureWorkerError(e, "Catalog export failed"),
|
||||||
|
);
|
||||||
|
});
|
||||||
logger.info("Worker started", { module: "jobs" });
|
logger.info("Worker started", { module: "jobs" });
|
||||||
|
|
||||||
if (env.EMULATOR_JAR_PATH && env.EMULATOR_BACKUP_DIR) {
|
if (env.EMULATOR_JAR_PATH && env.EMULATOR_BACKUP_DIR) {
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
// Production builds and CI do not need Git hooks or dev-only executables.
|
||||||
|
if (process.env.NODE_ENV !== "production" && !process.env.CI) {
|
||||||
|
const { default: husky } = await import("husky");
|
||||||
|
husky();
|
||||||
|
}
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
const state = vi.hoisted(() => ({
|
||||||
|
rows: [] as unknown[][],
|
||||||
|
insert: vi.fn(),
|
||||||
|
update: vi.fn(),
|
||||||
|
invalidate: vi.fn(),
|
||||||
|
log: vi.fn(() => "news-error-1"),
|
||||||
|
notify: vi.fn(),
|
||||||
|
}));
|
||||||
|
vi.mock("@/lib/admin/guard", () => ({
|
||||||
|
requirePermission: async () => ({ id: 1, username: "staff" }),
|
||||||
|
}));
|
||||||
|
vi.mock("@/lib/permissions", () => ({ PERMS: { NEWS_EDIT: "news.edit" } }));
|
||||||
|
vi.mock("@/lib/services/webhook", () => ({ notify: state.notify }));
|
||||||
|
vi.mock("@/lib/services/news-cache", () => ({
|
||||||
|
invalidateNewsCache: state.invalidate,
|
||||||
|
}));
|
||||||
|
vi.mock("@/lib/logger", () => ({ logger: { error: state.log } }));
|
||||||
|
vi.mock("next-intl/server", () => ({
|
||||||
|
getTranslations: async () => (key: string, args?: { reference: string }) =>
|
||||||
|
key + (args?.reference ?? ""),
|
||||||
|
}));
|
||||||
|
vi.mock("next/cache", () => ({ revalidatePath: vi.fn() }));
|
||||||
|
vi.mock("next/navigation", () => ({
|
||||||
|
redirect: (url: string) => {
|
||||||
|
throw Error(`redirect ${url}`);
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
vi.mock("@/lib/db", async () => ({
|
||||||
|
...(await import("@/db/schema")),
|
||||||
|
db: {
|
||||||
|
select: () => ({
|
||||||
|
from: () => ({
|
||||||
|
where: () => ({ limit: async () => state.rows.shift() ?? [] }),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
insert: () => ({ values: state.insert }),
|
||||||
|
update: () => ({
|
||||||
|
set: (value: unknown) => {
|
||||||
|
state.update(value);
|
||||||
|
return { where: async () => [{ affectedRows: 1 }] };
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { createArticle, updateArticle } from "./admin-articles";
|
||||||
|
|
||||||
|
function form(extra: Record<string, string> = {}) {
|
||||||
|
const f = new FormData();
|
||||||
|
for (const [k, v] of Object.entries({
|
||||||
|
title: "Test news",
|
||||||
|
slug: "test-news",
|
||||||
|
shortStory: "Summary",
|
||||||
|
fullStory: "Body",
|
||||||
|
status: "published",
|
||||||
|
...extra,
|
||||||
|
}))
|
||||||
|
f.set(k, v);
|
||||||
|
return f;
|
||||||
|
}
|
||||||
|
describe("news saves", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
state.rows = [];
|
||||||
|
state.insert.mockResolvedValue([{ insertId: 1 }]);
|
||||||
|
});
|
||||||
|
it("preserves a recoverable error and logs its reference", async () => {
|
||||||
|
state.insert.mockRejectedValueOnce(Error("Unknown column status"));
|
||||||
|
const result = await createArticle(form());
|
||||||
|
expect(result).toEqual({
|
||||||
|
ok: false,
|
||||||
|
error: "saveFailedReferencenews-error-1",
|
||||||
|
});
|
||||||
|
expect(state.invalidate).not.toHaveBeenCalled();
|
||||||
|
expect(state.log).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
it("saves drafts without publication notifications", async () => {
|
||||||
|
expect((await createArticle(form({ status: "draft" }))).ok).toBe(true);
|
||||||
|
expect(state.insert).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
status: "draft",
|
||||||
|
publishAt: null,
|
||||||
|
publishedAt: null,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(state.notify).not.toHaveBeenCalled();
|
||||||
|
expect(state.invalidate).toHaveBeenCalledOnce();
|
||||||
|
});
|
||||||
|
it("preserves the slug and clears old scheduling for immediate publication", async () => {
|
||||||
|
state.rows = [[{ slug: "test-news", status: "draft", publishedAt: null }]];
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await updateArticle(
|
||||||
|
form({ id: "1", publishAt: "2099-01-01T00:00:00Z" }),
|
||||||
|
)
|
||||||
|
).ok,
|
||||||
|
).toBe(true);
|
||||||
|
expect(state.update).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
slug: "test-news",
|
||||||
|
publishAt: null,
|
||||||
|
status: "published",
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(state.invalidate).toHaveBeenCalledOnce();
|
||||||
|
});
|
||||||
|
it("rejects invalid scheduled dates before writing", async () => {
|
||||||
|
expect(
|
||||||
|
(await createArticle(form({ status: "scheduled", publishAt: "invalid" })))
|
||||||
|
.ok,
|
||||||
|
).toBe(false);
|
||||||
|
expect(state.insert).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
+98
-103
@@ -1,9 +1,15 @@
|
|||||||
"use server";
|
"use server";
|
||||||
|
|
||||||
import { eq } from "drizzle-orm";
|
import { and, eq, ne } from "drizzle-orm";
|
||||||
import { revalidatePath } from "next/cache";
|
import { revalidatePath } from "next/cache";
|
||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
|
import { getTranslations } from "next-intl/server";
|
||||||
import { requirePermission } from "@/lib/admin/guard";
|
import { requirePermission } from "@/lib/admin/guard";
|
||||||
|
import {
|
||||||
|
ArticleInputError,
|
||||||
|
type ArticleSaveResult,
|
||||||
|
readArticleInput,
|
||||||
|
} from "@/lib/article-input";
|
||||||
import {
|
import {
|
||||||
db,
|
db,
|
||||||
WebsiteArticleComments,
|
WebsiteArticleComments,
|
||||||
@@ -12,152 +18,139 @@ import {
|
|||||||
} from "@/lib/db";
|
} from "@/lib/db";
|
||||||
import { formPositiveBigInt } from "@/lib/form-data";
|
import { formPositiveBigInt } from "@/lib/form-data";
|
||||||
import { slugify } from "@/lib/format";
|
import { slugify } from "@/lib/format";
|
||||||
|
import { logger } from "@/lib/logger";
|
||||||
import { PERMS } from "@/lib/permissions";
|
import { PERMS } from "@/lib/permissions";
|
||||||
|
import { invalidateNewsCache } from "@/lib/services/news-cache";
|
||||||
import { notify } from "@/lib/services/webhook";
|
import { notify } from "@/lib/services/webhook";
|
||||||
|
|
||||||
const ARTICLE_STATUSES = ["published", "scheduled", "draft"] as const;
|
async function uniqueSlug(title: string, excludeId?: bigint): Promise<string> {
|
||||||
type ArticleStatus = (typeof ARTICLE_STATUSES)[number];
|
|
||||||
|
|
||||||
function parseArticleStatus(raw: unknown): ArticleStatus {
|
|
||||||
const value = String(raw ?? "published").trim();
|
|
||||||
return (ARTICLE_STATUSES as readonly string[]).includes(value)
|
|
||||||
? (value as ArticleStatus)
|
|
||||||
: "published";
|
|
||||||
}
|
|
||||||
|
|
||||||
function parsePublishAt(raw: unknown): Date | null {
|
|
||||||
const value = String(raw ?? "").trim();
|
|
||||||
if (!value) return null;
|
|
||||||
const date = new Date(value);
|
|
||||||
return Number.isNaN(date.getTime()) ? null : date;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function uniqueSlug(title: string): Promise<string> {
|
|
||||||
const base = slugify(title);
|
const base = slugify(title);
|
||||||
let slug = base;
|
let slug = base;
|
||||||
let n = 2;
|
for (let n = 2; ; n++) {
|
||||||
for (;;) {
|
|
||||||
const [existing] = await db
|
const [existing] = await db
|
||||||
.select({ id: WebsiteArticles.id })
|
.select({ id: WebsiteArticles.id })
|
||||||
.from(WebsiteArticles)
|
.from(WebsiteArticles)
|
||||||
.where(eq(WebsiteArticles.slug, slug))
|
.where(
|
||||||
|
and(
|
||||||
|
eq(WebsiteArticles.slug, slug),
|
||||||
|
excludeId ? ne(WebsiteArticles.id, excludeId) : undefined,
|
||||||
|
),
|
||||||
|
)
|
||||||
.limit(1);
|
.limit(1);
|
||||||
if (!existing) return slug;
|
if (!existing) return slug;
|
||||||
slug = `${base}-${n++}`;
|
const suffix = `-${n}`;
|
||||||
|
slug = base.slice(0, 255 - suffix.length) + suffix;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
async function saveFailure(
|
||||||
export async function createArticle(formData: FormData): Promise<void> {
|
error: unknown,
|
||||||
|
operation: string,
|
||||||
|
): Promise<ArticleSaveResult> {
|
||||||
|
const t = await getTranslations("pages.admin.articles.form");
|
||||||
|
if (error instanceof ArticleInputError)
|
||||||
|
return { ok: false, error: t(error.code) };
|
||||||
|
const reference = logger.error("News save failed", {
|
||||||
|
module: "news",
|
||||||
|
operation,
|
||||||
|
error,
|
||||||
|
});
|
||||||
|
return { ok: false, error: t("saveFailedReference", { reference }) };
|
||||||
|
}
|
||||||
|
async function refreshNews() {
|
||||||
|
await invalidateNewsCache();
|
||||||
|
revalidatePath("/admin/articles");
|
||||||
|
revalidatePath("/news", "layout");
|
||||||
|
revalidatePath("/me");
|
||||||
|
revalidatePath("/");
|
||||||
|
}
|
||||||
|
export async function createArticle(
|
||||||
|
formData: FormData,
|
||||||
|
): Promise<ArticleSaveResult> {
|
||||||
const staff = await requirePermission(PERMS.NEWS_EDIT);
|
const staff = await requirePermission(PERMS.NEWS_EDIT);
|
||||||
const title = String(formData.get("title") ?? "")
|
let input: ReturnType<typeof readArticleInput>;
|
||||||
.normalize("NFC")
|
let slug: string;
|
||||||
.trim();
|
|
||||||
const shortStory = String(formData.get("shortStory") ?? "")
|
|
||||||
.normalize("NFC")
|
|
||||||
.trim();
|
|
||||||
const fullStory = String(formData.get("fullStory") ?? "")
|
|
||||||
.normalize("NFC")
|
|
||||||
.trim();
|
|
||||||
const image = String(formData.get("image") ?? "")
|
|
||||||
.normalize("NFC")
|
|
||||||
.trim();
|
|
||||||
const rawSlug = String(formData.get("slug") ?? "").trim();
|
|
||||||
const status = parseArticleStatus(formData.get("status"));
|
|
||||||
const rawPublishAt = String(formData.get("publishAt") ?? "").trim();
|
|
||||||
if (!title) return;
|
|
||||||
if (status === "scheduled" && !parsePublishAt(rawPublishAt)) {
|
|
||||||
redirect(
|
|
||||||
"/admin/articles/new?error=Scheduled articles need a valid publish date.",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
input = readArticleInput(formData);
|
||||||
|
const { rawSlug, ...fields } = input;
|
||||||
|
slug = await uniqueSlug(rawSlug || fields.title);
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
const publishAt = parsePublishAt(rawPublishAt);
|
|
||||||
const slug = rawSlug ? await uniqueSlug(rawSlug) : await uniqueSlug(title);
|
|
||||||
await db.insert(WebsiteArticles).values({
|
await db.insert(WebsiteArticles).values({
|
||||||
|
...fields,
|
||||||
slug,
|
slug,
|
||||||
title: title.slice(0, 255),
|
|
||||||
shortStory: shortStory.slice(0, 255),
|
|
||||||
fullStory,
|
|
||||||
image: image.slice(0, 255),
|
|
||||||
userId: staff.id,
|
userId: staff.id,
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
status,
|
publishedAt: fields.status === "published" ? now : null,
|
||||||
publishAt,
|
|
||||||
publishedAt: status === "published" ? now : null,
|
|
||||||
});
|
});
|
||||||
|
} catch (error) {
|
||||||
|
return saveFailure(error, "create");
|
||||||
|
}
|
||||||
|
// Auxiliary services must not turn a committed insert into an apparent failure.
|
||||||
|
if (input.status === "published")
|
||||||
notify({
|
notify({
|
||||||
action: "news_publish",
|
action: "news_publish",
|
||||||
actor: staff.username,
|
actor: staff.username,
|
||||||
target: title,
|
target: input.title,
|
||||||
details: slug,
|
details: slug,
|
||||||
});
|
});
|
||||||
} catch {
|
await refreshNews();
|
||||||
// Database error — re-render unchanged with error.
|
return { ok: true, data: { redirectTo: "/admin/articles" } };
|
||||||
redirect(
|
|
||||||
"/admin/articles/new?error=Database error while creating article. Please try again.",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
redirect("/admin/articles");
|
|
||||||
}
|
}
|
||||||
|
export async function updateArticle(
|
||||||
export async function updateArticle(formData: FormData): Promise<void> {
|
formData: FormData,
|
||||||
await requirePermission(PERMS.NEWS_EDIT);
|
): Promise<ArticleSaveResult> {
|
||||||
|
const staff = await requirePermission(PERMS.NEWS_EDIT);
|
||||||
|
const t = await getTranslations("pages.admin.articles.form");
|
||||||
const id = formPositiveBigInt(formData, "id");
|
const id = formPositiveBigInt(formData, "id");
|
||||||
if (!id) redirect("/admin/articles?error=Missing article id");
|
if (!id) return { ok: false, error: t("articleNotFound") };
|
||||||
const rawSlug = String(formData.get("slug") ?? "").trim();
|
let input: ReturnType<typeof readArticleInput>;
|
||||||
const status = parseArticleStatus(formData.get("status"));
|
let becamePublished = false;
|
||||||
const rawPublishAt = String(formData.get("publishAt") ?? "").trim();
|
let slug: string;
|
||||||
if (status === "scheduled" && !parsePublishAt(rawPublishAt)) {
|
|
||||||
redirect(
|
|
||||||
"/admin/articles?error=Scheduled articles need a valid publish date.",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
try {
|
try {
|
||||||
const publishAt = parsePublishAt(rawPublishAt);
|
input = readArticleInput(formData);
|
||||||
const [existing] = await db
|
const [existing] = await db
|
||||||
.select({
|
.select({
|
||||||
|
slug: WebsiteArticles.slug,
|
||||||
status: WebsiteArticles.status,
|
status: WebsiteArticles.status,
|
||||||
publishedAt: WebsiteArticles.publishedAt,
|
publishedAt: WebsiteArticles.publishedAt,
|
||||||
})
|
})
|
||||||
.from(WebsiteArticles)
|
.from(WebsiteArticles)
|
||||||
.where(eq(WebsiteArticles.id, id))
|
.where(eq(WebsiteArticles.id, id))
|
||||||
.limit(1);
|
.limit(1);
|
||||||
const publishedAt =
|
if (!existing) return { ok: false, error: t("articleNotFound") };
|
||||||
status === "published" ? (existing?.publishedAt ?? new Date()) : null;
|
const { rawSlug, ...fields } = input;
|
||||||
|
const requestedSlug = rawSlug ? slugify(rawSlug) : existing.slug;
|
||||||
|
slug =
|
||||||
|
requestedSlug === existing.slug
|
||||||
|
? existing.slug
|
||||||
|
: await uniqueSlug(requestedSlug, id);
|
||||||
|
becamePublished =
|
||||||
|
fields.status === "published" && existing.status !== "published";
|
||||||
await db
|
await db
|
||||||
.update(WebsiteArticles)
|
.update(WebsiteArticles)
|
||||||
.set({
|
.set({
|
||||||
title: String(formData.get("title") ?? "")
|
...fields,
|
||||||
.normalize("NFC")
|
slug,
|
||||||
.trim()
|
publishedAt:
|
||||||
.slice(0, 255),
|
fields.status === "published"
|
||||||
...(rawSlug ? { slug: await uniqueSlug(rawSlug) } : {}),
|
? (existing.publishedAt ?? new Date())
|
||||||
shortStory: String(formData.get("shortStory") ?? "")
|
: null,
|
||||||
.normalize("NFC")
|
|
||||||
.trim()
|
|
||||||
.slice(0, 255),
|
|
||||||
fullStory: String(formData.get("fullStory") ?? "")
|
|
||||||
.normalize("NFC")
|
|
||||||
.trim(),
|
|
||||||
image: String(formData.get("image") ?? "")
|
|
||||||
.normalize("NFC")
|
|
||||||
.trim()
|
|
||||||
.slice(0, 255),
|
|
||||||
status,
|
|
||||||
publishAt,
|
|
||||||
publishedAt,
|
|
||||||
updatedAt: new Date(),
|
updatedAt: new Date(),
|
||||||
})
|
})
|
||||||
.where(eq(WebsiteArticles.id, id));
|
.where(eq(WebsiteArticles.id, id));
|
||||||
} catch {
|
} catch (error) {
|
||||||
redirect("/admin/articles?error=Update failed");
|
return saveFailure(error, "update");
|
||||||
}
|
}
|
||||||
|
if (becamePublished)
|
||||||
|
notify({
|
||||||
|
action: "news_publish",
|
||||||
|
actor: staff.username,
|
||||||
|
target: input.title,
|
||||||
|
details: slug,
|
||||||
|
});
|
||||||
|
await refreshNews();
|
||||||
revalidatePath(`/admin/articles/${id}`);
|
revalidatePath(`/admin/articles/${id}`);
|
||||||
redirect("/admin/articles");
|
return { ok: true, data: { redirectTo: "/admin/articles" } };
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function deleteArticle(formData: FormData): Promise<void> {
|
export async function deleteArticle(formData: FormData): Promise<void> {
|
||||||
@@ -185,8 +178,10 @@ export async function deleteArticle(formData: FormData): Promise<void> {
|
|||||||
actor: staff.username,
|
actor: staff.username,
|
||||||
target: article?.title ?? String(id),
|
target: article?.title ?? String(id),
|
||||||
});
|
});
|
||||||
} catch {
|
} catch (error) {
|
||||||
|
logger.error("News deletion failed", { module: "news", error });
|
||||||
redirect("/admin/articles?error=Delete failed");
|
redirect("/admin/articles?error=Delete failed");
|
||||||
}
|
}
|
||||||
|
await refreshNews();
|
||||||
redirect("/admin/articles");
|
redirect("/admin/articles");
|
||||||
}
|
}
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
"use server";
|
|
||||||
|
|
||||||
import { revalidatePath } from "next/cache";
|
|
||||||
import { z } from "zod";
|
|
||||||
import {
|
|
||||||
ADMIN_NAV_CONFIG_KEY,
|
|
||||||
type AdminNavConfig,
|
|
||||||
serializeAdminNavConfig,
|
|
||||||
} from "@/lib/admin-nav-config";
|
|
||||||
import { actionOk, adminAction } from "@/lib/foundation/action";
|
|
||||||
import { PERMS } from "@/lib/permissions";
|
|
||||||
import { siteSettings } from "@/lib/services/site-settings";
|
|
||||||
|
|
||||||
const schema = z.object({
|
|
||||||
groupOrder: z.array(z.string()),
|
|
||||||
hiddenGroups: z.array(z.string()),
|
|
||||||
hiddenItems: z.array(z.string()),
|
|
||||||
itemOrder: z.record(z.string(), z.array(z.string())),
|
|
||||||
});
|
|
||||||
|
|
||||||
export const saveAdminNavConfig = adminAction(
|
|
||||||
{
|
|
||||||
permission: PERMS.SETTINGS_EDIT,
|
|
||||||
schema,
|
|
||||||
rateLimitKey: "admin-nav-config-save",
|
|
||||||
rateLimitMax: 30,
|
|
||||||
},
|
|
||||||
async (ctx) => {
|
|
||||||
const config: AdminNavConfig = {
|
|
||||||
groupOrder: ctx.data.groupOrder,
|
|
||||||
hiddenGroups: ctx.data.hiddenGroups,
|
|
||||||
hiddenItems: ctx.data.hiddenItems,
|
|
||||||
itemOrder: ctx.data.itemOrder,
|
|
||||||
};
|
|
||||||
await siteSettings.update(
|
|
||||||
ADMIN_NAV_CONFIG_KEY,
|
|
||||||
serializeAdminNavConfig(config),
|
|
||||||
);
|
|
||||||
revalidatePath("/admin", "layout");
|
|
||||||
revalidatePath("/admin/menu");
|
|
||||||
return actionOk({ saved: true });
|
|
||||||
},
|
|
||||||
);
|
|
||||||
+146
-185
@@ -1,11 +1,24 @@
|
|||||||
"use server";
|
"use server";
|
||||||
|
|
||||||
import { eq, inArray } from "drizzle-orm";
|
import { eq } from "drizzle-orm";
|
||||||
import { revalidatePath } from "next/cache";
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { catalogFailure } from "@/features/catalog/server/errors";
|
||||||
|
import {
|
||||||
|
createBcOfferCommand,
|
||||||
|
updateBcOfferCommand,
|
||||||
|
} from "@/features/catalog/server/offer-commands";
|
||||||
|
import {
|
||||||
|
createPageCommand,
|
||||||
|
deletePageCommand,
|
||||||
|
reorderPagesCommand,
|
||||||
|
togglePageCommand,
|
||||||
|
updatePageCommand,
|
||||||
|
} from "@/features/catalog/server/page-commands";
|
||||||
|
import { sendCatalogUpdate } from "@/features/catalog/server/sync-status";
|
||||||
import { requirePermission } from "@/lib/admin/guard";
|
import { requirePermission } from "@/lib/admin/guard";
|
||||||
import { CatalogItemsBc, CatalogPagesBc, db } from "@/lib/db";
|
import { CatalogItemsBc, db } from "@/lib/db";
|
||||||
import { PERMS } from "@/lib/permissions";
|
import { PERMS } from "@/lib/permissions";
|
||||||
import { rcon } from "@/lib/services/rcon";
|
import { withCatalogExport } from "@/lib/services/catalog-git-queue";
|
||||||
import { logStaffActivity } from "@/lib/services/staff-activity";
|
import { logStaffActivity } from "@/lib/services/staff-activity";
|
||||||
|
|
||||||
const BC_PAGE_FIELDS = [
|
const BC_PAGE_FIELDS = [
|
||||||
@@ -49,42 +62,51 @@ function pickAllowed(
|
|||||||
|
|
||||||
export async function updateBcPage({
|
export async function updateBcPage({
|
||||||
id,
|
id,
|
||||||
|
expected,
|
||||||
...fields
|
...fields
|
||||||
}: { id: number } & Record<string, unknown>) {
|
}: { id: number; expected?: Record<string, unknown> } & Record<
|
||||||
|
string,
|
||||||
|
unknown
|
||||||
|
>) {
|
||||||
const staff = await requirePermission(PERMS.CATALOG_EDIT);
|
const staff = await requirePermission(PERMS.CATALOG_EDIT);
|
||||||
const data = pickAllowed(fields, BC_PAGE_FIELDS);
|
return await withCatalogExport(async () => {
|
||||||
if (Object.keys(data).length === 0) {
|
const data = pickAllowed(fields, BC_PAGE_FIELDS);
|
||||||
return { ok: false as const, error: "No valid fields to update" };
|
if (Object.keys(data).length === 0) {
|
||||||
}
|
return { ok: false as const, error: "No valid fields to update" };
|
||||||
await db
|
}
|
||||||
.update(CatalogPagesBc)
|
try {
|
||||||
.set(data as Partial<typeof CatalogPagesBc.$inferInsert>)
|
await updatePageCommand("bc", id, data, expected);
|
||||||
.where(eq(CatalogPagesBc.id, id));
|
} catch (error) {
|
||||||
await rcon.updateCatalog();
|
return { ok: false as const, error: catalogFailure(error).message };
|
||||||
await logStaffActivity({
|
}
|
||||||
staffId: staff.id,
|
await sendCatalogUpdate();
|
||||||
action: "bc_page_update",
|
await logStaffActivity({
|
||||||
description: `Updated BC catalog page #${id}`,
|
staffId: staff.id,
|
||||||
targetType: "catalog_page_bc",
|
action: "bc_page_update",
|
||||||
targetId: id,
|
description: `Updated BC catalog page #${id}`,
|
||||||
|
targetType: "catalog_page_bc",
|
||||||
|
targetId: id,
|
||||||
|
});
|
||||||
|
revalidatePath("/admin/catalog/builder-club");
|
||||||
|
return { ok: true as const };
|
||||||
});
|
});
|
||||||
revalidatePath("/admin/catalog/builder-club");
|
|
||||||
return { ok: true as const };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function deleteBcItem({ id }: { id: number }) {
|
export async function deleteBcItem({ id }: { id: number }) {
|
||||||
const staff = await requirePermission(PERMS.CATALOG_EDIT);
|
const staff = await requirePermission(PERMS.CATALOG_EDIT);
|
||||||
await db.delete(CatalogItemsBc).where(eq(CatalogItemsBc.id, id));
|
return await withCatalogExport(async () => {
|
||||||
await rcon.updateCatalog();
|
await db.delete(CatalogItemsBc).where(eq(CatalogItemsBc.id, id));
|
||||||
await logStaffActivity({
|
await sendCatalogUpdate();
|
||||||
staffId: staff.id,
|
await logStaffActivity({
|
||||||
action: "bc_item_delete",
|
staffId: staff.id,
|
||||||
description: `Deleted BC catalog item #${id}`,
|
action: "bc_item_delete",
|
||||||
targetType: "catalog_item_bc",
|
description: `Deleted BC catalog item #${id}`,
|
||||||
targetId: id,
|
targetType: "catalog_item_bc",
|
||||||
|
targetId: id,
|
||||||
|
});
|
||||||
|
revalidatePath("/admin/catalog/builder-club");
|
||||||
|
return { ok: true as const };
|
||||||
});
|
});
|
||||||
revalidatePath("/admin/catalog/builder-club");
|
|
||||||
return { ok: true as const };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function updateBcItem({
|
export async function updateBcItem({
|
||||||
@@ -98,24 +120,27 @@ export async function updateBcItem({
|
|||||||
extradata?: string;
|
extradata?: string;
|
||||||
}) {
|
}) {
|
||||||
const staff = await requirePermission(PERMS.CATALOG_EDIT);
|
const staff = await requirePermission(PERMS.CATALOG_EDIT);
|
||||||
const safe = pickAllowed(data as Record<string, unknown>, BC_ITEM_FIELDS);
|
return await withCatalogExport(async () => {
|
||||||
if (Object.keys(safe).length === 0) {
|
const safe = pickAllowed(data as Record<string, unknown>, BC_ITEM_FIELDS);
|
||||||
return { ok: false as const, error: "No valid fields to update" };
|
if (Object.keys(safe).length === 0) {
|
||||||
}
|
return { ok: false as const, error: "No valid fields to update" };
|
||||||
await db
|
}
|
||||||
.update(CatalogItemsBc)
|
try {
|
||||||
.set(safe as Partial<typeof CatalogItemsBc.$inferInsert>)
|
await updateBcOfferCommand(id, safe);
|
||||||
.where(eq(CatalogItemsBc.id, id));
|
} catch (error) {
|
||||||
await rcon.updateCatalog();
|
return { ok: false as const, error: catalogFailure(error).message };
|
||||||
await logStaffActivity({
|
}
|
||||||
staffId: staff.id,
|
await sendCatalogUpdate();
|
||||||
action: "bc_item_update",
|
await logStaffActivity({
|
||||||
description: `Updated BC catalog item #${id}`,
|
staffId: staff.id,
|
||||||
targetType: "catalog_item_bc",
|
action: "bc_item_update",
|
||||||
targetId: id,
|
description: `Updated BC catalog item #${id}`,
|
||||||
|
targetType: "catalog_item_bc",
|
||||||
|
targetId: id,
|
||||||
|
});
|
||||||
|
revalidatePath("/admin/catalog/builder-club");
|
||||||
|
return { ok: true as const };
|
||||||
});
|
});
|
||||||
revalidatePath("/admin/catalog/builder-club");
|
|
||||||
return { ok: true as const };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function createBcItem({
|
export async function createBcItem({
|
||||||
@@ -129,18 +154,19 @@ export async function createBcItem({
|
|||||||
extradata: string;
|
extradata: string;
|
||||||
}) {
|
}) {
|
||||||
const staff = await requirePermission(PERMS.CATALOG_EDIT);
|
const staff = await requirePermission(PERMS.CATALOG_EDIT);
|
||||||
const [result] = await db.insert(CatalogItemsBc).values({ pageId, ...data });
|
return await withCatalogExport(async () => {
|
||||||
const createdId = Number(result.insertId);
|
const createdId = await createBcOfferCommand({ pageId, ...data });
|
||||||
await rcon.updateCatalog();
|
await sendCatalogUpdate();
|
||||||
await logStaffActivity({
|
await logStaffActivity({
|
||||||
staffId: staff.id,
|
staffId: staff.id,
|
||||||
action: "bc_item_create",
|
action: "bc_item_create",
|
||||||
description: `Created BC catalog item #${createdId}`,
|
description: `Created BC catalog item #${createdId}`,
|
||||||
targetType: "catalog_item_bc",
|
targetType: "catalog_item_bc",
|
||||||
targetId: createdId,
|
targetId: createdId,
|
||||||
|
});
|
||||||
|
revalidatePath("/admin/catalog/builder-club");
|
||||||
|
return { ok: true as const, data: { id: createdId } };
|
||||||
});
|
});
|
||||||
revalidatePath("/admin/catalog/builder-club");
|
|
||||||
return { ok: true as const, data: { id: createdId } };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function toggleBcPage({
|
export async function toggleBcPage({
|
||||||
@@ -151,22 +177,12 @@ export async function toggleBcPage({
|
|||||||
field: "enabled" | "visible";
|
field: "enabled" | "visible";
|
||||||
}) {
|
}) {
|
||||||
await requirePermission(PERMS.CATALOG_EDIT);
|
await requirePermission(PERMS.CATALOG_EDIT);
|
||||||
const [page] = await db
|
return await withCatalogExport(async () => {
|
||||||
.select({
|
await togglePageCommand("bc", id, field);
|
||||||
enabled: CatalogPagesBc.enabled,
|
await sendCatalogUpdate();
|
||||||
visible: CatalogPagesBc.visible,
|
revalidatePath("/admin/catalog/builder-club");
|
||||||
})
|
return { ok: true as const };
|
||||||
.from(CatalogPagesBc)
|
});
|
||||||
.where(eq(CatalogPagesBc.id, id))
|
|
||||||
.limit(1);
|
|
||||||
if (!page) return { ok: false as const, error: "Page not found" };
|
|
||||||
await db
|
|
||||||
.update(CatalogPagesBc)
|
|
||||||
.set({ [field]: page[field] === "1" ? "0" : "1" })
|
|
||||||
.where(eq(CatalogPagesBc.id, id));
|
|
||||||
await rcon.updateCatalog();
|
|
||||||
revalidatePath("/admin/catalog/builder-club");
|
|
||||||
return { ok: true as const };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function createBcPage(input: {
|
export async function createBcPage(input: {
|
||||||
@@ -180,52 +196,31 @@ export async function createBcPage(input: {
|
|||||||
orderNum?: number;
|
orderNum?: number;
|
||||||
}) {
|
}) {
|
||||||
const staff = await requirePermission(PERMS.CATALOG_EDIT);
|
const staff = await requirePermission(PERMS.CATALOG_EDIT);
|
||||||
const [result] = await db.insert(CatalogPagesBc).values({
|
return await withCatalogExport(async () => {
|
||||||
caption: input.caption,
|
const createdId = await createPageCommand("bc", {
|
||||||
parentId: input.parentId,
|
caption: input.caption,
|
||||||
pageLayout: input.pageLayout ?? "default_3x3",
|
parentId: input.parentId,
|
||||||
iconColor: input.iconColor ?? 0,
|
pageLayout: input.pageLayout ?? "default_3x3",
|
||||||
iconImage: input.iconImage ?? 0,
|
iconColor: input.iconColor ?? 0,
|
||||||
orderNum: input.orderNum ?? 0,
|
iconImage: input.iconImage ?? 0,
|
||||||
visible: input.visible ?? "1",
|
orderNum: input.orderNum ?? 0,
|
||||||
enabled: input.enabled ?? "1",
|
visible: input.visible ?? "1",
|
||||||
pageHeadline: "",
|
enabled: input.enabled ?? "1",
|
||||||
pageTeaser: "",
|
pageHeadline: "",
|
||||||
|
pageTeaser: "",
|
||||||
|
});
|
||||||
|
await sendCatalogUpdate();
|
||||||
|
await logStaffActivity({
|
||||||
|
staffId: staff.id,
|
||||||
|
action: "bc_page_create",
|
||||||
|
description: `Created BC catalog page "${input.caption}"`,
|
||||||
|
targetType: "catalog_page_bc",
|
||||||
|
targetId: createdId,
|
||||||
|
});
|
||||||
|
revalidatePath("/admin/catalog");
|
||||||
|
revalidatePath("/admin/catalog/builder-club");
|
||||||
|
return { ok: true as const, data: { id: createdId } };
|
||||||
});
|
});
|
||||||
const createdId = Number(result.insertId);
|
|
||||||
await rcon.updateCatalog();
|
|
||||||
await logStaffActivity({
|
|
||||||
staffId: staff.id,
|
|
||||||
action: "bc_page_create",
|
|
||||||
description: `Created BC catalog page "${input.caption}"`,
|
|
||||||
targetType: "catalog_page_bc",
|
|
||||||
targetId: createdId,
|
|
||||||
});
|
|
||||||
revalidatePath("/admin/catalog");
|
|
||||||
revalidatePath("/admin/catalog/builder-club");
|
|
||||||
return { ok: true as const, data: { id: createdId } };
|
|
||||||
}
|
|
||||||
|
|
||||||
async function moveBcPage(pageId: number, newParentId: number): Promise<void> {
|
|
||||||
if (newParentId > 0) {
|
|
||||||
let currentId = newParentId;
|
|
||||||
for (let i = 0; i < 50; i++) {
|
|
||||||
if (currentId === pageId) {
|
|
||||||
throw new Error("Cannot move page: would create a circular hierarchy");
|
|
||||||
}
|
|
||||||
const [parent] = await db
|
|
||||||
.select({ parentId: CatalogPagesBc.parentId })
|
|
||||||
.from(CatalogPagesBc)
|
|
||||||
.where(eq(CatalogPagesBc.id, currentId))
|
|
||||||
.limit(1);
|
|
||||||
if (!parent || parent.parentId <= 0) break;
|
|
||||||
currentId = parent.parentId;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
await db
|
|
||||||
.update(CatalogPagesBc)
|
|
||||||
.set({ parentId: newParentId })
|
|
||||||
.where(eq(CatalogPagesBc.id, pageId));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function reorderBcTreePage(input: {
|
export async function reorderBcTreePage(input: {
|
||||||
@@ -234,24 +229,16 @@ export async function reorderBcTreePage(input: {
|
|||||||
newOrderNum: number;
|
newOrderNum: number;
|
||||||
}) {
|
}) {
|
||||||
await requirePermission(PERMS.CATALOG_EDIT);
|
await requirePermission(PERMS.CATALOG_EDIT);
|
||||||
if (input.newParentId !== undefined) {
|
return await withCatalogExport(async () => {
|
||||||
try {
|
await updatePageCommand("bc", input.pageId, {
|
||||||
await moveBcPage(input.pageId, input.newParentId);
|
parentId: input.newParentId,
|
||||||
} catch (err) {
|
orderNum: input.newOrderNum,
|
||||||
return {
|
});
|
||||||
ok: false as const,
|
await sendCatalogUpdate();
|
||||||
error: err instanceof Error ? err.message : "Invalid move",
|
revalidatePath("/admin/catalog");
|
||||||
};
|
revalidatePath("/admin/catalog/builder-club");
|
||||||
}
|
return { ok: true as const, data: {} };
|
||||||
}
|
});
|
||||||
await db
|
|
||||||
.update(CatalogPagesBc)
|
|
||||||
.set({ orderNum: input.newOrderNum })
|
|
||||||
.where(eq(CatalogPagesBc.id, input.pageId));
|
|
||||||
await rcon.updateCatalog();
|
|
||||||
revalidatePath("/admin/catalog");
|
|
||||||
revalidatePath("/admin/catalog/builder-club");
|
|
||||||
return { ok: true as const, data: {} };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function deleteBcTreePage(input: {
|
export async function deleteBcTreePage(input: {
|
||||||
@@ -259,52 +246,26 @@ export async function deleteBcTreePage(input: {
|
|||||||
mode: "reparent" | "cascade";
|
mode: "reparent" | "cascade";
|
||||||
}) {
|
}) {
|
||||||
await requirePermission(PERMS.CATALOG_EDIT);
|
await requirePermission(PERMS.CATALOG_EDIT);
|
||||||
const [page] = await db
|
return await withCatalogExport(async () => {
|
||||||
.select({ parentId: CatalogPagesBc.parentId })
|
await deletePageCommand("bc", input.pageId, input.mode);
|
||||||
.from(CatalogPagesBc)
|
await sendCatalogUpdate();
|
||||||
.where(eq(CatalogPagesBc.id, input.pageId))
|
revalidatePath("/admin/catalog");
|
||||||
.limit(1);
|
revalidatePath("/admin/catalog/builder-club");
|
||||||
if (!page) return { ok: false as const, error: "Page not found" };
|
return { ok: true as const, data: {} };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
if (input.mode === "reparent") {
|
export async function reorderBcCatalogPages(input: {
|
||||||
await db.transaction(async (tx) => {
|
parentId: number;
|
||||||
await tx
|
ids: number[];
|
||||||
.update(CatalogPagesBc)
|
expectedIds: number[];
|
||||||
.set({ parentId: page.parentId })
|
}) {
|
||||||
.where(eq(CatalogPagesBc.parentId, input.pageId));
|
await requirePermission(PERMS.CATALOG_EDIT);
|
||||||
await tx
|
return withCatalogExport(async () => {
|
||||||
.delete(CatalogItemsBc)
|
await reorderPagesCommand("bc", input);
|
||||||
.where(eq(CatalogItemsBc.pageId, input.pageId));
|
await sendCatalogUpdate();
|
||||||
await tx
|
revalidatePath("/admin/catalog");
|
||||||
.delete(CatalogPagesBc)
|
revalidatePath("/admin/catalog/builder-club");
|
||||||
.where(eq(CatalogPagesBc.id, input.pageId));
|
return { ok: true as const, data: {} };
|
||||||
});
|
});
|
||||||
} else {
|
|
||||||
const toDelete: number[] = [input.pageId];
|
|
||||||
const queue: number[] = [input.pageId];
|
|
||||||
while (queue.length > 0) {
|
|
||||||
const children = await db
|
|
||||||
.select({ id: CatalogPagesBc.id })
|
|
||||||
.from(CatalogPagesBc)
|
|
||||||
.where(inArray(CatalogPagesBc.parentId, queue));
|
|
||||||
queue.length = 0;
|
|
||||||
for (const child of children) {
|
|
||||||
toDelete.push(child.id);
|
|
||||||
queue.push(child.id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
await db.transaction(async (tx) => {
|
|
||||||
await tx
|
|
||||||
.delete(CatalogItemsBc)
|
|
||||||
.where(inArray(CatalogItemsBc.pageId, toDelete));
|
|
||||||
await tx
|
|
||||||
.delete(CatalogPagesBc)
|
|
||||||
.where(inArray(CatalogPagesBc.id, toDelete));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
await rcon.updateCatalog();
|
|
||||||
revalidatePath("/admin/catalog");
|
|
||||||
revalidatePath("/admin/catalog/builder-club");
|
|
||||||
return { ok: true as const, data: {} };
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
"use server";
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import type { BulkOfferInput } from "@/features/catalog/domain/bulk-offers";
|
||||||
|
import {
|
||||||
|
applyBulkOffersCommand,
|
||||||
|
listBulkOfferDestinationsCommand,
|
||||||
|
previewBulkOffersCommand,
|
||||||
|
} from "@/features/catalog/server/bulk-offers";
|
||||||
|
import { catalogFailure } from "@/features/catalog/server/errors";
|
||||||
|
import { sendCatalogUpdate } from "@/features/catalog/server/sync-status";
|
||||||
|
import { requirePermission } from "@/lib/admin/guard";
|
||||||
|
import { logger } from "@/lib/logger";
|
||||||
|
import { PERMS } from "@/lib/permissions";
|
||||||
|
import { logAudit } from "@/lib/services/audit";
|
||||||
|
import { withCatalogExport } from "@/lib/services/catalog-git-queue";
|
||||||
|
export async function previewBulkOffers(input: BulkOfferInput) {
|
||||||
|
await requirePermission(PERMS.CATALOG_VIEW);
|
||||||
|
try {
|
||||||
|
return { ok: true as const, data: await previewBulkOffersCommand(input) };
|
||||||
|
} catch (error) {
|
||||||
|
return { ok: false as const, error: catalogFailure(error).message };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
export async function applyBulkOffers(
|
||||||
|
input: BulkOfferInput,
|
||||||
|
fingerprint: string,
|
||||||
|
) {
|
||||||
|
const staff = await requirePermission(PERMS.CATALOG_EDIT);
|
||||||
|
try {
|
||||||
|
return await withCatalogExport(async () => {
|
||||||
|
const data = await applyBulkOffersCommand(input, fingerprint);
|
||||||
|
if (data.changedCount > 0) {
|
||||||
|
await logAudit({
|
||||||
|
userId: staff.id,
|
||||||
|
action: "catalog_offers_bulk_update",
|
||||||
|
target: "catalog",
|
||||||
|
after: {
|
||||||
|
ids: input.ids,
|
||||||
|
changes: input.changes,
|
||||||
|
changedCount: data.changedCount,
|
||||||
|
},
|
||||||
|
}).catch((error) =>
|
||||||
|
logger.error("Catalog bulk update committed; audit write failed", {
|
||||||
|
module: "catalog",
|
||||||
|
error,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
await sendCatalogUpdate();
|
||||||
|
revalidatePath("/admin/catalog", "layout");
|
||||||
|
}
|
||||||
|
return { ok: true as const, data };
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
return { ok: false as const, error: catalogFailure(error).message };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getBulkOfferDestinations() {
|
||||||
|
await requirePermission(PERMS.CATALOG_VIEW);
|
||||||
|
try {
|
||||||
|
return {
|
||||||
|
ok: true as const,
|
||||||
|
data: await listBulkOfferDestinationsCommand(),
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
return { ok: false as const, error: catalogFailure(error).message };
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
"use server";
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import type {
|
||||||
|
DuplicateInput,
|
||||||
|
DuplicatePreview,
|
||||||
|
} from "@/features/catalog/domain/duplicate";
|
||||||
|
import {
|
||||||
|
duplicateCategoryCommand,
|
||||||
|
duplicateDestinationsCommand,
|
||||||
|
previewDuplicateCommand,
|
||||||
|
} from "@/features/catalog/server/duplicate-commands";
|
||||||
|
import { catalogFailure } from "@/features/catalog/server/errors";
|
||||||
|
import { sendCatalogUpdate } from "@/features/catalog/server/sync-status";
|
||||||
|
import { requirePermission } from "@/lib/admin/guard";
|
||||||
|
import { logger } from "@/lib/logger";
|
||||||
|
import { PERMS } from "@/lib/permissions";
|
||||||
|
import { withCatalogExport } from "@/lib/services/catalog-git-queue";
|
||||||
|
import { logStaffActivity } from "@/lib/services/staff-activity";
|
||||||
|
export async function previewCatalogDuplicate(input: DuplicateInput) {
|
||||||
|
await requirePermission(PERMS.CATALOG_VIEW);
|
||||||
|
try {
|
||||||
|
return { ok: true as const, data: await previewDuplicateCommand(input) };
|
||||||
|
} catch (error) {
|
||||||
|
return { ok: false as const, error: catalogFailure(error).message };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
export async function applyCatalogDuplicate(input: DuplicatePreview) {
|
||||||
|
const staff = await requirePermission(PERMS.CATALOG_EDIT);
|
||||||
|
return withCatalogExport(async () => {
|
||||||
|
let data: Awaited<ReturnType<typeof duplicateCategoryCommand>>;
|
||||||
|
try {
|
||||||
|
data = await duplicateCategoryCommand(input);
|
||||||
|
} catch (error) {
|
||||||
|
return { ok: false as const, error: catalogFailure(error).message };
|
||||||
|
}
|
||||||
|
const hotel = await sendCatalogUpdate();
|
||||||
|
await logStaffActivity({
|
||||||
|
staffId: staff.id,
|
||||||
|
action: "catalog_page_create",
|
||||||
|
description: `Duplicated ${input.kind} category #${input.sourceId} to #${data.id}: ${data.pages} categories, ${data.offers} offers`,
|
||||||
|
targetType: "catalog_page",
|
||||||
|
targetId: data.id,
|
||||||
|
}).catch((error) => {
|
||||||
|
logger.error("Category duplicated but audit logging failed", {
|
||||||
|
module: "catalog",
|
||||||
|
error,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
revalidatePath("/admin/catalog");
|
||||||
|
return { ok: true as const, data: { ...data, hotel } };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function catalogDuplicateDestinations(
|
||||||
|
kind: DuplicateInput["kind"],
|
||||||
|
) {
|
||||||
|
await requirePermission(PERMS.CATALOG_VIEW);
|
||||||
|
try {
|
||||||
|
return {
|
||||||
|
ok: true as const,
|
||||||
|
data: await duplicateDestinationsCommand(kind),
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
return { ok: false as const, error: catalogFailure(error).message };
|
||||||
|
}
|
||||||
|
}
|
||||||
+259
-321
@@ -2,71 +2,23 @@
|
|||||||
|
|
||||||
import { eq, inArray, like, or, sql } from "drizzle-orm";
|
import { eq, inArray, like, or, sql } from "drizzle-orm";
|
||||||
import { revalidatePath } from "next/cache";
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { offerPatchSchema } from "@/features/catalog/domain/offer-input";
|
||||||
|
import {
|
||||||
|
createOfferCommand,
|
||||||
|
moveOffersCommand,
|
||||||
|
reorderOffersCommand,
|
||||||
|
updateOfferCommand,
|
||||||
|
} from "@/features/catalog/server/offer-commands";
|
||||||
|
import { sendCatalogUpdate } from "@/features/catalog/server/sync-status";
|
||||||
import { requirePermission } from "@/lib/admin/guard";
|
import { requirePermission } from "@/lib/admin/guard";
|
||||||
import { CatalogItems, db, ItemsBase } from "@/lib/db";
|
import { CatalogItems, db, ItemsBase } from "@/lib/db";
|
||||||
import { PERMS } from "@/lib/permissions";
|
import { PERMS } from "@/lib/permissions";
|
||||||
import { logAudit } from "@/lib/services/audit";
|
import { logAudit } from "@/lib/services/audit";
|
||||||
|
import { withCatalogExport } from "@/lib/services/catalog-git-queue";
|
||||||
import { allocateCatalogItemId } from "@/lib/services/furni-import";
|
import { allocateCatalogItemId } from "@/lib/services/furni-import";
|
||||||
import { rcon } from "@/lib/services/rcon";
|
|
||||||
import { logStaffActivity } from "@/lib/services/staff-activity";
|
import { logStaffActivity } from "@/lib/services/staff-activity";
|
||||||
import { translateItemsSchema } from "@/lib/validators/catalog";
|
import { translateItemsSchema } from "@/lib/validators/catalog";
|
||||||
|
|
||||||
const CATALOG_ITEM_FIELDS = [
|
|
||||||
"pageId",
|
|
||||||
"itemIds",
|
|
||||||
"catalogName",
|
|
||||||
"costCredits",
|
|
||||||
"costPoints",
|
|
||||||
"pointsType",
|
|
||||||
"amount",
|
|
||||||
"orderNumber",
|
|
||||||
"offerId",
|
|
||||||
"songId",
|
|
||||||
"limitedSells",
|
|
||||||
"limitedStack",
|
|
||||||
"extradata",
|
|
||||||
"haveOffer",
|
|
||||||
"clubOnly",
|
|
||||||
] as const;
|
|
||||||
|
|
||||||
const ITEMS_BASE_FIELDS = [
|
|
||||||
"publicName",
|
|
||||||
"itemName",
|
|
||||||
"type",
|
|
||||||
"width",
|
|
||||||
"length",
|
|
||||||
"stackHeight",
|
|
||||||
"allowStack",
|
|
||||||
"allowSit",
|
|
||||||
"allowLay",
|
|
||||||
"allowWalk",
|
|
||||||
"allowGift",
|
|
||||||
"allowTrade",
|
|
||||||
"allowRecycle",
|
|
||||||
"allowMarketplaceSell",
|
|
||||||
"allowInventoryStack",
|
|
||||||
"interactionType",
|
|
||||||
"interactionModesCount",
|
|
||||||
"vendingIds",
|
|
||||||
"customparams",
|
|
||||||
"effectIdMale",
|
|
||||||
"effectIdFemale",
|
|
||||||
"clothingOnWalk",
|
|
||||||
] as const;
|
|
||||||
|
|
||||||
function pickAllowed(
|
|
||||||
fields: Record<string, unknown>,
|
|
||||||
allowed: readonly string[],
|
|
||||||
): Record<string, unknown> {
|
|
||||||
const out: Record<string, unknown> = {};
|
|
||||||
for (const key of allowed) {
|
|
||||||
if (Object.hasOwn(fields, key) && fields[key] !== undefined) {
|
|
||||||
out[key] = fields[key];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Raw INSERT — catalog_items.id has no AUTO_INCREMENT on real Habbo DBs; page_id is often VARCHAR. */
|
/** Raw INSERT — catalog_items.id has no AUTO_INCREMENT on real Habbo DBs; page_id is often VARCHAR. */
|
||||||
async function insertCatalogItemRow(data: {
|
async function insertCatalogItemRow(data: {
|
||||||
pageId: number;
|
pageId: number;
|
||||||
@@ -86,8 +38,10 @@ async function insertCatalogItemRow(data: {
|
|||||||
clubOnly: string;
|
clubOnly: string;
|
||||||
}): Promise<number> {
|
}): Promise<number> {
|
||||||
const pageIdStr = String(data.pageId);
|
const pageIdStr = String(data.pageId);
|
||||||
return allocateCatalogItemId(async (nextId) => {
|
offerPatchSchema.required().parse(data);
|
||||||
await db.execute(sql`
|
return allocateCatalogItemId((nextId) =>
|
||||||
|
createOfferCommand("normal", data, async (tx) => {
|
||||||
|
await tx.execute(sql`
|
||||||
INSERT INTO catalog_items (
|
INSERT INTO catalog_items (
|
||||||
id, page_id, item_ids, catalog_name,
|
id, page_id, item_ids, catalog_name,
|
||||||
cost_credits, cost_points, points_type, amount,
|
cost_credits, cost_points, points_type, amount,
|
||||||
@@ -101,8 +55,9 @@ async function insertCatalogItemRow(data: {
|
|||||||
${data.haveOffer}, ${data.clubOnly}
|
${data.haveOffer}, ${data.clubOnly}
|
||||||
)
|
)
|
||||||
`);
|
`);
|
||||||
return nextId;
|
return nextId;
|
||||||
});
|
}),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function createCatalogItem(data: {
|
export async function createCatalogItem(data: {
|
||||||
@@ -123,32 +78,34 @@ export async function createCatalogItem(data: {
|
|||||||
clubOnly: "0" | "1";
|
clubOnly: "0" | "1";
|
||||||
}) {
|
}) {
|
||||||
const staff = await requirePermission(PERMS.CATALOG_EDIT);
|
const staff = await requirePermission(PERMS.CATALOG_EDIT);
|
||||||
let catalogName = data.catalogName.trim();
|
return await withCatalogExport(async () => {
|
||||||
if (!catalogName) {
|
let catalogName = data.catalogName.trim();
|
||||||
const firstId = Number.parseInt(data.itemIds.split(";")[0] || "", 10);
|
if (!catalogName) {
|
||||||
if (firstId > 0) {
|
const firstId = Number.parseInt(data.itemIds.split(";")[0] || "", 10);
|
||||||
const [base] = await db
|
if (firstId > 0) {
|
||||||
.select({
|
const [base] = await db
|
||||||
publicName: ItemsBase.publicName,
|
.select({
|
||||||
itemName: ItemsBase.itemName,
|
publicName: ItemsBase.publicName,
|
||||||
})
|
itemName: ItemsBase.itemName,
|
||||||
.from(ItemsBase)
|
})
|
||||||
.where(eq(ItemsBase.id, firstId))
|
.from(ItemsBase)
|
||||||
.limit(1);
|
.where(eq(ItemsBase.id, firstId))
|
||||||
catalogName = base?.publicName || base?.itemName || String(firstId);
|
.limit(1);
|
||||||
|
catalogName = base?.publicName || base?.itemName || String(firstId);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
const id = await insertCatalogItemRow({ ...data, catalogName });
|
||||||
const id = await insertCatalogItemRow({ ...data, catalogName });
|
await sendCatalogUpdate();
|
||||||
await rcon.updateCatalog();
|
await logStaffActivity({
|
||||||
await logStaffActivity({
|
staffId: staff.id,
|
||||||
staffId: staff.id,
|
action: "catalog_item_create",
|
||||||
action: "catalog_item_create",
|
description: `Created catalog item #${id}`,
|
||||||
description: `Created catalog item #${id}`,
|
targetType: "catalog_item",
|
||||||
targetType: "catalog_item",
|
targetId: id,
|
||||||
targetId: id,
|
});
|
||||||
|
revalidatePath("/admin/catalog");
|
||||||
|
return { ok: true as const, data: { id } };
|
||||||
});
|
});
|
||||||
revalidatePath("/admin/catalog");
|
|
||||||
return { ok: true as const, data: { id } };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Bulk create with one RCON refresh at the end. */
|
/** Bulk create with one RCON refresh at the end. */
|
||||||
@@ -165,84 +122,88 @@ export async function bulkCreateCatalogItems({
|
|||||||
}>;
|
}>;
|
||||||
}) {
|
}) {
|
||||||
const staff = await requirePermission(PERMS.CATALOG_EDIT);
|
const staff = await requirePermission(PERMS.CATALOG_EDIT);
|
||||||
if (rows.length === 0) {
|
return await withCatalogExport(async () => {
|
||||||
return { ok: true as const, data: { created: 0, failed: 0 } };
|
if (rows.length === 0) {
|
||||||
}
|
return { ok: true as const, data: { created: 0, failed: 0 } };
|
||||||
if (rows.length > 500) {
|
|
||||||
return { ok: false as const, error: "Max 500 items per bulk import" };
|
|
||||||
}
|
|
||||||
|
|
||||||
const baseIds = [...new Set(rows.map((r) => r.baseId))];
|
|
||||||
const bases = await db
|
|
||||||
.select({
|
|
||||||
id: ItemsBase.id,
|
|
||||||
publicName: ItemsBase.publicName,
|
|
||||||
itemName: ItemsBase.itemName,
|
|
||||||
})
|
|
||||||
.from(ItemsBase)
|
|
||||||
.where(inArray(ItemsBase.id, baseIds));
|
|
||||||
const baseMap = new Map(bases.map((b) => [b.id, b]));
|
|
||||||
|
|
||||||
let created = 0;
|
|
||||||
let failed = 0;
|
|
||||||
|
|
||||||
for (const row of rows) {
|
|
||||||
const base = baseMap.get(row.baseId);
|
|
||||||
if (!base) {
|
|
||||||
failed++;
|
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
try {
|
if (rows.length > 500) {
|
||||||
await insertCatalogItemRow({
|
return { ok: false as const, error: "Max 500 items per bulk import" };
|
||||||
pageId,
|
}
|
||||||
itemIds: String(row.baseId),
|
|
||||||
catalogName: base.publicName || base.itemName || String(row.baseId),
|
const baseIds = [...new Set(rows.map((r) => r.baseId))];
|
||||||
costCredits: row.credits ?? 0,
|
const bases = await db
|
||||||
costPoints: row.points ?? 0,
|
.select({
|
||||||
pointsType: row.pointsType ?? 0,
|
id: ItemsBase.id,
|
||||||
amount: 1,
|
publicName: ItemsBase.publicName,
|
||||||
limitedSells: 0,
|
itemName: ItemsBase.itemName,
|
||||||
limitedStack: 0,
|
})
|
||||||
orderNumber: 1,
|
.from(ItemsBase)
|
||||||
offerId: -1,
|
.where(inArray(ItemsBase.id, baseIds));
|
||||||
songId: 0,
|
const baseMap = new Map(bases.map((b) => [b.id, b]));
|
||||||
haveOffer: "1",
|
|
||||||
clubOnly: "0",
|
let created = 0;
|
||||||
extradata: "",
|
let failed = 0;
|
||||||
|
|
||||||
|
for (const row of rows) {
|
||||||
|
const base = baseMap.get(row.baseId);
|
||||||
|
if (!base) {
|
||||||
|
failed++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await insertCatalogItemRow({
|
||||||
|
pageId,
|
||||||
|
itemIds: String(row.baseId),
|
||||||
|
catalogName: base.publicName || base.itemName || String(row.baseId),
|
||||||
|
costCredits: row.credits ?? 0,
|
||||||
|
costPoints: row.points ?? 0,
|
||||||
|
pointsType: row.pointsType ?? 0,
|
||||||
|
amount: 1,
|
||||||
|
limitedSells: 0,
|
||||||
|
limitedStack: 0,
|
||||||
|
orderNumber: 1,
|
||||||
|
offerId: -1,
|
||||||
|
songId: 0,
|
||||||
|
haveOffer: "1",
|
||||||
|
clubOnly: "0",
|
||||||
|
extradata: "",
|
||||||
|
});
|
||||||
|
created++;
|
||||||
|
} catch {
|
||||||
|
failed++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (created > 0) {
|
||||||
|
await sendCatalogUpdate();
|
||||||
|
await logStaffActivity({
|
||||||
|
staffId: staff.id,
|
||||||
|
action: "catalog_items_bulk_create",
|
||||||
|
description: `Bulk imported ${created} catalog item(s) on page #${pageId}`,
|
||||||
|
targetType: "catalog_page",
|
||||||
|
targetId: pageId,
|
||||||
});
|
});
|
||||||
created++;
|
revalidatePath("/admin/catalog");
|
||||||
} catch {
|
|
||||||
failed++;
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
if (created > 0) {
|
return { ok: true as const, data: { created, failed } };
|
||||||
await rcon.updateCatalog();
|
});
|
||||||
await logStaffActivity({
|
|
||||||
staffId: staff.id,
|
|
||||||
action: "catalog_items_bulk_create",
|
|
||||||
description: `Bulk imported ${created} catalog item(s) on page #${pageId}`,
|
|
||||||
targetType: "catalog_page",
|
|
||||||
targetId: pageId,
|
|
||||||
});
|
|
||||||
revalidatePath("/admin/catalog");
|
|
||||||
}
|
|
||||||
|
|
||||||
return { ok: true as const, data: { created, failed } };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function deleteCatalogItems({ ids }: { ids: number[] }) {
|
export async function deleteCatalogItems({ ids }: { ids: number[] }) {
|
||||||
const staff = await requirePermission(PERMS.CATALOG_EDIT);
|
const staff = await requirePermission(PERMS.CATALOG_EDIT);
|
||||||
await db.delete(CatalogItems).where(inArray(CatalogItems.id, ids));
|
return await withCatalogExport(async () => {
|
||||||
await rcon.updateCatalog();
|
await db.delete(CatalogItems).where(inArray(CatalogItems.id, ids));
|
||||||
await logStaffActivity({
|
await sendCatalogUpdate();
|
||||||
staffId: staff.id,
|
await logStaffActivity({
|
||||||
action: "catalog_items_delete",
|
staffId: staff.id,
|
||||||
description: `Deleted catalog items: ${ids.join(", ")}`,
|
action: "catalog_items_delete",
|
||||||
targetType: "catalog_item",
|
description: `Deleted catalog items: ${ids.join(", ")}`,
|
||||||
|
targetType: "catalog_item",
|
||||||
|
});
|
||||||
|
revalidatePath("/admin/catalog");
|
||||||
|
return { ok: true as const, data: {} };
|
||||||
});
|
});
|
||||||
revalidatePath("/admin/catalog");
|
|
||||||
return { ok: true as const, data: {} };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function moveCatalogItems({
|
export async function moveCatalogItems({
|
||||||
@@ -253,21 +214,15 @@ export async function moveCatalogItems({
|
|||||||
targetPageId: number;
|
targetPageId: number;
|
||||||
}) {
|
}) {
|
||||||
await requirePermission(PERMS.CATALOG_EDIT);
|
await requirePermission(PERMS.CATALOG_EDIT);
|
||||||
if (ids.length === 0) {
|
return await withCatalogExport(async () => {
|
||||||
|
if (ids.length === 0) {
|
||||||
|
return { ok: true as const, data: {} };
|
||||||
|
}
|
||||||
|
await moveOffersCommand(ids, targetPageId);
|
||||||
|
await sendCatalogUpdate();
|
||||||
|
revalidatePath("/admin/catalog");
|
||||||
return { ok: true as const, data: {} };
|
return { ok: true as const, data: {} };
|
||||||
}
|
});
|
||||||
const pageIdStr = String(targetPageId);
|
|
||||||
await db.execute(sql`
|
|
||||||
UPDATE catalog_items
|
|
||||||
SET page_id = ${pageIdStr}
|
|
||||||
WHERE id IN (${sql.join(
|
|
||||||
ids.map((id) => sql`${id}`),
|
|
||||||
sql`, `,
|
|
||||||
)})
|
|
||||||
`);
|
|
||||||
await rcon.updateCatalog();
|
|
||||||
revalidatePath("/admin/catalog");
|
|
||||||
return { ok: true as const, data: {} };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function reorderCatalogItems({
|
export async function reorderCatalogItems({
|
||||||
@@ -276,15 +231,12 @@ export async function reorderCatalogItems({
|
|||||||
orders: Array<{ id: number; orderNumber: number }>;
|
orders: Array<{ id: number; orderNumber: number }>;
|
||||||
}) {
|
}) {
|
||||||
await requirePermission(PERMS.CATALOG_EDIT);
|
await requirePermission(PERMS.CATALOG_EDIT);
|
||||||
for (const { id, orderNumber } of orders) {
|
return await withCatalogExport(async () => {
|
||||||
await db
|
await reorderOffersCommand(orders);
|
||||||
.update(CatalogItems)
|
await sendCatalogUpdate();
|
||||||
.set({ orderNumber })
|
revalidatePath("/admin/catalog");
|
||||||
.where(eq(CatalogItems.id, id));
|
return { ok: true as const, data: {} };
|
||||||
}
|
});
|
||||||
await rcon.updateCatalog();
|
|
||||||
revalidatePath("/admin/catalog");
|
|
||||||
return { ok: true as const, data: {} };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function updateCatalogItem({
|
export async function updateCatalogItem({
|
||||||
@@ -297,46 +249,29 @@ export async function updateCatalogItem({
|
|||||||
baseItem?: { id: number; fields: Record<string, unknown> };
|
baseItem?: { id: number; fields: Record<string, unknown> };
|
||||||
}) {
|
}) {
|
||||||
const staff = await requirePermission(PERMS.CATALOG_EDIT);
|
const staff = await requirePermission(PERMS.CATALOG_EDIT);
|
||||||
const safeCatalog = pickAllowed(catalogFields, CATALOG_ITEM_FIELDS);
|
return await withCatalogExport(async () => {
|
||||||
if (Object.keys(safeCatalog).length === 0 && !baseItem) {
|
try {
|
||||||
return { ok: false as const, error: "No valid fields to update" };
|
await updateOfferCommand({ id, catalogFields, baseItem });
|
||||||
}
|
} catch (error) {
|
||||||
|
return {
|
||||||
// page_id is often VARCHAR — update it via raw SQL when present.
|
ok: false as const,
|
||||||
const pageIdRaw = safeCatalog.pageId;
|
error:
|
||||||
if (pageIdRaw !== undefined) {
|
error instanceof Error
|
||||||
const pageIdStr = String(pageIdRaw);
|
? error.message
|
||||||
await db.execute(sql`
|
: "Unable to update catalog item",
|
||||||
UPDATE catalog_items SET page_id = ${pageIdStr} WHERE id = ${id}
|
};
|
||||||
`);
|
|
||||||
delete safeCatalog.pageId;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (Object.keys(safeCatalog).length > 0) {
|
|
||||||
await db
|
|
||||||
.update(CatalogItems)
|
|
||||||
.set(safeCatalog as Partial<typeof CatalogItems.$inferInsert>)
|
|
||||||
.where(eq(CatalogItems.id, id));
|
|
||||||
}
|
|
||||||
if (baseItem) {
|
|
||||||
const safeBase = pickAllowed(baseItem.fields, ITEMS_BASE_FIELDS);
|
|
||||||
if (Object.keys(safeBase).length > 0) {
|
|
||||||
await db
|
|
||||||
.update(ItemsBase)
|
|
||||||
.set(safeBase as Partial<typeof ItemsBase.$inferInsert>)
|
|
||||||
.where(eq(ItemsBase.id, baseItem.id));
|
|
||||||
}
|
}
|
||||||
}
|
await sendCatalogUpdate();
|
||||||
await rcon.updateCatalog();
|
await logStaffActivity({
|
||||||
await logStaffActivity({
|
staffId: staff.id,
|
||||||
staffId: staff.id,
|
action: "catalog_item_update",
|
||||||
action: "catalog_item_update",
|
description: `Updated catalog item #${id}`,
|
||||||
description: `Updated catalog item #${id}`,
|
targetType: "catalog_item",
|
||||||
targetType: "catalog_item",
|
targetId: id,
|
||||||
targetId: id,
|
});
|
||||||
|
revalidatePath("/admin/catalog");
|
||||||
|
return { ok: true as const, data: {} };
|
||||||
});
|
});
|
||||||
revalidatePath("/admin/catalog");
|
|
||||||
return { ok: true as const, data: {} };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function translateCatalogItems(input: {
|
export async function translateCatalogItems(input: {
|
||||||
@@ -344,121 +279,124 @@ export async function translateCatalogItems(input: {
|
|||||||
items: Array<{ id: number; publicName: string; description?: string }>;
|
items: Array<{ id: number; publicName: string; description?: string }>;
|
||||||
}) {
|
}) {
|
||||||
const staff = await requirePermission(PERMS.CATALOG_EDIT);
|
const staff = await requirePermission(PERMS.CATALOG_EDIT);
|
||||||
const parsed = translateItemsSchema.safeParse(input);
|
return await withCatalogExport(async () => {
|
||||||
if (!parsed.success) {
|
const parsed = translateItemsSchema.safeParse(input);
|
||||||
return {
|
if (!parsed.success) {
|
||||||
ok: false as const,
|
return {
|
||||||
error: parsed.error.issues[0]?.message ?? "Invalid translate payload",
|
ok: false as const,
|
||||||
};
|
error: parsed.error.issues[0]?.message ?? "Invalid translate payload",
|
||||||
}
|
};
|
||||||
const { items } = parsed.data;
|
}
|
||||||
const { invalidateFurniDataCache } = await import(
|
const { items } = parsed.data;
|
||||||
"@/lib/services/catalog-items-loader"
|
const { invalidateFurniDataCache } = await import(
|
||||||
);
|
"@/lib/services/catalog-items-loader"
|
||||||
const { patchFurniEntryNames } = await import("@/lib/services/furni-data");
|
);
|
||||||
|
const { patchFurniEntryNames } = await import("@/lib/services/furni-data");
|
||||||
|
|
||||||
let namesUpdated = 0;
|
let namesUpdated = 0;
|
||||||
let descriptionsUpdated = 0;
|
let descriptionsUpdated = 0;
|
||||||
const furniPatches: Array<{
|
const furniPatches: Array<{
|
||||||
classname: string;
|
classname: string;
|
||||||
itemType: string;
|
itemType: string;
|
||||||
name?: string;
|
name?: string;
|
||||||
description?: string;
|
description?: string;
|
||||||
spriteId?: number;
|
spriteId?: number;
|
||||||
createIfMissing?: boolean;
|
createIfMissing?: boolean;
|
||||||
}> = [];
|
}> = [];
|
||||||
|
|
||||||
for (const item of items) {
|
for (const item of items) {
|
||||||
const [base] = await db
|
const [base] = await db
|
||||||
.select({
|
|
||||||
id: ItemsBase.id,
|
|
||||||
publicName: ItemsBase.publicName,
|
|
||||||
itemName: ItemsBase.itemName,
|
|
||||||
type: ItemsBase.type,
|
|
||||||
spriteId: ItemsBase.spriteId,
|
|
||||||
})
|
|
||||||
.from(ItemsBase)
|
|
||||||
.where(eq(ItemsBase.id, item.id))
|
|
||||||
.limit(1);
|
|
||||||
if (!base) continue;
|
|
||||||
|
|
||||||
const nextName = item.publicName?.trim() ?? "";
|
|
||||||
const nextDesc = item.description ?? "";
|
|
||||||
const nameChanged = nextName !== "" && nextName !== (base.publicName ?? "");
|
|
||||||
|
|
||||||
if (nameChanged) {
|
|
||||||
await db
|
|
||||||
.update(ItemsBase)
|
|
||||||
.set({ publicName: nextName })
|
|
||||||
.where(eq(ItemsBase.id, base.id));
|
|
||||||
const idStr = String(base.id);
|
|
||||||
const related = await db
|
|
||||||
.select({
|
.select({
|
||||||
id: CatalogItems.id,
|
id: ItemsBase.id,
|
||||||
catalogName: CatalogItems.catalogName,
|
publicName: ItemsBase.publicName,
|
||||||
|
itemName: ItemsBase.itemName,
|
||||||
|
type: ItemsBase.type,
|
||||||
|
spriteId: ItemsBase.spriteId,
|
||||||
})
|
})
|
||||||
.from(CatalogItems)
|
.from(ItemsBase)
|
||||||
.where(
|
.where(eq(ItemsBase.id, item.id))
|
||||||
or(
|
.limit(1);
|
||||||
eq(CatalogItems.itemIds, idStr),
|
if (!base) continue;
|
||||||
like(CatalogItems.itemIds, `${idStr};%`),
|
|
||||||
like(CatalogItems.itemIds, `%;${idStr};%`),
|
const nextName = item.publicName?.trim() ?? "";
|
||||||
like(CatalogItems.itemIds, `%;${idStr}`),
|
const nextDesc = item.description ?? "";
|
||||||
),
|
const nameChanged =
|
||||||
);
|
nextName !== "" && nextName !== (base.publicName ?? "");
|
||||||
for (const row of related) {
|
|
||||||
if (row.catalogName !== nextName) {
|
if (nameChanged) {
|
||||||
await db
|
await db
|
||||||
.update(CatalogItems)
|
.update(ItemsBase)
|
||||||
.set({ catalogName: nextName })
|
.set({ publicName: nextName })
|
||||||
.where(eq(CatalogItems.id, row.id));
|
.where(eq(ItemsBase.id, base.id));
|
||||||
|
const idStr = String(base.id);
|
||||||
|
const related = await db
|
||||||
|
.select({
|
||||||
|
id: CatalogItems.id,
|
||||||
|
catalogName: CatalogItems.catalogName,
|
||||||
|
})
|
||||||
|
.from(CatalogItems)
|
||||||
|
.where(
|
||||||
|
or(
|
||||||
|
eq(CatalogItems.itemIds, idStr),
|
||||||
|
like(CatalogItems.itemIds, `${idStr};%`),
|
||||||
|
like(CatalogItems.itemIds, `%;${idStr};%`),
|
||||||
|
like(CatalogItems.itemIds, `%;${idStr}`),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
for (const row of related) {
|
||||||
|
if (row.catalogName !== nextName) {
|
||||||
|
await db
|
||||||
|
.update(CatalogItems)
|
||||||
|
.set({ catalogName: nextName })
|
||||||
|
.where(eq(CatalogItems.id, row.id));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
namesUpdated++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (nextDesc !== "" || nameChanged) {
|
||||||
|
descriptionsUpdated += nextDesc !== "" ? 1 : 0;
|
||||||
|
furniPatches.push({
|
||||||
|
classname: base.itemName,
|
||||||
|
itemType: base.type || "s",
|
||||||
|
name: nextName || base.publicName || base.itemName,
|
||||||
|
description: nextDesc,
|
||||||
|
spriteId: base.spriteId,
|
||||||
|
createIfMissing: true,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
namesUpdated++;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (nextDesc !== "" || nameChanged) {
|
const furniResult =
|
||||||
descriptionsUpdated += nextDesc !== "" ? 1 : 0;
|
furniPatches.length > 0
|
||||||
furniPatches.push({
|
? await patchFurniEntryNames(furniPatches)
|
||||||
classname: base.itemName,
|
: { updated: 0, inserted: 0 };
|
||||||
itemType: base.type || "s",
|
if (furniResult.updated > 0 || furniResult.inserted > 0) {
|
||||||
name: nextName || base.publicName || base.itemName,
|
invalidateFurniDataCache();
|
||||||
description: nextDesc,
|
|
||||||
spriteId: base.spriteId,
|
|
||||||
createIfMissing: true,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
const furniResult =
|
await sendCatalogUpdate();
|
||||||
furniPatches.length > 0
|
await logAudit({
|
||||||
? await patchFurniEntryNames(furniPatches)
|
userId: staff.id,
|
||||||
: { updated: 0, inserted: 0 };
|
action: "items_base_translate",
|
||||||
if (furniResult.updated > 0 || furniResult.inserted > 0) {
|
target: "ItemsBase",
|
||||||
invalidateFurniDataCache();
|
after: {
|
||||||
}
|
namesUpdated,
|
||||||
|
descriptionsUpdated,
|
||||||
await rcon.updateCatalog();
|
furniDataUpdated: furniResult.updated > 0,
|
||||||
await logAudit({
|
furniDataInserted: furniResult.inserted,
|
||||||
userId: staff.id,
|
},
|
||||||
action: "items_base_translate",
|
});
|
||||||
target: "ItemsBase",
|
revalidatePath("/admin/catalog");
|
||||||
after: {
|
return {
|
||||||
namesUpdated,
|
ok: true as const,
|
||||||
descriptionsUpdated,
|
data: {
|
||||||
furniDataUpdated: furniResult.updated > 0,
|
namesUpdated,
|
||||||
furniDataInserted: furniResult.inserted,
|
descriptionsUpdated,
|
||||||
},
|
furniDataUpdated: furniResult.updated,
|
||||||
|
furniDataInserted: furniResult.inserted,
|
||||||
|
updated: items.length,
|
||||||
|
},
|
||||||
|
};
|
||||||
});
|
});
|
||||||
revalidatePath("/admin/catalog");
|
|
||||||
return {
|
|
||||||
ok: true as const,
|
|
||||||
data: {
|
|
||||||
namesUpdated,
|
|
||||||
descriptionsUpdated,
|
|
||||||
furniDataUpdated: furniResult.updated,
|
|
||||||
furniDataInserted: furniResult.inserted,
|
|
||||||
updated: items.length,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
+117
-101
@@ -1,13 +1,19 @@
|
|||||||
"use server";
|
"use server";
|
||||||
|
|
||||||
import { eq } from "drizzle-orm";
|
|
||||||
import { revalidatePath } from "next/cache";
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { catalogFailure } from "@/features/catalog/server/errors";
|
||||||
|
import {
|
||||||
|
createPageCommand,
|
||||||
|
deletePageCommand,
|
||||||
|
reorderPagesCommand,
|
||||||
|
togglePageCommand,
|
||||||
|
updatePageCommand,
|
||||||
|
} from "@/features/catalog/server/page-commands";
|
||||||
|
import { sendCatalogUpdate } from "@/features/catalog/server/sync-status";
|
||||||
import { requirePermission } from "@/lib/admin/guard";
|
import { requirePermission } from "@/lib/admin/guard";
|
||||||
import { CatalogPages, db } from "@/lib/db";
|
|
||||||
import { PERMS } from "@/lib/permissions";
|
import { PERMS } from "@/lib/permissions";
|
||||||
import type { ActionResult } from "@/lib/safe-action-shared";
|
import type { ActionResult } from "@/lib/safe-action-shared";
|
||||||
import { deletePage, movePage } from "@/lib/services/catalog-tree";
|
import { withCatalogExport } from "@/lib/services/catalog-git-queue";
|
||||||
import { rcon } from "@/lib/services/rcon";
|
|
||||||
import { logStaffActivity } from "@/lib/services/staff-activity";
|
import { logStaffActivity } from "@/lib/services/staff-activity";
|
||||||
|
|
||||||
const CATALOG_PAGE_FIELDS = [
|
const CATALOG_PAGE_FIELDS = [
|
||||||
@@ -45,45 +51,54 @@ function pickPageFields(fields: Record<string, unknown>) {
|
|||||||
|
|
||||||
export async function updateCatalogPage({
|
export async function updateCatalogPage({
|
||||||
id,
|
id,
|
||||||
|
expected,
|
||||||
...fields
|
...fields
|
||||||
}: { id: number } & Record<string, unknown>): Promise<ActionResult> {
|
}: { id: number; expected?: Record<string, unknown> } & Record<
|
||||||
|
string,
|
||||||
|
unknown
|
||||||
|
>): Promise<ActionResult> {
|
||||||
const staff = await requirePermission(PERMS.CATALOG_EDIT);
|
const staff = await requirePermission(PERMS.CATALOG_EDIT);
|
||||||
const data = pickPageFields(fields);
|
return await withCatalogExport(async () => {
|
||||||
if (Object.keys(data).length === 0) {
|
const data = pickPageFields(fields);
|
||||||
return { ok: false as const, error: "No valid fields to update" };
|
if (Object.keys(data).length === 0) {
|
||||||
}
|
return { ok: false as const, error: "No valid fields to update" };
|
||||||
if (typeof data.caption === "string" && !data.captionSave) {
|
}
|
||||||
data.captionSave = data.caption.slice(0, 25);
|
if (typeof data.caption === "string" && !data.captionSave) {
|
||||||
}
|
data.captionSave = data.caption.slice(0, 25);
|
||||||
await db
|
}
|
||||||
.update(CatalogPages)
|
try {
|
||||||
.set(data as Partial<typeof CatalogPages.$inferInsert>)
|
await updatePageCommand("normal", id, data, expected);
|
||||||
.where(eq(CatalogPages.id, id));
|
} catch (error) {
|
||||||
await rcon.updateCatalog();
|
return { ok: false as const, error: catalogFailure(error).message };
|
||||||
await logStaffActivity({
|
}
|
||||||
staffId: staff.id,
|
await sendCatalogUpdate();
|
||||||
action: "catalog_page_update",
|
await logStaffActivity({
|
||||||
description: `Updated catalog page #${id}`,
|
staffId: staff.id,
|
||||||
targetType: "catalog_page",
|
action: "catalog_page_update",
|
||||||
targetId: id,
|
description: `Updated catalog page #${id}`,
|
||||||
|
targetType: "catalog_page",
|
||||||
|
targetId: id,
|
||||||
|
});
|
||||||
|
revalidatePath("/admin/catalog");
|
||||||
|
return { ok: true as const, data: {} };
|
||||||
});
|
});
|
||||||
revalidatePath("/admin/catalog");
|
|
||||||
return { ok: true as const, data: {} };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function deleteCatalogPage({ id }: { id: number }) {
|
export async function deleteCatalogPage({ id }: { id: number }) {
|
||||||
const staff = await requirePermission(PERMS.CATALOG_EDIT);
|
const staff = await requirePermission(PERMS.CATALOG_EDIT);
|
||||||
await deletePage(id, "reparent");
|
return await withCatalogExport(async () => {
|
||||||
await rcon.updateCatalog();
|
await deletePageCommand("normal", id, "reparent");
|
||||||
await logStaffActivity({
|
await sendCatalogUpdate();
|
||||||
staffId: staff.id,
|
await logStaffActivity({
|
||||||
action: "catalog_page_delete",
|
staffId: staff.id,
|
||||||
description: `Deleted catalog page #${id}`,
|
action: "catalog_page_delete",
|
||||||
targetType: "catalog_page",
|
description: `Deleted catalog page #${id}`,
|
||||||
targetId: id,
|
targetType: "catalog_page",
|
||||||
|
targetId: id,
|
||||||
|
});
|
||||||
|
revalidatePath("/admin/catalog");
|
||||||
|
return { ok: true as const, data: {} };
|
||||||
});
|
});
|
||||||
revalidatePath("/admin/catalog");
|
|
||||||
return { ok: true as const, data: {} };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function toggleCatalogPage({
|
export async function toggleCatalogPage({
|
||||||
@@ -94,24 +109,16 @@ export async function toggleCatalogPage({
|
|||||||
action: "toggleEnabled" | "toggleVisible";
|
action: "toggleEnabled" | "toggleVisible";
|
||||||
}) {
|
}) {
|
||||||
await requirePermission(PERMS.CATALOG_EDIT);
|
await requirePermission(PERMS.CATALOG_EDIT);
|
||||||
const [page] = await db
|
return await withCatalogExport(async () => {
|
||||||
.select({
|
await togglePageCommand(
|
||||||
enabled: CatalogPages.enabled,
|
"normal",
|
||||||
visible: CatalogPages.visible,
|
id,
|
||||||
})
|
action === "toggleEnabled" ? "enabled" : "visible",
|
||||||
.from(CatalogPages)
|
);
|
||||||
.where(eq(CatalogPages.id, id))
|
await sendCatalogUpdate();
|
||||||
.limit(1);
|
revalidatePath("/admin/catalog");
|
||||||
if (!page) return { ok: false as const, error: "Catalog page not found" };
|
return { ok: true as const, data: {} };
|
||||||
const field = action === "toggleEnabled" ? "enabled" : "visible";
|
});
|
||||||
const current = action === "toggleEnabled" ? page.enabled : page.visible;
|
|
||||||
await db
|
|
||||||
.update(CatalogPages)
|
|
||||||
.set({ [field]: current === "1" ? "0" : "1" })
|
|
||||||
.where(eq(CatalogPages.id, id));
|
|
||||||
await rcon.updateCatalog();
|
|
||||||
revalidatePath("/admin/catalog");
|
|
||||||
return { ok: true as const, data: {} };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function createCatalogPage(input: {
|
export async function createCatalogPage(input: {
|
||||||
@@ -126,34 +133,35 @@ export async function createCatalogPage(input: {
|
|||||||
orderNum?: number;
|
orderNum?: number;
|
||||||
}): Promise<ActionResult<{ id: number }>> {
|
}): Promise<ActionResult<{ id: number }>> {
|
||||||
const staff = await requirePermission(PERMS.CATALOG_EDIT);
|
const staff = await requirePermission(PERMS.CATALOG_EDIT);
|
||||||
const [result] = await db.insert(CatalogPages).values({
|
return await withCatalogExport(async () => {
|
||||||
caption: input.caption,
|
const createdId = await createPageCommand("normal", {
|
||||||
parentId: input.parentId,
|
caption: input.caption,
|
||||||
pageLayout: input.pageLayout ?? "default_3x3",
|
parentId: input.parentId,
|
||||||
captionSave: input.caption.slice(0, 25),
|
pageLayout: input.pageLayout ?? "default_3x3",
|
||||||
iconColor: input.iconColor ?? 0,
|
captionSave: input.caption.slice(0, 25),
|
||||||
iconImage: input.iconImage ?? 0,
|
iconColor: input.iconColor ?? 0,
|
||||||
minRank: input.minRank ?? 1,
|
iconImage: input.iconImage ?? 0,
|
||||||
orderNum: input.orderNum ?? 0,
|
minRank: input.minRank ?? 1,
|
||||||
visible: input.visible ?? "1",
|
orderNum: input.orderNum ?? 0,
|
||||||
enabled: input.enabled ?? "1",
|
visible: input.visible ?? "1",
|
||||||
clubOnly: "0",
|
enabled: input.enabled ?? "1",
|
||||||
vipOnly: "0",
|
clubOnly: "0",
|
||||||
pageHeadline: "",
|
vipOnly: "0",
|
||||||
pageTeaser: "",
|
pageHeadline: "",
|
||||||
includes: "",
|
pageTeaser: "",
|
||||||
|
includes: "",
|
||||||
|
});
|
||||||
|
await sendCatalogUpdate();
|
||||||
|
await logStaffActivity({
|
||||||
|
staffId: staff.id,
|
||||||
|
action: "catalog_page_create",
|
||||||
|
description: `Created catalog page "${input.caption}"`,
|
||||||
|
targetType: "catalog_page",
|
||||||
|
targetId: createdId,
|
||||||
|
});
|
||||||
|
revalidatePath("/admin/catalog");
|
||||||
|
return { ok: true as const, data: { id: createdId } };
|
||||||
});
|
});
|
||||||
const createdId = Number(result.insertId);
|
|
||||||
await rcon.updateCatalog();
|
|
||||||
await logStaffActivity({
|
|
||||||
staffId: staff.id,
|
|
||||||
action: "catalog_page_create",
|
|
||||||
description: `Created catalog page "${input.caption}"`,
|
|
||||||
targetType: "catalog_page",
|
|
||||||
targetId: createdId,
|
|
||||||
});
|
|
||||||
revalidatePath("/admin/catalog");
|
|
||||||
return { ok: true as const, data: { id: createdId } };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function reorderTreePage(input: {
|
export async function reorderTreePage(input: {
|
||||||
@@ -162,23 +170,15 @@ export async function reorderTreePage(input: {
|
|||||||
newOrderNum: number;
|
newOrderNum: number;
|
||||||
}) {
|
}) {
|
||||||
await requirePermission(PERMS.CATALOG_EDIT);
|
await requirePermission(PERMS.CATALOG_EDIT);
|
||||||
if (input.newParentId !== undefined) {
|
return await withCatalogExport(async () => {
|
||||||
try {
|
await updatePageCommand("normal", input.pageId, {
|
||||||
await movePage(input.pageId, input.newParentId);
|
parentId: input.newParentId,
|
||||||
} catch (err) {
|
orderNum: input.newOrderNum,
|
||||||
return {
|
});
|
||||||
ok: false as const,
|
await sendCatalogUpdate();
|
||||||
error: err instanceof Error ? err.message : "Invalid move",
|
revalidatePath("/admin/catalog");
|
||||||
};
|
return { ok: true as const, data: {} };
|
||||||
}
|
});
|
||||||
}
|
|
||||||
await db
|
|
||||||
.update(CatalogPages)
|
|
||||||
.set({ orderNum: input.newOrderNum })
|
|
||||||
.where(eq(CatalogPages.id, input.pageId));
|
|
||||||
await rcon.updateCatalog();
|
|
||||||
revalidatePath("/admin/catalog");
|
|
||||||
return { ok: true as const, data: {} };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function deleteTreePage(input: {
|
export async function deleteTreePage(input: {
|
||||||
@@ -186,8 +186,24 @@ export async function deleteTreePage(input: {
|
|||||||
mode: "reparent" | "cascade";
|
mode: "reparent" | "cascade";
|
||||||
}) {
|
}) {
|
||||||
await requirePermission(PERMS.CATALOG_EDIT);
|
await requirePermission(PERMS.CATALOG_EDIT);
|
||||||
await deletePage(input.pageId, input.mode);
|
return await withCatalogExport(async () => {
|
||||||
await rcon.updateCatalog();
|
await deletePageCommand("normal", input.pageId, input.mode);
|
||||||
revalidatePath("/admin/catalog");
|
await sendCatalogUpdate();
|
||||||
return { ok: true as const, data: {} };
|
revalidatePath("/admin/catalog");
|
||||||
|
return { ok: true as const, data: {} };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function reorderCatalogPages(input: {
|
||||||
|
parentId: number;
|
||||||
|
ids: number[];
|
||||||
|
expectedIds: number[];
|
||||||
|
}) {
|
||||||
|
await requirePermission(PERMS.CATALOG_EDIT);
|
||||||
|
return withCatalogExport(async () => {
|
||||||
|
await reorderPagesCommand("normal", input);
|
||||||
|
await sendCatalogUpdate();
|
||||||
|
revalidatePath("/admin/catalog");
|
||||||
|
return { ok: true as const, data: {} };
|
||||||
|
});
|
||||||
}
|
}
|
||||||
@@ -7,6 +7,7 @@ import {
|
|||||||
actionOk,
|
actionOk,
|
||||||
handleActionError,
|
handleActionError,
|
||||||
} from "@/lib/safe-action-shared";
|
} from "@/lib/safe-action-shared";
|
||||||
|
import { withCatalogExport } from "@/lib/services/catalog-git-queue";
|
||||||
import type {
|
import type {
|
||||||
AlignResult,
|
AlignResult,
|
||||||
DedupResult,
|
DedupResult,
|
||||||
@@ -38,7 +39,9 @@ export async function fixSpriteIdsAction(): Promise<
|
|||||||
> {
|
> {
|
||||||
try {
|
try {
|
||||||
await guard();
|
await guard();
|
||||||
return actionOk(await maintenance.fixSpriteIds());
|
return await withCatalogExport(async () => {
|
||||||
|
return actionOk(await maintenance.fixSpriteIds());
|
||||||
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return handleActionError(e);
|
return handleActionError(e);
|
||||||
}
|
}
|
||||||
@@ -49,7 +52,9 @@ export async function fixCatalogOffersAction(): Promise<
|
|||||||
> {
|
> {
|
||||||
try {
|
try {
|
||||||
await guard();
|
await guard();
|
||||||
return actionOk(await maintenance.fixCatalogOffers());
|
return await withCatalogExport(async () => {
|
||||||
|
return actionOk(await maintenance.fixCatalogOffers());
|
||||||
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return handleActionError(e);
|
return handleActionError(e);
|
||||||
}
|
}
|
||||||
@@ -60,7 +65,9 @@ export async function reconcileIdsAction(): Promise<
|
|||||||
> {
|
> {
|
||||||
try {
|
try {
|
||||||
await guard();
|
await guard();
|
||||||
return actionOk(await maintenance.reconcileIds());
|
return await withCatalogExport(async () => {
|
||||||
|
return actionOk(await maintenance.reconcileIds());
|
||||||
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return handleActionError(e);
|
return handleActionError(e);
|
||||||
}
|
}
|
||||||
@@ -71,7 +78,9 @@ export async function removeDuplicateItemsBaseAction(): Promise<
|
|||||||
> {
|
> {
|
||||||
try {
|
try {
|
||||||
await guard();
|
await guard();
|
||||||
return actionOk(await maintenance.removeDuplicates());
|
return await withCatalogExport(async () => {
|
||||||
|
return actionOk(await maintenance.removeDuplicates());
|
||||||
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return handleActionError(e);
|
return handleActionError(e);
|
||||||
}
|
}
|
||||||
@@ -93,7 +102,9 @@ export async function applyAlignIdsAction(): Promise<
|
|||||||
> {
|
> {
|
||||||
try {
|
try {
|
||||||
await guard();
|
await guard();
|
||||||
return actionOk(await maintenance.forceItemsBaseIdsToFurnidata(true));
|
return await withCatalogExport(async () => {
|
||||||
|
return actionOk(await maintenance.forceItemsBaseIdsToFurnidata(true));
|
||||||
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return handleActionError(e);
|
return handleActionError(e);
|
||||||
}
|
}
|
||||||
@@ -104,7 +115,9 @@ export async function fixEverythingAction(input?: {
|
|||||||
}): Promise<ActionResult<maintenance.FixAllResult>> {
|
}): Promise<ActionResult<maintenance.FixAllResult>> {
|
||||||
try {
|
try {
|
||||||
await guard();
|
await guard();
|
||||||
return actionOk(await maintenance.fixEverything(input ?? {}));
|
return await withCatalogExport(async () => {
|
||||||
|
return actionOk(await maintenance.fixEverything(input ?? {}));
|
||||||
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return handleActionError(e);
|
return handleActionError(e);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { db, WebsiteSetting } from "@/lib/db";
|
|||||||
import { PERMS } from "@/lib/permissions";
|
import { PERMS } from "@/lib/permissions";
|
||||||
import { adminAction } from "@/lib/safe-action";
|
import { adminAction } from "@/lib/safe-action";
|
||||||
import { actionOk } from "@/lib/safe-action-shared";
|
import { actionOk } from "@/lib/safe-action-shared";
|
||||||
|
import { withCatalogExport } from "@/lib/services/catalog-git-queue";
|
||||||
import { deleteImportedItem } from "@/lib/services/furni-import";
|
import { deleteImportedItem } from "@/lib/services/furni-import";
|
||||||
import { siteSettings } from "@/lib/services/site-settings";
|
import { siteSettings } from "@/lib/services/site-settings";
|
||||||
|
|
||||||
@@ -14,10 +15,9 @@ export const deleteImportedFurni = adminAction(
|
|||||||
{ permission: PERMS.ASSETS_IMPORT, schema: deleteSchema },
|
{ permission: PERMS.ASSETS_IMPORT, schema: deleteSchema },
|
||||||
async (ctx) =>
|
async (ctx) =>
|
||||||
actionOk(
|
actionOk(
|
||||||
(await deleteImportedItem(ctx.data.classname)) as unknown as Record<
|
(await withCatalogExport(() =>
|
||||||
string,
|
deleteImportedItem(ctx.data.classname),
|
||||||
unknown
|
)) as unknown as Record<string, unknown>,
|
||||||
>,
|
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
+25
-38
@@ -3,60 +3,47 @@
|
|||||||
import fs from "node:fs/promises";
|
import fs from "node:fs/promises";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import * as JSONC from "jsonc-parser";
|
import * as JSONC from "jsonc-parser";
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { getTranslations } from "next-intl/server";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
|
import { SUPPORTED_LOCALES } from "@/i18n/locales";
|
||||||
import {
|
import {
|
||||||
CLIENT_TRANSLATION_FILES,
|
CLIENT_TRANSLATION_FILES,
|
||||||
getClientTranslationFile,
|
getClientTranslationFile,
|
||||||
} from "@/lib/client-translation-files";
|
} from "@/lib/client-translation-files";
|
||||||
|
import {
|
||||||
|
CmsTranslationError,
|
||||||
|
saveCmsTranslation,
|
||||||
|
} from "@/lib/cms-translations";
|
||||||
import { patchJson5 } from "@/lib/json5-patch";
|
import { patchJson5 } from "@/lib/json5-patch";
|
||||||
import { PERMS } from "@/lib/permissions";
|
import { PERMS } from "@/lib/permissions";
|
||||||
import { adminAction } from "@/lib/safe-action";
|
import { adminAction } from "@/lib/safe-action";
|
||||||
import { ActionError, actionOk } from "@/lib/safe-action-shared";
|
import { ActionError, actionOk } from "@/lib/safe-action-shared";
|
||||||
|
|
||||||
const saveTranslationsSchema = z.object({
|
const saveTranslationsSchema = z.object({
|
||||||
locale: z.enum([
|
locale: z.enum(SUPPORTED_LOCALES),
|
||||||
"en",
|
revision: z.string().regex(/^[a-f0-9]{64}$/),
|
||||||
"it",
|
changes: z
|
||||||
"nl",
|
.record(z.string().max(300), z.string().max(20000).nullable())
|
||||||
"de",
|
.refine((value) => Object.keys(value).length <= 5000),
|
||||||
"fr",
|
|
||||||
"es",
|
|
||||||
"pt",
|
|
||||||
"pl",
|
|
||||||
"sv",
|
|
||||||
"tr",
|
|
||||||
"ro",
|
|
||||||
"hu",
|
|
||||||
"cs",
|
|
||||||
"sk",
|
|
||||||
"da",
|
|
||||||
"no",
|
|
||||||
"el",
|
|
||||||
"bg",
|
|
||||||
"hr",
|
|
||||||
"sr",
|
|
||||||
"uk",
|
|
||||||
"ru",
|
|
||||||
]),
|
|
||||||
data: z.record(z.string(), z.unknown()),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
export const saveTranslations = adminAction(
|
export const saveTranslations = adminAction(
|
||||||
{ permission: PERMS.SETTINGS_EDIT, schema: saveTranslationsSchema },
|
{ permission: PERMS.SETTINGS_EDIT, schema: saveTranslationsSchema },
|
||||||
async (ctx) => {
|
async (ctx) => {
|
||||||
const filePath = path.join(
|
try {
|
||||||
process.cwd(),
|
const snapshot = await saveCmsTranslation(
|
||||||
"src",
|
ctx.data.locale,
|
||||||
"messages",
|
ctx.data.revision,
|
||||||
`${ctx.data.locale}.json`,
|
ctx.data.changes,
|
||||||
);
|
);
|
||||||
await fs.writeFile(
|
revalidatePath("/", "layout");
|
||||||
filePath,
|
return actionOk({ snapshot });
|
||||||
JSON.stringify(ctx.data.data, null, 2),
|
} catch (error) {
|
||||||
"utf-8",
|
if (!(error instanceof CmsTranslationError)) throw error;
|
||||||
);
|
const t = await getTranslations("pages.admin.translations.cms");
|
||||||
|
return { ok: false, error: t(error.code, { key: error.key }) };
|
||||||
return actionOk();
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { and, eq, sql } from "drizzle-orm";
|
|||||||
import { revalidatePath } from "next/cache";
|
import { revalidatePath } from "next/cache";
|
||||||
import { auth } from "@/lib/auth";
|
import { auth } from "@/lib/auth";
|
||||||
import { db, WebsiteShopVouchers, WebsiteUsedShopVouchers } from "@/lib/db";
|
import { db, WebsiteShopVouchers, WebsiteUsedShopVouchers } from "@/lib/db";
|
||||||
|
import { formatNumber } from "@/lib/format-date";
|
||||||
import { clientIp, rateLimit } from "@/lib/rate-limit";
|
import { clientIp, rateLimit } from "@/lib/rate-limit";
|
||||||
import { rcon } from "@/lib/services/rcon";
|
import { rcon } from "@/lib/services/rcon";
|
||||||
import { currencyDb, sendCurrency } from "@/lib/services/send-currency";
|
import { currencyDb, sendCurrency } from "@/lib/services/send-currency";
|
||||||
@@ -175,6 +176,6 @@ export async function redeem(
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
ok: true,
|
ok: true,
|
||||||
message: `Success! Your balance has been increased by ${voucher.amount.toLocaleString()} credits.`,
|
message: `Success! Your balance has been increased by ${formatNumber(voucher.amount)} credits.`,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -2,9 +2,10 @@
|
|||||||
|
|
||||||
import { Home, RefreshCw } from "lucide-react";
|
import { Home, RefreshCw } from "lucide-react";
|
||||||
import { useTranslations } from "next-intl";
|
import { useTranslations } from "next-intl";
|
||||||
import { useEffect } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { ErrorScreen } from "@/components/error-screen";
|
import { ErrorScreen } from "@/components/error-screen";
|
||||||
import Link from "@/components/link";
|
import Link from "@/components/link";
|
||||||
|
import { reportBrowserError } from "@/lib/browser-errors";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Site route-segment error boundary. Renders inside the site shell layout.
|
* Site route-segment error boundary. Renders inside the site shell layout.
|
||||||
@@ -19,8 +20,10 @@ export default function SiteErrorPage({
|
|||||||
}) {
|
}) {
|
||||||
const t = useTranslations("pages.error");
|
const t = useTranslations("pages.error");
|
||||||
|
|
||||||
|
const [reference, setReference] = useState(error.digest);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
console.error(error);
|
setReference(error.digest ?? reportBrowserError(error, "browser.boundary"));
|
||||||
|
if (error.digest) reportBrowserError(error, "browser.boundary");
|
||||||
}, [error]);
|
}, [error]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -46,9 +49,9 @@ export default function SiteErrorPage({
|
|||||||
</>
|
</>
|
||||||
}
|
}
|
||||||
footer={
|
footer={
|
||||||
error.digest ? (
|
reference ? (
|
||||||
<p className="error-screen-digest">
|
<p className="error-screen-digest">
|
||||||
{t("reference", { digest: error.digest })}
|
{t("reference", { digest: reference })}
|
||||||
</p>
|
</p>
|
||||||
) : null
|
) : null
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,5 @@
|
|||||||
export default function FriendsLoading() {
|
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||||
return (
|
|
||||||
<div
|
export default function Loading() {
|
||||||
style={{ display: "flex", justifyContent: "center", padding: "4rem 0" }}
|
return <LoadingSpinner />;
|
||||||
>
|
|
||||||
<div
|
|
||||||
className="animate-spin w-8 h-8 border-4 rounded-full"
|
|
||||||
style={{
|
|
||||||
borderColor: "var(--color-primary)",
|
|
||||||
borderTopColor: "transparent",
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
@@ -1,15 +1,5 @@
|
|||||||
export default function GuildForumLoading() {
|
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||||
return (
|
|
||||||
<div
|
export default function Loading() {
|
||||||
style={{ display: "flex", justifyContent: "center", padding: "4rem 0" }}
|
return <LoadingSpinner />;
|
||||||
>
|
|
||||||
<div
|
|
||||||
className="animate-spin w-8 h-8 border-4 rounded-full"
|
|
||||||
style={{
|
|
||||||
borderColor: "var(--color-primary)",
|
|
||||||
borderTopColor: "transparent",
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
@@ -1,15 +1,5 @@
|
|||||||
export default function SiteLoading() {
|
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||||
return (
|
|
||||||
<div
|
export default function Loading() {
|
||||||
style={{ display: "flex", justifyContent: "center", padding: "4rem 0" }}
|
return <LoadingSpinner />;
|
||||||
>
|
|
||||||
<div
|
|
||||||
className="animate-spin w-8 h-8 border-4 rounded-full"
|
|
||||||
style={{
|
|
||||||
borderColor: "var(--color-primary)",
|
|
||||||
borderTopColor: "transparent",
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
@@ -1,11 +1,16 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
|
|
||||||
export default function CopyReferralButton({ value }: { value: string }) {
|
export default function CopyReferralButton({ value }: { value: string }) {
|
||||||
const [copied, setCopied] = useState(false);
|
const [copied, setCopied] = useState(false);
|
||||||
|
const [failed, setFailed] = useState(false);
|
||||||
|
const t = useTranslations("pages.myDashboard");
|
||||||
|
|
||||||
async function copy() {
|
async function copy() {
|
||||||
|
setFailed(false);
|
||||||
|
setCopied(false);
|
||||||
const absolute =
|
const absolute =
|
||||||
typeof window !== "undefined" && value.startsWith("/")
|
typeof window !== "undefined" && value.startsWith("/")
|
||||||
? `${window.location.origin}${value}`
|
? `${window.location.origin}${value}`
|
||||||
@@ -20,9 +25,11 @@ export default function CopyReferralButton({ value }: { value: string }) {
|
|||||||
document.body.appendChild(ta);
|
document.body.appendChild(ta);
|
||||||
ta.select();
|
ta.select();
|
||||||
try {
|
try {
|
||||||
document.execCommand("copy");
|
if (!document.execCommand("copy")) throw new Error("copy-failed");
|
||||||
} catch {
|
} catch {
|
||||||
/* give up silently */
|
setFailed(true);
|
||||||
|
document.body.removeChild(ta);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
document.body.removeChild(ta);
|
document.body.removeChild(ta);
|
||||||
}
|
}
|
||||||
@@ -31,17 +38,21 @@ export default function CopyReferralButton({ value }: { value: string }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<button
|
<>
|
||||||
type="button"
|
<button
|
||||||
onClick={copy}
|
type="button"
|
||||||
className="rounded-xl font-bold text-sm px-5 py-2.5 transition-all duration-200 hover:scale-[1.02] active:scale-95 shrink-0"
|
onClick={copy}
|
||||||
style={{
|
className="rounded-xl font-bold text-sm px-5 py-2.5 transition-all duration-200 hover:scale-[1.02] active:scale-95 shrink-0"
|
||||||
background: "color-mix(in srgb, var(--color-primary) 12%, transparent)",
|
style={{
|
||||||
color: "var(--color-primary-readable, var(--color-primary))",
|
background:
|
||||||
border: `2px solid color-mix(in srgb, var(--color-primary) 20%, transparent)`,
|
"color-mix(in srgb, var(--color-primary) 12%, transparent)",
|
||||||
}}
|
color: "var(--color-primary-readable, var(--color-primary))",
|
||||||
>
|
border: `2px solid color-mix(in srgb, var(--color-primary) 20%, transparent)`,
|
||||||
{copied ? "Copied!" : "Copy link"}
|
}}
|
||||||
</button>
|
>
|
||||||
|
{copied ? t("copied") : t("copy")}
|
||||||
|
</button>
|
||||||
|
{failed && <p role="alert">{t("copyFailed")}</p>}
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,249 @@
|
|||||||
|
.dashboard {
|
||||||
|
display: grid;
|
||||||
|
gap: 20px;
|
||||||
|
padding-bottom: 24px;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.hero {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: 24px;
|
||||||
|
padding: 24px;
|
||||||
|
background: linear-gradient(
|
||||||
|
130deg,
|
||||||
|
color-mix(in srgb, var(--color-primary) 10%, var(--color-surface)),
|
||||||
|
var(--color-surface)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
.avatar {
|
||||||
|
flex-shrink: 0;
|
||||||
|
object-fit: contain;
|
||||||
|
image-rendering: pixelated;
|
||||||
|
border-radius: 16px;
|
||||||
|
background: color-mix(in srgb, var(--color-primary) 10%, transparent);
|
||||||
|
}
|
||||||
|
.identity {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 180px;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
.identity h1 {
|
||||||
|
font-size: clamp(1.6rem, 3vw, 2rem);
|
||||||
|
margin: 4px 0;
|
||||||
|
}
|
||||||
|
.dates {
|
||||||
|
font-size: 0.8rem;
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
margin-top: 12px;
|
||||||
|
}
|
||||||
|
.shortcuts {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
.shortcut {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 14px;
|
||||||
|
border-radius: 12px;
|
||||||
|
background: var(--color-surface);
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--color-text-readable);
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
.shortcut:hover,
|
||||||
|
.friend:hover,
|
||||||
|
.room:hover {
|
||||||
|
background: color-mix(in srgb, var(--color-primary) 8%, var(--color-surface));
|
||||||
|
}
|
||||||
|
.count {
|
||||||
|
border-radius: 999px;
|
||||||
|
padding: 2px 7px;
|
||||||
|
background: var(--color-danger);
|
||||||
|
color: white;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
}
|
||||||
|
.wallet {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
.currency {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 14px;
|
||||||
|
padding: 20px;
|
||||||
|
}
|
||||||
|
.currency > div {
|
||||||
|
display: grid;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.currency strong {
|
||||||
|
font-size: 1.3rem;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
.currency span {
|
||||||
|
font-size: 0.8rem;
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
}
|
||||||
|
.columns {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: minmax(0, 1fr) minmax(280px, 350px);
|
||||||
|
gap: 20px;
|
||||||
|
align-items: start;
|
||||||
|
}
|
||||||
|
.stack {
|
||||||
|
display: grid;
|
||||||
|
gap: 20px;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.friends,
|
||||||
|
.rooms {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(min(100%, 180px), 1fr));
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
.friend,
|
||||||
|
.room {
|
||||||
|
display: flex;
|
||||||
|
gap: 12px;
|
||||||
|
padding: 12px;
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
border-radius: 12px;
|
||||||
|
color: var(--color-text-readable);
|
||||||
|
text-decoration: none;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.friend > div,
|
||||||
|
.room {
|
||||||
|
display: grid;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.friend strong,
|
||||||
|
.friend span,
|
||||||
|
.room strong {
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.friend span,
|
||||||
|
.room span {
|
||||||
|
font-size: 0.8rem;
|
||||||
|
}
|
||||||
|
.stats {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
gap: 20px;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
.stats dt {
|
||||||
|
font-size: 0.8rem;
|
||||||
|
}
|
||||||
|
.stats dd {
|
||||||
|
margin: 4px 0 0;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
.feedback {
|
||||||
|
margin: 0;
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
border-left: 4px solid var(--color-primary);
|
||||||
|
border-radius: 12px;
|
||||||
|
background: var(--color-surface);
|
||||||
|
padding: 16px;
|
||||||
|
}
|
||||||
|
.progressLabel {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
margin-top: 16px;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
}
|
||||||
|
.progress {
|
||||||
|
width: 100%;
|
||||||
|
height: 10px;
|
||||||
|
accent-color: var(--color-primary);
|
||||||
|
}
|
||||||
|
.reward {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
}
|
||||||
|
.referralInput {
|
||||||
|
width: 100%;
|
||||||
|
min-width: 0;
|
||||||
|
margin: 8px 0;
|
||||||
|
}
|
||||||
|
.claim {
|
||||||
|
margin-top: 16px;
|
||||||
|
}
|
||||||
|
.claim button {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
.rules {
|
||||||
|
border-top: 1px solid var(--color-border);
|
||||||
|
margin-top: 16px;
|
||||||
|
padding-top: 12px;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
}
|
||||||
|
.rules summary {
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.badges {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
.badges img {
|
||||||
|
object-fit: contain;
|
||||||
|
image-rendering: pixelated;
|
||||||
|
}
|
||||||
|
@media (max-width: 760px) {
|
||||||
|
.columns {
|
||||||
|
grid-template-columns: minmax(0, 1fr);
|
||||||
|
}
|
||||||
|
.shortcuts {
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
}
|
||||||
|
.hero {
|
||||||
|
padding: 18px;
|
||||||
|
gap: 16px;
|
||||||
|
}
|
||||||
|
.hero > a {
|
||||||
|
width: 100%;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
.currency {
|
||||||
|
padding: 12px;
|
||||||
|
gap: 8px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
.currency strong {
|
||||||
|
font-size: 1rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.progress {
|
||||||
|
appearance: none;
|
||||||
|
border: 0;
|
||||||
|
border-radius: 999px;
|
||||||
|
overflow: hidden;
|
||||||
|
background: var(--color-border);
|
||||||
|
}
|
||||||
|
.progress::-webkit-progress-bar {
|
||||||
|
background: var(--color-border);
|
||||||
|
border-radius: 999px;
|
||||||
|
}
|
||||||
|
.progress::-webkit-progress-value {
|
||||||
|
background: var(--color-primary);
|
||||||
|
border-radius: 999px;
|
||||||
|
}
|
||||||
|
.progress::-moz-progress-bar {
|
||||||
|
background: var(--color-primary);
|
||||||
|
border-radius: 999px;
|
||||||
|
}
|
||||||
+301
-677
File diff suppressed because it is too large.
Load diff
@@ -1,15 +1,5 @@
|
|||||||
export default function MessagesLoading() {
|
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||||
return (
|
|
||||||
<div
|
export default function Loading() {
|
||||||
style={{ display: "flex", justifyContent: "center", padding: "4rem 0" }}
|
return <LoadingSpinner />;
|
||||||
>
|
|
||||||
<div
|
|
||||||
className="animate-spin w-8 h-8 border-4 rounded-full"
|
|
||||||
style={{
|
|
||||||
borderColor: "var(--color-primary)",
|
|
||||||
borderTopColor: "transparent",
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
@@ -8,8 +8,8 @@ import { toggleReaction } from "@/actions/article-reactions";
|
|||||||
import Link from "@/components/link";
|
import Link from "@/components/link";
|
||||||
import { ContentCard, EmptyState } from "@/components/public/ui";
|
import { ContentCard, EmptyState } from "@/components/public/ui";
|
||||||
import { SanitizedHtml } from "@/components/shared/sanitized-html";
|
import { SanitizedHtml } from "@/components/shared/sanitized-html";
|
||||||
|
import { articleSlug } from "@/lib/article-input";
|
||||||
import { auth } from "@/lib/auth";
|
import { auth } from "@/lib/auth";
|
||||||
import { cachedQuery } from "@/lib/cached-db";
|
|
||||||
import {
|
import {
|
||||||
db,
|
db,
|
||||||
User,
|
User,
|
||||||
@@ -20,6 +20,7 @@ import {
|
|||||||
import { excerpt } from "@/lib/format";
|
import { excerpt } from "@/lib/format";
|
||||||
import { formatDate } from "@/lib/format-date";
|
import { formatDate } from "@/lib/format-date";
|
||||||
import { sanitize } from "@/lib/sanitize";
|
import { sanitize } from "@/lib/sanitize";
|
||||||
|
import { cacheNews } from "@/lib/services/news-cache";
|
||||||
|
|
||||||
type SearchParams = Promise<{
|
type SearchParams = Promise<{
|
||||||
comment?: string;
|
comment?: string;
|
||||||
@@ -46,10 +47,10 @@ function feedbackStyle(tone: "success" | "error"): CSSProperties {
|
|||||||
export async function generateMetadata({
|
export async function generateMetadata({
|
||||||
params,
|
params,
|
||||||
}: {
|
}: {
|
||||||
params: Promise<{ slug: string }>;
|
params: Promise<{ slug: string[] }>;
|
||||||
}): Promise<Metadata> {
|
}): Promise<Metadata> {
|
||||||
const appUrl = process.env.APP_URL ?? "http://localhost:3000";
|
const appUrl = process.env.APP_URL ?? "http://localhost:3000";
|
||||||
const { slug } = await params;
|
const slug = articleSlug((await params).slug);
|
||||||
const [article] = await db
|
const [article] = await db
|
||||||
.select({
|
.select({
|
||||||
title: WebsiteArticles.title,
|
title: WebsiteArticles.title,
|
||||||
@@ -95,44 +96,40 @@ export default async function ArticlePage({
|
|||||||
params,
|
params,
|
||||||
searchParams,
|
searchParams,
|
||||||
}: {
|
}: {
|
||||||
params: Promise<{ slug: string }>;
|
params: Promise<{ slug: string[] }>;
|
||||||
searchParams: SearchParams;
|
searchParams: SearchParams;
|
||||||
}) {
|
}) {
|
||||||
const { slug } = await params;
|
const slug = articleSlug((await params).slug);
|
||||||
const { comment, reaction, error } = await searchParams;
|
const { comment, reaction, error } = await searchParams;
|
||||||
const t = await getTranslations("pages.article");
|
const t = await getTranslations("pages.article");
|
||||||
|
|
||||||
const article = await cachedQuery(
|
const article = await cacheNews(`article:slug:${slug}`, 60_000, async () => {
|
||||||
`article:slug:${slug}`,
|
const [row] = await db
|
||||||
async () => {
|
.select({
|
||||||
const [row] = await db
|
id: WebsiteArticles.id,
|
||||||
.select({
|
slug: WebsiteArticles.slug,
|
||||||
id: WebsiteArticles.id,
|
title: WebsiteArticles.title,
|
||||||
slug: WebsiteArticles.slug,
|
shortStory: WebsiteArticles.shortStory,
|
||||||
title: WebsiteArticles.title,
|
fullStory: WebsiteArticles.fullStory,
|
||||||
shortStory: WebsiteArticles.shortStory,
|
image: WebsiteArticles.image,
|
||||||
fullStory: WebsiteArticles.fullStory,
|
createdAt: WebsiteArticles.createdAt,
|
||||||
image: WebsiteArticles.image,
|
updatedAt: WebsiteArticles.updatedAt,
|
||||||
createdAt: WebsiteArticles.createdAt,
|
})
|
||||||
updatedAt: WebsiteArticles.updatedAt,
|
.from(WebsiteArticles)
|
||||||
})
|
.where(
|
||||||
.from(WebsiteArticles)
|
and(
|
||||||
.where(
|
eq(WebsiteArticles.slug, slug),
|
||||||
and(
|
eq(WebsiteArticles.status, "published"),
|
||||||
eq(WebsiteArticles.slug, slug),
|
or(
|
||||||
eq(WebsiteArticles.status, "published"),
|
sql`${WebsiteArticles.publishAt} IS NULL`,
|
||||||
or(
|
sql`${WebsiteArticles.publishAt} <= NOW()`,
|
||||||
sql`${WebsiteArticles.publishAt} IS NULL`,
|
|
||||||
sql`${WebsiteArticles.publishAt} <= NOW()`,
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
)
|
),
|
||||||
.limit(1)
|
)
|
||||||
.catch(() => []);
|
.limit(1)
|
||||||
return row ?? null;
|
.catch(() => []);
|
||||||
},
|
return row ?? null;
|
||||||
60,
|
});
|
||||||
);
|
|
||||||
if (!article) notFound();
|
if (!article) notFound();
|
||||||
|
|
||||||
const articleId = article.id;
|
const articleId = article.id;
|
||||||
|
|||||||
@@ -1,15 +1,5 @@
|
|||||||
export default function NewsLoading() {
|
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||||
return (
|
|
||||||
<div
|
export default function Loading() {
|
||||||
style={{ display: "flex", justifyContent: "center", padding: "4rem 0" }}
|
return <LoadingSpinner />;
|
||||||
>
|
|
||||||
<div
|
|
||||||
className="animate-spin w-8 h-8 border-4 rounded-full"
|
|
||||||
style={{
|
|
||||||
borderColor: "var(--color-primary)",
|
|
||||||
borderTopColor: "transparent",
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
@@ -1,15 +1,5 @@
|
|||||||
export default function ShopLoading() {
|
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||||
return (
|
|
||||||
<div
|
export default function Loading() {
|
||||||
style={{ display: "flex", justifyContent: "center", padding: "4rem 0" }}
|
return <LoadingSpinner />;
|
||||||
>
|
|
||||||
<div
|
|
||||||
className="animate-spin w-8 h-8 border-4 rounded-full"
|
|
||||||
style={{
|
|
||||||
borderColor: "var(--color-primary)",
|
|
||||||
borderTopColor: "transparent",
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
@@ -2,9 +2,12 @@ import { asc, desc, eq, gte } from "drizzle-orm";
|
|||||||
import type { Metadata } from "next";
|
import type { Metadata } from "next";
|
||||||
import { getTranslations } from "next-intl/server";
|
import { getTranslations } from "next-intl/server";
|
||||||
import Link from "@/components/link";
|
import Link from "@/components/link";
|
||||||
import { ContentCard, EmptyState } from "@/components/public/ui";
|
import { ProfileImage } from "@/components/shared/profile-image";
|
||||||
|
import { SurfaceCard } from "@/components/surface-card";
|
||||||
import { db, User, WebsiteTeams } from "@/lib/db";
|
import { db, User, WebsiteTeams } from "@/lib/db";
|
||||||
|
import { avatarImageUrl } from "@/lib/format";
|
||||||
import { siteSettings } from "@/lib/services/site-settings";
|
import { siteSettings } from "@/lib/services/site-settings";
|
||||||
|
import styles from "./staff.module.css";
|
||||||
|
|
||||||
export async function generateMetadata(): Promise<Metadata> {
|
export async function generateMetadata(): Promise<Metadata> {
|
||||||
const t = await getTranslations("pages.staff");
|
const t = await getTranslations("pages.staff");
|
||||||
@@ -52,7 +55,7 @@ export default async function StaffPage() {
|
|||||||
.where(gte(User.rank, minStaffRank))
|
.where(gte(User.rank, minStaffRank))
|
||||||
.orderBy(desc(User.rank), asc(User.username))
|
.orderBy(desc(User.rank), asc(User.username))
|
||||||
.limit(100)
|
.limit(100)
|
||||||
.catch((): StaffMember[] => []),
|
.catch((): StaffMember[] | null => null),
|
||||||
db
|
db
|
||||||
.select({
|
.select({
|
||||||
id: WebsiteTeams.id,
|
id: WebsiteTeams.id,
|
||||||
@@ -69,71 +72,92 @@ export default async function StaffPage() {
|
|||||||
]);
|
]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<main className={styles.page}>
|
||||||
<ContentCard icon="🛡️" title={t("title")} subtitle={t("subtitle")} />
|
<SurfaceCard className={styles.hero}>
|
||||||
|
<div>
|
||||||
{teams.length > 0 ? (
|
<h1>{t("title")}</h1>
|
||||||
<ContentCard
|
<p>{t("subtitle")}</p>
|
||||||
icon="⭐"
|
</div>
|
||||||
title={t("ranksTitle")}
|
{staff && staff.length > 0 && (
|
||||||
subtitle={t("ranksSubtitle")}
|
<span className={styles.count}>
|
||||||
>
|
{t("membersSubtitle", { count: staff.length })}
|
||||||
<div className="card-grid sm-2 lg-3">
|
</span>
|
||||||
{teams.map((team) => (
|
|
||||||
<div key={team.id} className="card">
|
|
||||||
<h3 style={{ margin: "0 0 0.25rem", color: team.staffColor }}>
|
|
||||||
{team.rankName}
|
|
||||||
</h3>
|
|
||||||
{team.jobDescription ? (
|
|
||||||
<p className="muted" style={{ margin: 0 }}>
|
|
||||||
{team.jobDescription}
|
|
||||||
</p>
|
|
||||||
) : null}
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</ContentCard>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
<ContentCard
|
|
||||||
icon="👥"
|
|
||||||
title={t("membersTitle")}
|
|
||||||
subtitle={
|
|
||||||
staff.length === 0
|
|
||||||
? t("membersEmptySubtitle")
|
|
||||||
: t("membersSubtitle", { count: staff.length })
|
|
||||||
}
|
|
||||||
padded={staff.length === 0}
|
|
||||||
>
|
|
||||||
{staff.length === 0 ? (
|
|
||||||
<EmptyState icon="🛡️">{t("emptyState")}</EmptyState>
|
|
||||||
) : (
|
|
||||||
<div className="table-scroll">
|
|
||||||
<table>
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th>{t("colUsername")}</th>
|
|
||||||
<th>{t("colRank")}</th>
|
|
||||||
<th>{t("colMotto")}</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
{staff.map((u) => (
|
|
||||||
<tr key={u.username}>
|
|
||||||
<td>
|
|
||||||
<Link href={`/u/${u.username}`}>{u.username}</Link>
|
|
||||||
</td>
|
|
||||||
<td>{u.rank}</td>
|
|
||||||
<td className="muted table-cell-truncate">
|
|
||||||
{u.motto || "—"}
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
))}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
)}
|
)}
|
||||||
</ContentCard>
|
</SurfaceCard>
|
||||||
|
<section aria-labelledby="staff-members">
|
||||||
|
<h2 id="staff-members" className={styles.heading}>
|
||||||
|
{t("membersTitle")}
|
||||||
|
</h2>
|
||||||
|
{staff === null ? (
|
||||||
|
<SurfaceCard className={styles.notice}>
|
||||||
|
<p role="alert">{t("loadError")}</p>
|
||||||
|
<Link href="/staff" className="btn btn-outline">
|
||||||
|
{t("retry")}
|
||||||
|
</Link>
|
||||||
|
</SurfaceCard>
|
||||||
|
) : staff.length === 0 ? (
|
||||||
|
<SurfaceCard className={styles.notice}>
|
||||||
|
<p>{t("emptyState")}</p>
|
||||||
|
</SurfaceCard>
|
||||||
|
) : (
|
||||||
|
<ul className={styles.grid}>
|
||||||
|
{staff.map((member) => (
|
||||||
|
<li key={member.username}>
|
||||||
|
<Link
|
||||||
|
href={`/u/${encodeURIComponent(member.username)}`}
|
||||||
|
className={styles.member}
|
||||||
|
>
|
||||||
|
<ProfileImage
|
||||||
|
src={avatarImageUrl(member.look, {
|
||||||
|
size: "m",
|
||||||
|
direction: 2,
|
||||||
|
headDirection: 3,
|
||||||
|
})}
|
||||||
|
alt={member.username}
|
||||||
|
width={64}
|
||||||
|
height={110}
|
||||||
|
className={styles.avatar}
|
||||||
|
/>
|
||||||
|
<div className={styles.identity}>
|
||||||
|
<h3>{member.username}</h3>
|
||||||
|
<p>{member.motto || t("noMotto")}</p>
|
||||||
|
<span className={styles.profile}>
|
||||||
|
{t("viewProfile")} <span aria-hidden="true">→</span>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</Link>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
{teams.length > 0 && (
|
||||||
|
<section aria-labelledby="staff-teams">
|
||||||
|
<h2 id="staff-teams" className={styles.heading}>
|
||||||
|
{t("ranksTitle")}
|
||||||
|
</h2>
|
||||||
|
<p className={styles.subtitle}>{t("ranksSubtitle")}</p>
|
||||||
|
<ul className={styles.grid}>
|
||||||
|
{teams.map((team) => (
|
||||||
|
<li key={team.id}>
|
||||||
|
<SurfaceCard className={styles.team}>
|
||||||
|
<span
|
||||||
|
className={styles.accent}
|
||||||
|
style={{
|
||||||
|
backgroundColor: /^#[0-9a-f]{6}$/i.test(team.staffColor)
|
||||||
|
? team.staffColor
|
||||||
|
: "var(--color-primary)",
|
||||||
|
}}
|
||||||
|
aria-hidden="true"
|
||||||
|
/>
|
||||||
|
<h3>{team.rankName}</h3>
|
||||||
|
{team.jobDescription && <p>{team.jobDescription}</p>}
|
||||||
|
</SurfaceCard>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
</main>
|
</main>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
.page {
|
||||||
|
display: grid;
|
||||||
|
gap: 28px;
|
||||||
|
min-width: 0;
|
||||||
|
padding-bottom: 24px;
|
||||||
|
}
|
||||||
|
.hero {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 20px;
|
||||||
|
padding: 28px;
|
||||||
|
background: linear-gradient(
|
||||||
|
130deg,
|
||||||
|
color-mix(in srgb, var(--color-primary) 10%, var(--color-surface)),
|
||||||
|
var(--color-surface)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
.hero h1 {
|
||||||
|
margin: 0 0 6px;
|
||||||
|
font-size: clamp(1.6rem, 3vw, 2rem);
|
||||||
|
}
|
||||||
|
.hero p,
|
||||||
|
.subtitle {
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
.count {
|
||||||
|
font-size: 0.85rem;
|
||||||
|
padding: 10px 14px;
|
||||||
|
border-radius: 12px;
|
||||||
|
background: var(--color-surface);
|
||||||
|
color: var(--color-text-readable);
|
||||||
|
}
|
||||||
|
.heading {
|
||||||
|
font-size: 1.15rem;
|
||||||
|
margin: 0 0 14px;
|
||||||
|
}
|
||||||
|
.subtitle {
|
||||||
|
margin: -6px 0 18px;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
.grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||||
|
gap: 16px;
|
||||||
|
list-style: none;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
.grid li {
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.member {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 18px;
|
||||||
|
height: 100%;
|
||||||
|
padding: 20px;
|
||||||
|
background: var(--color-surface);
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
border-radius: 16px;
|
||||||
|
color: var(--color-text-readable);
|
||||||
|
text-decoration: none;
|
||||||
|
transition:
|
||||||
|
border-color 0.15s,
|
||||||
|
box-shadow 0.15s;
|
||||||
|
}
|
||||||
|
.member:hover {
|
||||||
|
border-color: var(--color-primary);
|
||||||
|
box-shadow: 0 4px 16px
|
||||||
|
color-mix(in srgb, var(--color-primary) 10%, transparent);
|
||||||
|
}
|
||||||
|
.member:focus-visible {
|
||||||
|
outline: 3px solid var(--color-primary);
|
||||||
|
outline-offset: 4px;
|
||||||
|
}
|
||||||
|
.avatar {
|
||||||
|
flex-shrink: 0;
|
||||||
|
image-rendering: pixelated;
|
||||||
|
object-fit: contain;
|
||||||
|
border-radius: 12px;
|
||||||
|
background: color-mix(in srgb, var(--color-primary) 8%, transparent);
|
||||||
|
}
|
||||||
|
.identity {
|
||||||
|
min-width: 0;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
.identity h3,
|
||||||
|
.team h3 {
|
||||||
|
margin: 0 0 8px;
|
||||||
|
font-size: 1.05rem;
|
||||||
|
}
|
||||||
|
.identity p,
|
||||||
|
.team p {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
white-space: pre-line;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
.profile {
|
||||||
|
display: inline-block;
|
||||||
|
margin-top: 16px;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
.team {
|
||||||
|
position: relative;
|
||||||
|
height: 100%;
|
||||||
|
padding: 22px;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
.accent {
|
||||||
|
display: block;
|
||||||
|
width: 32px;
|
||||||
|
height: 4px;
|
||||||
|
border-radius: 4px;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
.notice {
|
||||||
|
padding: 24px;
|
||||||
|
}
|
||||||
|
.notice p {
|
||||||
|
margin: 0 0 12px;
|
||||||
|
}
|
||||||
|
@media (max-width: 1000px) {
|
||||||
|
.grid {
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@media (max-width: 600px) {
|
||||||
|
.grid {
|
||||||
|
grid-template-columns: minmax(0, 1fr);
|
||||||
|
}
|
||||||
|
.hero {
|
||||||
|
padding: 22px;
|
||||||
|
}
|
||||||
|
.member {
|
||||||
|
padding: 18px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
.member {
|
||||||
|
transition: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,12 +6,9 @@ import type { CSSProperties } from "react";
|
|||||||
import { postGuestbook } from "@/actions/guestbook";
|
import { postGuestbook } from "@/actions/guestbook";
|
||||||
import { sendFriendRequest } from "@/actions/social";
|
import { sendFriendRequest } from "@/actions/social";
|
||||||
import Link from "@/components/link";
|
import Link from "@/components/link";
|
||||||
import {
|
import { ContentCard, EmptyState, OnlineBadge } from "@/components/public/ui";
|
||||||
ContentCard,
|
import { CurrencyIcon } from "@/components/shared/currency-icon";
|
||||||
EmptyState,
|
import { ProfileImage } from "@/components/shared/profile-image";
|
||||||
OnlineBadge,
|
|
||||||
StatBlock,
|
|
||||||
} from "@/components/public/ui";
|
|
||||||
import { UserAvatarThumbnail } from "@/components/shared/user-avatar-thumbnail";
|
import { UserAvatarThumbnail } from "@/components/shared/user-avatar-thumbnail";
|
||||||
import { auth } from "@/lib/auth";
|
import { auth } from "@/lib/auth";
|
||||||
import {
|
import {
|
||||||
@@ -23,10 +20,12 @@ import {
|
|||||||
User,
|
User,
|
||||||
UsersBadges,
|
UsersBadges,
|
||||||
UsersCurrency,
|
UsersCurrency,
|
||||||
|
WebsiteBadges,
|
||||||
WebsiteUserGuestbooks,
|
WebsiteUserGuestbooks,
|
||||||
} from "@/lib/db";
|
} from "@/lib/db";
|
||||||
import { avatarImageUrl } from "@/lib/format";
|
import { avatarImageUrl } from "@/lib/format";
|
||||||
import { formatDate } from "@/lib/format-date";
|
import { formatDate } from "@/lib/format-date";
|
||||||
|
import styles from "./profile.module.css";
|
||||||
|
|
||||||
type SearchParams = Promise<{
|
type SearchParams = Promise<{
|
||||||
friend?: string;
|
friend?: string;
|
||||||
@@ -94,7 +93,6 @@ export default async function ProfilePage({
|
|||||||
username: User.username,
|
username: User.username,
|
||||||
motto: User.motto,
|
motto: User.motto,
|
||||||
look: User.look,
|
look: User.look,
|
||||||
rank: User.rank,
|
|
||||||
credits: User.credits,
|
credits: User.credits,
|
||||||
online: User.online,
|
online: User.online,
|
||||||
accountCreated: User.accountCreated,
|
accountCreated: User.accountCreated,
|
||||||
@@ -261,32 +259,26 @@ export default async function ProfilePage({
|
|||||||
const wallet = [
|
const wallet = [
|
||||||
{
|
{
|
||||||
key: "credits",
|
key: "credits",
|
||||||
icon: "💰",
|
|
||||||
label: t("statCredits"),
|
label: t("statCredits"),
|
||||||
value: user.credits,
|
value: user.credits,
|
||||||
color: "var(--color-primary-readable, var(--color-primary))",
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: "duckets",
|
key: "duckets",
|
||||||
icon: "🪙",
|
|
||||||
label: t("statDuckets"),
|
label: t("statDuckets"),
|
||||||
value: ducketsAmount,
|
value: ducketsAmount,
|
||||||
color: "var(--color-accent-readable, var(--color-accent))",
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: "diamonds",
|
key: "diamonds",
|
||||||
icon: "💎",
|
|
||||||
label: t("statDiamonds"),
|
label: t("statDiamonds"),
|
||||||
value: diamondsAmount,
|
value: diamondsAmount,
|
||||||
color: "var(--color-text-readable, var(--color-text))",
|
|
||||||
},
|
},
|
||||||
];
|
] as const;
|
||||||
|
|
||||||
// Resolve friend usernames/looks and the guestbook author usernames/looks in
|
// Resolve friend usernames/looks and the guestbook author usernames/looks in
|
||||||
// two parallel queries (the ids come from the queries above).
|
// parallel queries (the ids come from the queries above).
|
||||||
const friendIds = Array.from(new Set(friendships.map((f) => f.userTwoId)));
|
const friendIds = Array.from(new Set(friendships.map((f) => f.userTwoId)));
|
||||||
const authorIds = Array.from(new Set(guestbook.map((g) => g.userId)));
|
const authorIds = Array.from(new Set(guestbook.map((g) => g.userId)));
|
||||||
const [friendUsers, authors] = await Promise.all([
|
const [friendUsers, authors, badgeDetails] = await Promise.all([
|
||||||
friendIds.length
|
friendIds.length
|
||||||
? db
|
? db
|
||||||
.select({
|
.select({
|
||||||
@@ -309,15 +301,28 @@ export default async function ProfilePage({
|
|||||||
.where(inArray(User.id, authorIds))
|
.where(inArray(User.id, authorIds))
|
||||||
.catch(() => [])
|
.catch(() => [])
|
||||||
: [],
|
: [],
|
||||||
|
badges.length
|
||||||
|
? db
|
||||||
|
.select()
|
||||||
|
.from(WebsiteBadges)
|
||||||
|
.where(
|
||||||
|
inArray(
|
||||||
|
WebsiteBadges.badgeKey,
|
||||||
|
badges.map((b) => b.badgeCode),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.catch(() => [])
|
||||||
|
: [],
|
||||||
]);
|
]);
|
||||||
const friendById = new Map(friendUsers.map((f) => [f.id, f]));
|
const friendById = new Map(friendUsers.map((f) => [f.id, f]));
|
||||||
const friends = friendships
|
const friends = friendships
|
||||||
.map((f) => friendById.get(f.userTwoId))
|
.map((f) => friendById.get(f.userTwoId))
|
||||||
.filter((f): f is NonNullable<typeof f> => Boolean(f));
|
.filter((f): f is NonNullable<typeof f> => Boolean(f));
|
||||||
const authorById = new Map(authors.map((a) => [a.id, a]));
|
const authorById = new Map(authors.map((a) => [a.id, a]));
|
||||||
|
const badgeByCode = new Map(badgeDetails.map((b) => [b.badgeKey, b]));
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="page-grid">
|
<main className={`page-grid ${styles.profile}`}>
|
||||||
{friend === "sent" ? (
|
{friend === "sent" ? (
|
||||||
<div role="status" style={feedbackStyle("success")}>
|
<div role="status" style={feedbackStyle("success")}>
|
||||||
{t("success.sent")}
|
{t("success.sent")}
|
||||||
@@ -335,7 +340,7 @@ export default async function ProfilePage({
|
|||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{/* ── Profile header ──────────────────── */}
|
{/* ── Profile header ──────────────────── */}
|
||||||
<ContentCard padded={false}>
|
<ContentCard padded={false} className={styles.hero}>
|
||||||
<div
|
<div
|
||||||
className="content-card-body"
|
className="content-card-body"
|
||||||
style={{
|
style={{
|
||||||
@@ -346,18 +351,24 @@ export default async function ProfilePage({
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||||
<img
|
<ProfileImage
|
||||||
src={avatar}
|
src={avatar}
|
||||||
alt={`${user.username} avatar`}
|
alt={user.username}
|
||||||
width={100}
|
width={100}
|
||||||
height={150}
|
height={150}
|
||||||
|
className={styles.avatar}
|
||||||
/>
|
/>
|
||||||
<div style={{ minWidth: 0, flex: 1 }}>
|
<div className={styles.identity}>
|
||||||
<h1 style={{ margin: "0 0 0.25rem" }}>{user.username}</h1>
|
<h1 style={{ margin: "0 0 0.25rem" }}>{user.username}</h1>
|
||||||
<p style={{ margin: "0 0 0.6rem" }}>
|
<p style={{ margin: "0 0 0.6rem" }}>
|
||||||
{user.motto || <span className="muted">{t("noMotto")}</span>}
|
{user.motto || <span className="muted">{t("noMotto")}</span>}
|
||||||
</p>
|
</p>
|
||||||
<OnlineBadge online={user.online === "1"} />
|
<div className={styles.meta}>
|
||||||
|
<OnlineBadge online={user.online === "1"} />
|
||||||
|
<span>
|
||||||
|
{t("statRegistered")}: {registered}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{isLoggedIn && !isSelf ? (
|
{isLoggedIn && !isSelf ? (
|
||||||
<div style={{ display: "flex", gap: "0.5rem", flexWrap: "wrap" }}>
|
<div style={{ display: "flex", gap: "0.5rem", flexWrap: "wrap" }}>
|
||||||
@@ -385,330 +396,291 @@ export default async function ProfilePage({
|
|||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
<div className="stat-grid" style={{ padding: "0 1.1rem 1.1rem" }}>
|
|
||||||
<StatBlock icon="🏅" value={user.rank} label={t("statRank")} />
|
|
||||||
<StatBlock
|
|
||||||
icon="💰"
|
|
||||||
value={user.credits.toLocaleString()}
|
|
||||||
label={t("statCredits")}
|
|
||||||
/>
|
|
||||||
<StatBlock icon="📅" value={registered} label={t("statRegistered")} />
|
|
||||||
</div>
|
|
||||||
</ContentCard>
|
</ContentCard>
|
||||||
|
|
||||||
{/* ── Wallet / currencies ─────────────── */}
|
<div className={styles.columns}>
|
||||||
<ContentCard icon="💰" title={t("walletTitle")}>
|
<aside className={styles.sidebar}>
|
||||||
<div
|
{/* Wallet */}
|
||||||
style={{
|
<ContentCard title={t("walletTitle")}>
|
||||||
display: "grid",
|
<div className={styles.wallet}>
|
||||||
gridTemplateColumns: "repeat(auto-fit, minmax(150px, 1fr))",
|
{wallet.map((w) => (
|
||||||
gap: "0.75rem",
|
<div key={w.key} className={styles.currency}>
|
||||||
}}
|
<CurrencyIcon kind={w.key} size={28} alt="" />
|
||||||
>
|
<div>
|
||||||
{wallet.map((w) => (
|
<strong>{w.value.toLocaleString()}</strong>
|
||||||
<div
|
<span className="muted">{w.label}</span>
|
||||||
key={w.key}
|
|
||||||
className="card"
|
|
||||||
style={{
|
|
||||||
display: "flex",
|
|
||||||
alignItems: "center",
|
|
||||||
gap: "0.75rem",
|
|
||||||
borderLeft: `4px solid ${w.color}`,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<span
|
|
||||||
aria-hidden
|
|
||||||
style={{
|
|
||||||
fontSize: "1.6rem",
|
|
||||||
lineHeight: 1,
|
|
||||||
display: "flex",
|
|
||||||
width: "2.4rem",
|
|
||||||
height: "2.4rem",
|
|
||||||
alignItems: "center",
|
|
||||||
justifyContent: "center",
|
|
||||||
borderRadius: "10px",
|
|
||||||
background: `color-mix(in srgb, ${w.color} 16%, transparent)`,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{w.icon}
|
|
||||||
</span>
|
|
||||||
<div style={{ minWidth: 0 }}>
|
|
||||||
<div
|
|
||||||
style={{
|
|
||||||
fontSize: "1.35rem",
|
|
||||||
fontWeight: 700,
|
|
||||||
color: w.color,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{w.value.toLocaleString()}
|
|
||||||
</div>
|
|
||||||
<div className="muted" style={{ fontSize: "0.85rem" }}>
|
|
||||||
{w.label}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</ContentCard>
|
|
||||||
|
|
||||||
{/* ── Friends ──────────────────────── */}
|
|
||||||
<ContentCard
|
|
||||||
icon="👥"
|
|
||||||
title={t("friendsTitle")}
|
|
||||||
subtitle={t("friendsSubtitle", { count: friends.length })}
|
|
||||||
padded={friends.length === 0}
|
|
||||||
>
|
|
||||||
{friends.length === 0 ? (
|
|
||||||
<EmptyState icon="👥">{t("friendsEmpty")}</EmptyState>
|
|
||||||
) : (
|
|
||||||
<div
|
|
||||||
style={{
|
|
||||||
display: "grid",
|
|
||||||
gridTemplateColumns: "repeat(auto-fill, minmax(72px, 1fr))",
|
|
||||||
gap: "0.75rem",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{friends.map((f) => (
|
|
||||||
<Link
|
|
||||||
key={f.id}
|
|
||||||
href={`/u/${encodeURIComponent(f.username)}`}
|
|
||||||
className="card"
|
|
||||||
title={f.username}
|
|
||||||
style={{
|
|
||||||
display: "flex",
|
|
||||||
flexDirection: "column",
|
|
||||||
alignItems: "center",
|
|
||||||
gap: "0.35rem",
|
|
||||||
padding: "0.6rem 0.4rem",
|
|
||||||
textAlign: "center",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<UserAvatarThumbnail figure={f.look} alt={f.username} />
|
|
||||||
<span
|
|
||||||
style={{
|
|
||||||
fontSize: "0.8rem",
|
|
||||||
fontWeight: 600,
|
|
||||||
maxWidth: "100%",
|
|
||||||
overflow: "hidden",
|
|
||||||
textOverflow: "ellipsis",
|
|
||||||
whiteSpace: "nowrap",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{f.username}
|
|
||||||
</span>
|
|
||||||
</Link>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</ContentCard>
|
|
||||||
|
|
||||||
{/* ── Rooms ────────────────────────── */}
|
|
||||||
<ContentCard
|
|
||||||
icon="🏠"
|
|
||||||
title={t("roomsTitle")}
|
|
||||||
subtitle={t("roomsSubtitle", { username: user.username })}
|
|
||||||
padded={rooms.length === 0}
|
|
||||||
>
|
|
||||||
{rooms.length === 0 ? (
|
|
||||||
<EmptyState icon="🏠">{t("roomsEmpty")}</EmptyState>
|
|
||||||
) : (
|
|
||||||
<div className="card-grid sm-2 lg-3" style={{ padding: "1rem" }}>
|
|
||||||
{rooms.map((r) => (
|
|
||||||
<div
|
|
||||||
key={r.id}
|
|
||||||
className="card"
|
|
||||||
style={{
|
|
||||||
display: "flex",
|
|
||||||
flexDirection: "column",
|
|
||||||
gap: "0.4rem",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<div
|
|
||||||
style={{
|
|
||||||
display: "flex",
|
|
||||||
alignItems: "center",
|
|
||||||
gap: "0.5rem",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<span aria-hidden style={{ fontSize: "1.2rem" }}>
|
|
||||||
{"🏠"}
|
|
||||||
</span>
|
|
||||||
<strong
|
|
||||||
style={{
|
|
||||||
minWidth: 0,
|
|
||||||
overflow: "hidden",
|
|
||||||
textOverflow: "ellipsis",
|
|
||||||
whiteSpace: "nowrap",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{r.name || t("roomUntitled")}
|
|
||||||
</strong>
|
|
||||||
</div>
|
|
||||||
<div
|
|
||||||
className="muted"
|
|
||||||
style={{
|
|
||||||
display: "flex",
|
|
||||||
justifyContent: "space-between",
|
|
||||||
fontSize: "0.85rem",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<span>
|
|
||||||
{"👤"} {r.users}/{r.usersMax}
|
|
||||||
</span>
|
|
||||||
<span style={{ textTransform: "capitalize" }}>{r.state}</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</ContentCard>
|
|
||||||
|
|
||||||
{/* ── Badges ────────────────────── */}
|
|
||||||
<ContentCard
|
|
||||||
icon="🏅"
|
|
||||||
title={t("badgesTitle")}
|
|
||||||
padded={badges.length === 0}
|
|
||||||
>
|
|
||||||
{badges.length === 0 ? (
|
|
||||||
<EmptyState icon="🏅">{t("badgesEmpty")}</EmptyState>
|
|
||||||
) : (
|
|
||||||
<div
|
|
||||||
style={{
|
|
||||||
display: "flex",
|
|
||||||
flexWrap: "wrap",
|
|
||||||
gap: "0.75rem",
|
|
||||||
alignItems: "center",
|
|
||||||
padding: "1rem",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{badges.map((b) => (
|
|
||||||
/* eslint-disable-next-line @next/next/no-img-element */
|
|
||||||
<img
|
|
||||||
key={b.id}
|
|
||||||
src={`${BADGE_IMG_BASE}/${b.badgeCode}.gif`}
|
|
||||||
alt={b.badgeCode}
|
|
||||||
title={b.badgeCode}
|
|
||||||
width={40}
|
|
||||||
height={40}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</ContentCard>
|
|
||||||
|
|
||||||
{/* ── Photos ────────────────────── */}
|
|
||||||
<ContentCard
|
|
||||||
icon="📸"
|
|
||||||
title={t("photosTitle")}
|
|
||||||
padded={photos.length === 0}
|
|
||||||
>
|
|
||||||
{photos.length === 0 ? (
|
|
||||||
<EmptyState icon="📸">{t("photosEmpty")}</EmptyState>
|
|
||||||
) : (
|
|
||||||
<div className="card-grid sm-2 lg-3" style={{ padding: "1rem" }}>
|
|
||||||
{photos.map((p) => (
|
|
||||||
<div key={p.id} className="card" style={{ padding: "0.5rem" }}>
|
|
||||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
|
||||||
<img
|
|
||||||
src={p.url}
|
|
||||||
alt={`by ${user.username}`}
|
|
||||||
style={{
|
|
||||||
width: "100%",
|
|
||||||
height: "auto",
|
|
||||||
display: "block",
|
|
||||||
borderRadius: "8px",
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<p className="muted" style={{ margin: "0.4rem 0 0" }}>
|
|
||||||
{formatDate(new Date(p.timestamp * 1000), "date")}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</ContentCard>
|
|
||||||
|
|
||||||
{/* ── Guestbook ───────────────────── */}
|
|
||||||
<ContentCard
|
|
||||||
icon="📝"
|
|
||||||
title={t("guestbookTitle")}
|
|
||||||
subtitle={t("guestbookSubtitle", { username: user.username })}
|
|
||||||
>
|
|
||||||
{isLoggedIn ? (
|
|
||||||
<form
|
|
||||||
action={postGuestbook}
|
|
||||||
className="card"
|
|
||||||
style={{ marginBottom: "1rem" }}
|
|
||||||
>
|
|
||||||
{/* Profile owner id drives the write target; the author is taken from
|
|
||||||
the session inside the action, never from this form. */}
|
|
||||||
<input type="hidden" name="profileId" value={String(user.id)} />
|
|
||||||
<input type="hidden" name="username" value={user.username} />
|
|
||||||
<label htmlFor="gb-message" className="muted">
|
|
||||||
{t("leaveMessage")}
|
|
||||||
</label>
|
|
||||||
<textarea
|
|
||||||
id="gb-message"
|
|
||||||
name="message"
|
|
||||||
required
|
|
||||||
maxLength={255}
|
|
||||||
rows={3}
|
|
||||||
placeholder={t("guestbookPlaceholder", {
|
|
||||||
username: user.username,
|
|
||||||
})}
|
|
||||||
style={{
|
|
||||||
width: "100%",
|
|
||||||
margin: "0.4rem 0 0.75rem",
|
|
||||||
resize: "vertical",
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<button type="submit" className="btn btn-primary">
|
|
||||||
{t("post")}
|
|
||||||
</button>
|
|
||||||
</form>
|
|
||||||
) : (
|
|
||||||
<p className="muted">{t("loginToPost")}</p>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{guestbook.length === 0 ? (
|
|
||||||
<EmptyState icon="📝">{t("guestbookEmpty")}</EmptyState>
|
|
||||||
) : (
|
|
||||||
<div className="grid" style={{ gap: "0.75rem" }}>
|
|
||||||
{guestbook.map((g) => {
|
|
||||||
const author = authorById.get(g.userId);
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
key={String(g.id)}
|
|
||||||
className="card"
|
|
||||||
style={{
|
|
||||||
display: "flex",
|
|
||||||
gap: "0.75rem",
|
|
||||||
alignItems: "flex-start",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{author ? (
|
|
||||||
<UserAvatarThumbnail
|
|
||||||
figure={author.look}
|
|
||||||
alt={author?.username ?? "author"}
|
|
||||||
/>
|
|
||||||
) : null}
|
|
||||||
<div style={{ flex: 1 }}>
|
|
||||||
<p style={{ margin: "0 0 0.25rem" }}>
|
|
||||||
<strong>
|
|
||||||
{author?.username ?? t("unknownUser", { id: g.userId })}
|
|
||||||
</strong>{" "}
|
|
||||||
<span className="muted">
|
|
||||||
{formatDate(g.createdAt, "date", "")}
|
|
||||||
</span>
|
|
||||||
</p>
|
|
||||||
<p style={{ margin: 0 }}>{g.message}</p>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
))}
|
||||||
})}
|
</div>
|
||||||
</div>
|
</ContentCard>
|
||||||
)}
|
|
||||||
</ContentCard>
|
{/* ── Friends ──────────────────────── */}
|
||||||
|
<ContentCard
|
||||||
|
icon="👥"
|
||||||
|
title={t("friendsTitle")}
|
||||||
|
subtitle={t("friendsSubtitle", { count: friends.length })}
|
||||||
|
padded={true}
|
||||||
|
>
|
||||||
|
{friends.length === 0 ? (
|
||||||
|
<EmptyState icon="👥">{t("friendsEmpty")}</EmptyState>
|
||||||
|
) : (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
display: "grid",
|
||||||
|
gridTemplateColumns: "repeat(auto-fill, minmax(72px, 1fr))",
|
||||||
|
gap: "0.75rem",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{friends.map((f) => (
|
||||||
|
<Link
|
||||||
|
key={f.id}
|
||||||
|
href={`/u/${encodeURIComponent(f.username)}`}
|
||||||
|
className="card"
|
||||||
|
title={f.username}
|
||||||
|
style={{
|
||||||
|
display: "flex",
|
||||||
|
flexDirection: "column",
|
||||||
|
alignItems: "center",
|
||||||
|
gap: "0.35rem",
|
||||||
|
padding: "0.6rem 0.4rem",
|
||||||
|
textAlign: "center",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<UserAvatarThumbnail figure={f.look} alt={f.username} />
|
||||||
|
<span
|
||||||
|
style={{
|
||||||
|
fontSize: "0.8rem",
|
||||||
|
fontWeight: 600,
|
||||||
|
maxWidth: "100%",
|
||||||
|
overflow: "hidden",
|
||||||
|
textOverflow: "ellipsis",
|
||||||
|
whiteSpace: "nowrap",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{f.username}
|
||||||
|
</span>
|
||||||
|
</Link>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</ContentCard>
|
||||||
|
|
||||||
|
{/* Badges */}
|
||||||
|
<ContentCard icon="🏅" title={t("badgesTitle")}>
|
||||||
|
{badges.length === 0 ? (
|
||||||
|
<EmptyState icon="🏅">{t("badgesEmpty")}</EmptyState>
|
||||||
|
) : (
|
||||||
|
<div className={styles.badges}>
|
||||||
|
{badges.map((b) => {
|
||||||
|
const details = badgeByCode.get(b.badgeCode);
|
||||||
|
const name = details?.badgeName || b.badgeCode;
|
||||||
|
return (
|
||||||
|
<details key={b.id} className={styles.badge}>
|
||||||
|
<summary title={name}>
|
||||||
|
<img
|
||||||
|
src={
|
||||||
|
BADGE_IMG_BASE +
|
||||||
|
"/" +
|
||||||
|
encodeURIComponent(b.badgeCode) +
|
||||||
|
".gif"
|
||||||
|
}
|
||||||
|
alt={name}
|
||||||
|
width={40}
|
||||||
|
height={40}
|
||||||
|
loading="lazy"
|
||||||
|
/>
|
||||||
|
</summary>
|
||||||
|
<div className={styles.badgeInfo}>
|
||||||
|
<strong>{name}</strong>
|
||||||
|
{details?.badgeDescription && (
|
||||||
|
<p>{details.badgeDescription}</p>
|
||||||
|
)}
|
||||||
|
<small>{b.badgeCode}</small>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</ContentCard>
|
||||||
|
</aside>
|
||||||
|
<div className={styles.content}>
|
||||||
|
{/* Rooms */}
|
||||||
|
<ContentCard
|
||||||
|
icon="🏠"
|
||||||
|
title={t("roomsTitle")}
|
||||||
|
subtitle={t("roomsSubtitle", { username: user.username })}
|
||||||
|
>
|
||||||
|
{rooms.length === 0 ? (
|
||||||
|
<EmptyState icon="🏠">{t("roomsEmpty")}</EmptyState>
|
||||||
|
) : (
|
||||||
|
<div className={styles.rooms}>
|
||||||
|
{rooms.map((r) => {
|
||||||
|
const photo = photos.find((photo) => photo.roomId === r.id);
|
||||||
|
return (
|
||||||
|
<Link
|
||||||
|
href={`/room/${r.id}`}
|
||||||
|
key={r.id}
|
||||||
|
className={styles.room}
|
||||||
|
>
|
||||||
|
<ProfileImage
|
||||||
|
src={
|
||||||
|
photo?.url ||
|
||||||
|
"/assets/images/profile/room_placeholder.png"
|
||||||
|
}
|
||||||
|
fallback="/assets/images/profile/room_placeholder.png"
|
||||||
|
alt=""
|
||||||
|
width={320}
|
||||||
|
height={140}
|
||||||
|
className={styles.roomImage}
|
||||||
|
/>
|
||||||
|
<div className={styles.roomBody}>
|
||||||
|
<strong>{r.name || t("roomUntitled")}</strong>
|
||||||
|
{!photo && (
|
||||||
|
<span className="muted">{t("noRoomPreview")}</span>
|
||||||
|
)}
|
||||||
|
<div className={styles.roomMeta}>
|
||||||
|
<span>
|
||||||
|
{r.users}/{r.usersMax}
|
||||||
|
</span>
|
||||||
|
<span>
|
||||||
|
{t.has(`roomStates.${r.state}`)
|
||||||
|
? t(`roomStates.${r.state}`)
|
||||||
|
: r.state}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<span className={styles.roomLink}>
|
||||||
|
{t("viewRoom")} →
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</Link>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</ContentCard>
|
||||||
|
|
||||||
|
{/* ── Photos ────────────────────── */}
|
||||||
|
<ContentCard
|
||||||
|
icon="📸"
|
||||||
|
title={t("photosTitle")}
|
||||||
|
padded={photos.length === 0}
|
||||||
|
>
|
||||||
|
{photos.length === 0 ? (
|
||||||
|
<EmptyState icon="📸">{t("photosEmpty")}</EmptyState>
|
||||||
|
) : (
|
||||||
|
<div className="card-grid sm-2 lg-3" style={{ padding: "1rem" }}>
|
||||||
|
{photos.map((p) => (
|
||||||
|
<div
|
||||||
|
key={p.id}
|
||||||
|
className="card"
|
||||||
|
style={{ padding: "0.5rem" }}
|
||||||
|
>
|
||||||
|
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||||
|
<img
|
||||||
|
src={p.url}
|
||||||
|
alt={`by ${user.username}`}
|
||||||
|
style={{
|
||||||
|
width: "100%",
|
||||||
|
height: "auto",
|
||||||
|
display: "block",
|
||||||
|
borderRadius: "8px",
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<p className="muted" style={{ margin: "0.4rem 0 0" }}>
|
||||||
|
{formatDate(new Date(p.timestamp * 1000), "date")}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</ContentCard>
|
||||||
|
|
||||||
|
{/* ── Guestbook ───────────────────── */}
|
||||||
|
<ContentCard
|
||||||
|
icon="📝"
|
||||||
|
title={t("guestbookTitle")}
|
||||||
|
subtitle={t("guestbookSubtitle", { username: user.username })}
|
||||||
|
>
|
||||||
|
{isLoggedIn ? (
|
||||||
|
<form
|
||||||
|
action={postGuestbook}
|
||||||
|
className="card"
|
||||||
|
style={{ marginBottom: "1rem" }}
|
||||||
|
>
|
||||||
|
{/* Profile owner id drives the write target; the author is taken from
|
||||||
|
the session inside the action, never from this form. */}
|
||||||
|
<input type="hidden" name="profileId" value={String(user.id)} />
|
||||||
|
<input type="hidden" name="username" value={user.username} />
|
||||||
|
<label htmlFor="gb-message" className="muted">
|
||||||
|
{t("leaveMessage")}
|
||||||
|
</label>
|
||||||
|
<textarea
|
||||||
|
id="gb-message"
|
||||||
|
name="message"
|
||||||
|
required
|
||||||
|
maxLength={255}
|
||||||
|
rows={3}
|
||||||
|
placeholder={t("guestbookPlaceholder", {
|
||||||
|
username: user.username,
|
||||||
|
})}
|
||||||
|
style={{
|
||||||
|
width: "100%",
|
||||||
|
margin: "0.4rem 0 0.75rem",
|
||||||
|
resize: "vertical",
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<button type="submit" className="btn btn-primary">
|
||||||
|
{t("post")}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
) : (
|
||||||
|
<p className="muted">{t("loginToPost")}</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{guestbook.length === 0 ? (
|
||||||
|
<EmptyState icon="📝">{t("guestbookEmpty")}</EmptyState>
|
||||||
|
) : (
|
||||||
|
<div className="grid" style={{ gap: "0.75rem" }}>
|
||||||
|
{guestbook.map((g) => {
|
||||||
|
const author = authorById.get(g.userId);
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={String(g.id)}
|
||||||
|
className="card"
|
||||||
|
style={{
|
||||||
|
display: "flex",
|
||||||
|
gap: "0.75rem",
|
||||||
|
alignItems: "flex-start",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{author ? (
|
||||||
|
<UserAvatarThumbnail
|
||||||
|
figure={author.look}
|
||||||
|
alt={author?.username ?? "author"}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
<div style={{ flex: 1 }}>
|
||||||
|
<p style={{ margin: "0 0 0.25rem" }}>
|
||||||
|
<strong>
|
||||||
|
{author?.username ??
|
||||||
|
t("unknownUser", { id: g.userId })}
|
||||||
|
</strong>{" "}
|
||||||
|
<span className="muted">
|
||||||
|
{formatDate(g.createdAt, "date", "")}
|
||||||
|
</span>
|
||||||
|
</p>
|
||||||
|
<p style={{ margin: 0 }}>{g.message}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</ContentCard>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</main>
|
</main>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,176 @@
|
|||||||
|
.profile {
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.hero {
|
||||||
|
overflow: hidden;
|
||||||
|
border-top: 4px solid var(--color-primary);
|
||||||
|
background: linear-gradient(
|
||||||
|
120deg,
|
||||||
|
color-mix(in srgb, var(--color-primary) 9%, var(--color-surface)),
|
||||||
|
var(--color-surface)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
.avatar {
|
||||||
|
object-fit: contain;
|
||||||
|
image-rendering: pixelated;
|
||||||
|
border-radius: 20px;
|
||||||
|
background: color-mix(
|
||||||
|
in srgb,
|
||||||
|
var(--color-primary) 12%,
|
||||||
|
var(--color-surface)
|
||||||
|
);
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
.identity {
|
||||||
|
min-width: 0;
|
||||||
|
flex: 1;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
.meta {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
}
|
||||||
|
.columns {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: minmax(260px, 340px) minmax(0, 1fr);
|
||||||
|
gap: 24px;
|
||||||
|
align-items: start;
|
||||||
|
}
|
||||||
|
.sidebar,
|
||||||
|
.content {
|
||||||
|
display: grid;
|
||||||
|
gap: 24px;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.wallet {
|
||||||
|
display: grid;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
.currency {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 14px;
|
||||||
|
padding: 12px 14px;
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
border-radius: 12px;
|
||||||
|
}
|
||||||
|
.currency > div {
|
||||||
|
min-width: 0;
|
||||||
|
display: grid;
|
||||||
|
gap: 2px;
|
||||||
|
}
|
||||||
|
.currency strong {
|
||||||
|
font-size: 1.25rem;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
.currency span {
|
||||||
|
font-size: 0.8rem;
|
||||||
|
}
|
||||||
|
.profile [class~="empty-state"] {
|
||||||
|
padding: 18px 12px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: flex-start;
|
||||||
|
gap: 12px;
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
.profile [class~="empty-state-icon"] {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 1.5rem;
|
||||||
|
}
|
||||||
|
.rooms {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(min(100%, 230px), 1fr));
|
||||||
|
gap: 16px;
|
||||||
|
}
|
||||||
|
.room {
|
||||||
|
display: block;
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
border-radius: 12px;
|
||||||
|
overflow: hidden;
|
||||||
|
text-decoration: none;
|
||||||
|
color: inherit;
|
||||||
|
}
|
||||||
|
.room:hover,
|
||||||
|
.room:focus-visible {
|
||||||
|
border-color: var(--color-primary);
|
||||||
|
}
|
||||||
|
.roomImage {
|
||||||
|
width: 100%;
|
||||||
|
height: 140px;
|
||||||
|
object-fit: contain;
|
||||||
|
background: color-mix(in srgb, var(--color-primary) 6%, var(--color-surface));
|
||||||
|
}
|
||||||
|
.roomBody {
|
||||||
|
padding: 14px;
|
||||||
|
display: grid;
|
||||||
|
gap: 8px;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
.roomBody > [class~="muted"],
|
||||||
|
.roomMeta {
|
||||||
|
font-size: 0.8rem;
|
||||||
|
}
|
||||||
|
.roomMeta {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
.roomLink {
|
||||||
|
font-size: 0.85rem;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--color-primary-readable, var(--color-primary));
|
||||||
|
}
|
||||||
|
.badges {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 8px;
|
||||||
|
align-items: start;
|
||||||
|
}
|
||||||
|
.badge {
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
border-radius: 8px;
|
||||||
|
}
|
||||||
|
.badge summary {
|
||||||
|
padding: 6px;
|
||||||
|
cursor: pointer;
|
||||||
|
list-style: none;
|
||||||
|
}
|
||||||
|
.badge summary::-webkit-details-marker {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
.badge img {
|
||||||
|
display: block;
|
||||||
|
object-fit: contain;
|
||||||
|
image-rendering: pixelated;
|
||||||
|
}
|
||||||
|
.badge[open] {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
.badgeInfo {
|
||||||
|
padding: 0 12px 12px;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
.badgeInfo p {
|
||||||
|
margin: 6px 0;
|
||||||
|
}
|
||||||
|
@media (max-width: 760px) {
|
||||||
|
.columns {
|
||||||
|
grid-template-columns: minmax(0, 1fr);
|
||||||
|
gap: 16px;
|
||||||
|
}
|
||||||
|
.sidebar,
|
||||||
|
.content {
|
||||||
|
gap: 16px;
|
||||||
|
}
|
||||||
|
.avatar {
|
||||||
|
width: 80px;
|
||||||
|
height: 120px;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -31,6 +31,8 @@ export default async function EditArticle({
|
|||||||
title: WebsiteArticles.title,
|
title: WebsiteArticles.title,
|
||||||
shortStory: WebsiteArticles.shortStory,
|
shortStory: WebsiteArticles.shortStory,
|
||||||
fullStory: WebsiteArticles.fullStory,
|
fullStory: WebsiteArticles.fullStory,
|
||||||
|
status: WebsiteArticles.status,
|
||||||
|
publishAt: WebsiteArticles.publishAt,
|
||||||
image: WebsiteArticles.image,
|
image: WebsiteArticles.image,
|
||||||
})
|
})
|
||||||
.from(WebsiteArticles)
|
.from(WebsiteArticles)
|
||||||
@@ -63,7 +65,7 @@ export default async function EditArticle({
|
|||||||
action={async (fd) => {
|
action={async (fd) => {
|
||||||
"use server";
|
"use server";
|
||||||
fd.set("id", String(article.id));
|
fd.set("id", String(article.id));
|
||||||
await updateArticle(fd);
|
return updateArticle(fd);
|
||||||
}}
|
}}
|
||||||
defaultValues={{
|
defaultValues={{
|
||||||
title: article.title,
|
title: article.title,
|
||||||
@@ -71,6 +73,8 @@ export default async function EditArticle({
|
|||||||
image: article.image,
|
image: article.image,
|
||||||
shortStory: article.shortStory,
|
shortStory: article.shortStory,
|
||||||
fullStory: article.fullStory,
|
fullStory: article.fullStory,
|
||||||
|
status: article.status,
|
||||||
|
publishAt: article.publishAt?.toISOString(),
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<form action={deleteArticle} style={{ marginTop: "1rem" }}>
|
<form action={deleteArticle} style={{ marginTop: "1rem" }}>
|
||||||
|
|||||||
@@ -192,12 +192,13 @@ export function BannersManager({ banners }: Props) {
|
|||||||
<div className="flex gap-6">
|
<div className="flex gap-6">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<Switch
|
<Switch
|
||||||
|
id="banner-active"
|
||||||
checked={form.isActive === 1}
|
checked={form.isActive === 1}
|
||||||
onCheckedChange={(v) =>
|
onCheckedChange={(v) =>
|
||||||
setForm({ ...form, isActive: v ? 1 : 0 })
|
setForm({ ...form, isActive: v ? 1 : 0 })
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<Label>Active</Label>
|
<Label htmlFor="banner-active">Active</Label>
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-2 flex items-center gap-2">
|
<div className="space-y-2 flex items-center gap-2">
|
||||||
<Label>Order</Label>
|
<Label>Order</Label>
|
||||||
|
|||||||
@@ -30,11 +30,11 @@ import {
|
|||||||
RotateCcw,
|
RotateCcw,
|
||||||
Rows3,
|
Rows3,
|
||||||
Save,
|
Save,
|
||||||
Search,
|
|
||||||
Trash2,
|
Trash2,
|
||||||
X,
|
X,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import {
|
import {
|
||||||
@@ -48,6 +48,7 @@ import { BulkImportItems } from "@/components/admin/catalog/bulk-import-items";
|
|||||||
import { ItemsShopPreview } from "@/components/admin/catalog/items-shop-preview";
|
import { ItemsShopPreview } from "@/components/admin/catalog/items-shop-preview";
|
||||||
import { QuickAddFurni } from "@/components/admin/catalog/quick-add-furni";
|
import { QuickAddFurni } from "@/components/admin/catalog/quick-add-furni";
|
||||||
import { useConfirmDialog } from "@/components/admin/confirm-dialog";
|
import { useConfirmDialog } from "@/components/admin/confirm-dialog";
|
||||||
|
import { SearchInput } from "@/components/admin/search-input";
|
||||||
import {
|
import {
|
||||||
CurrencyIcon,
|
CurrencyIcon,
|
||||||
currencyKindFromPointsType,
|
currencyKindFromPointsType,
|
||||||
@@ -80,6 +81,12 @@ import {
|
|||||||
TableRow,
|
TableRow,
|
||||||
} from "@/components/ui/table";
|
} from "@/components/ui/table";
|
||||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||||
|
import { BulkOfferEditor } from "@/features/catalog/components/bulk-offer-editor";
|
||||||
|
import {
|
||||||
|
discoverOffers,
|
||||||
|
OFFER_FILTERS,
|
||||||
|
type OfferFilter,
|
||||||
|
} from "@/features/catalog/domain/offer-discovery";
|
||||||
import { useServerAction } from "@/hooks/use-server-action";
|
import { useServerAction } from "@/hooks/use-server-action";
|
||||||
import { getSuggestions, recordMove } from "@/lib/move-suggestions";
|
import { getSuggestions, recordMove } from "@/lib/move-suggestions";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
@@ -144,6 +151,9 @@ function SortableRow({
|
|||||||
}
|
}
|
||||||
|
|
||||||
interface CatalogItemsTableProps {
|
interface CatalogItemsTableProps {
|
||||||
|
initialSearch?: string;
|
||||||
|
onDirtyChange?: (dirty: boolean) => void;
|
||||||
|
onRefresh?: () => void;
|
||||||
items: CatalogItemData[];
|
items: CatalogItemData[];
|
||||||
pageId: number;
|
pageId: number;
|
||||||
pageLayout: string;
|
pageLayout: string;
|
||||||
@@ -154,6 +164,9 @@ interface CatalogItemsTableProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function CatalogItemsTable({
|
export function CatalogItemsTable({
|
||||||
|
initialSearch = "",
|
||||||
|
onDirtyChange,
|
||||||
|
onRefresh,
|
||||||
items,
|
items,
|
||||||
pageId,
|
pageId,
|
||||||
pageLayout,
|
pageLayout,
|
||||||
@@ -163,6 +176,11 @@ export function CatalogItemsTable({
|
|||||||
allPages,
|
allPages,
|
||||||
}: CatalogItemsTableProps) {
|
}: CatalogItemsTableProps) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
const bulk = useTranslations("pages.admin.catalog.bulk");
|
||||||
|
const discovery = useTranslations("pages.admin.catalog.discovery");
|
||||||
|
const [bulkRefreshFrom, setBulkRefreshFrom] = useState<
|
||||||
|
CatalogItemData[] | null
|
||||||
|
>(null);
|
||||||
const { run, isPending } = useServerAction();
|
const { run, isPending } = useServerAction();
|
||||||
const { confirm, dialog: confirmDialog } = useConfirmDialog();
|
const { confirm, dialog: confirmDialog } = useConfirmDialog();
|
||||||
const [addOpen, setAddOpen] = useState(false);
|
const [addOpen, setAddOpen] = useState(false);
|
||||||
@@ -176,20 +194,14 @@ export function CatalogItemsTable({
|
|||||||
const [viewMode, setViewMode] = useState<"table" | "grid">("table");
|
const [viewMode, setViewMode] = useState<"table" | "grid">("table");
|
||||||
|
|
||||||
// ── Search / Filter ─────────────────────────────────────────────
|
// ── Search / Filter ─────────────────────────────────────────────
|
||||||
const [searchQuery, setSearchQuery] = useState("");
|
const [searchQuery, setSearchQuery] = useState(initialSearch);
|
||||||
|
const [offerFilter, setOfferFilter] = useState<OfferFilter>("all");
|
||||||
const filteredItems = useMemo(() => {
|
const { items: filteredItems, counts: filterCounts } = useMemo(
|
||||||
if (!searchQuery.trim()) return items;
|
() => discoverOffers(items, searchQuery, offerFilter),
|
||||||
const q = searchQuery.toLowerCase();
|
[items, searchQuery, offerFilter],
|
||||||
return items.filter(
|
);
|
||||||
(item) =>
|
const hasDiscoveryFilter =
|
||||||
item.catalogName.toLowerCase().includes(q) ||
|
Boolean(searchQuery.trim()) || offerFilter !== "all";
|
||||||
item.baseItemName.toLowerCase().includes(q) ||
|
|
||||||
item.baseName.toLowerCase().includes(q) ||
|
|
||||||
item.itemIds.includes(q) ||
|
|
||||||
String(item.id).includes(q),
|
|
||||||
);
|
|
||||||
}, [items, searchQuery]);
|
|
||||||
|
|
||||||
// ── Move items dialog ───────────────────────────────────────────
|
// ── Move items dialog ───────────────────────────────────────────
|
||||||
const [moveOpen, setMoveOpen] = useState(false);
|
const [moveOpen, setMoveOpen] = useState(false);
|
||||||
@@ -232,13 +244,36 @@ export function CatalogItemsTable({
|
|||||||
});
|
});
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
const allVisibleSelected =
|
||||||
|
filteredItems.length > 0 &&
|
||||||
|
filteredItems.every((item) => selected.has(item.id));
|
||||||
|
const someVisibleSelected = filteredItems.some((item) =>
|
||||||
|
selected.has(item.id),
|
||||||
|
);
|
||||||
const toggleAll = useCallback(() => {
|
const toggleAll = useCallback(() => {
|
||||||
setSelected((prev) =>
|
setSelected((previous) => {
|
||||||
prev.size === filteredItems.length
|
const next = new Set(previous);
|
||||||
? new Set()
|
const allSelected = filteredItems.every((item) => previous.has(item.id));
|
||||||
: new Set(filteredItems.map((i) => i.id)),
|
for (const item of filteredItems) {
|
||||||
);
|
if (allSelected) next.delete(item.id);
|
||||||
|
else next.add(item.id);
|
||||||
|
}
|
||||||
|
return next;
|
||||||
|
});
|
||||||
}, [filteredItems]);
|
}, [filteredItems]);
|
||||||
|
function updateSearch(query: string) {
|
||||||
|
setSearchQuery(query);
|
||||||
|
setSelected(new Set());
|
||||||
|
}
|
||||||
|
function updateOfferFilter(value: string) {
|
||||||
|
setOfferFilter(value as OfferFilter);
|
||||||
|
setSelected(new Set());
|
||||||
|
}
|
||||||
|
function resetDiscovery() {
|
||||||
|
setSearchQuery("");
|
||||||
|
setOfferFilter("all");
|
||||||
|
setSelected(new Set());
|
||||||
|
}
|
||||||
|
|
||||||
// ── Inline edits ─────────────────────────────────────────────────
|
// ── Inline edits ─────────────────────────────────────────────────
|
||||||
const [inlineEdits, setInlineEdits] = useState<Record<number, InlineEdit>>(
|
const [inlineEdits, setInlineEdits] = useState<Record<number, InlineEdit>>(
|
||||||
@@ -290,7 +325,29 @@ export function CatalogItemsTable({
|
|||||||
return itemOrder.some((id, idx) => id !== originalOrder[idx]);
|
return itemOrder.some((id, idx) => id !== originalOrder[idx]);
|
||||||
}, [items, itemOrder]);
|
}, [items, itemOrder]);
|
||||||
|
|
||||||
const hasUnsavedChanges = modifiedItems.length > 0 || hasOrderChanges;
|
const hasUnsavedChanges =
|
||||||
|
bulkRefreshFrom === null && (modifiedItems.length > 0 || hasOrderChanges);
|
||||||
|
useEffect(() => {
|
||||||
|
if (bulkRefreshFrom === null || items === bulkRefreshFrom) return;
|
||||||
|
setInlineEdits(
|
||||||
|
Object.fromEntries(
|
||||||
|
items.map((item) => [
|
||||||
|
item.id,
|
||||||
|
{
|
||||||
|
costCredits: item.costCredits,
|
||||||
|
costPoints: item.costPoints,
|
||||||
|
pointsType: item.pointsType,
|
||||||
|
amount: item.amount,
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
setItemOrder(items.map((item) => item.id));
|
||||||
|
setBulkRefreshFrom(null);
|
||||||
|
}, [items, bulkRefreshFrom]);
|
||||||
|
useEffect(() => {
|
||||||
|
onDirtyChange?.(hasUnsavedChanges);
|
||||||
|
}, [hasUnsavedChanges, onDirtyChange]);
|
||||||
|
|
||||||
// Warn before navigating away with unsaved changes
|
// Warn before navigating away with unsaved changes
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -383,7 +440,8 @@ export function CatalogItemsTable({
|
|||||||
errorMessage: `Failed to save item #${item.id}.`,
|
errorMessage: `Failed to save item #${item.id}.`,
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
setSavingItemId(null);
|
setSavingItemId(null);
|
||||||
router.refresh();
|
if (onRefresh) onRefresh();
|
||||||
|
else router.refresh();
|
||||||
},
|
},
|
||||||
onError: () => setSavingItemId(null),
|
onError: () => setSavingItemId(null),
|
||||||
},
|
},
|
||||||
@@ -426,6 +484,10 @@ export function CatalogItemsTable({
|
|||||||
else failedCount++;
|
else failedCount++;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (savedCount > 0) {
|
||||||
|
if (onRefresh) onRefresh();
|
||||||
|
else router.refresh();
|
||||||
|
}
|
||||||
if (failedCount > 0) {
|
if (failedCount > 0) {
|
||||||
return {
|
return {
|
||||||
ok: false as const,
|
ok: false as const,
|
||||||
@@ -456,7 +518,8 @@ export function CatalogItemsTable({
|
|||||||
errorMessage: "Failed to delete items.",
|
errorMessage: "Failed to delete items.",
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
setSelected(new Set());
|
setSelected(new Set());
|
||||||
router.refresh();
|
if (onRefresh) onRefresh();
|
||||||
|
else router.refresh();
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -490,7 +553,8 @@ export function CatalogItemsTable({
|
|||||||
setSelected(new Set());
|
setSelected(new Set());
|
||||||
setMoveOpen(false);
|
setMoveOpen(false);
|
||||||
setMoveTargetPageId(null);
|
setMoveTargetPageId(null);
|
||||||
router.refresh();
|
if (onRefresh) onRefresh();
|
||||||
|
else router.refresh();
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -590,7 +654,8 @@ export function CatalogItemsTable({
|
|||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
setAddOpen(false);
|
setAddOpen(false);
|
||||||
setNewItem({ ...DEFAULT_NEW_ITEM });
|
setNewItem({ ...DEFAULT_NEW_ITEM });
|
||||||
router.refresh();
|
if (onRefresh) onRefresh();
|
||||||
|
else router.refresh();
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -641,7 +706,8 @@ export function CatalogItemsTable({
|
|||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
setMoveOneId(null);
|
setMoveOneId(null);
|
||||||
setMoveOneTarget(null);
|
setMoveOneTarget(null);
|
||||||
router.refresh();
|
if (onRefresh) onRefresh();
|
||||||
|
else router.refresh();
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -711,7 +777,8 @@ export function CatalogItemsTable({
|
|||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
setEditingItem(null);
|
setEditingItem(null);
|
||||||
setEditingBase(null);
|
setEditingBase(null);
|
||||||
router.refresh();
|
if (onRefresh) onRefresh();
|
||||||
|
else router.refresh();
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -887,21 +954,34 @@ export function CatalogItemsTable({
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{confirmDialog}
|
{confirmDialog}
|
||||||
<Card>
|
{bulkRefreshFrom !== null && (
|
||||||
|
<p
|
||||||
|
role="status"
|
||||||
|
className="flex items-center gap-2 text-sm text-muted-foreground"
|
||||||
|
>
|
||||||
|
<Loader2 className="size-4 animate-spin" />
|
||||||
|
{bulk("refreshing")}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<Card
|
||||||
|
inert={bulkRefreshFrom !== null}
|
||||||
|
aria-busy={bulkRefreshFrom !== null}
|
||||||
|
>
|
||||||
<CardHeader className="space-y-3">
|
<CardHeader className="space-y-3">
|
||||||
<div className="flex flex-row items-center justify-between gap-4">
|
<div className="flex flex-row items-center justify-between gap-4">
|
||||||
<div className="min-w-0">
|
<div className="min-w-0">
|
||||||
<CardTitle>
|
<CardTitle>
|
||||||
Items ({items.length})
|
Items ({items.length})
|
||||||
{searchQuery && filteredItems.length !== items.length && (
|
{hasDiscoveryFilter &&
|
||||||
<span className="text-muted-foreground font-normal text-sm ml-2">
|
filteredItems.length !== items.length && (
|
||||||
({filteredItems.length} shown)
|
<span className="text-muted-foreground font-normal text-sm ml-2">
|
||||||
</span>
|
{discovery("shown", { count: filteredItems.length })}
|
||||||
)}
|
</span>
|
||||||
|
)}
|
||||||
</CardTitle>
|
</CardTitle>
|
||||||
{selected.size > 0 && (
|
{selected.size > 0 && (
|
||||||
<p className="text-sm text-muted-foreground mt-1">
|
<p className="text-sm text-muted-foreground mt-1">
|
||||||
{selected.size} selected
|
{discovery("selected", { count: selected.size })}
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -941,6 +1021,21 @@ export function CatalogItemsTable({
|
|||||||
<>
|
<>
|
||||||
{selected.size > 0 && (
|
{selected.size > 0 && (
|
||||||
<>
|
<>
|
||||||
|
<BulkOfferEditor
|
||||||
|
ids={[...selected]}
|
||||||
|
allPages={allPages}
|
||||||
|
disabled={
|
||||||
|
hasUnsavedChanges ||
|
||||||
|
isPending ||
|
||||||
|
savingItemId !== null
|
||||||
|
}
|
||||||
|
onApplied={() => {
|
||||||
|
setBulkRefreshFrom(items);
|
||||||
|
setSelected(new Set());
|
||||||
|
if (onRefresh) onRefresh();
|
||||||
|
else router.refresh();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
size="sm"
|
size="sm"
|
||||||
@@ -1080,25 +1175,50 @@ export function CatalogItemsTable({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Search bar */}
|
{/* Offer discovery */}
|
||||||
{items.length > 0 && (
|
{items.length > 0 && (
|
||||||
<div className="relative">
|
<div className="space-y-2">
|
||||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
<div className="flex flex-col gap-2 sm:flex-row sm:items-center">
|
||||||
<Input
|
<div className="min-w-0 flex-1">
|
||||||
placeholder="Filter by name, classname, item ID..."
|
<SearchInput
|
||||||
value={searchQuery}
|
placeholder={discovery("searchPlaceholder")}
|
||||||
onChange={(e) => setSearchQuery(e.target.value)}
|
value={searchQuery}
|
||||||
className="pl-9 h-9"
|
onChange={updateSearch}
|
||||||
/>
|
onClear={() => updateSearch("")}
|
||||||
{searchQuery && (
|
/>
|
||||||
<button
|
</div>
|
||||||
type="button"
|
<Select value={offerFilter} onValueChange={updateOfferFilter}>
|
||||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
|
<SelectTrigger
|
||||||
onClick={() => setSearchQuery("")}
|
aria-label={discovery("filterLabel")}
|
||||||
>
|
className="w-full sm:w-52"
|
||||||
<X className="h-4 w-4" />
|
>
|
||||||
</button>
|
<SelectValue>
|
||||||
)}
|
{discovery(`filters.${offerFilter}`)} (
|
||||||
|
{filterCounts[offerFilter]})
|
||||||
|
</SelectValue>
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{OFFER_FILTERS.map((filter) => (
|
||||||
|
<SelectItem key={filter} value={filter}>
|
||||||
|
{discovery(`filters.${filter}`)} ({filterCounts[filter]}
|
||||||
|
)
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
{hasDiscoveryFilter && (
|
||||||
|
<Button variant="ghost" size="sm" onClick={resetDiscovery}>
|
||||||
|
{discovery("reset")}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
{discovery("results", {
|
||||||
|
count: filteredItems.length,
|
||||||
|
total: items.length,
|
||||||
|
})}
|
||||||
|
{canEdit && ` ${discovery("selectionHint")}`}
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
@@ -1121,7 +1241,7 @@ export function CatalogItemsTable({
|
|||||||
</div>
|
</div>
|
||||||
) : filteredItems.length === 0 ? (
|
) : filteredItems.length === 0 ? (
|
||||||
<p className="text-sm text-muted-foreground text-center py-8">
|
<p className="text-sm text-muted-foreground text-center py-8">
|
||||||
No items match "{searchQuery}".
|
{discovery("noResults")}
|
||||||
</p>
|
</p>
|
||||||
) : viewMode === "grid" ? (
|
) : viewMode === "grid" ? (
|
||||||
<ItemsShopPreview
|
<ItemsShopPreview
|
||||||
@@ -1147,12 +1267,12 @@ export function CatalogItemsTable({
|
|||||||
{canEdit && (
|
{canEdit && (
|
||||||
<TableHead className="w-[40px] px-2">
|
<TableHead className="w-[40px] px-2">
|
||||||
<Checkbox
|
<Checkbox
|
||||||
checked={
|
checked={allVisibleSelected}
|
||||||
filteredItems.length > 0 &&
|
indeterminate={
|
||||||
selected.size === filteredItems.length
|
someVisibleSelected && !allVisibleSelected
|
||||||
}
|
}
|
||||||
onCheckedChange={toggleAll}
|
onCheckedChange={toggleAll}
|
||||||
aria-label="Select all"
|
aria-label={discovery("selectVisible")}
|
||||||
/>
|
/>
|
||||||
</TableHead>
|
</TableHead>
|
||||||
)}
|
)}
|
||||||
@@ -1180,7 +1300,7 @@ export function CatalogItemsTable({
|
|||||||
const modified = isItemModified(item);
|
const modified = isItemModified(item);
|
||||||
const isSaving = savingItemId === item.id;
|
const isSaving = savingItemId === item.id;
|
||||||
const furniInfo = getFurniInfo(item);
|
const furniInfo = getFurniInfo(item);
|
||||||
const sortableDisabled = !canEdit || !!searchQuery;
|
const sortableDisabled = !canEdit || hasDiscoveryFilter;
|
||||||
return (
|
return (
|
||||||
<SortableRow
|
<SortableRow
|
||||||
key={item.id}
|
key={item.id}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { Check, ChevronsUpDown, Star } from "lucide-react";
|
import { Check, ChevronsUpDown, Star } from "lucide-react";
|
||||||
import { useMemo, useState } from "react";
|
import { useId, useMemo, useState } from "react";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import {
|
import {
|
||||||
Command,
|
Command,
|
||||||
@@ -37,11 +37,15 @@ export function ToggleField({
|
|||||||
onChange: (v: boolean) => void;
|
onChange: (v: boolean) => void;
|
||||||
disabled?: boolean;
|
disabled?: boolean;
|
||||||
}) {
|
}) {
|
||||||
|
const id = useId();
|
||||||
const isChecked = checked ?? (value === 1 || value === "1");
|
const isChecked = checked ?? (value === 1 || value === "1");
|
||||||
return (
|
return (
|
||||||
<div className="flex items-center justify-between gap-2">
|
<div className="flex items-center justify-between gap-2">
|
||||||
<Label className="text-xs">{label}</Label>
|
<Label htmlFor={id} className="text-xs">
|
||||||
|
{label}
|
||||||
|
</Label>
|
||||||
<Switch
|
<Switch
|
||||||
|
id={id}
|
||||||
checked={isChecked}
|
checked={isChecked}
|
||||||
onCheckedChange={onChange}
|
onCheckedChange={onChange}
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
@@ -151,6 +155,8 @@ export function MovePageCombobox({
|
|||||||
pages,
|
pages,
|
||||||
currentPageId,
|
currentPageId,
|
||||||
suggestedPageIds,
|
suggestedPageIds,
|
||||||
|
disabled = false,
|
||||||
|
labels,
|
||||||
}: {
|
}: {
|
||||||
value: number | null;
|
value: number | null;
|
||||||
onChange: (id: number | null) => void;
|
onChange: (id: number | null) => void;
|
||||||
@@ -158,6 +164,14 @@ export function MovePageCombobox({
|
|||||||
currentPageId: number;
|
currentPageId: number;
|
||||||
/** Page IDs to show first as suggestions (from move-suggestions.ts) */
|
/** Page IDs to show first as suggestions (from move-suggestions.ts) */
|
||||||
suggestedPageIds?: number[];
|
suggestedPageIds?: number[];
|
||||||
|
disabled?: boolean;
|
||||||
|
labels?: {
|
||||||
|
placeholder: string;
|
||||||
|
search: string;
|
||||||
|
empty: string;
|
||||||
|
suggested: string;
|
||||||
|
all: string;
|
||||||
|
};
|
||||||
}) {
|
}) {
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
|
|
||||||
@@ -194,6 +208,7 @@ export function MovePageCombobox({
|
|||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
role="combobox"
|
role="combobox"
|
||||||
|
disabled={disabled}
|
||||||
aria-expanded={open}
|
aria-expanded={open}
|
||||||
className="w-full justify-between font-normal"
|
className="w-full justify-between font-normal"
|
||||||
>
|
>
|
||||||
@@ -205,7 +220,9 @@ export function MovePageCombobox({
|
|||||||
{selectedPage.caption}
|
{selectedPage.caption}
|
||||||
</span>
|
</span>
|
||||||
) : (
|
) : (
|
||||||
<span className="text-muted-foreground">Select target page...</span>
|
<span className="text-muted-foreground">
|
||||||
|
{labels?.placeholder ?? "Select target page..."}
|
||||||
|
</span>
|
||||||
)}
|
)}
|
||||||
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
|
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
|
||||||
</Button>
|
</Button>
|
||||||
@@ -215,13 +232,13 @@ export function MovePageCombobox({
|
|||||||
align="start"
|
align="start"
|
||||||
>
|
>
|
||||||
<Command>
|
<Command>
|
||||||
<CommandInput placeholder="Search pages..." />
|
<CommandInput placeholder={labels?.search ?? "Search pages..."} />
|
||||||
<CommandList>
|
<CommandList>
|
||||||
<CommandEmpty>No page found.</CommandEmpty>
|
<CommandEmpty>{labels?.empty ?? "No page found."}</CommandEmpty>
|
||||||
|
|
||||||
{/* Suggested pages */}
|
{/* Suggested pages */}
|
||||||
{suggested.length > 0 && (
|
{suggested.length > 0 && (
|
||||||
<CommandGroup heading="Suggested">
|
<CommandGroup heading={labels?.suggested ?? "Suggested"}>
|
||||||
{suggested.map((page) => (
|
{suggested.map((page) => (
|
||||||
<CommandItem
|
<CommandItem
|
||||||
key={`s-${page.id}`}
|
key={`s-${page.id}`}
|
||||||
@@ -249,7 +266,9 @@ export function MovePageCombobox({
|
|||||||
|
|
||||||
{/* All pages */}
|
{/* All pages */}
|
||||||
<CommandGroup
|
<CommandGroup
|
||||||
heading={suggested.length > 0 ? "All pages" : undefined}
|
heading={
|
||||||
|
suggested.length > 0 ? (labels?.all ?? "All pages") : undefined
|
||||||
|
}
|
||||||
>
|
>
|
||||||
{remaining.map((page) => (
|
{remaining.map((page) => (
|
||||||
<CommandItem
|
<CommandItem
|
||||||
|
|||||||
@@ -136,10 +136,18 @@ export function CatalogPageForm({
|
|||||||
|
|
||||||
function handleSubmit(e: React.FormEvent) {
|
function handleSubmit(e: React.FormEvent) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
run(() => updateCatalogPage({ id: catalogPage.id, ...form }), {
|
run(
|
||||||
successMessage: "Page updated and catalog synced.",
|
() =>
|
||||||
errorMessage: "Failed to update.",
|
updateCatalogPage({
|
||||||
});
|
id: catalogPage.id,
|
||||||
|
...form,
|
||||||
|
expected: catalogPage as unknown as Record<string, unknown>,
|
||||||
|
}),
|
||||||
|
{
|
||||||
|
successMessage: "Page saved.",
|
||||||
|
errorMessage: "Failed to update.",
|
||||||
|
},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function handleDelete() {
|
async function handleDelete() {
|
||||||
|
|||||||
@@ -11,3 +11,11 @@ export const CatalogManagerDialog = dynamic(
|
|||||||
),
|
),
|
||||||
{ ssr: false },
|
{ ssr: false },
|
||||||
);
|
);
|
||||||
|
|
||||||
|
export const CatalogManagerWorkspace = dynamic(
|
||||||
|
() =>
|
||||||
|
import("@/components/admin/catalog-manager/catalog-manager-dialog").then(
|
||||||
|
(m) => ({ default: m.CatalogManagerWorkspace }),
|
||||||
|
),
|
||||||
|
{ ssr: false },
|
||||||
|
);
|
||||||
@@ -2,7 +2,9 @@
|
|||||||
|
|
||||||
import { FolderTree, HardHat, List, Package } from "lucide-react";
|
import { FolderTree, HardHat, List, Package } from "lucide-react";
|
||||||
import { useRouter, useSearchParams } from "next/navigation";
|
import { useRouter, useSearchParams } from "next/navigation";
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { requestCatalogNavigation } from "@/features/catalog/client/use-catalog-navigation";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
interface CatalogViewToggleProps {
|
interface CatalogViewToggleProps {
|
||||||
@@ -15,9 +17,11 @@ export function CatalogViewToggle({
|
|||||||
catalogType = "normal",
|
catalogType = "normal",
|
||||||
}: CatalogViewToggleProps) {
|
}: CatalogViewToggleProps) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
const t = useTranslations("pages.admin.catalog.workspace");
|
||||||
const searchParams = useSearchParams();
|
const searchParams = useSearchParams();
|
||||||
|
|
||||||
function setView(view: string) {
|
function setView(view: string) {
|
||||||
|
if (view === currentView || !requestCatalogNavigation()) return;
|
||||||
const params = new URLSearchParams(searchParams.toString());
|
const params = new URLSearchParams(searchParams.toString());
|
||||||
if (view === "tree") {
|
if (view === "tree") {
|
||||||
params.delete("view");
|
params.delete("view");
|
||||||
@@ -28,18 +32,21 @@ export function CatalogViewToggle({
|
|||||||
}
|
}
|
||||||
|
|
||||||
function setCatalog(type: string) {
|
function setCatalog(type: string) {
|
||||||
|
if (type === catalogType || !requestCatalogNavigation()) return;
|
||||||
const params = new URLSearchParams(searchParams.toString());
|
const params = new URLSearchParams(searchParams.toString());
|
||||||
if (type === "normal") {
|
if (type === "normal") {
|
||||||
params.delete("catalog");
|
params.delete("catalog");
|
||||||
} else {
|
} else {
|
||||||
params.set("catalog", type);
|
params.set("catalog", type);
|
||||||
}
|
}
|
||||||
params.delete("view"); // reset to tree when switching
|
params.delete("view");
|
||||||
|
params.delete("root");
|
||||||
|
params.delete("category");
|
||||||
router.push(`?${params.toString()}`);
|
router.push(`?${params.toString()}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
{/* Catalog type selector */}
|
{/* Catalog type selector */}
|
||||||
<div className="flex items-center rounded-md border bg-card">
|
<div className="flex items-center rounded-md border bg-card">
|
||||||
<Button
|
<Button
|
||||||
@@ -52,7 +59,7 @@ export function CatalogViewToggle({
|
|||||||
onClick={() => setCatalog("normal")}
|
onClick={() => setCatalog("normal")}
|
||||||
>
|
>
|
||||||
<Package className="mr-1.5 h-4 w-4" />
|
<Package className="mr-1.5 h-4 w-4" />
|
||||||
Catalog
|
{t("normal")}
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
@@ -80,7 +87,7 @@ export function CatalogViewToggle({
|
|||||||
onClick={() => setView("tree")}
|
onClick={() => setView("tree")}
|
||||||
>
|
>
|
||||||
<FolderTree className="mr-1.5 h-4 w-4" />
|
<FolderTree className="mr-1.5 h-4 w-4" />
|
||||||
Tree
|
{t("tree")}
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
@@ -92,7 +99,7 @@ export function CatalogViewToggle({
|
|||||||
onClick={() => setView("table")}
|
onClick={() => setView("table")}
|
||||||
>
|
>
|
||||||
<List className="mr-1.5 h-4 w-4" />
|
<List className="mr-1.5 h-4 w-4" />
|
||||||
Table
|
{t("table")}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -15,8 +15,10 @@ import { Store } from "lucide-react";
|
|||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
import { getTranslations } from "next-intl/server";
|
import { getTranslations } from "next-intl/server";
|
||||||
import { AdminPageShell } from "@/components/admin/admin-page-shell";
|
import { AdminPageShell } from "@/components/admin/admin-page-shell";
|
||||||
import { CatalogFixAllButton } from "@/components/admin/catalog/catalog-fix-all-button";
|
|
||||||
import { CatalogTree } from "@/components/admin/catalog-tree";
|
import { CatalogTree } from "@/components/admin/catalog-tree";
|
||||||
|
import Link from "@/components/link";
|
||||||
|
import { CatalogSearch } from "@/features/catalog/components/catalog-search";
|
||||||
|
import { CatalogSyncStatus } from "@/features/catalog/components/catalog-sync-status";
|
||||||
import { calcPagination, parseListParams } from "@/lib/admin-helpers";
|
import { calcPagination, parseListParams } from "@/lib/admin-helpers";
|
||||||
import {
|
import {
|
||||||
CatalogItems,
|
CatalogItems,
|
||||||
@@ -56,8 +58,9 @@ export default async function CatalogPagesPage({
|
|||||||
const params = await searchParams;
|
const params = await searchParams;
|
||||||
const sp = new URLSearchParams(params);
|
const sp = new URLSearchParams(params);
|
||||||
const { search, perPage, page, sort, order } = parseListParams(sp);
|
const { search, perPage, page, sort, order } = parseListParams(sp);
|
||||||
const viewMode = sp.get("view") || "tree";
|
const requestedView = sp.get("view");
|
||||||
const catalogType = sp.get("catalog") || "normal";
|
const viewMode = requestedView === "table" ? "table" : "tree";
|
||||||
|
const catalogType = sp.get("catalog") === "bc" ? "bc" : "normal";
|
||||||
|
|
||||||
type TreeNodeShape = {
|
type TreeNodeShape = {
|
||||||
id: number;
|
id: number;
|
||||||
@@ -94,7 +97,7 @@ export default async function CatalogPagesPage({
|
|||||||
.where(
|
.where(
|
||||||
or(eq(CatalogPagesBc.parentId, -1), eq(CatalogPagesBc.parentId, 0)),
|
or(eq(CatalogPagesBc.parentId, -1), eq(CatalogPagesBc.parentId, 0)),
|
||||||
)
|
)
|
||||||
.orderBy(asc(CatalogPagesBc.orderNum));
|
.orderBy(asc(CatalogPagesBc.orderNum), asc(CatalogPagesBc.id));
|
||||||
const bcRootIds = bcRootRaw.map((p) => p.id);
|
const bcRootIds = bcRootRaw.map((p) => p.id);
|
||||||
const [bcChildCounts, bcItemCounts] = await Promise.all([
|
const [bcChildCounts, bcItemCounts] = await Promise.all([
|
||||||
bcRootIds.length > 0
|
bcRootIds.length > 0
|
||||||
@@ -258,13 +261,17 @@ export default async function CatalogPagesPage({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<AdminPageShell icon={Store} title={t("title")} subtitle={t("subtitle")}>
|
<AdminPageShell icon={Store} title={t("title")} subtitle={t("subtitle")}>
|
||||||
|
<div className="mb-4 space-y-3">
|
||||||
|
<CatalogSyncStatus canEdit={canEdit} />
|
||||||
|
<CatalogSearch catalogType={catalogType} canEdit={canEdit} />
|
||||||
|
</div>
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<p className="text-muted-foreground">
|
<p className="text-muted-foreground">
|
||||||
{totalBcPages} BC pages ({enabledBcPages} enabled) ·{" "}
|
{totalBcPages} BC pages ({enabledBcPages} enabled) ·{" "}
|
||||||
{totalBcItems} items
|
{totalBcItems} items
|
||||||
</p>
|
</p>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
<CatalogViewToggle currentView={viewMode} catalogType="bc" />
|
<CatalogViewToggle currentView={viewMode} catalogType="bc" />
|
||||||
{canEdit && (
|
{canEdit && (
|
||||||
<CatalogManagerDialog
|
<CatalogManagerDialog
|
||||||
@@ -290,7 +297,12 @@ export default async function CatalogPagesPage({
|
|||||||
initialParentId={sp.get("newPageParent")}
|
initialParentId={sp.get("newPageParent")}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
<CatalogFixAllButton />
|
<Link
|
||||||
|
className="btn btn-outline"
|
||||||
|
href="/admin/catalog/maintenance"
|
||||||
|
>
|
||||||
|
{t("workspace.diagnostics")}
|
||||||
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{viewMode === "tree" ? (
|
{viewMode === "tree" ? (
|
||||||
@@ -323,7 +335,7 @@ export default async function CatalogPagesPage({
|
|||||||
.select()
|
.select()
|
||||||
.from(CatalogPages)
|
.from(CatalogPages)
|
||||||
.where(or(eq(CatalogPages.parentId, -1), eq(CatalogPages.parentId, 0)))
|
.where(or(eq(CatalogPages.parentId, -1), eq(CatalogPages.parentId, 0)))
|
||||||
.orderBy(asc(CatalogPages.orderNum));
|
.orderBy(asc(CatalogPages.orderNum), asc(CatalogPages.id));
|
||||||
const rootIds = rootPagesRaw.map((p) => p.id);
|
const rootIds = rootPagesRaw.map((p) => p.id);
|
||||||
const [rootChildCounts, rootItemCountMap] = await Promise.all([
|
const [rootChildCounts, rootItemCountMap] = await Promise.all([
|
||||||
rootIds.length > 0
|
rootIds.length > 0
|
||||||
@@ -482,13 +494,17 @@ export default async function CatalogPagesPage({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<AdminPageShell icon={Store} title={t("title")} subtitle={t("subtitle")}>
|
<AdminPageShell icon={Store} title={t("title")} subtitle={t("subtitle")}>
|
||||||
|
<div className="mb-4 space-y-3">
|
||||||
|
<CatalogSyncStatus canEdit={canEdit} />
|
||||||
|
<CatalogSearch catalogType={catalogType} canEdit={canEdit} />
|
||||||
|
</div>
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<p className="text-muted-foreground">
|
<p className="text-muted-foreground">
|
||||||
{totalPages} pages ({enabledPages} enabled) · {totalItems}{" "}
|
{totalPages} pages ({enabledPages} enabled) · {totalItems}{" "}
|
||||||
items
|
items
|
||||||
</p>
|
</p>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
<CatalogViewToggle currentView={viewMode} catalogType="normal" />
|
<CatalogViewToggle currentView={viewMode} catalogType="normal" />
|
||||||
{canEdit && (
|
{canEdit && (
|
||||||
<CatalogManagerDialog
|
<CatalogManagerDialog
|
||||||
@@ -511,7 +527,9 @@ export default async function CatalogPagesPage({
|
|||||||
{canEdit && (
|
{canEdit && (
|
||||||
<CatalogActions initialParentId={sp.get("newPageParent")} />
|
<CatalogActions initialParentId={sp.get("newPageParent")} />
|
||||||
)}
|
)}
|
||||||
<CatalogFixAllButton />
|
<Link className="btn btn-outline" href="/admin/catalog/maintenance">
|
||||||
|
{t("workspace.diagnostics")}
|
||||||
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ export function CommandocentrumControls() {
|
|||||||
const t = useTranslations("pages.admin.commandocentrum");
|
const t = useTranslations("pages.admin.commandocentrum");
|
||||||
const { run, isPending } = useServerAction();
|
const { run, isPending } = useServerAction();
|
||||||
|
|
||||||
|
const [category, setCategory] = useState("hotel");
|
||||||
const [hotelMessage, setHotelMessage] = useState("");
|
const [hotelMessage, setHotelMessage] = useState("");
|
||||||
const [disconnect, setDisconnect] = useState({ userId: "", username: "" });
|
const [disconnect, setDisconnect] = useState({ userId: "", username: "" });
|
||||||
const [alert, setAlert] = useState({ userId: "", message: "" });
|
const [alert, setAlert] = useState({ userId: "", message: "" });
|
||||||
@@ -46,10 +47,30 @@ export function CommandocentrumControls() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<section id="commands" className="my-6 scroll-mt-4 space-y-4">
|
||||||
<section className="mt-6">
|
<h2 className="admin-section-title">{t("emulatorControls")}</h2>
|
||||||
<h2 className="admin-section-title">{t("emulatorControls")}</h2>
|
<fieldset
|
||||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
|
className="flex flex-wrap gap-2"
|
||||||
|
aria-label={t("commandCategories")}
|
||||||
|
>
|
||||||
|
{["hotel", "players", "rewards", "advanced"].map((group) => (
|
||||||
|
<Button
|
||||||
|
key={group}
|
||||||
|
type="button"
|
||||||
|
variant={category === group ? "default" : "outline"}
|
||||||
|
aria-pressed={category === group}
|
||||||
|
disabled={isPending}
|
||||||
|
onClick={() => setCategory(group)}
|
||||||
|
>
|
||||||
|
{t(`groups.${group}`)}
|
||||||
|
</Button>
|
||||||
|
))}
|
||||||
|
</fieldset>
|
||||||
|
<p className="text-sm text-[var(--admin-text-muted)]" role="status">
|
||||||
|
{isPending ? t("executing") : t("chooseCommand")}
|
||||||
|
</p>
|
||||||
|
<div className="grid grid-cols-1 gap-4 lg:grid-cols-2 xl:grid-cols-3">
|
||||||
|
{category === "hotel" && (
|
||||||
<div className="admin-card">
|
<div className="admin-card">
|
||||||
<h3 className="text-sm font-bold text-[var(--admin-text)] mb-2">
|
<h3 className="text-sm font-bold text-[var(--admin-text)] mb-2">
|
||||||
{t("updateCatalog")}
|
{t("updateCatalog")}
|
||||||
@@ -71,7 +92,8 @@ export function CommandocentrumControls() {
|
|||||||
{t("updateCatalog")}
|
{t("updateCatalog")}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
|
{category === "hotel" && (
|
||||||
<div className="admin-card">
|
<div className="admin-card">
|
||||||
<h3 className="text-sm font-bold text-[var(--admin-text)] mb-2">
|
<h3 className="text-sm font-bold text-[var(--admin-text)] mb-2">
|
||||||
{t("updateWordFilter")}
|
{t("updateWordFilter")}
|
||||||
@@ -93,7 +115,8 @@ export function CommandocentrumControls() {
|
|||||||
{t("updateWordFilter")}
|
{t("updateWordFilter")}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
|
{category === "hotel" && (
|
||||||
<div className="admin-card">
|
<div className="admin-card">
|
||||||
<h3 className="text-sm font-bold text-[var(--admin-text)] mb-2">
|
<h3 className="text-sm font-bold text-[var(--admin-text)] mb-2">
|
||||||
{t("updateNavigator")}
|
{t("updateNavigator")}
|
||||||
@@ -115,50 +138,44 @@ export function CommandocentrumControls() {
|
|||||||
{t("updateNavigator")}
|
{t("updateNavigator")}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
)}
|
||||||
|
{category === "hotel" && (
|
||||||
<div className="admin-card mt-6">
|
<div className="admin-card">
|
||||||
<h3 className="text-sm font-bold text-[var(--admin-text)] mb-2">
|
<h3 className="text-sm font-bold text-[var(--admin-text)] mb-2">
|
||||||
{t("hotelAlert")}
|
{t("hotelAlert")}
|
||||||
</h3>
|
</h3>
|
||||||
<p className="text-xs text-[var(--admin-text-muted)] mb-3">
|
<p className="text-xs text-[var(--admin-text-muted)] mb-3">
|
||||||
{t("hotelAlertDesc")}
|
{t("hotelAlertDesc")}
|
||||||
</p>
|
</p>
|
||||||
<div className="flex gap-2">
|
<div className="flex flex-wrap gap-2">
|
||||||
<input
|
<input
|
||||||
value={hotelMessage}
|
value={hotelMessage}
|
||||||
onChange={(e) => setHotelMessage(e.target.value)}
|
onChange={(e) => setHotelMessage(e.target.value)}
|
||||||
required
|
required
|
||||||
maxLength={512}
|
maxLength={512}
|
||||||
placeholder={t("messageToBroadcast")}
|
aria-label={t("messageToBroadcast")}
|
||||||
className="flex-1 min-w-[220px]"
|
placeholder={t("messageToBroadcast")}
|
||||||
disabled={isPending}
|
className="flex-1 min-w-0 w-full sm:w-auto"
|
||||||
/>
|
disabled={isPending}
|
||||||
<Button
|
/>
|
||||||
type="button"
|
<Button
|
||||||
variant="destructive"
|
type="button"
|
||||||
disabled={isPending || !hotelMessage.trim()}
|
variant="destructive"
|
||||||
onClick={() =>
|
disabled={isPending || !hotelMessage.trim()}
|
||||||
run(() => hotelAlert({ message: hotelMessage }), {
|
onClick={() =>
|
||||||
successMessage: "Hotel alert sent.",
|
run(() => hotelAlert({ message: hotelMessage }), {
|
||||||
errorMessage: RCON_ERROR,
|
successMessage: "Hotel alert sent.",
|
||||||
onSuccess: () => setHotelMessage(""),
|
errorMessage: RCON_ERROR,
|
||||||
})
|
onSuccess: () => setHotelMessage(""),
|
||||||
}
|
})
|
||||||
>
|
}
|
||||||
{t("sendAlert")}
|
>
|
||||||
</Button>
|
{t("sendAlert")}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
)}
|
||||||
</section>
|
{category === "players" && (
|
||||||
|
|
||||||
<section className="mt-6">
|
|
||||||
<h2 className="admin-section-title">{t("userActions")}</h2>
|
|
||||||
<p className="text-xs text-[var(--admin-text-muted)] mb-4">
|
|
||||||
{t("userActionsDesc")}
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
|
|
||||||
<div className="admin-card">
|
<div className="admin-card">
|
||||||
<h3 className="text-sm font-bold text-[var(--admin-text)] mb-2">
|
<h3 className="text-sm font-bold text-[var(--admin-text)] mb-2">
|
||||||
{t("actions.disconnect")}
|
{t("actions.disconnect")}
|
||||||
@@ -170,6 +187,7 @@ export function CommandocentrumControls() {
|
|||||||
<input
|
<input
|
||||||
type="number"
|
type="number"
|
||||||
min={1}
|
min={1}
|
||||||
|
aria-label={t("userId")}
|
||||||
placeholder={t("userId")}
|
placeholder={t("userId")}
|
||||||
value={disconnect.userId}
|
value={disconnect.userId}
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
@@ -180,6 +198,7 @@ export function CommandocentrumControls() {
|
|||||||
/>
|
/>
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
|
aria-label={t("usernameRequired")}
|
||||||
placeholder={t("usernameRequired")}
|
placeholder={t("usernameRequired")}
|
||||||
value={disconnect.username}
|
value={disconnect.username}
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
@@ -215,7 +234,8 @@ export function CommandocentrumControls() {
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
|
{category === "players" && (
|
||||||
<div className="admin-card">
|
<div className="admin-card">
|
||||||
<h3 className="text-sm font-bold text-[var(--admin-text)] mb-2">
|
<h3 className="text-sm font-bold text-[var(--admin-text)] mb-2">
|
||||||
{t("actions.alert")}
|
{t("actions.alert")}
|
||||||
@@ -227,6 +247,7 @@ export function CommandocentrumControls() {
|
|||||||
<input
|
<input
|
||||||
type="number"
|
type="number"
|
||||||
min={1}
|
min={1}
|
||||||
|
aria-label={t("userId")}
|
||||||
placeholder={t("userId")}
|
placeholder={t("userId")}
|
||||||
value={alert.userId}
|
value={alert.userId}
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
@@ -237,6 +258,7 @@ export function CommandocentrumControls() {
|
|||||||
/>
|
/>
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
|
aria-label={t("alertMessage")}
|
||||||
placeholder={t("alertMessage")}
|
placeholder={t("alertMessage")}
|
||||||
value={alert.message}
|
value={alert.message}
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
@@ -270,7 +292,8 @@ export function CommandocentrumControls() {
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
|
{category === "players" && (
|
||||||
<div className="admin-card">
|
<div className="admin-card">
|
||||||
<h3 className="text-sm font-bold text-[var(--admin-text)] mb-2">
|
<h3 className="text-sm font-bold text-[var(--admin-text)] mb-2">
|
||||||
{t("forwardToRoom")}
|
{t("forwardToRoom")}
|
||||||
@@ -282,6 +305,7 @@ export function CommandocentrumControls() {
|
|||||||
<input
|
<input
|
||||||
type="number"
|
type="number"
|
||||||
min={1}
|
min={1}
|
||||||
|
aria-label={t("userId")}
|
||||||
placeholder={t("userId")}
|
placeholder={t("userId")}
|
||||||
value={forward.userId}
|
value={forward.userId}
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
@@ -293,6 +317,7 @@ export function CommandocentrumControls() {
|
|||||||
<input
|
<input
|
||||||
type="number"
|
type="number"
|
||||||
min={1}
|
min={1}
|
||||||
|
aria-label={t("roomId")}
|
||||||
placeholder={t("roomId")}
|
placeholder={t("roomId")}
|
||||||
value={forward.roomId}
|
value={forward.roomId}
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
@@ -325,9 +350,8 @@ export function CommandocentrumControls() {
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
)}
|
||||||
|
{category === "rewards" && (
|
||||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4 mt-4">
|
|
||||||
<div className="admin-card">
|
<div className="admin-card">
|
||||||
<h3 className="text-sm font-bold text-[var(--admin-text)] mb-2">
|
<h3 className="text-sm font-bold text-[var(--admin-text)] mb-2">
|
||||||
{t("giveCredits")}
|
{t("giveCredits")}
|
||||||
@@ -339,6 +363,7 @@ export function CommandocentrumControls() {
|
|||||||
<input
|
<input
|
||||||
type="number"
|
type="number"
|
||||||
min={1}
|
min={1}
|
||||||
|
aria-label={t("userId")}
|
||||||
placeholder={t("userId")}
|
placeholder={t("userId")}
|
||||||
value={credits.userId}
|
value={credits.userId}
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
@@ -350,6 +375,7 @@ export function CommandocentrumControls() {
|
|||||||
<input
|
<input
|
||||||
type="number"
|
type="number"
|
||||||
min={1}
|
min={1}
|
||||||
|
aria-label={t("amount")}
|
||||||
placeholder={t("amount")}
|
placeholder={t("amount")}
|
||||||
value={credits.credits}
|
value={credits.credits}
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
@@ -382,7 +408,8 @@ export function CommandocentrumControls() {
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
|
{category === "rewards" && (
|
||||||
<div className="admin-card">
|
<div className="admin-card">
|
||||||
<h3 className="text-sm font-bold text-[var(--admin-text)] mb-2">
|
<h3 className="text-sm font-bold text-[var(--admin-text)] mb-2">
|
||||||
{t("giveDuckets")}
|
{t("giveDuckets")}
|
||||||
@@ -394,6 +421,7 @@ export function CommandocentrumControls() {
|
|||||||
<input
|
<input
|
||||||
type="number"
|
type="number"
|
||||||
min={1}
|
min={1}
|
||||||
|
aria-label={t("userId")}
|
||||||
placeholder={t("userId")}
|
placeholder={t("userId")}
|
||||||
value={duckets.userId}
|
value={duckets.userId}
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
@@ -405,6 +433,7 @@ export function CommandocentrumControls() {
|
|||||||
<input
|
<input
|
||||||
type="number"
|
type="number"
|
||||||
min={1}
|
min={1}
|
||||||
|
aria-label={t("amount")}
|
||||||
placeholder={t("amount")}
|
placeholder={t("amount")}
|
||||||
value={duckets.amount}
|
value={duckets.amount}
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
@@ -437,7 +466,8 @@ export function CommandocentrumControls() {
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
|
{category === "rewards" && (
|
||||||
<div className="admin-card">
|
<div className="admin-card">
|
||||||
<h3 className="text-sm font-bold text-[var(--admin-text)] mb-2">
|
<h3 className="text-sm font-bold text-[var(--admin-text)] mb-2">
|
||||||
{t("giveDiamonds")}
|
{t("giveDiamonds")}
|
||||||
@@ -449,6 +479,7 @@ export function CommandocentrumControls() {
|
|||||||
<input
|
<input
|
||||||
type="number"
|
type="number"
|
||||||
min={1}
|
min={1}
|
||||||
|
aria-label={t("userId")}
|
||||||
placeholder={t("userId")}
|
placeholder={t("userId")}
|
||||||
value={diamonds.userId}
|
value={diamonds.userId}
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
@@ -460,6 +491,7 @@ export function CommandocentrumControls() {
|
|||||||
<input
|
<input
|
||||||
type="number"
|
type="number"
|
||||||
min={1}
|
min={1}
|
||||||
|
aria-label={t("amount")}
|
||||||
placeholder={t("amount")}
|
placeholder={t("amount")}
|
||||||
value={diamonds.amount}
|
value={diamonds.amount}
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
@@ -492,9 +524,8 @@ export function CommandocentrumControls() {
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
)}
|
||||||
|
{category === "rewards" && (
|
||||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4 mt-4">
|
|
||||||
<div className="admin-card">
|
<div className="admin-card">
|
||||||
<h3 className="text-sm font-bold text-[var(--admin-text)] mb-2">
|
<h3 className="text-sm font-bold text-[var(--admin-text)] mb-2">
|
||||||
{t("giveBadge")}
|
{t("giveBadge")}
|
||||||
@@ -506,6 +537,7 @@ export function CommandocentrumControls() {
|
|||||||
<input
|
<input
|
||||||
type="number"
|
type="number"
|
||||||
min={1}
|
min={1}
|
||||||
|
aria-label={t("userId")}
|
||||||
placeholder={t("userId")}
|
placeholder={t("userId")}
|
||||||
value={badge.userId}
|
value={badge.userId}
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
@@ -516,6 +548,7 @@ export function CommandocentrumControls() {
|
|||||||
/>
|
/>
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
|
aria-label={t("badgeCode")}
|
||||||
placeholder={t("badgeCode")}
|
placeholder={t("badgeCode")}
|
||||||
value={badge.badge}
|
value={badge.badge}
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
@@ -549,7 +582,8 @@ export function CommandocentrumControls() {
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
|
{category === "players" && (
|
||||||
<div className="admin-card">
|
<div className="admin-card">
|
||||||
<h3 className="text-sm font-bold text-[var(--admin-text)] mb-2">
|
<h3 className="text-sm font-bold text-[var(--admin-text)] mb-2">
|
||||||
{t("setMotto")}
|
{t("setMotto")}
|
||||||
@@ -561,6 +595,7 @@ export function CommandocentrumControls() {
|
|||||||
<input
|
<input
|
||||||
type="number"
|
type="number"
|
||||||
min={1}
|
min={1}
|
||||||
|
aria-label={t("userId")}
|
||||||
placeholder={t("userId")}
|
placeholder={t("userId")}
|
||||||
value={motto.userId}
|
value={motto.userId}
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
@@ -571,6 +606,7 @@ export function CommandocentrumControls() {
|
|||||||
/>
|
/>
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
|
aria-label={t("newMotto")}
|
||||||
placeholder={t("newMotto")}
|
placeholder={t("newMotto")}
|
||||||
value={motto.motto}
|
value={motto.motto}
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
@@ -604,7 +640,8 @@ export function CommandocentrumControls() {
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
|
{category === "players" && (
|
||||||
<div className="admin-card">
|
<div className="admin-card">
|
||||||
<h3 className="text-sm font-bold text-[var(--admin-text)] mb-2">
|
<h3 className="text-sm font-bold text-[var(--admin-text)] mb-2">
|
||||||
{t("setRank")}
|
{t("setRank")}
|
||||||
@@ -616,6 +653,7 @@ export function CommandocentrumControls() {
|
|||||||
<input
|
<input
|
||||||
type="number"
|
type="number"
|
||||||
min={1}
|
min={1}
|
||||||
|
aria-label={t("userId")}
|
||||||
placeholder={t("userId")}
|
placeholder={t("userId")}
|
||||||
value={rank.userId}
|
value={rank.userId}
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
@@ -628,6 +666,7 @@ export function CommandocentrumControls() {
|
|||||||
type="number"
|
type="number"
|
||||||
min={0}
|
min={0}
|
||||||
max={10}
|
max={10}
|
||||||
|
aria-label={t("rankPlaceholder")}
|
||||||
placeholder={t("rankPlaceholder")}
|
placeholder={t("rankPlaceholder")}
|
||||||
value={rank.rank}
|
value={rank.rank}
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
@@ -660,9 +699,8 @@ export function CommandocentrumControls() {
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
)}
|
||||||
|
{category === "advanced" && (
|
||||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4 mt-4">
|
|
||||||
<div className="admin-card">
|
<div className="admin-card">
|
||||||
<h3 className="text-sm font-bold text-[var(--admin-text)] mb-2">
|
<h3 className="text-sm font-bold text-[var(--admin-text)] mb-2">
|
||||||
{t("executeCommand")}
|
{t("executeCommand")}
|
||||||
@@ -674,6 +712,7 @@ export function CommandocentrumControls() {
|
|||||||
<input
|
<input
|
||||||
type="number"
|
type="number"
|
||||||
min={1}
|
min={1}
|
||||||
|
aria-label={t("userId")}
|
||||||
placeholder={t("userId")}
|
placeholder={t("userId")}
|
||||||
value={command.userId}
|
value={command.userId}
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
@@ -684,6 +723,7 @@ export function CommandocentrumControls() {
|
|||||||
/>
|
/>
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
|
aria-label={t("commandPlaceholder")}
|
||||||
placeholder={t("commandPlaceholder")}
|
placeholder={t("commandPlaceholder")}
|
||||||
value={command.command}
|
value={command.command}
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
@@ -719,7 +759,8 @@ export function CommandocentrumControls() {
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
|
{category === "rewards" && (
|
||||||
<div className="admin-card">
|
<div className="admin-card">
|
||||||
<h3 className="text-sm font-bold text-[var(--admin-text)] mb-2">
|
<h3 className="text-sm font-bold text-[var(--admin-text)] mb-2">
|
||||||
{t("sendGift")}
|
{t("sendGift")}
|
||||||
@@ -731,6 +772,7 @@ export function CommandocentrumControls() {
|
|||||||
<input
|
<input
|
||||||
type="number"
|
type="number"
|
||||||
min={1}
|
min={1}
|
||||||
|
aria-label={t("userId")}
|
||||||
placeholder={t("userId")}
|
placeholder={t("userId")}
|
||||||
value={gift.userId}
|
value={gift.userId}
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
@@ -742,6 +784,7 @@ export function CommandocentrumControls() {
|
|||||||
<input
|
<input
|
||||||
type="number"
|
type="number"
|
||||||
min={1}
|
min={1}
|
||||||
|
aria-label={t("furniId")}
|
||||||
placeholder={t("furniId")}
|
placeholder={t("furniId")}
|
||||||
value={gift.itemId}
|
value={gift.itemId}
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
@@ -752,6 +795,7 @@ export function CommandocentrumControls() {
|
|||||||
/>
|
/>
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
|
aria-label={t("giftMessage")}
|
||||||
placeholder={t("giftMessage")}
|
placeholder={t("giftMessage")}
|
||||||
value={gift.message}
|
value={gift.message}
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
@@ -791,8 +835,8 @@ export function CommandocentrumControls() {
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
)}
|
||||||
</section>
|
</div>
|
||||||
</>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -10,6 +10,8 @@ import {
|
|||||||
OnlineUsersWidget,
|
OnlineUsersWidget,
|
||||||
StatusCard,
|
StatusCard,
|
||||||
} from "@/components/admin/dashboard";
|
} from "@/components/admin/dashboard";
|
||||||
|
import Link from "@/components/link";
|
||||||
|
import { env } from "@/env";
|
||||||
import { fetchOpsHealth } from "@/lib/admin/ops-health";
|
import { fetchOpsHealth } from "@/lib/admin/ops-health";
|
||||||
import { fetchOpsOnlineUsers } from "@/lib/admin/ops-online-users";
|
import { fetchOpsOnlineUsers } from "@/lib/admin/ops-online-users";
|
||||||
import { db, EmulatorErrors, StaffActivities, User } from "@/lib/db";
|
import { db, EmulatorErrors, StaffActivities, User } from "@/lib/db";
|
||||||
@@ -17,6 +19,7 @@ import { formatDate } from "@/lib/format-date";
|
|||||||
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
|
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
|
||||||
import { siteSettings } from "@/lib/services/site-settings";
|
import { siteSettings } from "@/lib/services/site-settings";
|
||||||
import { CommandocentrumControls } from "./commandocentrum-controls";
|
import { CommandocentrumControls } from "./commandocentrum-controls";
|
||||||
|
import { RefreshStatus } from "./refresh-status";
|
||||||
|
|
||||||
function decodeStacktrace(raw: unknown): string {
|
function decodeStacktrace(raw: unknown): string {
|
||||||
if (raw == null) return "";
|
if (raw == null) return "";
|
||||||
@@ -47,28 +50,36 @@ export default async function CommandoCentrum() {
|
|||||||
|
|
||||||
const t = await getTranslations("pages.admin.commandocentrum");
|
const t = await getTranslations("pages.admin.commandocentrum");
|
||||||
|
|
||||||
const [totalUsersRows, errors, health, maintenance, activity, onlineRoster] =
|
const [
|
||||||
await Promise.all([
|
totalUsersRows,
|
||||||
db
|
errorRows,
|
||||||
.select({ total: count() })
|
health,
|
||||||
.from(User)
|
maintenance,
|
||||||
.catch(() => [{ total: -1 }]),
|
activity,
|
||||||
db
|
onlineRoster,
|
||||||
.select()
|
] = await Promise.all([
|
||||||
.from(EmulatorErrors)
|
db
|
||||||
.orderBy(desc(EmulatorErrors.timestamp))
|
.select({ total: count() })
|
||||||
.limit(50)
|
.from(User)
|
||||||
.catch(() => []),
|
.catch(() => [{ total: -1 }]),
|
||||||
fetchOpsHealth(),
|
db
|
||||||
siteSettings.getBool("maintenance_enabled", false),
|
.select()
|
||||||
db
|
.from(EmulatorErrors)
|
||||||
.select()
|
.orderBy(desc(EmulatorErrors.timestamp))
|
||||||
.from(StaffActivities)
|
.limit(50)
|
||||||
.orderBy(desc(StaffActivities.createdAt))
|
.catch(() => null),
|
||||||
.limit(12)
|
fetchOpsHealth(),
|
||||||
.catch(() => [] as (typeof StaffActivities.$inferSelect)[]),
|
siteSettings.getBool("maintenance_enabled", false),
|
||||||
fetchOpsOnlineUsers(40),
|
db
|
||||||
]);
|
.select()
|
||||||
|
.from(StaffActivities)
|
||||||
|
.orderBy(desc(StaffActivities.createdAt))
|
||||||
|
.limit(12)
|
||||||
|
.catch(() => [] as (typeof StaffActivities.$inferSelect)[]),
|
||||||
|
fetchOpsOnlineUsers(40),
|
||||||
|
]);
|
||||||
|
const errors = errorRows ?? [];
|
||||||
|
const errorsAvailable = errorRows !== null;
|
||||||
const totalUsers = Number(totalUsersRows[0]?.total ?? -1);
|
const totalUsers = Number(totalUsersRows[0]?.total ?? -1);
|
||||||
|
|
||||||
const dbOk = health.dbOk;
|
const dbOk = health.dbOk;
|
||||||
@@ -91,12 +102,30 @@ export default async function CommandoCentrum() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const appKeySet = !!process.env.APP_KEY;
|
const appKeySet = !!process.env.APP_KEY;
|
||||||
const smtpSet = !!process.env.SMTP_HOST;
|
const smtpSet = !!(env.SMTP_HOST || env.RESEND_API_KEY);
|
||||||
const rconSet = !!process.env.RCON_HOST;
|
const rconSet =
|
||||||
|
env.EMULATOR_MODE === "api" ? !!env.EMULATOR_API_URL : !!env.RCON_HOST;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AdminPageShell icon={Terminal} title={t("title")} subtitle={t("subtitle")}>
|
<AdminPageShell icon={Terminal} title={t("title")} subtitle={t("subtitle")}>
|
||||||
<main>
|
<div className="min-w-0">
|
||||||
|
<div className="mb-4 flex flex-wrap items-center gap-3">
|
||||||
|
<p className="text-sm">
|
||||||
|
{dbOk && emulatorOnline && redisOk !== false
|
||||||
|
? t("servicesHealthy")
|
||||||
|
: t("serviceAttention")}{" "}
|
||||||
|
·{" "}
|
||||||
|
{t("checkedAt", {
|
||||||
|
time: formatDate(new Date(), "datetime-seconds"),
|
||||||
|
})}
|
||||||
|
</p>
|
||||||
|
<RefreshStatus label={t("refreshStatus")} />
|
||||||
|
{canAccess(permissions, PERMS.DEVOPS_VIEW, session.user.rank) ? (
|
||||||
|
<Link href="/admin/devops/cms-errors" className="btn btn-outline">
|
||||||
|
{t("cmsErrors")}
|
||||||
|
</Link>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
{/* ── Live status ────────────────────────────────────────── */}
|
{/* ── Live status ────────────────────────────────────────── */}
|
||||||
<div
|
<div
|
||||||
className="grid grid-cols-[repeat(auto-fit,minmax(180px,1fr))] gap-3.5 mb-6"
|
className="grid grid-cols-[repeat(auto-fit,minmax(180px,1fr))] gap-3.5 mb-6"
|
||||||
@@ -104,7 +133,7 @@ export default async function CommandoCentrum() {
|
|||||||
>
|
>
|
||||||
<StatusCard
|
<StatusCard
|
||||||
label={t("playersOnline")}
|
label={t("playersOnline")}
|
||||||
value={onlineCount}
|
value={dbOk ? onlineCount : "—"}
|
||||||
hint={
|
hint={
|
||||||
totalUsers >= 0
|
totalUsers >= 0
|
||||||
? t("totalAccounts", { count: totalUsers })
|
? t("totalAccounts", { count: totalUsers })
|
||||||
@@ -129,13 +158,15 @@ export default async function CommandoCentrum() {
|
|||||||
/>
|
/>
|
||||||
<StatusCard
|
<StatusCard
|
||||||
label={t("emulatorErrors")}
|
label={t("emulatorErrors")}
|
||||||
value={errors.length}
|
value={errorsAvailable ? errors.length : "—"}
|
||||||
hint={t("last50Logged")}
|
hint={errorsAvailable ? t("last50Logged") : t("readFailed")}
|
||||||
state={errors.length === 0 ? "ok" : "warn"}
|
state={errorsAvailable && errors.length === 0 ? "ok" : "warn"}
|
||||||
icon="⚠️"
|
icon="⚠️"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<CommandocentrumControls />
|
||||||
|
|
||||||
{/* ── Online users widget ───────────────────────────────── */}
|
{/* ── Online users widget ───────────────────────────────── */}
|
||||||
<section id="online" className="admin-card mb-6 scroll-mt-4">
|
<section id="online" className="admin-card mb-6 scroll-mt-4">
|
||||||
<h2 className="admin-section-title">{t("onlineUsers")}</h2>
|
<h2 className="admin-section-title">{t("onlineUsers")}</h2>
|
||||||
@@ -144,8 +175,10 @@ export default async function CommandoCentrum() {
|
|||||||
|
|
||||||
{/* ── Server info + diagnostics ──────────────────────────── */}
|
{/* ── Server info + diagnostics ──────────────────────────── */}
|
||||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
|
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
|
||||||
<section className="admin-card p-5">
|
<details className="admin-card p-5 self-start">
|
||||||
<h2 className="admin-section-title">{t("serverInfo")}</h2>
|
<summary className="admin-section-title cursor-pointer">
|
||||||
|
{t("serverInfo")}
|
||||||
|
</summary>
|
||||||
<div className="grid grid-cols-[repeat(auto-fit,minmax(150px,1fr))] gap-2.5">
|
<div className="grid grid-cols-[repeat(auto-fit,minmax(150px,1fr))] gap-2.5">
|
||||||
<InfoItem label={t("node")} value={process.version} />
|
<InfoItem label={t("node")} value={process.version} />
|
||||||
<InfoItem
|
<InfoItem
|
||||||
@@ -171,7 +204,7 @@ export default async function CommandoCentrum() {
|
|||||||
/>
|
/>
|
||||||
<InfoItem label={t("cpus")} value={os.cpus().length} />
|
<InfoItem label={t("cpus")} value={os.cpus().length} />
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</details>
|
||||||
|
|
||||||
<section className="admin-card p-5">
|
<section className="admin-card p-5">
|
||||||
<h2 className="admin-section-title">{t("systemDiagnostics")}</h2>
|
<h2 className="admin-section-title">{t("systemDiagnostics")}</h2>
|
||||||
@@ -206,8 +239,8 @@ export default async function CommandoCentrum() {
|
|||||||
state={emulatorOnline ? "ok" : "warn"}
|
state={emulatorOnline ? "ok" : "warn"}
|
||||||
/>
|
/>
|
||||||
<DiagnosticRow
|
<DiagnosticRow
|
||||||
label={t("rconConfig")}
|
label={t("emulatorConfig")}
|
||||||
detail={rconSet ? t("rconHostSet") : t("rconHostNotConfigured")}
|
detail={rconSet ? t("configured") : t("notConfigured")}
|
||||||
state={rconSet ? "ok" : "warn"}
|
state={rconSet ? "ok" : "warn"}
|
||||||
/>
|
/>
|
||||||
<DiagnosticRow
|
<DiagnosticRow
|
||||||
@@ -216,8 +249,8 @@ export default async function CommandoCentrum() {
|
|||||||
state={appKeySet ? "ok" : "warn"}
|
state={appKeySet ? "ok" : "warn"}
|
||||||
/>
|
/>
|
||||||
<DiagnosticRow
|
<DiagnosticRow
|
||||||
label={t("emailSmtp")}
|
label={t("emailConfig")}
|
||||||
detail={smtpSet ? t("smtpHostSet") : t("notConfigured")}
|
detail={smtpSet ? t("configured") : t("notConfigured")}
|
||||||
state={smtpSet ? "ok" : "warn"}
|
state={smtpSet ? "ok" : "warn"}
|
||||||
/>
|
/>
|
||||||
<DiagnosticRow
|
<DiagnosticRow
|
||||||
@@ -231,8 +264,6 @@ export default async function CommandoCentrum() {
|
|||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<CommandocentrumControls />
|
|
||||||
|
|
||||||
{/* ── Staff activity ─────────────────────────────────────── */}
|
{/* ── Staff activity ─────────────────────────────────────── */}
|
||||||
<section className="mt-6">
|
<section className="mt-6">
|
||||||
<h2 className="admin-section-title">{t("recentStaffActivity")}</h2>
|
<h2 className="admin-section-title">{t("recentStaffActivity")}</h2>
|
||||||
@@ -277,7 +308,9 @@ export default async function CommandoCentrum() {
|
|||||||
{/* ── Emulator errors ────────────────────────────────────── */}
|
{/* ── Emulator errors ────────────────────────────────────── */}
|
||||||
<section className="mt-6">
|
<section className="mt-6">
|
||||||
<h2 className="admin-section-title">{t("recentEmulatorErrors")}</h2>
|
<h2 className="admin-section-title">{t("recentEmulatorErrors")}</h2>
|
||||||
{errors.length === 0 ? (
|
{!errorsAvailable ? (
|
||||||
|
<div className="admin-empty">{t("readFailed")}</div>
|
||||||
|
) : errors.length === 0 ? (
|
||||||
<div className="admin-empty">{t("noEmulatorErrors")}</div>
|
<div className="admin-empty">{t("noEmulatorErrors")}</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="admin-card overflow-x-auto">
|
<div className="admin-card overflow-x-auto">
|
||||||
@@ -312,9 +345,15 @@ export default async function CommandoCentrum() {
|
|||||||
{e.version}
|
{e.version}
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<pre className="text-xs p-2 bg-[var(--admin-canvas)] text-[var(--color-text-readable)] rounded overflow-auto max-h-[160px]">
|
<details>
|
||||||
{snippet}
|
<summary className="cursor-pointer text-xs">
|
||||||
</pre>
|
{trace.split("\n")[0]?.slice(0, 120) ||
|
||||||
|
t("empty")}
|
||||||
|
</summary>
|
||||||
|
<pre className="text-xs p-2 bg-[var(--admin-canvas)] text-[var(--color-text-readable)] rounded overflow-auto max-h-[160px]">
|
||||||
|
{snippet}
|
||||||
|
</pre>
|
||||||
|
</details>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
);
|
);
|
||||||
@@ -324,7 +363,7 @@ export default async function CommandoCentrum() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</section>
|
</section>
|
||||||
</main>
|
</div>
|
||||||
</AdminPageShell>
|
</AdminPageShell>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
"use client";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { useTransition } from "react";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
export function RefreshStatus({ label }: { label: string }) {
|
||||||
|
const router = useRouter();
|
||||||
|
const [pending, startTransition] = useTransition();
|
||||||
|
return (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
disabled={pending}
|
||||||
|
aria-busy={pending}
|
||||||
|
onClick={() => startTransition(() => router.refresh())}
|
||||||
|
>
|
||||||
|
{pending ? "… " : ""}
|
||||||
|
{label}
|
||||||
|
</Button>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import { expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
const mocks = vi.hoisted(() => ({
|
||||||
|
guard: vi.fn(),
|
||||||
|
resolve: vi.fn(),
|
||||||
|
audit: vi.fn(),
|
||||||
|
}));
|
||||||
|
vi.mock("@/lib/admin/guard", () => ({ requirePermission: mocks.guard }));
|
||||||
|
vi.mock("@/lib/error-monitor", () => ({
|
||||||
|
ErrorStore: class {
|
||||||
|
resolve = mocks.resolve;
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
vi.mock("@/lib/permissions", () => ({
|
||||||
|
PERMS: { DEVOPS_EDIT: "admin.devops.edit" },
|
||||||
|
}));
|
||||||
|
vi.mock("@/lib/services/audit", () => ({ logAudit: mocks.audit }));
|
||||||
|
vi.mock("next/cache", () => ({ revalidatePath: vi.fn() }));
|
||||||
|
|
||||||
|
import { resolveCmsError } from "./actions";
|
||||||
|
|
||||||
|
it("requires edit permission before resolving or auditing", async () => {
|
||||||
|
mocks.guard.mockRejectedValue(new Error("denied"));
|
||||||
|
await expect(resolveCmsError(new FormData())).rejects.toThrow("denied");
|
||||||
|
expect(mocks.resolve).not.toHaveBeenCalled();
|
||||||
|
expect(mocks.audit).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
it("records who resolved the problem", async () => {
|
||||||
|
mocks.guard.mockResolvedValue({ id: 42 });
|
||||||
|
mocks.resolve.mockResolvedValue(undefined);
|
||||||
|
mocks.audit.mockResolvedValue(undefined);
|
||||||
|
const data = new FormData();
|
||||||
|
data.set("fingerprint", "aabbccddeeff0011");
|
||||||
|
await resolveCmsError(data);
|
||||||
|
expect(mocks.guard).toHaveBeenCalledWith("admin.devops.edit");
|
||||||
|
expect(mocks.audit).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({ userId: 42, action: "cms.error.resolve" }),
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
"use server";
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { requirePermission } from "@/lib/admin/guard";
|
||||||
|
import { ErrorStore } from "@/lib/error-monitor";
|
||||||
|
import { PERMS } from "@/lib/permissions";
|
||||||
|
import { logAudit } from "@/lib/services/audit";
|
||||||
|
export async function resolveCmsError(data: FormData) {
|
||||||
|
const staff = await requirePermission(PERMS.DEVOPS_EDIT);
|
||||||
|
await new ErrorStore().resolve(String(data.get("fingerprint") ?? ""));
|
||||||
|
await logAudit({
|
||||||
|
userId: staff.id,
|
||||||
|
action: "cms.error.resolve",
|
||||||
|
target: "cms-error",
|
||||||
|
after: { fingerprint: String(data.get("fingerprint")) },
|
||||||
|
});
|
||||||
|
revalidatePath("/admin/devops/cms-errors");
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import { expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
const mocks = vi.hoisted(() => ({ read: vi.fn(), access: vi.fn() }));
|
||||||
|
vi.mock("@/lib/permissions", () => ({
|
||||||
|
getAdminContext: async () => ({
|
||||||
|
session: { user: { rank: 1 } },
|
||||||
|
permissions: {},
|
||||||
|
}),
|
||||||
|
canAccess: mocks.access,
|
||||||
|
PERMS: { DEVOPS_VIEW: "devops.view" },
|
||||||
|
}));
|
||||||
|
vi.mock("next/navigation", () => ({
|
||||||
|
redirect: () => {
|
||||||
|
throw new Error("redirect");
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
vi.mock("@/lib/error-monitor", () => ({
|
||||||
|
ErrorStore: class {
|
||||||
|
read = mocks.read;
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
vi.mock("@/components/link", () => ({ default: () => null }));
|
||||||
|
|
||||||
|
import Page from "./page";
|
||||||
|
|
||||||
|
it("rejects access before reading diagnostic data", async () => {
|
||||||
|
mocks.access.mockReturnValue(false);
|
||||||
|
await expect(Page({ searchParams: Promise.resolve({}) })).rejects.toThrow(
|
||||||
|
"redirect",
|
||||||
|
);
|
||||||
|
expect(mocks.read).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
import { redirect } from "next/navigation";
|
||||||
|
import { getTranslations } from "next-intl/server";
|
||||||
|
import Link from "@/components/link";
|
||||||
|
import { ErrorStore } from "@/lib/error-monitor";
|
||||||
|
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
|
||||||
|
import { resolveCmsError } from "./actions";
|
||||||
|
export default async function CmsErrorsPage({
|
||||||
|
searchParams,
|
||||||
|
}: {
|
||||||
|
searchParams: Promise<Record<string, string>>;
|
||||||
|
}) {
|
||||||
|
const { session, permissions } = await getAdminContext();
|
||||||
|
if (!canAccess(permissions, PERMS.DEVOPS_VIEW, session.user.rank))
|
||||||
|
redirect("/admin");
|
||||||
|
const t = await getTranslations("pages.admin.cmsErrors");
|
||||||
|
const params = await searchParams;
|
||||||
|
const query = (params.q ?? "").trim().slice(0, 200).toLowerCase();
|
||||||
|
let result: Awaited<ReturnType<ErrorStore["read"]>>;
|
||||||
|
try {
|
||||||
|
result = await new ErrorStore().read();
|
||||||
|
} catch {
|
||||||
|
return (
|
||||||
|
<div className="admin-card" role="alert">
|
||||||
|
{t("storageError")}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const filtered = result.records.filter(
|
||||||
|
(r) =>
|
||||||
|
(!params.source || r.source === params.source) &&
|
||||||
|
(params.status !== "open" || !r.resolved) &&
|
||||||
|
(params.status !== "resolved" || r.resolved) &&
|
||||||
|
(!query || JSON.stringify(r).toLowerCase().includes(query)),
|
||||||
|
);
|
||||||
|
const groups = new Map<string, typeof filtered>();
|
||||||
|
for (const r of filtered) {
|
||||||
|
const list = groups.get(r.fingerprint) ?? [];
|
||||||
|
list.push(r);
|
||||||
|
groups.set(r.fingerprint, list);
|
||||||
|
}
|
||||||
|
const page = Math.max(
|
||||||
|
1,
|
||||||
|
Math.min(
|
||||||
|
Number(params.page) || 1,
|
||||||
|
Math.max(1, Math.ceil(groups.size / 25)),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
const pageHref = (next: number) =>
|
||||||
|
`?${new URLSearchParams({ q: params.q ?? "", source: params.source ?? "", status: params.status ?? "", page: String(next) })}`;
|
||||||
|
return (
|
||||||
|
<div className="space-y-5">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-2xl font-semibold">{t("title")}</h1>
|
||||||
|
<p className="text-muted-foreground">{t("subtitle")}</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-wrap gap-3">
|
||||||
|
<Link href="/admin/devops" className="btn btn-outline">
|
||||||
|
DevOps
|
||||||
|
</Link>
|
||||||
|
<Link href="/admin/devops/errors" className="btn btn-outline">
|
||||||
|
{t("emulator")}
|
||||||
|
</Link>
|
||||||
|
<Link href="/admin/devops/cms-errors" className="btn btn-outline">
|
||||||
|
{t("refresh")}
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
<form className="admin-card flex flex-wrap gap-3">
|
||||||
|
<input
|
||||||
|
aria-label={t("search")}
|
||||||
|
name="q"
|
||||||
|
defaultValue={params.q}
|
||||||
|
placeholder={t("searchHint")}
|
||||||
|
className="input min-w-0 flex-1"
|
||||||
|
/>
|
||||||
|
<select
|
||||||
|
name="source"
|
||||||
|
aria-label={t("source")}
|
||||||
|
defaultValue={params.source ?? ""}
|
||||||
|
className="input"
|
||||||
|
>
|
||||||
|
<option value="">{t("allSources")}</option>
|
||||||
|
<option value="server">Server</option>
|
||||||
|
<option value="browser">Browser</option>
|
||||||
|
</select>
|
||||||
|
<select
|
||||||
|
name="status"
|
||||||
|
aria-label={t("status")}
|
||||||
|
defaultValue={params.status ?? ""}
|
||||||
|
className="input"
|
||||||
|
>
|
||||||
|
<option value="">{t("allStatuses")}</option>
|
||||||
|
<option value="open">{t("open")}</option>
|
||||||
|
<option value="resolved">{t("resolved")}</option>
|
||||||
|
</select>
|
||||||
|
<button type="submit" className="btn btn-primary">
|
||||||
|
{t("search")}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
{t("counts", { count: filtered.length, groups: groups.size })}{" "}
|
||||||
|
{result.truncated ? t("truncated") : ""} {t("retention")}
|
||||||
|
</p>
|
||||||
|
{groups.size === 0 ? (
|
||||||
|
<div className="admin-card">{t("empty")}</div>
|
||||||
|
) : null}
|
||||||
|
{[...groups.entries()]
|
||||||
|
.slice((page - 1) * 25, page * 25)
|
||||||
|
.map(([fingerprint, events]) => {
|
||||||
|
const r = events[0];
|
||||||
|
return (
|
||||||
|
<details key={fingerprint} className="admin-card overflow-hidden">
|
||||||
|
<summary className="cursor-pointer">
|
||||||
|
<span className="text-xs text-muted-foreground">
|
||||||
|
{t(r.resolved ? "resolved" : "open")} · {r.source} ·{" "}
|
||||||
|
{t("occurrences", { count: events.length })} · {r.at}
|
||||||
|
</span>
|
||||||
|
<p className="font-semibold break-words">{r.event}</p>
|
||||||
|
<p className="text-sm break-words">{r.message}</p>
|
||||||
|
</summary>
|
||||||
|
<div className="mt-4 space-y-3 text-sm">
|
||||||
|
<p>
|
||||||
|
{t("reference")}: <code className="break-all">{r.id}</code>
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
{t("release")}: <code className="break-all">{r.release}</code>
|
||||||
|
</p>
|
||||||
|
<pre className="whitespace-pre-wrap break-all rounded bg-muted p-3">
|
||||||
|
{JSON.stringify(r.context, null, 2)}
|
||||||
|
</pre>
|
||||||
|
<pre className="max-h-96 overflow-auto whitespace-pre-wrap break-all rounded bg-muted p-3">
|
||||||
|
{r.stack || t("noStack")}
|
||||||
|
</pre>
|
||||||
|
{!r.resolved &&
|
||||||
|
canAccess(permissions, PERMS.DEVOPS_EDIT, session.user.rank) ? (
|
||||||
|
<form action={resolveCmsError}>
|
||||||
|
<input
|
||||||
|
type="hidden"
|
||||||
|
name="fingerprint"
|
||||||
|
value={r.fingerprint}
|
||||||
|
/>
|
||||||
|
<button type="submit" className="btn btn-outline">
|
||||||
|
{t("resolve")}
|
||||||
|
</button>
|
||||||
|
<p className="text-muted-foreground text-xs">
|
||||||
|
{t("reopenHint")}
|
||||||
|
</p>
|
||||||
|
</form>
|
||||||
|
) : null}
|
||||||
|
<details>
|
||||||
|
<summary className="cursor-pointer">
|
||||||
|
{t("references")}
|
||||||
|
</summary>
|
||||||
|
<ul>
|
||||||
|
{events.map((e) => (
|
||||||
|
<li key={e.id} className="break-all">
|
||||||
|
{e.at} · {e.id}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</details>
|
||||||
|
<p className="text-muted-foreground">{t("stackHint")}</p>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
<nav aria-label={t("pages")} className="flex gap-3">
|
||||||
|
{page > 1 ? (
|
||||||
|
<Link href={pageHref(page - 1)} className="btn btn-outline">
|
||||||
|
{t("previous")}
|
||||||
|
</Link>
|
||||||
|
) : null}
|
||||||
|
{page * 25 < groups.size ? (
|
||||||
|
<Link href={pageHref(page + 1)} className="btn btn-outline">
|
||||||
|
{t("next")}
|
||||||
|
</Link>
|
||||||
|
) : null}
|
||||||
|
</nav>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ import { redirect } from "next/navigation";
|
|||||||
import { getTranslations } from "next-intl/server";
|
import { getTranslations } from "next-intl/server";
|
||||||
import { Card, CardContent } from "@/components/ui/card";
|
import { Card, CardContent } from "@/components/ui/card";
|
||||||
import { db, EmulatorErrors } from "@/lib/db";
|
import { db, EmulatorErrors } from "@/lib/db";
|
||||||
|
import { formatDate } from "@/lib/format-date";
|
||||||
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
|
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
|
||||||
|
|
||||||
export default async function EmulatorErrorsPage({
|
export default async function EmulatorErrorsPage({
|
||||||
@@ -35,6 +36,9 @@ export default async function EmulatorErrorsPage({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
|
<a href="/admin/devops/cms-errors" className="btn btn-outline">
|
||||||
|
CMS error center
|
||||||
|
</a>
|
||||||
<p className="text-muted-foreground">
|
<p className="text-muted-foreground">
|
||||||
{total} total errors — showing page {page} of {lastPage}
|
{total} total errors — showing page {page} of {lastPage}
|
||||||
</p>
|
</p>
|
||||||
@@ -52,7 +56,7 @@ export default async function EmulatorErrorsPage({
|
|||||||
#{error.id}
|
#{error.id}
|
||||||
</span>
|
</span>
|
||||||
<span className="text-xs text-muted-foreground">
|
<span className="text-xs text-muted-foreground">
|
||||||
{new Date(error.timestamp * 1000).toLocaleString()}
|
{formatDate(new Date(error.timestamp * 1000))}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<pre className="text-xs whitespace-pre-wrap break-all font-mono bg-muted p-2 rounded">
|
<pre className="text-xs whitespace-pre-wrap break-all font-mono bg-muted p-2 rounded">
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { Badge } from "@/components/ui/badge";
|
|||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
import { fetchOpsHealth } from "@/lib/admin/ops-health";
|
import { fetchOpsHealth } from "@/lib/admin/ops-health";
|
||||||
import { db, EmulatorErrors, EmulatorSettings } from "@/lib/db";
|
import { db, EmulatorErrors, EmulatorSettings } from "@/lib/db";
|
||||||
|
import { formatDate } from "@/lib/format-date";
|
||||||
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
|
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
|
||||||
import { HealthCheckClient } from "./health-check-client";
|
import { HealthCheckClient } from "./health-check-client";
|
||||||
|
|
||||||
@@ -55,6 +56,9 @@ export default async function DevOpsPage() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
|
<a href="/admin/devops/cms-errors" className="btn btn-outline">
|
||||||
|
{t("cmsErrors")}
|
||||||
|
</a>
|
||||||
{/* Status cards */}
|
{/* Status cards */}
|
||||||
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-5">
|
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-5">
|
||||||
<Card>
|
<Card>
|
||||||
@@ -165,7 +169,7 @@ export default async function DevOpsPage() {
|
|||||||
#{error.id}
|
#{error.id}
|
||||||
</span>
|
</span>
|
||||||
<span className="text-xs text-muted-foreground">
|
<span className="text-xs text-muted-foreground">
|
||||||
{new Date(error.timestamp * 1000).toLocaleString()}
|
{formatDate(new Date(error.timestamp * 1000))}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<pre className="text-xs whitespace-pre-wrap break-all font-mono text-destructive">
|
<pre className="text-xs whitespace-pre-wrap break-all font-mono text-destructive">
|
||||||
|
|||||||
@@ -2,9 +2,10 @@
|
|||||||
|
|
||||||
import { LayoutDashboard, RefreshCw } from "lucide-react";
|
import { LayoutDashboard, RefreshCw } from "lucide-react";
|
||||||
import { useTranslations } from "next-intl";
|
import { useTranslations } from "next-intl";
|
||||||
import { useEffect } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import Link from "@/components/link";
|
import Link from "@/components/link";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { reportBrowserError } from "@/lib/browser-errors";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Admin route-segment error boundary. Renders inside the admin layout shell.
|
* Admin route-segment error boundary. Renders inside the admin layout shell.
|
||||||
@@ -17,10 +18,12 @@ export default function AdminErrorPage({
|
|||||||
reset: () => void;
|
reset: () => void;
|
||||||
}) {
|
}) {
|
||||||
const t = useTranslations("pages.error");
|
const t = useTranslations("pages.error");
|
||||||
const tNav = useTranslations("admin.nav");
|
const tNav = useTranslations("pages.admin.nav");
|
||||||
|
|
||||||
|
const [reference, setReference] = useState(error.digest);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
console.error(error);
|
setReference(error.digest ?? reportBrowserError(error, "browser.boundary"));
|
||||||
|
if (error.digest) reportBrowserError(error, "browser.boundary");
|
||||||
}, [error]);
|
}, [error]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -63,12 +66,12 @@ export default function AdminErrorPage({
|
|||||||
</Link>
|
</Link>
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
{error.digest ? (
|
{reference ? (
|
||||||
<p
|
<p
|
||||||
className="mt-6 text-xs font-mono"
|
className="mt-6 text-xs font-mono"
|
||||||
style={{ color: "var(--admin-muted, #9ca3af)" }}
|
style={{ color: "var(--admin-muted, #9ca3af)" }}
|
||||||
>
|
>
|
||||||
{t("reference", { digest: error.digest })}
|
{t("reference", { digest: reference })}
|
||||||
</p>
|
</p>
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
import { useTranslations } from "next-intl";
|
import { useTranslations } from "next-intl";
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
|
import { formatDate } from "@/lib/format-date";
|
||||||
|
|
||||||
interface Registration {
|
interface Registration {
|
||||||
id: number;
|
id: number;
|
||||||
@@ -36,7 +37,7 @@ export function EventRegistrations({ registrations }: Props) {
|
|||||||
>
|
>
|
||||||
<span className="text-sm font-medium">{r.username}</span>
|
<span className="text-sm font-medium">{r.username}</span>
|
||||||
<span className="text-xs text-muted-foreground">
|
<span className="text-xs text-muted-foreground">
|
||||||
{new Date(r.createdAt).toLocaleString()}
|
{formatDate(new Date(r.createdAt))}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
|||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { Label } from "@/components/ui/label";
|
import { Label } from "@/components/ui/label";
|
||||||
import { useServerAction } from "@/hooks/use-server-action";
|
import { useServerAction } from "@/hooks/use-server-action";
|
||||||
|
import { formatDate } from "@/lib/format-date";
|
||||||
|
|
||||||
interface Winner {
|
interface Winner {
|
||||||
id: number;
|
id: number;
|
||||||
@@ -93,7 +94,7 @@ export function EventWinnersManager({ eventId, winners }: Props) {
|
|||||||
</span>
|
</span>
|
||||||
<span className="font-medium text-sm">{w.username}</span>
|
<span className="font-medium text-sm">{w.username}</span>
|
||||||
<span className="text-xs text-muted-foreground ml-auto">
|
<span className="text-xs text-muted-foreground ml-auto">
|
||||||
{new Date(w.createdAt).toLocaleDateString()}
|
{formatDate(new Date(w.createdAt), "date")}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { AdminBreadcrumb } from "@/components/admin/admin-breadcrumb";
|
|||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
import { db, User, WebsiteEvent, WebsiteEventType } from "@/lib/db";
|
import { db, User, WebsiteEvent, WebsiteEventType } from "@/lib/db";
|
||||||
|
import { formatDate } from "@/lib/format-date";
|
||||||
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
|
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
|
||||||
import { EventForm } from "../event-form";
|
import { EventForm } from "../event-form";
|
||||||
import { EventPrizesManager } from "./event-prizes";
|
import { EventPrizesManager } from "./event-prizes";
|
||||||
@@ -94,7 +95,7 @@ export default async function EventDetailPage({
|
|||||||
</Badge>
|
</Badge>
|
||||||
</div>
|
</div>
|
||||||
<p className="m-0 mt-1 text-sm text-[var(--admin-text-muted)]">
|
<p className="m-0 mt-1 text-sm text-[var(--admin-text-muted)]">
|
||||||
{event.type.name} · {new Date(event.startsAt).toLocaleString()}
|
{event.type.name} · {formatDate(new Date(event.startsAt))}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -156,7 +157,7 @@ export default async function EventDetailPage({
|
|||||||
{event.endsAt && (
|
{event.endsAt && (
|
||||||
<p className="text-xs text-muted-foreground">
|
<p className="text-xs text-muted-foreground">
|
||||||
{t("endsAt", {
|
{t("endsAt", {
|
||||||
date: new Date(event.endsAt).toLocaleString(),
|
date: formatDate(new Date(event.endsAt)),
|
||||||
})}
|
})}
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import Link from "@/components/link";
|
|||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { useServerAction } from "@/hooks/use-server-action";
|
import { useServerAction } from "@/hooks/use-server-action";
|
||||||
|
import { formatDate } from "@/lib/format-date";
|
||||||
import type { DataTableColumn, PaginatedResult } from "@/types/common";
|
import type { DataTableColumn, PaginatedResult } from "@/types/common";
|
||||||
|
|
||||||
interface EventRow {
|
interface EventRow {
|
||||||
@@ -86,7 +87,7 @@ export function EventsTable({ data }: EventsTableProps) {
|
|||||||
sortable: true,
|
sortable: true,
|
||||||
render: (value) => (
|
render: (value) => (
|
||||||
<span className="text-sm">
|
<span className="text-sm">
|
||||||
{new Date(value as unknown as string).toLocaleString()}
|
{formatDate(new Date(value as unknown as string))}
|
||||||
</span>
|
</span>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import { Button } from "@/components/ui/button";
|
|||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
import { Textarea } from "@/components/ui/textarea";
|
import { Textarea } from "@/components/ui/textarea";
|
||||||
import { useServerAction } from "@/hooks/use-server-action";
|
import { useServerAction } from "@/hooks/use-server-action";
|
||||||
|
import { formatDate } from "@/lib/format-date";
|
||||||
|
|
||||||
interface ThreadMessage {
|
interface ThreadMessage {
|
||||||
key: string;
|
key: string;
|
||||||
@@ -162,7 +163,7 @@ export function AdminHelpTicketDetail({
|
|||||||
{msg.isStaff ? ` (${t("staffBadge")})` : ""}
|
{msg.isStaff ? ` (${t("staffBadge")})` : ""}
|
||||||
</span>
|
</span>
|
||||||
<span className="text-[10px] text-muted-foreground">
|
<span className="text-[10px] text-muted-foreground">
|
||||||
{new Date(msg.createdAt).toLocaleString()}
|
{formatDate(new Date(msg.createdAt))}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
@@ -308,11 +309,11 @@ export function AdminHelpTicketDetail({
|
|||||||
<CardContent className="space-y-2 text-xs text-muted-foreground">
|
<CardContent className="space-y-2 text-xs text-muted-foreground">
|
||||||
<div className="flex justify-between gap-2">
|
<div className="flex justify-between gap-2">
|
||||||
<span>{t("colCreated")}</span>
|
<span>{t("colCreated")}</span>
|
||||||
<span>{new Date(ticket.createdAt).toLocaleString()}</span>
|
<span>{formatDate(new Date(ticket.createdAt))}</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex justify-between gap-2">
|
<div className="flex justify-between gap-2">
|
||||||
<span>{t("colUpdated")}</span>
|
<span>{t("colUpdated")}</span>
|
||||||
<span>{new Date(ticket.updatedAt).toLocaleString()}</span>
|
<span>{formatDate(new Date(ticket.updatedAt))}</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex justify-between gap-2">
|
<div className="flex justify-between gap-2">
|
||||||
<span>{t("messageCountLabel")}</span>
|
<span>{t("messageCountLabel")}</span>
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
AlertCircle,
|
|
||||||
BadgeCheck,
|
BadgeCheck,
|
||||||
Check,
|
Check,
|
||||||
CheckCircle2,
|
CheckCircle2,
|
||||||
@@ -15,6 +14,7 @@ import {
|
|||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
|
import { ImportErrorBanner } from "@/components/admin/import-error-banner";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
@@ -348,12 +348,7 @@ export function ImportBadgesClient() {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Error */}
|
{/* Error */}
|
||||||
{error && (
|
{error && <ImportErrorBanner error={error} />}
|
||||||
<div className="rounded-lg border px-4 py-3 text-sm bg-destructive/10 border-destructive/20 text-destructive flex items-center gap-2">
|
|
||||||
<AlertCircle className="w-4 h-4 shrink-0" />
|
|
||||||
{error}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Loading skeleton */}
|
{/* Loading skeleton */}
|
||||||
{loading && badges.length === 0 && (
|
{loading && badges.length === 0 && (
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
AlertCircle,
|
|
||||||
Check,
|
Check,
|
||||||
CloudDownload,
|
CloudDownload,
|
||||||
Download,
|
Download,
|
||||||
@@ -16,6 +15,7 @@ import {
|
|||||||
import { useCallback, useEffect, useRef, useState } from "react";
|
import { useCallback, useEffect, useRef, useState } from "react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import { useConfirmDialog } from "@/components/admin/confirm-dialog";
|
import { useConfirmDialog } from "@/components/admin/confirm-dialog";
|
||||||
|
import { ImportErrorBanner } from "@/components/admin/import-error-banner";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
@@ -782,12 +782,7 @@ function FurniGrid({ source }: FurniGridProps) {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Error */}
|
{/* Error */}
|
||||||
{error && (
|
{error && <ImportErrorBanner error={error} />}
|
||||||
<div className="rounded-lg border px-4 py-3 text-sm bg-destructive/10 border-destructive/20 text-destructive flex items-center gap-2">
|
|
||||||
<AlertCircle className="w-4 h-4 shrink-0" />
|
|
||||||
{error}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Empty state */}
|
{/* Empty state */}
|
||||||
{!loading && items.length === 0 && !error && (
|
{!loading && items.length === 0 && !error && (
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
AlertCircle,
|
|
||||||
Check,
|
Check,
|
||||||
Download,
|
Download,
|
||||||
Loader2,
|
Loader2,
|
||||||
@@ -11,14 +10,18 @@ import {
|
|||||||
Trash2,
|
Trash2,
|
||||||
X,
|
X,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
|
import {
|
||||||
|
BatchImportProgress,
|
||||||
|
useBatchImport,
|
||||||
|
} from "@/components/admin/import/use-batch-import";
|
||||||
|
import { ImportErrorBanner } from "@/components/admin/import-error-banner";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { adminFetch } from "@/lib/admin-fetch";
|
import { adminFetch } from "@/lib/admin-fetch";
|
||||||
import { getAvatarUrl } from "@/lib/imager";
|
import { getAvatarUrl } from "@/lib/imager";
|
||||||
import { runSseImport } from "@/lib/sse-client";
|
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
// ── Shared types ─────────────────────────────────────────────────────────────
|
// ── Shared types ─────────────────────────────────────────────────────────────
|
||||||
@@ -97,12 +100,14 @@ function LibsView() {
|
|||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
const [selected, setSelected] = useState<Set<string>>(new Set());
|
const [selected, setSelected] = useState<Set<string>>(new Set());
|
||||||
const [batchProgress, setBatchProgress] = useState<{
|
|
||||||
done: number;
|
|
||||||
total: number;
|
|
||||||
} | null>(null);
|
|
||||||
const [busyLib, setBusyLib] = useState<string | null>(null);
|
const [busyLib, setBusyLib] = useState<string | null>(null);
|
||||||
const batchAbortRef = useRef<AbortController | null>(null);
|
const batch = useBatchImport({
|
||||||
|
url: "/api/admin/import/clothing/batch",
|
||||||
|
successAction: "libraries imported",
|
||||||
|
cancelledMessage: "Import cancelled",
|
||||||
|
onItemDone: (label) => markDone(label),
|
||||||
|
onComplete: () => setSelected(new Set()),
|
||||||
|
});
|
||||||
|
|
||||||
const fetchItems = useCallback(async (search: string, pageNum: number) => {
|
const fetchItems = useCallback(async (search: string, pageNum: number) => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
@@ -168,41 +173,10 @@ function LibsView() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function importViaSse(toImport: FigureItem[]) {
|
async function importViaSse(toImport: FigureItem[]) {
|
||||||
batchAbortRef.current?.abort();
|
await batch.run(
|
||||||
const abort = new AbortController();
|
toImport.map((p) => p.lib),
|
||||||
batchAbortRef.current = abort;
|
{ items: toImport, concurrency: 3 },
|
||||||
setBatchProgress({ done: 0, total: toImport.length });
|
);
|
||||||
let done = 0;
|
|
||||||
try {
|
|
||||||
await runSseImport(
|
|
||||||
"/api/admin/import/clothing/batch",
|
|
||||||
{ items: toImport, concurrency: 3 },
|
|
||||||
(label) => {
|
|
||||||
done++;
|
|
||||||
markDone(label);
|
|
||||||
setBatchProgress({ done, total: toImport.length });
|
|
||||||
},
|
|
||||||
(succeeded, failed) => {
|
|
||||||
setSelected(new Set());
|
|
||||||
if (succeeded > 0) toast.success(`${succeeded} libraries imported`);
|
|
||||||
if (failed > 0) toast.error(`${failed} failed`);
|
|
||||||
},
|
|
||||||
abort.signal,
|
|
||||||
() => {
|
|
||||||
done++;
|
|
||||||
setBatchProgress({ done, total: toImport.length });
|
|
||||||
},
|
|
||||||
);
|
|
||||||
} catch (err) {
|
|
||||||
if ((err as Error)?.name === "AbortError") {
|
|
||||||
toast.info("Import cancelled");
|
|
||||||
} else {
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
if (batchAbortRef.current === abort) batchAbortRef.current = null;
|
|
||||||
setBatchProgress(null);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function importOne(p: FigureItem) {
|
async function importOne(p: FigureItem) {
|
||||||
@@ -315,7 +289,7 @@ function LibsView() {
|
|||||||
variant="outline"
|
variant="outline"
|
||||||
size="sm"
|
size="sm"
|
||||||
className="text-xs h-8"
|
className="text-xs h-8"
|
||||||
disabled={!!batchProgress}
|
disabled={batch.running}
|
||||||
onClick={() =>
|
onClick={() =>
|
||||||
setSelected((prev) =>
|
setSelected((prev) =>
|
||||||
prev.size === importable.length
|
prev.size === importable.length
|
||||||
@@ -333,9 +307,9 @@ function LibsView() {
|
|||||||
size="sm"
|
size="sm"
|
||||||
className="h-8"
|
className="h-8"
|
||||||
onClick={importSelected}
|
onClick={importSelected}
|
||||||
disabled={!!batchProgress}
|
disabled={batch.running}
|
||||||
>
|
>
|
||||||
{batchProgress ? (
|
{batch.running ? (
|
||||||
<Loader2 className="w-4 h-4 animate-spin mr-1" />
|
<Loader2 className="w-4 h-4 animate-spin mr-1" />
|
||||||
) : (
|
) : (
|
||||||
<Download className="w-4 h-4 mr-1" />
|
<Download className="w-4 h-4 mr-1" />
|
||||||
@@ -343,30 +317,16 @@ function LibsView() {
|
|||||||
Import {selected.size} selected
|
Import {selected.size} selected
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
{batchProgress && (
|
{batch.progress && (
|
||||||
<>
|
<BatchImportProgress
|
||||||
<span className="text-xs text-muted-foreground">
|
progress={batch.progress}
|
||||||
{batchProgress.done}/{batchProgress.total}
|
onCancel={batch.cancel}
|
||||||
</span>
|
/>
|
||||||
<Button
|
|
||||||
size="sm"
|
|
||||||
variant="outline"
|
|
||||||
className="h-8"
|
|
||||||
onClick={() => batchAbortRef.current?.abort()}
|
|
||||||
>
|
|
||||||
Cancel
|
|
||||||
</Button>
|
|
||||||
</>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{error && (
|
{error && <ImportErrorBanner error={error} />}
|
||||||
<div className="rounded-lg border px-4 py-3 text-sm bg-destructive/10 border-destructive/20 text-destructive flex items-center gap-2">
|
|
||||||
<AlertCircle className="w-4 h-4 shrink-0" />
|
|
||||||
{error}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{!loading && items.length === 0 && !error && (
|
{!loading && items.length === 0 && !error && (
|
||||||
<div className="text-center py-12 text-muted-foreground">
|
<div className="text-center py-12 text-muted-foreground">
|
||||||
@@ -428,7 +388,7 @@ function LibsView() {
|
|||||||
size="sm"
|
size="sm"
|
||||||
className="h-5 w-5 p-0 shrink-0"
|
className="h-5 w-5 p-0 shrink-0"
|
||||||
title="Remove library"
|
title="Remove library"
|
||||||
disabled={busyLib === p.lib || !!batchProgress}
|
disabled={busyLib === p.lib || batch.running}
|
||||||
onClick={() => remove(p)}
|
onClick={() => remove(p)}
|
||||||
>
|
>
|
||||||
<Trash2 className="w-3 h-3" />
|
<Trash2 className="w-3 h-3" />
|
||||||
@@ -439,7 +399,7 @@ function LibsView() {
|
|||||||
size="sm"
|
size="sm"
|
||||||
variant="outline"
|
variant="outline"
|
||||||
className="w-full text-xs h-7"
|
className="w-full text-xs h-7"
|
||||||
disabled={busyLib === p.lib || !!batchProgress}
|
disabled={busyLib === p.lib || batch.running}
|
||||||
onClick={() => importOne(p)}
|
onClick={() => importOne(p)}
|
||||||
>
|
>
|
||||||
{busyLib === p.lib ? (
|
{busyLib === p.lib ? (
|
||||||
@@ -498,12 +458,14 @@ function SetsView() {
|
|||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
const [selected, setSelected] = useState<Set<string>>(new Set());
|
const [selected, setSelected] = useState<Set<string>>(new Set());
|
||||||
const [batchProgress, setBatchProgress] = useState<{
|
|
||||||
done: number;
|
|
||||||
total: number;
|
|
||||||
} | null>(null);
|
|
||||||
const [busyKey, setBusyKey] = useState<string | null>(null);
|
const [busyKey, setBusyKey] = useState<string | null>(null);
|
||||||
const batchAbortRef = useRef<AbortController | null>(null);
|
const batch = useBatchImport({
|
||||||
|
url: "/api/admin/import/clothing/sets/batch",
|
||||||
|
successAction: "sets imported",
|
||||||
|
cancelledMessage: "Import cancelled",
|
||||||
|
onItemDone: (label) => markDone(label),
|
||||||
|
onComplete: () => setSelected(new Set()),
|
||||||
|
});
|
||||||
|
|
||||||
function itemKey(it: ClothingSetItem): string {
|
function itemKey(it: ClothingSetItem): string {
|
||||||
return `${it.setType}-${it.setId}`;
|
return `${it.setType}-${it.setId}`;
|
||||||
@@ -570,47 +532,16 @@ function SetsView() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function importViaSse(toImport: ClothingSetItem[]) {
|
async function importViaSse(toImport: ClothingSetItem[]) {
|
||||||
batchAbortRef.current?.abort();
|
await batch.run(
|
||||||
const abort = new AbortController();
|
toImport.map((it) => itemKey(it)),
|
||||||
batchAbortRef.current = abort;
|
{
|
||||||
setBatchProgress({ done: 0, total: toImport.length });
|
items: toImport.map((it) => ({
|
||||||
let done = 0;
|
setType: it.setType,
|
||||||
try {
|
setId: it.setId,
|
||||||
await runSseImport(
|
})),
|
||||||
"/api/admin/import/clothing/sets/batch",
|
concurrency: 3,
|
||||||
{
|
},
|
||||||
items: toImport.map((it) => ({
|
);
|
||||||
setType: it.setType,
|
|
||||||
setId: it.setId,
|
|
||||||
})),
|
|
||||||
concurrency: 3,
|
|
||||||
},
|
|
||||||
(label) => {
|
|
||||||
done++;
|
|
||||||
markDone(label);
|
|
||||||
setBatchProgress({ done, total: toImport.length });
|
|
||||||
},
|
|
||||||
(succeeded, failed) => {
|
|
||||||
setSelected(new Set());
|
|
||||||
if (succeeded > 0) toast.success(`${succeeded} sets imported`);
|
|
||||||
if (failed > 0) toast.error(`${failed} failed`);
|
|
||||||
},
|
|
||||||
abort.signal,
|
|
||||||
() => {
|
|
||||||
done++;
|
|
||||||
setBatchProgress({ done, total: toImport.length });
|
|
||||||
},
|
|
||||||
);
|
|
||||||
} catch (err) {
|
|
||||||
if ((err as Error)?.name === "AbortError") {
|
|
||||||
toast.info("Import cancelled");
|
|
||||||
} else {
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
if (batchAbortRef.current === abort) batchAbortRef.current = null;
|
|
||||||
setBatchProgress(null);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function importOne(it: ClothingSetItem) {
|
async function importOne(it: ClothingSetItem) {
|
||||||
@@ -703,7 +634,7 @@ function SetsView() {
|
|||||||
variant="outline"
|
variant="outline"
|
||||||
size="sm"
|
size="sm"
|
||||||
className="text-xs h-8"
|
className="text-xs h-8"
|
||||||
disabled={!!batchProgress}
|
disabled={batch.running}
|
||||||
onClick={() =>
|
onClick={() =>
|
||||||
setSelected((prev) =>
|
setSelected((prev) =>
|
||||||
prev.size === importable.length
|
prev.size === importable.length
|
||||||
@@ -721,9 +652,9 @@ function SetsView() {
|
|||||||
size="sm"
|
size="sm"
|
||||||
className="h-8"
|
className="h-8"
|
||||||
onClick={importSelected}
|
onClick={importSelected}
|
||||||
disabled={!!batchProgress}
|
disabled={batch.running}
|
||||||
>
|
>
|
||||||
{batchProgress ? (
|
{batch.running ? (
|
||||||
<Loader2 className="w-4 h-4 animate-spin mr-1" />
|
<Loader2 className="w-4 h-4 animate-spin mr-1" />
|
||||||
) : (
|
) : (
|
||||||
<Download className="w-4 h-4 mr-1" />
|
<Download className="w-4 h-4 mr-1" />
|
||||||
@@ -731,30 +662,16 @@ function SetsView() {
|
|||||||
Import {selected.size} selected
|
Import {selected.size} selected
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
{batchProgress && (
|
{batch.progress && (
|
||||||
<>
|
<BatchImportProgress
|
||||||
<span className="text-xs text-muted-foreground">
|
progress={batch.progress}
|
||||||
{batchProgress.done}/{batchProgress.total}
|
onCancel={batch.cancel}
|
||||||
</span>
|
/>
|
||||||
<Button
|
|
||||||
size="sm"
|
|
||||||
variant="outline"
|
|
||||||
className="h-8"
|
|
||||||
onClick={() => batchAbortRef.current?.abort()}
|
|
||||||
>
|
|
||||||
Cancel
|
|
||||||
</Button>
|
|
||||||
</>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{error && (
|
{error && <ImportErrorBanner error={error} />}
|
||||||
<div className="rounded-lg border px-4 py-3 text-sm bg-destructive/10 border-destructive/20 text-destructive flex items-center gap-2">
|
|
||||||
<AlertCircle className="w-4 h-4 shrink-0" />
|
|
||||||
{error}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{!loading && items.length === 0 && !error && (
|
{!loading && items.length === 0 && !error && (
|
||||||
<div className="text-center py-12 text-muted-foreground">
|
<div className="text-center py-12 text-muted-foreground">
|
||||||
@@ -834,7 +751,7 @@ function SetsView() {
|
|||||||
size="sm"
|
size="sm"
|
||||||
variant="outline"
|
variant="outline"
|
||||||
className="w-full text-xs h-7"
|
className="w-full text-xs h-7"
|
||||||
disabled={busyKey === key || !!batchProgress}
|
disabled={busyKey === key || batch.running}
|
||||||
onClick={() => importOne(it)}
|
onClick={() => importOne(it)}
|
||||||
>
|
>
|
||||||
{busyKey === key ? (
|
{busyKey === key ? (
|
||||||
|
|||||||
@@ -2,7 +2,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
AlertCircle,
|
|
||||||
Check,
|
Check,
|
||||||
Download,
|
Download,
|
||||||
Loader2,
|
Loader2,
|
||||||
@@ -13,13 +12,17 @@ import {
|
|||||||
Trash2,
|
Trash2,
|
||||||
X,
|
X,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
|
import {
|
||||||
|
BatchImportProgress,
|
||||||
|
useBatchImport,
|
||||||
|
} from "@/components/admin/import/use-batch-import";
|
||||||
|
import { ImportErrorBanner } from "@/components/admin/import-error-banner";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { adminFetch } from "@/lib/admin-fetch";
|
import { adminFetch } from "@/lib/admin-fetch";
|
||||||
import { runSseImport } from "@/lib/sse-client";
|
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
interface EffectItem {
|
interface EffectItem {
|
||||||
@@ -40,12 +43,14 @@ export function ImportEffectsClient() {
|
|||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
const [filter, setFilter] = useState<Filter>("all");
|
const [filter, setFilter] = useState<Filter>("all");
|
||||||
const [selected, setSelected] = useState<Set<string>>(new Set());
|
const [selected, setSelected] = useState<Set<string>>(new Set());
|
||||||
const [batchProgress, setBatchProgress] = useState<{
|
|
||||||
done: number;
|
|
||||||
total: number;
|
|
||||||
} | null>(null);
|
|
||||||
const [busyLib, setBusyLib] = useState<string | null>(null);
|
const [busyLib, setBusyLib] = useState<string | null>(null);
|
||||||
const batchAbortRef = useRef<AbortController | null>(null);
|
const batch = useBatchImport({
|
||||||
|
url: "/api/admin/import/effects/batch",
|
||||||
|
successAction: "effect(s) imported",
|
||||||
|
cancelledMessage: "Import cancelled",
|
||||||
|
onItemDone: (lib) => markDone(lib),
|
||||||
|
onComplete: () => setSelected(new Set()),
|
||||||
|
});
|
||||||
|
|
||||||
const fetchEffects = useCallback(async (search: string) => {
|
const fetchEffects = useCallback(async (search: string) => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
@@ -103,41 +108,10 @@ export function ImportEffectsClient() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function importViaSse(items: EffectItem[]) {
|
async function importViaSse(items: EffectItem[]) {
|
||||||
batchAbortRef.current?.abort();
|
await batch.run(
|
||||||
const abort = new AbortController();
|
items.map((e) => e.lib),
|
||||||
batchAbortRef.current = abort;
|
{ items, concurrency: 3 },
|
||||||
setBatchProgress({ done: 0, total: items.length });
|
);
|
||||||
let done = 0;
|
|
||||||
try {
|
|
||||||
await runSseImport(
|
|
||||||
"/api/admin/import/effects/batch",
|
|
||||||
{ items, concurrency: 3 },
|
|
||||||
(lib) => {
|
|
||||||
done++;
|
|
||||||
markDone(lib);
|
|
||||||
setBatchProgress({ done, total: items.length });
|
|
||||||
},
|
|
||||||
(succeeded, failed) => {
|
|
||||||
setSelected(new Set());
|
|
||||||
if (succeeded > 0) toast.success(`${succeeded} effect(s) imported`);
|
|
||||||
if (failed > 0) toast.error(`${failed} failed`);
|
|
||||||
},
|
|
||||||
abort.signal,
|
|
||||||
() => {
|
|
||||||
done++;
|
|
||||||
setBatchProgress({ done, total: items.length });
|
|
||||||
},
|
|
||||||
);
|
|
||||||
} catch (err) {
|
|
||||||
if ((err as Error)?.name === "AbortError") {
|
|
||||||
toast.info("Import cancelled");
|
|
||||||
} else {
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
if (batchAbortRef.current === abort) batchAbortRef.current = null;
|
|
||||||
setBatchProgress(null);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function importOne(e: EffectItem) {
|
async function importOne(e: EffectItem) {
|
||||||
@@ -267,7 +241,7 @@ export function ImportEffectsClient() {
|
|||||||
variant="outline"
|
variant="outline"
|
||||||
size="sm"
|
size="sm"
|
||||||
className="text-xs h-8"
|
className="text-xs h-8"
|
||||||
disabled={!!batchProgress}
|
disabled={batch.running}
|
||||||
onClick={() =>
|
onClick={() =>
|
||||||
setSelected((prev) =>
|
setSelected((prev) =>
|
||||||
prev.size === importable.length
|
prev.size === importable.length
|
||||||
@@ -285,9 +259,9 @@ export function ImportEffectsClient() {
|
|||||||
size="sm"
|
size="sm"
|
||||||
className="h-8"
|
className="h-8"
|
||||||
onClick={importSelected}
|
onClick={importSelected}
|
||||||
disabled={!!batchProgress}
|
disabled={batch.running}
|
||||||
>
|
>
|
||||||
{batchProgress ? (
|
{batch.running ? (
|
||||||
<Loader2 className="w-4 h-4 animate-spin mr-1" />
|
<Loader2 className="w-4 h-4 animate-spin mr-1" />
|
||||||
) : (
|
) : (
|
||||||
<Download className="w-4 h-4 mr-1" />
|
<Download className="w-4 h-4 mr-1" />
|
||||||
@@ -295,31 +269,17 @@ export function ImportEffectsClient() {
|
|||||||
Import {selected.size} selected
|
Import {selected.size} selected
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
{batchProgress && (
|
{batch.progress && (
|
||||||
<>
|
<BatchImportProgress
|
||||||
<span className="text-xs text-muted-foreground">
|
progress={batch.progress}
|
||||||
{batchProgress.done}/{batchProgress.total}
|
onCancel={batch.cancel}
|
||||||
</span>
|
/>
|
||||||
<Button
|
|
||||||
size="sm"
|
|
||||||
variant="outline"
|
|
||||||
className="h-8"
|
|
||||||
onClick={() => batchAbortRef.current?.abort()}
|
|
||||||
>
|
|
||||||
Cancel
|
|
||||||
</Button>
|
|
||||||
</>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Error */}
|
{/* Error */}
|
||||||
{error && (
|
{error && <ImportErrorBanner error={error} />}
|
||||||
<div className="rounded-lg border px-4 py-3 text-sm bg-destructive/10 border-destructive/20 text-destructive flex items-center gap-2">
|
|
||||||
<AlertCircle className="w-4 h-4 shrink-0" />
|
|
||||||
{error}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Empty */}
|
{/* Empty */}
|
||||||
{!loading && visible.length === 0 && !error && (
|
{!loading && visible.length === 0 && !error && (
|
||||||
@@ -397,7 +357,7 @@ export function ImportEffectsClient() {
|
|||||||
size="sm"
|
size="sm"
|
||||||
className="h-5 w-5 p-0 shrink-0"
|
className="h-5 w-5 p-0 shrink-0"
|
||||||
title="Remove effect"
|
title="Remove effect"
|
||||||
disabled={busyLib === e.lib || !!batchProgress}
|
disabled={busyLib === e.lib || batch.running}
|
||||||
onClick={() => remove(e)}
|
onClick={() => remove(e)}
|
||||||
>
|
>
|
||||||
<Trash2 className="w-3 h-3" />
|
<Trash2 className="w-3 h-3" />
|
||||||
@@ -408,7 +368,7 @@ export function ImportEffectsClient() {
|
|||||||
size="sm"
|
size="sm"
|
||||||
variant="outline"
|
variant="outline"
|
||||||
className="w-full text-xs h-7"
|
className="w-full text-xs h-7"
|
||||||
disabled={busyLib === e.lib || !!batchProgress}
|
disabled={busyLib === e.lib || batch.running}
|
||||||
onClick={() => importOne(e)}
|
onClick={() => importOne(e)}
|
||||||
>
|
>
|
||||||
{busyLib === e.lib ? (
|
{busyLib === e.lib ? (
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
import "./nitro-editor.css";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
Box,
|
Box,
|
||||||
@@ -15,8 +16,10 @@ import {
|
|||||||
Save,
|
Save,
|
||||||
Sparkles,
|
Sparkles,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { useCallback, useEffect, useState } from "react";
|
import { useEffect, useEffectEvent, useState } from "react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
|
import { NitroQualityPanel } from "@/components/admin/studio/nitro-quality-panel";
|
||||||
|
import { NitroScale32Generator } from "@/components/admin/studio/nitro-scale32-generator";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import {
|
import {
|
||||||
@@ -138,6 +141,7 @@ export function NitroEditorDialog({
|
|||||||
const [jsonText, setJsonText] = useState("");
|
const [jsonText, setJsonText] = useState("");
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [saving, setSaving] = useState(false);
|
const [saving, setSaving] = useState(false);
|
||||||
|
const [bundleRevision, setBundleRevision] = useState(0);
|
||||||
const [activeTab, setActiveTab] = useState<string>("visual");
|
const [activeTab, setActiveTab] = useState<string>("visual");
|
||||||
const [flags, setFlags] = useState({
|
const [flags, setFlags] = useState({
|
||||||
canstandon: false,
|
canstandon: false,
|
||||||
@@ -184,52 +188,55 @@ export function NitroEditorDialog({
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const fetchMetadata = useCallback(async () => {
|
const closeAfterLoadError = useEffectEvent(() => onOpenChange(false));
|
||||||
if (!classname) return;
|
useEffect(() => {
|
||||||
|
if (!open || !classname) return;
|
||||||
|
const controller = new AbortController();
|
||||||
|
setActiveTab("visual");
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setJsonError(null);
|
setJsonError(null);
|
||||||
try {
|
setAutoDetectResult(null);
|
||||||
const res = await adminFetch(
|
void (async () => {
|
||||||
`/api/admin/import/furni/nitro-editor?classname=${encodeURIComponent(classname)}`,
|
try {
|
||||||
);
|
const res = await adminFetch(
|
||||||
if (!res.ok) {
|
`/api/admin/import/furni/nitro-editor?classname=${encodeURIComponent(classname)}`,
|
||||||
const err = await res.json().catch(() => ({}));
|
{ signal: controller.signal },
|
||||||
toast.error(err.error || "Failed to load .nitro metadata");
|
);
|
||||||
onOpenChange(false);
|
const data = await res.json();
|
||||||
return;
|
if (controller.signal.aborted) return;
|
||||||
|
if (!res.ok) {
|
||||||
|
toast.error(data.error || "Failed to load .nitro metadata");
|
||||||
|
closeAfterLoadError();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setMetadata(data.metadata);
|
||||||
|
setOriginalMetadata(structuredClone(data.metadata));
|
||||||
|
setJsonText(JSON.stringify(data.metadata, null, 2));
|
||||||
|
setFlags(data.flags);
|
||||||
|
setOriginalFlags({ ...data.flags });
|
||||||
|
} catch {
|
||||||
|
if (!controller.signal.aborted) {
|
||||||
|
toast.error("Network error loading .nitro metadata");
|
||||||
|
closeAfterLoadError();
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
if (!controller.signal.aborted) setLoading(false);
|
||||||
}
|
}
|
||||||
const data = await res.json();
|
})();
|
||||||
setMetadata(data.metadata);
|
return () => controller.abort();
|
||||||
setOriginalMetadata(JSON.parse(JSON.stringify(data.metadata)));
|
}, [open, classname]);
|
||||||
setJsonText(JSON.stringify(data.metadata, null, 2));
|
|
||||||
setFlags(data.flags);
|
|
||||||
setOriginalFlags({ ...data.flags });
|
|
||||||
} catch {
|
|
||||||
toast.error("Network error loading .nitro metadata");
|
|
||||||
onOpenChange(false);
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
}, [classname, onOpenChange]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (open && classname) {
|
|
||||||
setActiveTab("visual");
|
|
||||||
fetchMetadata();
|
|
||||||
}
|
|
||||||
}, [open, classname, fetchMetadata]);
|
|
||||||
|
|
||||||
const handleTabChange = (newTab: string) => {
|
const handleTabChange = (newTab: string) => {
|
||||||
if (activeTab === "json" && newTab === "visual") {
|
if (activeTab === "json" && newTab !== "json") {
|
||||||
try {
|
try {
|
||||||
const parsed = JSON.parse(jsonText);
|
const parsed = JSON.parse(jsonText);
|
||||||
setMetadata(parsed);
|
setMetadata(parsed);
|
||||||
setJsonError(null);
|
setJsonError(null);
|
||||||
} catch {
|
} catch {
|
||||||
toast.error("Invalid JSON — fix it before switching to Visual tab");
|
toast.error("Invalid JSON — fix it before switching tabs");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
} else if (activeTab === "visual" && newTab === "json") {
|
} else if (activeTab !== "json" && newTab === "json") {
|
||||||
setJsonText(JSON.stringify(metadata, null, 2));
|
setJsonText(JSON.stringify(metadata, null, 2));
|
||||||
}
|
}
|
||||||
setActiveTab(newTab);
|
setActiveTab(newTab);
|
||||||
@@ -240,6 +247,7 @@ export function NitroEditorDialog({
|
|||||||
setMetadata(JSON.parse(JSON.stringify(originalMetadata)));
|
setMetadata(JSON.parse(JSON.stringify(originalMetadata)));
|
||||||
setFlags({ ...originalFlags });
|
setFlags({ ...originalFlags });
|
||||||
setJsonText(JSON.stringify(originalMetadata, null, 2));
|
setJsonText(JSON.stringify(originalMetadata, null, 2));
|
||||||
|
setJsonError(null);
|
||||||
toast.info("Reset to original values");
|
toast.info("Reset to original values");
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -334,7 +342,9 @@ export function NitroEditorDialog({
|
|||||||
const hasChanges =
|
const hasChanges =
|
||||||
metadata &&
|
metadata &&
|
||||||
originalMetadata &&
|
originalMetadata &&
|
||||||
(JSON.stringify(metadata) !== JSON.stringify(originalMetadata) ||
|
((activeTab === "json"
|
||||||
|
? jsonText !== JSON.stringify(originalMetadata, null, 2)
|
||||||
|
: JSON.stringify(metadata) !== JSON.stringify(originalMetadata)) ||
|
||||||
JSON.stringify(flags) !== JSON.stringify(originalFlags));
|
JSON.stringify(flags) !== JSON.stringify(originalFlags));
|
||||||
|
|
||||||
// Furni preview URL
|
// Furni preview URL
|
||||||
@@ -344,13 +354,16 @@ export function NitroEditorDialog({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
<DialogContent className="sm:max-w-4xl max-h-[90vh] flex flex-col p-0 gap-0">
|
<DialogContent
|
||||||
|
data-nitro-editor
|
||||||
|
className="sm:max-w-4xl h-[min(840px,92dvh)] max-h-[92dvh] flex flex-col overflow-hidden p-0 gap-0"
|
||||||
|
>
|
||||||
{/* Header with preview */}
|
{/* Header with preview */}
|
||||||
<DialogHeader className="px-6 pt-5 pb-4 border-b bg-muted/30">
|
<DialogHeader className="px-6 pt-5 pb-4 border-b bg-muted/30">
|
||||||
<div className="flex items-start gap-4">
|
<div className="flex items-start gap-4">
|
||||||
{/* Furni preview */}
|
{/* Furni preview */}
|
||||||
<div
|
<div
|
||||||
className="w-20 h-20 rounded-lg border bg-card flex items-center justify-center shrink-0 overflow-hidden"
|
className="w-16 h-16 rounded-lg border bg-card flex items-center justify-center shrink-0 overflow-hidden"
|
||||||
style={{
|
style={{
|
||||||
backgroundImage: "url(/images/furni_floor.png)",
|
backgroundImage: "url(/images/furni_floor.png)",
|
||||||
backgroundRepeat: "repeat",
|
backgroundRepeat: "repeat",
|
||||||
@@ -423,6 +436,7 @@ export function NitroEditorDialog({
|
|||||||
<Box className="w-3.5 h-3.5" />
|
<Box className="w-3.5 h-3.5" />
|
||||||
Visual
|
Visual
|
||||||
</TabsTrigger>
|
</TabsTrigger>
|
||||||
|
<TabsTrigger value="quality">32 / 64</TabsTrigger>
|
||||||
<TabsTrigger value="json" className="gap-1.5">
|
<TabsTrigger value="json" className="gap-1.5">
|
||||||
{"{ }"}
|
{"{ }"}
|
||||||
JSON
|
JSON
|
||||||
@@ -430,72 +444,121 @@ export function NitroEditorDialog({
|
|||||||
</TabsList>
|
</TabsList>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<TabsContent
|
||||||
|
value="quality"
|
||||||
|
className="min-h-0 overflow-y-auto flex-1 px-4 sm:px-6 py-4"
|
||||||
|
>
|
||||||
|
<NitroScale32Generator
|
||||||
|
classname={classname}
|
||||||
|
disabled={hasChanges || saving}
|
||||||
|
onChanged={(updated) => {
|
||||||
|
setBundleRevision((value) => value + 1);
|
||||||
|
setMetadata(updated as NitroMetadata);
|
||||||
|
setOriginalMetadata(
|
||||||
|
structuredClone(updated) as NitroMetadata,
|
||||||
|
);
|
||||||
|
setJsonText(JSON.stringify(updated, null, 2));
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<NitroQualityPanel key={bundleRevision} classname={classname} />
|
||||||
|
</TabsContent>
|
||||||
{/* ── Visual Tab ── */}
|
{/* ── Visual Tab ── */}
|
||||||
<TabsContent
|
<TabsContent
|
||||||
value="visual"
|
value="visual"
|
||||||
className="overflow-y-auto flex-1 px-6 py-4 space-y-5"
|
className="min-h-0 overflow-y-auto flex-1 px-4 sm:px-6 py-4 space-y-4"
|
||||||
>
|
>
|
||||||
{/* Dimensions + Interaction in 2-column layout */}
|
{/* Dimensions + Interaction in 2-column layout */}
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-5">
|
<div className="grid grid-cols-1 md:grid-cols-2 items-start gap-4">
|
||||||
{/* Dimensions card */}
|
<div className="space-y-4">
|
||||||
<section className="rounded-lg border bg-card p-4">
|
{/* Dimensions card */}
|
||||||
<div className="flex items-center gap-2 mb-3">
|
<section className="rounded-lg border bg-card p-4">
|
||||||
<Ruler className="w-4 h-4 text-muted-foreground" />
|
<div className="flex items-center gap-2 mb-3">
|
||||||
<h3 className="text-sm font-medium">Dimensions</h3>
|
<Ruler className="w-4 h-4 text-muted-foreground" />
|
||||||
</div>
|
<h3 className="text-sm font-medium">Dimensions</h3>
|
||||||
<div className="grid grid-cols-3 gap-3">
|
|
||||||
<div>
|
|
||||||
<Label
|
|
||||||
htmlFor="dim-x"
|
|
||||||
className="text-xs text-muted-foreground"
|
|
||||||
>
|
|
||||||
X (width)
|
|
||||||
</Label>
|
|
||||||
<Input
|
|
||||||
id="dim-x"
|
|
||||||
type="number"
|
|
||||||
min={1}
|
|
||||||
value={dims.x}
|
|
||||||
onChange={(e) => setDim("x", e.target.value)}
|
|
||||||
className="mt-1"
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div className="grid grid-cols-3 gap-3">
|
||||||
<Label
|
<div>
|
||||||
htmlFor="dim-y"
|
<Label
|
||||||
className="text-xs text-muted-foreground"
|
htmlFor="dim-x"
|
||||||
>
|
className="text-xs text-muted-foreground"
|
||||||
Y (depth)
|
>
|
||||||
</Label>
|
X (width)
|
||||||
<Input
|
</Label>
|
||||||
id="dim-y"
|
<Input
|
||||||
type="number"
|
id="dim-x"
|
||||||
min={1}
|
type="number"
|
||||||
value={dims.y}
|
min={1}
|
||||||
onChange={(e) => setDim("y", e.target.value)}
|
value={dims.x}
|
||||||
className="mt-1"
|
onChange={(e) => setDim("x", e.target.value)}
|
||||||
/>
|
className="mt-1"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<Label
|
||||||
|
htmlFor="dim-y"
|
||||||
|
className="text-xs text-muted-foreground"
|
||||||
|
>
|
||||||
|
Y (depth)
|
||||||
|
</Label>
|
||||||
|
<Input
|
||||||
|
id="dim-y"
|
||||||
|
type="number"
|
||||||
|
min={1}
|
||||||
|
value={dims.y}
|
||||||
|
onChange={(e) => setDim("y", e.target.value)}
|
||||||
|
className="mt-1"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<Label
|
||||||
|
htmlFor="dim-z"
|
||||||
|
className="text-xs text-muted-foreground"
|
||||||
|
>
|
||||||
|
Z (height)
|
||||||
|
</Label>
|
||||||
|
<Input
|
||||||
|
id="dim-z"
|
||||||
|
type="number"
|
||||||
|
step={0.01}
|
||||||
|
min={0}
|
||||||
|
value={dims.z}
|
||||||
|
onChange={(e) => setDim("z", e.target.value)}
|
||||||
|
className="mt-1"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
</section>
|
||||||
<Label
|
|
||||||
htmlFor="dim-z"
|
|
||||||
className="text-xs text-muted-foreground"
|
|
||||||
>
|
|
||||||
Z (height)
|
|
||||||
</Label>
|
|
||||||
<Input
|
|
||||||
id="dim-z"
|
|
||||||
type="number"
|
|
||||||
step={0.01}
|
|
||||||
min={0}
|
|
||||||
value={dims.z}
|
|
||||||
onChange={(e) => setDim("z", e.target.value)}
|
|
||||||
className="mt-1"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
|
{/* Available rotations */}
|
||||||
|
<section className="rounded-lg border bg-card p-4">
|
||||||
|
<div className="flex items-center gap-2 mb-3">
|
||||||
|
<Compass className="w-4 h-4 text-muted-foreground" />
|
||||||
|
<h3 className="text-sm font-medium">Directions</h3>
|
||||||
|
<span className="ml-auto text-xs text-muted-foreground">
|
||||||
|
{directions.length} / 8 active
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="grid grid-cols-4 gap-2">
|
||||||
|
{ALL_DIRECTIONS.map((dir) => (
|
||||||
|
<button
|
||||||
|
key={dir}
|
||||||
|
type="button"
|
||||||
|
className="nitro-direction"
|
||||||
|
aria-label={`Direction ${dir} (${DIR_LABELS[dir]})`}
|
||||||
|
aria-pressed={directions.includes(dir)}
|
||||||
|
onClick={() => toggleDirection(dir)}
|
||||||
|
>
|
||||||
|
<strong>{DIR_LABELS[dir]}</strong>
|
||||||
|
<span>{dir}</span>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<p className="mt-3 text-xs text-muted-foreground">
|
||||||
|
Choose the available rotations. Keep at least one
|
||||||
|
direction active.
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
{/* Interaction card */}
|
{/* Interaction card */}
|
||||||
<section className="rounded-lg border bg-card p-4">
|
<section className="rounded-lg border bg-card p-4">
|
||||||
<div className="flex items-center gap-2 mb-3">
|
<div className="flex items-center gap-2 mb-3">
|
||||||
@@ -506,6 +569,7 @@ export function NitroEditorDialog({
|
|||||||
<div className="flex items-center justify-between rounded-md border px-3 py-2 hover:bg-muted/50 transition-colors">
|
<div className="flex items-center justify-between rounded-md border px-3 py-2 hover:bg-muted/50 transition-colors">
|
||||||
<span className="text-sm">Can Stand On</span>
|
<span className="text-sm">Can Stand On</span>
|
||||||
<Switch
|
<Switch
|
||||||
|
aria-label="Can Stand On"
|
||||||
checked={flags.canstandon}
|
checked={flags.canstandon}
|
||||||
onCheckedChange={(v) =>
|
onCheckedChange={(v) =>
|
||||||
setFlags((f) => ({ ...f, canstandon: !!v }))
|
setFlags((f) => ({ ...f, canstandon: !!v }))
|
||||||
@@ -515,6 +579,7 @@ export function NitroEditorDialog({
|
|||||||
<div className="flex items-center justify-between rounded-md border px-3 py-2 hover:bg-muted/50 transition-colors">
|
<div className="flex items-center justify-between rounded-md border px-3 py-2 hover:bg-muted/50 transition-colors">
|
||||||
<span className="text-sm">Can Sit On</span>
|
<span className="text-sm">Can Sit On</span>
|
||||||
<Switch
|
<Switch
|
||||||
|
aria-label="Can Sit On"
|
||||||
checked={flags.cansiton}
|
checked={flags.cansiton}
|
||||||
onCheckedChange={(v) =>
|
onCheckedChange={(v) =>
|
||||||
setFlags((f) => ({ ...f, cansiton: !!v }))
|
setFlags((f) => ({ ...f, cansiton: !!v }))
|
||||||
@@ -524,6 +589,7 @@ export function NitroEditorDialog({
|
|||||||
<div className="flex items-center justify-between rounded-md border px-3 py-2 hover:bg-muted/50 transition-colors">
|
<div className="flex items-center justify-between rounded-md border px-3 py-2 hover:bg-muted/50 transition-colors">
|
||||||
<span className="text-sm">Can Lay On</span>
|
<span className="text-sm">Can Lay On</span>
|
||||||
<Switch
|
<Switch
|
||||||
|
aria-label="Can Lay On"
|
||||||
checked={flags.canlayon}
|
checked={flags.canlayon}
|
||||||
onCheckedChange={(v) =>
|
onCheckedChange={(v) =>
|
||||||
setFlags((f) => ({ ...f, canlayon: !!v }))
|
setFlags((f) => ({ ...f, canlayon: !!v }))
|
||||||
@@ -581,58 +647,6 @@ export function NitroEditorDialog({
|
|||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Directions - visual compass */}
|
|
||||||
<section className="rounded-lg border bg-card p-4">
|
|
||||||
<div className="flex items-center gap-2 mb-3">
|
|
||||||
<Compass className="w-4 h-4 text-muted-foreground" />
|
|
||||||
<h3 className="text-sm font-medium">Directions</h3>
|
|
||||||
<span className="text-xs text-muted-foreground ml-auto">
|
|
||||||
{directions.length} active
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center justify-center">
|
|
||||||
<div className="relative w-48 h-48">
|
|
||||||
{/* Compass circle */}
|
|
||||||
<div className="absolute inset-0 rounded-full border-2 border-muted" />
|
|
||||||
<div className="absolute inset-4 rounded-full border border-muted/50" />
|
|
||||||
{/* Direction buttons arranged in circle */}
|
|
||||||
{ALL_DIRECTIONS.map((dir) => {
|
|
||||||
const angle = (dir * 45 - 90) * (Math.PI / 180);
|
|
||||||
const r = 80;
|
|
||||||
const x = 96 + r * Math.cos(angle) - 18;
|
|
||||||
const y = 96 + r * Math.sin(angle) - 18;
|
|
||||||
const isActive = directions.includes(dir);
|
|
||||||
return (
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
key={dir}
|
|
||||||
className={`absolute w-9 h-9 rounded-full border-2 flex flex-col items-center justify-center text-xs font-medium transition-all ${
|
|
||||||
isActive
|
|
||||||
? "bg-primary text-primary-foreground border-primary shadow-md scale-110"
|
|
||||||
: "bg-card text-muted-foreground border-muted hover:border-foreground/30 hover:scale-105"
|
|
||||||
}`}
|
|
||||||
style={{ left: x, top: y }}
|
|
||||||
onClick={() => toggleDirection(dir)}
|
|
||||||
>
|
|
||||||
<span className="text-[9px] leading-none">
|
|
||||||
{DIR_LABELS[dir]}
|
|
||||||
</span>
|
|
||||||
<span className="text-[8px] leading-none opacity-60">
|
|
||||||
{dir}
|
|
||||||
</span>
|
|
||||||
</button>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
{/* Center label */}
|
|
||||||
<div className="absolute inset-0 flex items-center justify-center">
|
|
||||||
<span className="text-xs text-muted-foreground font-medium">
|
|
||||||
{directions.length}/8
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
{/* Types */}
|
{/* Types */}
|
||||||
<section className="rounded-lg border bg-card p-4">
|
<section className="rounded-lg border bg-card p-4">
|
||||||
<div className="flex items-center gap-2 mb-3">
|
<div className="flex items-center gap-2 mb-3">
|
||||||
@@ -858,7 +872,8 @@ export function NitroEditorDialog({
|
|||||||
>
|
>
|
||||||
<div className="relative flex-1 min-h-0">
|
<div className="relative flex-1 min-h-0">
|
||||||
<Textarea
|
<Textarea
|
||||||
className="h-full min-h-[400px] font-mono text-xs resize-none"
|
aria-label="Nitro metadata JSON"
|
||||||
|
className="h-full min-h-0 font-mono text-xs resize-none"
|
||||||
value={jsonText}
|
value={jsonText}
|
||||||
onChange={(e) => handleJsonTextChange(e.target.value)}
|
onChange={(e) => handleJsonTextChange(e.target.value)}
|
||||||
spellCheck={false}
|
spellCheck={false}
|
||||||
@@ -903,7 +918,13 @@ export function NitroEditorDialog({
|
|||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
onClick={handleSave}
|
onClick={handleSave}
|
||||||
disabled={saving || loading || !metadata}
|
disabled={
|
||||||
|
saving ||
|
||||||
|
loading ||
|
||||||
|
!metadata ||
|
||||||
|
!hasChanges ||
|
||||||
|
(activeTab === "json" && !!jsonError)
|
||||||
|
}
|
||||||
className="gap-1.5"
|
className="gap-1.5"
|
||||||
>
|
>
|
||||||
{saving ? (
|
{saving ? (
|
||||||
|
|||||||
@@ -0,0 +1,63 @@
|
|||||||
|
[data-nitro-editor] {
|
||||||
|
color: var(--admin-text);
|
||||||
|
background: var(--admin-surface);
|
||||||
|
border-color: var(--admin-border);
|
||||||
|
}
|
||||||
|
[data-nitro-editor] section,
|
||||||
|
[data-nitro-editor] .border,
|
||||||
|
[data-nitro-editor] .border-b,
|
||||||
|
[data-nitro-editor] .border-t {
|
||||||
|
border-color: var(--admin-border);
|
||||||
|
}
|
||||||
|
[data-nitro-editor] section {
|
||||||
|
background: var(--admin-canvas);
|
||||||
|
}
|
||||||
|
[data-nitro-editor] h3 {
|
||||||
|
font-size: 14px;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
[data-nitro-editor] [data-slot="switch"] {
|
||||||
|
width: 40px;
|
||||||
|
height: 24px;
|
||||||
|
background: var(--admin-border);
|
||||||
|
border: 1px solid var(--admin-text-muted);
|
||||||
|
}
|
||||||
|
[data-nitro-editor] [data-slot="switch"][data-checked] {
|
||||||
|
background: var(--admin-accent);
|
||||||
|
border-color: var(--admin-accent);
|
||||||
|
}
|
||||||
|
[data-nitro-editor] [data-slot="switch-thumb"] {
|
||||||
|
width: 18px;
|
||||||
|
height: 18px;
|
||||||
|
background: var(--admin-text);
|
||||||
|
color: var(--admin-canvas);
|
||||||
|
left: 2px;
|
||||||
|
}
|
||||||
|
[data-nitro-editor] [data-slot="switch-thumb"][data-checked] {
|
||||||
|
left: calc(100% - 20px);
|
||||||
|
}
|
||||||
|
[data-nitro-editor] .nitro-direction {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
gap: 3px;
|
||||||
|
min-height: 52px;
|
||||||
|
border: 1px solid var(--admin-border);
|
||||||
|
border-radius: 8px;
|
||||||
|
background: var(--admin-surface);
|
||||||
|
color: var(--admin-text-muted);
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
[data-nitro-editor] .nitro-direction[aria-pressed="true"] {
|
||||||
|
border-color: var(--admin-accent);
|
||||||
|
background: var(--admin-accent);
|
||||||
|
color: var(--admin-accent-foreground);
|
||||||
|
}
|
||||||
|
[data-nitro-editor] .nitro-direction:focus-visible {
|
||||||
|
outline: 2px solid var(--admin-accent);
|
||||||
|
outline-offset: 3px;
|
||||||
|
}
|
||||||
|
[data-nitro-editor] [data-slot="dialog-footer"] {
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@
|
|||||||
import { AlertCircle, Check, Loader2, Upload } from "lucide-react";
|
import { AlertCircle, Check, Loader2, Upload } from "lucide-react";
|
||||||
import { useRef, useState } from "react";
|
import { useRef, useState } from "react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
|
import { ImportErrorBanner } from "@/components/admin/import-error-banner";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { Label } from "@/components/ui/label";
|
import { Label } from "@/components/ui/label";
|
||||||
@@ -303,12 +304,7 @@ export function UploadFurniClient() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{error && (
|
{error && <ImportErrorBanner error={error} />}
|
||||||
<div className="rounded-lg border px-4 py-3 text-sm bg-destructive/10 border-destructive/20 text-destructive flex items-center gap-2">
|
|
||||||
<AlertCircle className="w-4 h-4 shrink-0" />
|
|
||||||
{error}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="flex gap-3">
|
<div className="flex gap-3">
|
||||||
<Button type="submit" disabled={uploading}>
|
<Button type="submit" disabled={uploading}>
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
AlertCircle,
|
|
||||||
Check,
|
Check,
|
||||||
Download,
|
Download,
|
||||||
Loader2,
|
Loader2,
|
||||||
@@ -11,13 +10,17 @@ import {
|
|||||||
Trash2,
|
Trash2,
|
||||||
X,
|
X,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
|
import {
|
||||||
|
BatchImportProgress,
|
||||||
|
useBatchImport,
|
||||||
|
} from "@/components/admin/import/use-batch-import";
|
||||||
|
import { ImportErrorBanner } from "@/components/admin/import-error-banner";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { adminFetch } from "@/lib/admin-fetch";
|
import { adminFetch } from "@/lib/admin-fetch";
|
||||||
import { runSseImport } from "@/lib/sse-client";
|
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
interface PetItem {
|
interface PetItem {
|
||||||
@@ -46,12 +49,14 @@ export function ImportPetsClient() {
|
|||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
const [selected, setSelected] = useState<Set<string>>(new Set());
|
const [selected, setSelected] = useState<Set<string>>(new Set());
|
||||||
const [batchProgress, setBatchProgress] = useState<{
|
|
||||||
done: number;
|
|
||||||
total: number;
|
|
||||||
} | null>(null);
|
|
||||||
const [busyLib, setBusyLib] = useState<string | null>(null);
|
const [busyLib, setBusyLib] = useState<string | null>(null);
|
||||||
const batchAbortRef = useRef<AbortController | null>(null);
|
const batch = useBatchImport({
|
||||||
|
url: "/api/admin/import/pets/batch",
|
||||||
|
successAction: "pet(s) imported",
|
||||||
|
cancelledMessage: "Import cancelled",
|
||||||
|
onItemDone: (lib) => markDone(lib),
|
||||||
|
onComplete: () => setSelected(new Set()),
|
||||||
|
});
|
||||||
|
|
||||||
const fetchPets = useCallback(async (search: string) => {
|
const fetchPets = useCallback(async (search: string) => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
@@ -100,41 +105,10 @@ export function ImportPetsClient() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function importViaSse(items: PetItem[]) {
|
async function importViaSse(items: PetItem[]) {
|
||||||
batchAbortRef.current?.abort();
|
await batch.run(
|
||||||
const abort = new AbortController();
|
items.map((p) => p.lib),
|
||||||
batchAbortRef.current = abort;
|
{ items, concurrency: 3 },
|
||||||
setBatchProgress({ done: 0, total: items.length });
|
);
|
||||||
let done = 0;
|
|
||||||
try {
|
|
||||||
await runSseImport(
|
|
||||||
"/api/admin/import/pets/batch",
|
|
||||||
{ items, concurrency: 3 },
|
|
||||||
(lib) => {
|
|
||||||
done++;
|
|
||||||
markDone(lib);
|
|
||||||
setBatchProgress({ done, total: items.length });
|
|
||||||
},
|
|
||||||
(succeeded, failed) => {
|
|
||||||
setSelected(new Set());
|
|
||||||
if (succeeded > 0) toast.success(`${succeeded} pet(s) imported`);
|
|
||||||
if (failed > 0) toast.error(`${failed} failed`);
|
|
||||||
},
|
|
||||||
abort.signal,
|
|
||||||
() => {
|
|
||||||
done++;
|
|
||||||
setBatchProgress({ done, total: items.length });
|
|
||||||
},
|
|
||||||
);
|
|
||||||
} catch (err) {
|
|
||||||
if ((err as Error)?.name === "AbortError") {
|
|
||||||
toast.info("Import cancelled");
|
|
||||||
} else {
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
if (batchAbortRef.current === abort) batchAbortRef.current = null;
|
|
||||||
setBatchProgress(null);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function importOne(p: PetItem) {
|
async function importOne(p: PetItem) {
|
||||||
@@ -247,7 +221,7 @@ export function ImportPetsClient() {
|
|||||||
variant="outline"
|
variant="outline"
|
||||||
size="sm"
|
size="sm"
|
||||||
className="text-xs h-8"
|
className="text-xs h-8"
|
||||||
disabled={!!batchProgress}
|
disabled={batch.running}
|
||||||
onClick={() =>
|
onClick={() =>
|
||||||
setSelected((prev) =>
|
setSelected((prev) =>
|
||||||
prev.size === importable.length
|
prev.size === importable.length
|
||||||
@@ -265,9 +239,9 @@ export function ImportPetsClient() {
|
|||||||
size="sm"
|
size="sm"
|
||||||
className="h-8"
|
className="h-8"
|
||||||
onClick={importSelected}
|
onClick={importSelected}
|
||||||
disabled={!!batchProgress}
|
disabled={batch.running}
|
||||||
>
|
>
|
||||||
{batchProgress ? (
|
{batch.running ? (
|
||||||
<Loader2 className="w-4 h-4 animate-spin mr-1" />
|
<Loader2 className="w-4 h-4 animate-spin mr-1" />
|
||||||
) : (
|
) : (
|
||||||
<Download className="w-4 h-4 mr-1" />
|
<Download className="w-4 h-4 mr-1" />
|
||||||
@@ -275,30 +249,16 @@ export function ImportPetsClient() {
|
|||||||
Import {selected.size} selected
|
Import {selected.size} selected
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
{batchProgress && (
|
{batch.progress && (
|
||||||
<>
|
<BatchImportProgress
|
||||||
<span className="text-xs text-muted-foreground">
|
progress={batch.progress}
|
||||||
{batchProgress.done}/{batchProgress.total}
|
onCancel={batch.cancel}
|
||||||
</span>
|
/>
|
||||||
<Button
|
|
||||||
size="sm"
|
|
||||||
variant="outline"
|
|
||||||
className="h-8"
|
|
||||||
onClick={() => batchAbortRef.current?.abort()}
|
|
||||||
>
|
|
||||||
Cancel
|
|
||||||
</Button>
|
|
||||||
</>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{error && (
|
{error && <ImportErrorBanner error={error} />}
|
||||||
<div className="rounded-lg border px-4 py-3 text-sm bg-destructive/10 border-destructive/20 text-destructive flex items-center gap-2">
|
|
||||||
<AlertCircle className="w-4 h-4 shrink-0" />
|
|
||||||
{error}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{!loading && pets.length === 0 && !error && (
|
{!loading && pets.length === 0 && !error && (
|
||||||
<div className="text-center py-12 text-muted-foreground">
|
<div className="text-center py-12 text-muted-foreground">
|
||||||
@@ -356,7 +316,7 @@ export function ImportPetsClient() {
|
|||||||
size="sm"
|
size="sm"
|
||||||
className="h-5 w-5 p-0 shrink-0"
|
className="h-5 w-5 p-0 shrink-0"
|
||||||
title="Remove pet"
|
title="Remove pet"
|
||||||
disabled={busyLib === p.lib || !!batchProgress}
|
disabled={busyLib === p.lib || batch.running}
|
||||||
onClick={() => remove(p)}
|
onClick={() => remove(p)}
|
||||||
>
|
>
|
||||||
<Trash2 className="w-3 h-3" />
|
<Trash2 className="w-3 h-3" />
|
||||||
@@ -367,7 +327,7 @@ export function ImportPetsClient() {
|
|||||||
size="sm"
|
size="sm"
|
||||||
variant="outline"
|
variant="outline"
|
||||||
className="w-full text-xs h-7"
|
className="w-full text-xs h-7"
|
||||||
disabled={busyLib === p.lib || !!batchProgress}
|
disabled={busyLib === p.lib || batch.running}
|
||||||
onClick={() => importOne(p)}
|
onClick={() => importOne(p)}
|
||||||
>
|
>
|
||||||
{busyLib === p.lib ? (
|
{busyLib === p.lib ? (
|
||||||
|
|||||||
@@ -11,14 +11,9 @@ import { LanguageSwitcher } from "@/components/language-switcher";
|
|||||||
import Link from "@/components/link";
|
import Link from "@/components/link";
|
||||||
import { ThemeSwitcher } from "@/components/theme-switcher";
|
import { ThemeSwitcher } from "@/components/theme-switcher";
|
||||||
import { requireStaff } from "@/lib/admin/guard";
|
import { requireStaff } from "@/lib/admin/guard";
|
||||||
import { collectNavPermissionSlugs } from "@/lib/admin-nav";
|
import { loadAdminNavigation } from "@/lib/admin/navigation";
|
||||||
import {
|
|
||||||
ADMIN_NAV_CONFIG_KEY,
|
|
||||||
parseAdminNavConfig,
|
|
||||||
} from "@/lib/admin-nav-config";
|
|
||||||
import { db, User } from "@/lib/db";
|
import { db, User } from "@/lib/db";
|
||||||
import { readCsrfCookieToken } from "@/lib/foundation/security";
|
import { readCsrfCookieToken } from "@/lib/foundation/security";
|
||||||
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
|
|
||||||
import { siteSettings } from "@/lib/services/site-settings";
|
import { siteSettings } from "@/lib/services/site-settings";
|
||||||
|
|
||||||
// Request-time auth, existing CSRF cookie, and optional 2FA gate cannot be
|
// Request-time auth, existing CSRF cookie, and optional 2FA gate cannot be
|
||||||
@@ -31,6 +26,7 @@ export default async function AdminLayout({
|
|||||||
children: ReactNode;
|
children: ReactNode;
|
||||||
}) {
|
}) {
|
||||||
const staff = await requireStaff();
|
const staff = await requireStaff();
|
||||||
|
const navigation = await loadAdminNavigation();
|
||||||
const csrfToken = await readCsrfCookieToken();
|
const csrfToken = await readCsrfCookieToken();
|
||||||
if (await siteSettings.getBool("force_staff_2fa", false)) {
|
if (await siteSettings.getBool("force_staff_2fa", false)) {
|
||||||
const u = await db
|
const u = await db
|
||||||
@@ -49,10 +45,10 @@ export default async function AdminLayout({
|
|||||||
<AdminMobileWrapper sidebar={<Sidebar staff={staff} />}>
|
<AdminMobileWrapper sidebar={<Sidebar staff={staff} />}>
|
||||||
<div
|
<div
|
||||||
data-admin
|
data-admin
|
||||||
className="flex flex-col min-w-0 p-5 lg:p-6 min-h-screen"
|
className="flex flex-col min-w-0 p-5 lg:p-6 min-h-full"
|
||||||
style={{ backgroundColor: "var(--admin-canvas)" }}
|
style={{ backgroundColor: "var(--admin-canvas)" }}
|
||||||
>
|
>
|
||||||
<AdminTopbar staff={staff} />
|
<AdminTopbar staff={staff} navigation={navigation} />
|
||||||
<section className="admin-page flex-1">
|
<section className="admin-page flex-1">
|
||||||
<AdminHubChrome>{children}</AdminHubChrome>
|
<AdminHubChrome>{children}</AdminHubChrome>
|
||||||
</section>
|
</section>
|
||||||
@@ -69,27 +65,8 @@ async function Sidebar({
|
|||||||
}) {
|
}) {
|
||||||
const t = await getTranslations("pages.admin.nav");
|
const t = await getTranslations("pages.admin.nav");
|
||||||
const initial = staff.username.charAt(0).toUpperCase();
|
const initial = staff.username.charAt(0).toUpperCase();
|
||||||
const { permissions } = await getAdminContext();
|
const { allowedPermissions, isSuperAdmin, navConfig } =
|
||||||
const isSuperAdmin = permissions.isSuperAdmin;
|
await loadAdminNavigation();
|
||||||
const hasDashboard = canAccess(
|
|
||||||
permissions,
|
|
||||||
PERMS.ADMIN_DASHBOARD,
|
|
||||||
staff.rank,
|
|
||||||
);
|
|
||||||
// Super-admins see everything. Everyone else sees items their ACL grants.
|
|
||||||
// If they can open the admin panel but ACL is incomplete (common after HK→ACL
|
|
||||||
// migration gaps), still show *.view nav entries so categories do not vanish.
|
|
||||||
const allowedPermissions = isSuperAdmin
|
|
||||||
? []
|
|
||||||
: collectNavPermissionSlugs().filter((slug) => {
|
|
||||||
if (canAccess(permissions, slug, staff.rank)) return true;
|
|
||||||
if (!hasDashboard) return false;
|
|
||||||
return slug.endsWith(".view") || slug === PERMS.ADMIN_DASHBOARD;
|
|
||||||
});
|
|
||||||
|
|
||||||
const navConfig = parseAdminNavConfig(
|
|
||||||
await siteSettings.get(ADMIN_NAV_CONFIG_KEY, ""),
|
|
||||||
);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<aside
|
<aside
|
||||||
|
|||||||
@@ -1,15 +1,5 @@
|
|||||||
export default function AdminLoading() {
|
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||||
return (
|
|
||||||
<div
|
export default function Loading() {
|
||||||
style={{ display: "flex", justifyContent: "center", padding: "4rem 0" }}
|
return <LoadingSpinner accentVar="var(--admin-accent)" />;
|
||||||
>
|
|
||||||
<div
|
|
||||||
className="animate-spin w-8 h-8 border-4 rounded-full"
|
|
||||||
style={{
|
|
||||||
borderColor: "var(--admin-accent)",
|
|
||||||
borderTopColor: "transparent",
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
@@ -9,6 +9,16 @@ type ListParamsInput = {
|
|||||||
defaultPerPage?: number;
|
defaultPerPage?: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
type SqlFragment = ReturnType<typeof sql>;
|
||||||
|
|
||||||
|
type LogListSpec<RawRow, Row> = {
|
||||||
|
select: SqlFragment;
|
||||||
|
from: SqlFragment;
|
||||||
|
searchWhere: (like: string) => SqlFragment;
|
||||||
|
orderBy: SqlFragment;
|
||||||
|
mapRow: (raw: RawRow, index: number, offset: number) => Row;
|
||||||
|
};
|
||||||
|
|
||||||
async function requireLogsView() {
|
async function requireLogsView() {
|
||||||
const { session, permissions } = await getAdminContext();
|
const { session, permissions } = await getAdminContext();
|
||||||
if (!canAccess(permissions, PERMS.LOGS_VIEW, session.user.rank)) {
|
if (!canAccess(permissions, PERMS.LOGS_VIEW, session.user.rank)) {
|
||||||
@@ -26,11 +36,56 @@ function parsePageParams(
|
|||||||
return { search: parsed.search.trim(), page: parsed.page, perPage };
|
return { search: parsed.search.trim(), page: parsed.page, perPage };
|
||||||
}
|
}
|
||||||
|
|
||||||
async function rawRows<T>(query: ReturnType<typeof sql>): Promise<T[]> {
|
async function rawRows<T>(query: SqlFragment): Promise<T[]> {
|
||||||
const [rows] = (await db.execute(query)) as unknown as [T[], unknown];
|
const [rows] = (await db.execute(query)) as unknown as [T[], unknown];
|
||||||
return rows ?? [];
|
return rows ?? [];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shared list loader for the chat / command / trade log tables. The SQL
|
||||||
|
* fragments come from a per-table spec while the request handling, search
|
||||||
|
* branching, count + pagination and row mapping stay in one place.
|
||||||
|
*/
|
||||||
|
async function loadLogList<RawRow, Row>(
|
||||||
|
input: ListParamsInput,
|
||||||
|
spec: LogListSpec<RawRow, Row>,
|
||||||
|
): Promise<{
|
||||||
|
rows: Row[];
|
||||||
|
total: number;
|
||||||
|
page: number;
|
||||||
|
perPage: number;
|
||||||
|
lastPage: number;
|
||||||
|
offset: number;
|
||||||
|
}> {
|
||||||
|
await requireLogsView();
|
||||||
|
|
||||||
|
const rawParams = await input.searchParams;
|
||||||
|
const { search, page, perPage } = parsePageParams(
|
||||||
|
rawParams,
|
||||||
|
input.defaultPerPage ?? 50,
|
||||||
|
);
|
||||||
|
const offset = (page - 1) * perPage;
|
||||||
|
const like = `%${search}%`;
|
||||||
|
const where = search ? sql`WHERE ${spec.searchWhere(like)}` : sql``;
|
||||||
|
|
||||||
|
const [rawRowsResult, countRows] = await Promise.all([
|
||||||
|
rawRows<RawRow>(
|
||||||
|
sql`${spec.select} ${spec.from} ${where} ${spec.orderBy} LIMIT ${perPage} OFFSET ${offset}`,
|
||||||
|
),
|
||||||
|
rawRows<{ count: bigint }>(
|
||||||
|
sql`SELECT COUNT(*) AS count ${spec.from} ${where}`,
|
||||||
|
),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const total = Number(countRows[0]?.count ?? 0);
|
||||||
|
const pagination = calcPagination(total, page, perPage);
|
||||||
|
const rows = rawRowsResult.map((row, index) =>
|
||||||
|
spec.mapRow(row, index, pagination.offset),
|
||||||
|
);
|
||||||
|
|
||||||
|
return { rows, ...pagination };
|
||||||
|
}
|
||||||
|
|
||||||
export type ChatLogListRow = {
|
export type ChatLogListRow = {
|
||||||
id: number;
|
id: number;
|
||||||
username: string;
|
username: string;
|
||||||
@@ -39,17 +94,7 @@ export type ChatLogListRow = {
|
|||||||
roomId: number;
|
roomId: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
export async function loadChatLogList({
|
export function loadChatLogList(input: ListParamsInput) {
|
||||||
searchParams,
|
|
||||||
defaultPerPage = 50,
|
|
||||||
}: ListParamsInput) {
|
|
||||||
await requireLogsView();
|
|
||||||
|
|
||||||
const rawParams = await searchParams;
|
|
||||||
const { search, page, perPage } = parsePageParams(rawParams, defaultPerPage);
|
|
||||||
const offset = (page - 1) * perPage;
|
|
||||||
const like = `%${search}%`;
|
|
||||||
|
|
||||||
type RawRow = {
|
type RawRow = {
|
||||||
roomId: number;
|
roomId: number;
|
||||||
message: string;
|
message: string;
|
||||||
@@ -57,43 +102,20 @@ export async function loadChatLogList({
|
|||||||
username: string | null;
|
username: string | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
const [rawRowsResult, countRows] = search
|
return loadLogList<RawRow, ChatLogListRow>(input, {
|
||||||
? await Promise.all([
|
select: sql`SELECT c.room_id AS roomId, c.message, c.timestamp, u.username AS username`,
|
||||||
rawRows<RawRow>(sql`
|
from: sql`FROM chatlogs_room c LEFT JOIN users u ON u.id = c.user_from_id`,
|
||||||
SELECT c.room_id AS roomId, c.message, c.timestamp, u.username AS username
|
searchWhere: (like) =>
|
||||||
FROM chatlogs_room c
|
sql`c.message LIKE ${like} OR u.username LIKE ${like}`,
|
||||||
LEFT JOIN users u ON u.id = c.user_from_id
|
orderBy: sql`ORDER BY c.timestamp DESC`,
|
||||||
WHERE c.message LIKE ${like} OR u.username LIKE ${like}
|
mapRow: (row, index, offset) => ({
|
||||||
ORDER BY c.timestamp DESC
|
id: offset + index + 1,
|
||||||
LIMIT ${perPage} OFFSET ${offset}`),
|
username: row.username ?? "-",
|
||||||
rawRows<{ count: bigint }>(sql`
|
message: row.message,
|
||||||
SELECT COUNT(*) AS count
|
timestamp: row.timestamp,
|
||||||
FROM chatlogs_room c
|
roomId: row.roomId,
|
||||||
LEFT JOIN users u ON u.id = c.user_from_id
|
}),
|
||||||
WHERE c.message LIKE ${like} OR u.username LIKE ${like}`),
|
});
|
||||||
])
|
|
||||||
: await Promise.all([
|
|
||||||
rawRows<RawRow>(sql`
|
|
||||||
SELECT c.room_id AS roomId, c.message, c.timestamp, u.username AS username
|
|
||||||
FROM chatlogs_room c
|
|
||||||
LEFT JOIN users u ON u.id = c.user_from_id
|
|
||||||
ORDER BY c.timestamp DESC
|
|
||||||
LIMIT ${perPage} OFFSET ${offset}`),
|
|
||||||
rawRows<{ count: bigint }>(sql`
|
|
||||||
SELECT COUNT(*) AS count FROM chatlogs_room`),
|
|
||||||
]);
|
|
||||||
|
|
||||||
const total = Number(countRows[0]?.count ?? 0);
|
|
||||||
const pagination = calcPagination(total, page, perPage);
|
|
||||||
const rows: ChatLogListRow[] = rawRowsResult.map((row, index) => ({
|
|
||||||
id: pagination.offset + index + 1,
|
|
||||||
username: row.username ?? "-",
|
|
||||||
message: row.message,
|
|
||||||
timestamp: row.timestamp,
|
|
||||||
roomId: row.roomId,
|
|
||||||
}));
|
|
||||||
|
|
||||||
return { rows, ...pagination };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export type CommandLogListRow = {
|
export type CommandLogListRow = {
|
||||||
@@ -104,17 +126,7 @@ export type CommandLogListRow = {
|
|||||||
timestamp: number;
|
timestamp: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
export async function loadCommandLogList({
|
export function loadCommandLogList(input: ListParamsInput) {
|
||||||
searchParams,
|
|
||||||
defaultPerPage = 50,
|
|
||||||
}: ListParamsInput) {
|
|
||||||
await requireLogsView();
|
|
||||||
|
|
||||||
const rawParams = await searchParams;
|
|
||||||
const { search, page, perPage } = parsePageParams(rawParams, defaultPerPage);
|
|
||||||
const offset = (page - 1) * perPage;
|
|
||||||
const like = `%${search}%`;
|
|
||||||
|
|
||||||
type RawRow = {
|
type RawRow = {
|
||||||
command: string;
|
command: string;
|
||||||
params: string;
|
params: string;
|
||||||
@@ -122,47 +134,20 @@ export async function loadCommandLogList({
|
|||||||
username: string | null;
|
username: string | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
const [rawRowsResult, countRows] = search
|
return loadLogList<RawRow, CommandLogListRow>(input, {
|
||||||
? await Promise.all([
|
select: sql`SELECT c.command, c.params, c.timestamp, u.username AS username`,
|
||||||
rawRows<RawRow>(sql`
|
from: sql`FROM commandlogs c LEFT JOIN users u ON u.id = c.user_id`,
|
||||||
SELECT c.command, c.params, c.timestamp, u.username AS username
|
searchWhere: (like) =>
|
||||||
FROM commandlogs c
|
sql`c.command LIKE ${like} OR c.params LIKE ${like} OR u.username LIKE ${like}`,
|
||||||
LEFT JOIN users u ON u.id = c.user_id
|
orderBy: sql`ORDER BY c.timestamp DESC`,
|
||||||
WHERE c.command LIKE ${like}
|
mapRow: (row, index, offset) => ({
|
||||||
OR c.params LIKE ${like}
|
id: offset + index + 1,
|
||||||
OR u.username LIKE ${like}
|
username: row.username ?? "-",
|
||||||
ORDER BY c.timestamp DESC
|
command: row.command,
|
||||||
LIMIT ${perPage} OFFSET ${offset}`),
|
params: row.params,
|
||||||
rawRows<{ count: bigint }>(sql`
|
timestamp: row.timestamp,
|
||||||
SELECT COUNT(*) AS count
|
}),
|
||||||
FROM commandlogs c
|
});
|
||||||
LEFT JOIN users u ON u.id = c.user_id
|
|
||||||
WHERE c.command LIKE ${like}
|
|
||||||
OR c.params LIKE ${like}
|
|
||||||
OR u.username LIKE ${like}`),
|
|
||||||
])
|
|
||||||
: await Promise.all([
|
|
||||||
rawRows<RawRow>(sql`
|
|
||||||
SELECT c.command, c.params, c.timestamp, u.username AS username
|
|
||||||
FROM commandlogs c
|
|
||||||
LEFT JOIN users u ON u.id = c.user_id
|
|
||||||
ORDER BY c.timestamp DESC
|
|
||||||
LIMIT ${perPage} OFFSET ${offset}`),
|
|
||||||
rawRows<{ count: bigint }>(sql`
|
|
||||||
SELECT COUNT(*) AS count FROM commandlogs`),
|
|
||||||
]);
|
|
||||||
|
|
||||||
const total = Number(countRows[0]?.count ?? 0);
|
|
||||||
const pagination = calcPagination(total, page, perPage);
|
|
||||||
const rows: CommandLogListRow[] = rawRowsResult.map((row, index) => ({
|
|
||||||
id: pagination.offset + index + 1,
|
|
||||||
username: row.username ?? "-",
|
|
||||||
command: row.command,
|
|
||||||
params: row.params,
|
|
||||||
timestamp: row.timestamp,
|
|
||||||
}));
|
|
||||||
|
|
||||||
return { rows, ...pagination };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export type TradeLogListRow = {
|
export type TradeLogListRow = {
|
||||||
@@ -173,17 +158,7 @@ export type TradeLogListRow = {
|
|||||||
timestamp: number;
|
timestamp: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
export async function loadTradeLogList({
|
export function loadTradeLogList(input: ListParamsInput) {
|
||||||
searchParams,
|
|
||||||
defaultPerPage = 50,
|
|
||||||
}: ListParamsInput) {
|
|
||||||
await requireLogsView();
|
|
||||||
|
|
||||||
const rawParams = await searchParams;
|
|
||||||
const { search, page, perPage } = parsePageParams(rawParams, defaultPerPage);
|
|
||||||
const offset = (page - 1) * perPage;
|
|
||||||
const like = `%${search}%`;
|
|
||||||
|
|
||||||
type RawRow = {
|
type RawRow = {
|
||||||
id: number;
|
id: number;
|
||||||
timestamp: number;
|
timestamp: number;
|
||||||
@@ -191,47 +166,19 @@ export async function loadTradeLogList({
|
|||||||
userTwoName: string | null;
|
userTwoName: string | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
const [rawRowsResult, countRows] = search
|
return loadLogList<RawRow, TradeLogListRow>(input, {
|
||||||
? await Promise.all([
|
select: sql`SELECT t.id, t.timestamp, u1.username AS userOneName, u2.username AS userTwoName`,
|
||||||
rawRows<RawRow>(sql`
|
from: sql`FROM room_trade_log t LEFT JOIN users u1 ON u1.id = t.user_one_id LEFT JOIN users u2 ON u2.id = t.user_two_id`,
|
||||||
SELECT t.id, t.timestamp,
|
searchWhere: (like) =>
|
||||||
u1.username AS userOneName, u2.username AS userTwoName
|
sql`u1.username LIKE ${like} OR u2.username LIKE ${like}`,
|
||||||
FROM room_trade_log t
|
orderBy: sql`ORDER BY t.timestamp DESC`,
|
||||||
LEFT JOIN users u1 ON u1.id = t.user_one_id
|
mapRow: (row) => ({
|
||||||
LEFT JOIN users u2 ON u2.id = t.user_two_id
|
id: row.id,
|
||||||
WHERE u1.username LIKE ${like} OR u2.username LIKE ${like}
|
userOneName: row.userOneName ?? "-",
|
||||||
ORDER BY t.timestamp DESC
|
userTwoName: row.userTwoName ?? "-",
|
||||||
LIMIT ${perPage} OFFSET ${offset}`),
|
// room_trade_log only stores completed trades; no status column exists
|
||||||
rawRows<{ count: bigint }>(sql`
|
status: "completed",
|
||||||
SELECT COUNT(*) AS count
|
timestamp: row.timestamp,
|
||||||
FROM room_trade_log t
|
}),
|
||||||
LEFT JOIN users u1 ON u1.id = t.user_one_id
|
});
|
||||||
LEFT JOIN users u2 ON u2.id = t.user_two_id
|
|
||||||
WHERE u1.username LIKE ${like} OR u2.username LIKE ${like}`),
|
|
||||||
])
|
|
||||||
: await Promise.all([
|
|
||||||
rawRows<RawRow>(sql`
|
|
||||||
SELECT t.id, t.timestamp,
|
|
||||||
u1.username AS userOneName, u2.username AS userTwoName
|
|
||||||
FROM room_trade_log t
|
|
||||||
LEFT JOIN users u1 ON u1.id = t.user_one_id
|
|
||||||
LEFT JOIN users u2 ON u2.id = t.user_two_id
|
|
||||||
ORDER BY t.timestamp DESC
|
|
||||||
LIMIT ${perPage} OFFSET ${offset}`),
|
|
||||||
rawRows<{ count: bigint }>(sql`
|
|
||||||
SELECT COUNT(*) AS count FROM room_trade_log`),
|
|
||||||
]);
|
|
||||||
|
|
||||||
const total = Number(countRows[0]?.count ?? 0);
|
|
||||||
const pagination = calcPagination(total, page, perPage);
|
|
||||||
const rows: TradeLogListRow[] = rawRowsResult.map((row) => ({
|
|
||||||
id: row.id,
|
|
||||||
userOneName: row.userOneName ?? "-",
|
|
||||||
userTwoName: row.userTwoName ?? "-",
|
|
||||||
// room_trade_log only stores completed trades; no status column exists
|
|
||||||
status: "completed",
|
|
||||||
timestamp: row.timestamp,
|
|
||||||
}));
|
|
||||||
|
|
||||||
return { rows, ...pagination };
|
|
||||||
}
|
}
|
||||||
@@ -1,318 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import {
|
|
||||||
ChevronDown,
|
|
||||||
ChevronUp,
|
|
||||||
Eye,
|
|
||||||
EyeOff,
|
|
||||||
RotateCcw,
|
|
||||||
Save,
|
|
||||||
} from "lucide-react";
|
|
||||||
import { useTranslations } from "next-intl";
|
|
||||||
import { useMemo, useState, useTransition } from "react";
|
|
||||||
import { toast } from "sonner";
|
|
||||||
import { saveAdminNavConfig } from "@/actions/admin-nav-menu";
|
|
||||||
import { Button } from "@/components/ui/button";
|
|
||||||
import {
|
|
||||||
ADMIN_NAV_PINNED_HREFS,
|
|
||||||
type AdminNavConfig,
|
|
||||||
} from "@/lib/admin-nav-config";
|
|
||||||
import { cn } from "@/lib/utils";
|
|
||||||
|
|
||||||
export type EditableNavGroup = {
|
|
||||||
labelKey: string;
|
|
||||||
items: { href: string; labelKey: string }[];
|
|
||||||
};
|
|
||||||
|
|
||||||
function moveIndex<T>(arr: T[], from: number, to: number): T[] {
|
|
||||||
if (to < 0 || to >= arr.length || from === to) return arr;
|
|
||||||
const next = [...arr];
|
|
||||||
const [item] = next.splice(from, 1);
|
|
||||||
if (item === undefined) return arr;
|
|
||||||
next.splice(to, 0, item);
|
|
||||||
return next;
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildConfig(
|
|
||||||
groups: EditableNavGroup[],
|
|
||||||
hiddenGroups: Set<string>,
|
|
||||||
hiddenItems: Set<string>,
|
|
||||||
): Required<AdminNavConfig> {
|
|
||||||
return {
|
|
||||||
groupOrder: groups.map((g) => g.labelKey),
|
|
||||||
hiddenGroups: [...hiddenGroups],
|
|
||||||
hiddenItems: [...hiddenItems].filter((h) => !ADMIN_NAV_PINNED_HREFS.has(h)),
|
|
||||||
itemOrder: Object.fromEntries(
|
|
||||||
groups.map((g) => [g.labelKey, g.items.map((i) => i.href)]),
|
|
||||||
),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export function AdminMenuEditor({
|
|
||||||
catalog,
|
|
||||||
initialConfig,
|
|
||||||
canEdit,
|
|
||||||
}: {
|
|
||||||
catalog: EditableNavGroup[];
|
|
||||||
initialConfig: AdminNavConfig;
|
|
||||||
canEdit: boolean;
|
|
||||||
}) {
|
|
||||||
const tNav = useTranslations("pages.admin.nav");
|
|
||||||
const t = useTranslations("pages.admin.menu");
|
|
||||||
const [pending, startTransition] = useTransition();
|
|
||||||
|
|
||||||
const initialGroups = useMemo(() => {
|
|
||||||
const order = initialConfig.groupOrder ?? [];
|
|
||||||
const byKey = new Map(catalog.map((g) => [g.labelKey, g]));
|
|
||||||
const ordered: EditableNavGroup[] = [];
|
|
||||||
const seen = new Set<string>();
|
|
||||||
for (const key of order) {
|
|
||||||
const g = byKey.get(key);
|
|
||||||
if (!g || seen.has(key)) continue;
|
|
||||||
const itemOrder = initialConfig.itemOrder?.[key] ?? [];
|
|
||||||
const itemsByHref = new Map(g.items.map((i) => [i.href, i]));
|
|
||||||
const items = [
|
|
||||||
...itemOrder
|
|
||||||
.map((href) => itemsByHref.get(href))
|
|
||||||
.filter((i): i is NonNullable<typeof i> => Boolean(i)),
|
|
||||||
...g.items.filter((i) => !itemOrder.includes(i.href)),
|
|
||||||
];
|
|
||||||
ordered.push({ labelKey: g.labelKey, items });
|
|
||||||
seen.add(key);
|
|
||||||
}
|
|
||||||
for (const g of catalog) {
|
|
||||||
if (seen.has(g.labelKey)) continue;
|
|
||||||
ordered.push({ ...g, items: [...g.items] });
|
|
||||||
}
|
|
||||||
return ordered;
|
|
||||||
}, [catalog, initialConfig]);
|
|
||||||
|
|
||||||
const [groups, setGroups] = useState(initialGroups);
|
|
||||||
const [hiddenGroups, setHiddenGroups] = useState(
|
|
||||||
() => new Set(initialConfig.hiddenGroups ?? []),
|
|
||||||
);
|
|
||||||
const [hiddenItems, setHiddenItems] = useState(
|
|
||||||
() => new Set(initialConfig.hiddenItems ?? []),
|
|
||||||
);
|
|
||||||
|
|
||||||
function reset() {
|
|
||||||
setGroups(catalog.map((g) => ({ ...g, items: [...g.items] })));
|
|
||||||
setHiddenGroups(new Set());
|
|
||||||
setHiddenItems(new Set());
|
|
||||||
}
|
|
||||||
|
|
||||||
function save() {
|
|
||||||
if (!canEdit) return;
|
|
||||||
const config = buildConfig(groups, hiddenGroups, hiddenItems);
|
|
||||||
startTransition(async () => {
|
|
||||||
const res = await saveAdminNavConfig(config);
|
|
||||||
if (res.ok) {
|
|
||||||
toast.success(t("saved"));
|
|
||||||
} else {
|
|
||||||
toast.error(res.error ?? t("saveFailed"));
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="space-y-4">
|
|
||||||
<div className="flex flex-wrap items-center gap-2">
|
|
||||||
{canEdit ? (
|
|
||||||
<>
|
|
||||||
<Button type="button" onClick={save} disabled={pending}>
|
|
||||||
<Save className="h-4 w-4" />
|
|
||||||
{pending ? t("saving") : t("save")}
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
type="button"
|
|
||||||
variant="outline"
|
|
||||||
onClick={reset}
|
|
||||||
disabled={pending}
|
|
||||||
>
|
|
||||||
<RotateCcw className="h-4 w-4" />
|
|
||||||
{t("reset")}
|
|
||||||
</Button>
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<p className="text-sm text-muted-foreground">{t("viewOnly")}</p>
|
|
||||||
)}
|
|
||||||
<p className="text-sm text-muted-foreground w-full sm:w-auto sm:ml-auto">
|
|
||||||
{t("hint")}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-3">
|
|
||||||
{groups.map((group, gi) => {
|
|
||||||
const groupHidden = hiddenGroups.has(group.labelKey);
|
|
||||||
return (
|
|
||||||
<section
|
|
||||||
key={group.labelKey}
|
|
||||||
className={cn(
|
|
||||||
"rounded-lg border border-[var(--admin-border)] bg-[var(--admin-surface)] p-3",
|
|
||||||
groupHidden && "opacity-55",
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<div className="flex flex-wrap items-center gap-2 mb-2">
|
|
||||||
<span className="font-semibold text-sm uppercase tracking-wide flex-1 min-w-0">
|
|
||||||
{tNav(group.labelKey)}
|
|
||||||
</span>
|
|
||||||
{canEdit && (
|
|
||||||
<>
|
|
||||||
<Button
|
|
||||||
type="button"
|
|
||||||
size="icon"
|
|
||||||
variant="ghost"
|
|
||||||
disabled={gi === 0}
|
|
||||||
aria-label={t("moveUp")}
|
|
||||||
onClick={() =>
|
|
||||||
setGroups((prev) => moveIndex(prev, gi, gi - 1))
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<ChevronUp className="h-4 w-4" />
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
type="button"
|
|
||||||
size="icon"
|
|
||||||
variant="ghost"
|
|
||||||
disabled={gi === groups.length - 1}
|
|
||||||
aria-label={t("moveDown")}
|
|
||||||
onClick={() =>
|
|
||||||
setGroups((prev) => moveIndex(prev, gi, gi + 1))
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<ChevronDown className="h-4 w-4" />
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
type="button"
|
|
||||||
size="icon"
|
|
||||||
variant="ghost"
|
|
||||||
aria-label={groupHidden ? t("showGroup") : t("hideGroup")}
|
|
||||||
onClick={() =>
|
|
||||||
setHiddenGroups((prev) => {
|
|
||||||
const next = new Set(prev);
|
|
||||||
if (next.has(group.labelKey))
|
|
||||||
next.delete(group.labelKey);
|
|
||||||
else next.add(group.labelKey);
|
|
||||||
return next;
|
|
||||||
})
|
|
||||||
}
|
|
||||||
>
|
|
||||||
{groupHidden ? (
|
|
||||||
<EyeOff className="h-4 w-4" />
|
|
||||||
) : (
|
|
||||||
<Eye className="h-4 w-4" />
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<ul className="space-y-1">
|
|
||||||
{group.items.map((item, ii) => {
|
|
||||||
const pinned = ADMIN_NAV_PINNED_HREFS.has(item.href);
|
|
||||||
const itemHidden = !pinned && hiddenItems.has(item.href);
|
|
||||||
return (
|
|
||||||
<li
|
|
||||||
key={item.href}
|
|
||||||
className={cn(
|
|
||||||
"flex flex-wrap items-center gap-2 rounded-md px-2 py-1.5 text-sm",
|
|
||||||
"bg-[var(--admin-canvas)]/60",
|
|
||||||
itemHidden && "opacity-50",
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<span className="flex-1 min-w-0 truncate">
|
|
||||||
{tNav(item.labelKey)}
|
|
||||||
<span className="ml-2 text-xs text-muted-foreground font-mono">
|
|
||||||
{item.href}
|
|
||||||
</span>
|
|
||||||
{pinned && (
|
|
||||||
<span className="ml-2 text-[0.65rem] uppercase tracking-wide text-muted-foreground">
|
|
||||||
{t("pinned")}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</span>
|
|
||||||
{canEdit && (
|
|
||||||
<>
|
|
||||||
<Button
|
|
||||||
type="button"
|
|
||||||
size="icon"
|
|
||||||
variant="ghost"
|
|
||||||
disabled={ii === 0}
|
|
||||||
aria-label={t("moveUp")}
|
|
||||||
onClick={() =>
|
|
||||||
setGroups((prev) =>
|
|
||||||
prev.map((g, idx) =>
|
|
||||||
idx === gi
|
|
||||||
? {
|
|
||||||
...g,
|
|
||||||
items: moveIndex(g.items, ii, ii - 1),
|
|
||||||
}
|
|
||||||
: g,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<ChevronUp className="h-4 w-4" />
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
type="button"
|
|
||||||
size="icon"
|
|
||||||
variant="ghost"
|
|
||||||
disabled={ii === group.items.length - 1}
|
|
||||||
aria-label={t("moveDown")}
|
|
||||||
onClick={() =>
|
|
||||||
setGroups((prev) =>
|
|
||||||
prev.map((g, idx) =>
|
|
||||||
idx === gi
|
|
||||||
? {
|
|
||||||
...g,
|
|
||||||
items: moveIndex(g.items, ii, ii + 1),
|
|
||||||
}
|
|
||||||
: g,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<ChevronDown className="h-4 w-4" />
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
type="button"
|
|
||||||
size="icon"
|
|
||||||
variant="ghost"
|
|
||||||
disabled={pinned}
|
|
||||||
aria-label={
|
|
||||||
itemHidden ? t("showItem") : t("hideItem")
|
|
||||||
}
|
|
||||||
onClick={() => {
|
|
||||||
if (pinned) return;
|
|
||||||
setHiddenItems((prev) => {
|
|
||||||
const next = new Set(prev);
|
|
||||||
if (next.has(item.href)) next.delete(item.href);
|
|
||||||
else next.add(item.href);
|
|
||||||
return next;
|
|
||||||
});
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{itemHidden || pinned ? (
|
|
||||||
itemHidden ? (
|
|
||||||
<EyeOff className="h-4 w-4" />
|
|
||||||
) : (
|
|
||||||
<Eye className="h-4 w-4 opacity-40" />
|
|
||||||
)
|
|
||||||
) : (
|
|
||||||
<Eye className="h-4 w-4" />
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</li>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</ul>
|
|
||||||
</section>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,49 +0,0 @@
|
|||||||
import { ListOrdered } from "lucide-react";
|
|
||||||
import { redirect } from "next/navigation";
|
|
||||||
import { getTranslations } from "next-intl/server";
|
|
||||||
import { AdminPageShell } from "@/components/admin/admin-page-shell";
|
|
||||||
import { ADMIN_NAV_GROUPS } from "@/lib/admin-nav";
|
|
||||||
import {
|
|
||||||
ADMIN_NAV_CONFIG_KEY,
|
|
||||||
parseAdminNavConfig,
|
|
||||||
} from "@/lib/admin-nav-config";
|
|
||||||
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
|
|
||||||
import { siteSettings } from "@/lib/services/site-settings";
|
|
||||||
import { AdminMenuEditor } from "./admin-menu-editor";
|
|
||||||
|
|
||||||
export const metadata = { title: "Admin menu" };
|
|
||||||
|
|
||||||
export default async function AdminMenuPage() {
|
|
||||||
const { session, permissions } = await getAdminContext();
|
|
||||||
if (!canAccess(permissions, PERMS.SETTINGS_VIEW, session.user.rank)) {
|
|
||||||
redirect("/admin");
|
|
||||||
}
|
|
||||||
const canEdit = canAccess(
|
|
||||||
permissions,
|
|
||||||
PERMS.SETTINGS_EDIT,
|
|
||||||
session.user.rank,
|
|
||||||
);
|
|
||||||
const t = await getTranslations("pages.admin.menu");
|
|
||||||
|
|
||||||
const catalog = ADMIN_NAV_GROUPS.map((g) => ({
|
|
||||||
labelKey: g.labelKey,
|
|
||||||
items: g.items.map((i) => ({ href: i.href, labelKey: i.labelKey })),
|
|
||||||
}));
|
|
||||||
const initialConfig = parseAdminNavConfig(
|
|
||||||
await siteSettings.get(ADMIN_NAV_CONFIG_KEY, ""),
|
|
||||||
);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<AdminPageShell
|
|
||||||
icon={ListOrdered}
|
|
||||||
title={t("title")}
|
|
||||||
subtitle={t("subtitle")}
|
|
||||||
>
|
|
||||||
<AdminMenuEditor
|
|
||||||
catalog={catalog}
|
|
||||||
initialConfig={initialConfig}
|
|
||||||
canEdit={canEdit}
|
|
||||||
/>
|
|
||||||
</AdminPageShell>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -34,6 +34,7 @@ import {
|
|||||||
} from "@/components/ui/select";
|
} from "@/components/ui/select";
|
||||||
import { Textarea } from "@/components/ui/textarea";
|
import { Textarea } from "@/components/ui/textarea";
|
||||||
import { useServerAction } from "@/hooks/use-server-action";
|
import { useServerAction } from "@/hooks/use-server-action";
|
||||||
|
import { formatDate } from "@/lib/format-date";
|
||||||
|
|
||||||
const CFH_STATES: Record<number, { label: string; class: string }> = {
|
const CFH_STATES: Record<number, { label: string; class: string }> = {
|
||||||
0: {
|
0: {
|
||||||
@@ -130,7 +131,7 @@ export function CfhDetail({
|
|||||||
</div>
|
</div>
|
||||||
<h1 className="text-xl font-bold">Call For Help Report</h1>
|
<h1 className="text-xl font-bold">Call For Help Report</h1>
|
||||||
<p className="text-xs text-muted-foreground">
|
<p className="text-xs text-muted-foreground">
|
||||||
{new Date(ticket.timestamp * 1000).toLocaleString()} · Room #
|
{formatDate(new Date(ticket.timestamp * 1000))} · Room #
|
||||||
{ticket.roomId}
|
{ticket.roomId}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
@@ -317,7 +318,7 @@ export function CfhDetail({
|
|||||||
<p className="font-medium">{ban.reason || "No reason"}</p>
|
<p className="font-medium">{ban.reason || "No reason"}</p>
|
||||||
<p className="text-muted-foreground">
|
<p className="text-muted-foreground">
|
||||||
{ban.type} · by {ban.staff} ·{" "}
|
{ban.type} · by {ban.staff} ·{" "}
|
||||||
{new Date(ban.timestamp * 1000).toLocaleDateString()}
|
{formatDate(new Date(ban.timestamp * 1000), "date")}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
@@ -431,9 +432,7 @@ export function CfhDetail({
|
|||||||
<CardContent className="space-y-2 text-xs text-muted-foreground">
|
<CardContent className="space-y-2 text-xs text-muted-foreground">
|
||||||
<div className="flex justify-between">
|
<div className="flex justify-between">
|
||||||
<span>Created</span>
|
<span>Created</span>
|
||||||
<span>
|
<span>{formatDate(new Date(ticket.timestamp * 1000))}</span>
|
||||||
{new Date(ticket.timestamp * 1000).toLocaleString()}
|
|
||||||
</span>
|
|
||||||
</div>
|
</div>
|
||||||
<div className="flex justify-between">
|
<div className="flex justify-between">
|
||||||
<span>Room</span>
|
<span>Room</span>
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import {
|
|||||||
User,
|
User,
|
||||||
WebsiteTicket,
|
WebsiteTicket,
|
||||||
} from "@/lib/db";
|
} from "@/lib/db";
|
||||||
|
import { formatDate } from "@/lib/format-date";
|
||||||
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
|
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
|
||||||
|
|
||||||
export default async function ModTeamPage() {
|
export default async function ModTeamPage() {
|
||||||
@@ -169,7 +170,7 @@ export default async function ModTeamPage() {
|
|||||||
{member.online === "1"
|
{member.online === "1"
|
||||||
? "Online"
|
? "Online"
|
||||||
: member.lastOnline
|
: member.lastOnline
|
||||||
? new Date(member.lastOnline * 1000).toLocaleDateString()
|
? formatDate(new Date(member.lastOnline * 1000), "date")
|
||||||
: "—"}
|
: "—"}
|
||||||
</span>
|
</span>
|
||||||
</Link>
|
</Link>
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { useCallback, useEffect, useState } from "react";
|
|||||||
import { DataTable } from "@/components/admin/data-table";
|
import { DataTable } from "@/components/admin/data-table";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { formatDate } from "@/lib/format-date";
|
||||||
import { getAvatarUrl } from "@/lib/imager";
|
import { getAvatarUrl } from "@/lib/imager";
|
||||||
import type { DataTableColumn, PaginatedResult } from "@/types/common";
|
import type { DataTableColumn, PaginatedResult } from "@/types/common";
|
||||||
|
|
||||||
@@ -123,7 +124,7 @@ export function OnlineTable({ data }: OnlineTableProps) {
|
|||||||
</Badge>
|
</Badge>
|
||||||
)}
|
)}
|
||||||
<span className="text-xs text-muted-foreground ml-auto">
|
<span className="text-xs text-muted-foreground ml-auto">
|
||||||
Last updated: {lastUpdated.toLocaleTimeString()}
|
Last updated: {formatDate(lastUpdated, "time")}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import {
|
|||||||
Users,
|
Users,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { getTranslations } from "next-intl/server";
|
import { getTranslations } from "next-intl/server";
|
||||||
|
import { AdminWorkQueue } from "@/components/admin/admin-work-queue";
|
||||||
import { StatusCard } from "@/components/admin/dashboard";
|
import { StatusCard } from "@/components/admin/dashboard";
|
||||||
import Link from "@/components/link";
|
import Link from "@/components/link";
|
||||||
import { unixNow } from "@/lib/bans";
|
import { unixNow } from "@/lib/bans";
|
||||||
@@ -126,6 +127,7 @@ export default async function AdminDashboard() {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<AdminWorkQueue />
|
||||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||||
<section className="admin-card p-5">
|
<section className="admin-card p-5">
|
||||||
<h2 className="text-sm font-bold text-[var(--admin-text)] mb-4 admin-section-title">
|
<h2 className="text-sm font-bold text-[var(--admin-text)] mb-4 admin-section-title">
|
||||||
|
|||||||
Loaded 100 of 422 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user