Compare commits

..

9 Commits

Author SHA1 Message Date
orangecoding
3249881771 ability to restore (soft deleted) listings 2026-06-11 08:24:26 +02:00
orangecoding
3b727ea708 next release version 2026-06-10 17:11:49 +02:00
orangecoding
a2a765f43d new usersetting to blacklist (filter) also on description 2026-06-10 17:10:39 +02:00
Michel
c17a815263 fix: use absolute vite base so SPA deep links don't white-screen (#336)
With base '' the built index.html references assets relatively
(./assets/*). On deep links like /listings/listing/:id the browser
resolves those below the route path, the SPA fallback answers with
index.html and the page dies trying to execute HTML as a JS module.
Notification emails link directly to listing details, so every
'Open in fredy' link landed on a white screen.
2026-06-10 16:44:39 +02:00
Michel
7a2dacaa61 fix(immoscout): map exclusioncriteria swapflat to mobile API value swap_flat (#332)
The web UI encodes the 'no swap flats' filter as exclusioncriteria=swapflat,
but the mobile API only accepts swap_flat. Unknown values are not ignored by
the API - the whole search silently returns 0 results, so any saved search
with this filter never finds a single listing.

Map the value during web-to-mobile conversion and leave all other
exclusioncriteria values (e.g. projectlisting, which both APIs share)
untouched.
2026-06-10 16:43:12 +02:00
Michel
359e00e69f fix: use hash-router URL format for listing links in email adapters (#335)
The UI is served through a HashRouter, and most adapters (telegram,
slack, discord, ntfy, ...) already link to ${baseUrl}/#/listings/listing/:id.
The email adapters (resend, smtp, mailJet, sendGrid) and the http adapter
were missing the /# - the router never saw the route and dumped the user
on the default overview instead of the listing.
2026-06-10 16:38:36 +02:00
orangecoding
bc9c56a224 storing last run in database 2026-06-09 16:52:37 +02:00
orangecoding
6bef907416 adding ability to record logs for debug purposes 2026-06-09 15:42:25 +02:00
AdriDevelopsThings
6c7d655277 added redirect after login (#325)
The old behaviour was: You open a page without being authorized, you are getting redirected to /login that
redirects you after a successful authentication to /dashboard. This is really annoying if you want to open
listenings directly from your notification adapter for example. This commit introduces a method to redirect
you back to the original page you opened after the authentication process by adding the navigation of the
opened page as state to the navigation to /login. The login component than unpacks the state that contains
the old navigation and redirects the user back to path from the original navigation. The path /dashboard is
used as a fallback if no navigation in the state is present.
2026-06-09 11:59:18 +02:00
54 changed files with 3368 additions and 249 deletions

View File

@@ -5,6 +5,40 @@ labels: [bug]
assignees: []
body:
- type: markdown
attributes:
value: |
## Please attach a debug bundle (available since Fredy 22.5.0+)
Since **Fredy 22.5.0** you can export a debug bundle that contains a system
snapshot (`sys.txt`, Fredy version, Node.js version, OS, Docker detection,
CPU, memory, sanitized settings) and the full log buffer (`logs.txt`) that
Fredy recorded while you reproduced the issue. Attaching it dramatically
speeds up triage.
Oh and before you ask: I decided against simply putting all logs into the debug
due to privacy reasons :)
**The bundle is only useful when the error is actually inside `logs.txt`.**
That means you have to record first, reproduce after:
1. Log in to Fredy as **admin** and open **Settings → Debug**.
2. Click **"Enable debug logging" / "Debug-Logging aktivieren"**. A red banner
appears across the whole app while recording is on.
3. **Now reproduce the bug.** Trigger the broken job, click the failing
button, wait for the failing scrape — whatever it was.
4. Come back to **Settings → Debug** and confirm the progress bar moved
(i.e. log entries were actually written). If it stayed at 0%, nothing was
captured and the bundle won't help us.
5. Click **"Download debug information" / "Debug Informationen herunterladen"**
and drop the resulting `FredyDebug-*.zip` into the "Screenshots / Logs"
field below.
6. Optional but recommended: click **"Disable debug logging"** to stop the
recording, and **"Delete stored debug logs"** once you have the zip so the
database does not keep them around.
On Fredy versions older than 22.5.0, paste the relevant log lines from your
console / Docker / systemd journal manually instead.
- type: textarea
id: description
attributes:
@@ -49,8 +83,11 @@ body:
id: screenshots
attributes:
label: Screenshots / Logs
description: Add screenshots or paste log output to help explain the problem.
placeholder: "Drag and drop screenshots here, or paste logs."
description: |
Drop the FredyDebug-*.zip here (see the instructions at the top, available
since Fredy 22.5.0) and/or any additional screenshots. If you cannot produce
the bundle, paste relevant log lines instead.
placeholder: "Drag and drop the FredyDebug-*.zip and any screenshots here."
validations:
required: false
@@ -58,8 +95,10 @@ body:
id: environment
attributes:
label: Environment
description: Provide details about your environment.
placeholder: "OS: macOS 15, Browser: Chrome 124, App version: 1.2.3"
description: |
Provide details about your environment. You can copy most of this from
sys.txt inside the debug bundle.
placeholder: "OS: macOS 15, Browser: Chrome 124, App version: 22.5.0, Docker: yes"
validations:
required: true

1
.gitignore vendored
View File

@@ -7,3 +7,4 @@ npm-debug.log
.idea
.vscode
tools/release/config.json
.agents

View File

@@ -210,6 +210,50 @@ The data includes: names of active adapters/providers, OS, architecture, Node ve
**Thanks**🤘
## 🐞 Debug Information
Since Fredy **22.5.0** there is a built-in way to capture everything Fredy logs into the
database for a limited time and download it as a single zip file. This is the recommended
way to attach diagnostics to a bug report. I decided against simply putting all logs into
a debug bundle due to privacy reasons!
**How it works**
- Debug logging is **opt-in** and admin-only. As long as it is off, Fredy behaves exactly
as before (console output only, nothing in the DB).
- When you turn it on, every log line (`debug`, `info`, `warn`, `error`) is additionally
written into the `debug_logs` SQLite table. The console keeps logging at its usual level.
- The recorded data is hard-capped at **5 MiB** via a rolling buffer: once the cap is hit,
the oldest entries are dropped automatically so the newest ones always survive.
- The on/off flag is persisted, so debug logging stays on across restarts (and you'll see
the warning banner everywhere until you turn it off again).
**Capturing a debug bundle**
1. Open Fredy as an **admin** and go to **Settings → Debug**.
2. Click **"Enable debug logging" / "Debug-Logging aktivieren"**. A red banner appears on
every page while recording is on.
3. **Reproduce the bug**.
4. Come back to **Settings → Debug** and check the progress bar, if it stayed at 0 %,
nothing was captured.
5. Click **"Download debug information" / "Debug Informationen herunterladen"**. You get a
zip named `YYYY-MM-DD-FredyDebug-<version>.zip` containing two files:
- `logs.txt` - every log line captured while recording was on, prefixed with timestamp
and level.
- `sys.txt` - runtime snapshot (Fredy version, Node.js version, OS, Docker detection,
CPU, memory, sanitized settings). Proxy credentials and session secrets are
**stripped** before export.
6. Attach the zip to the bug report.
7. Optional but recommended: click **"Disable debug logging"** to stop recording, and
**"Delete stored debug logs"** once you've sent the zip so the DB does not keep them
around.
**What is _not_ included**
- passwords/privacy relevant things
- Anything that Fredy itself does not pass through its `logger`. If a third-party library
writes directly to `process.stderr`, that output stays on the console only.
## 🛠️ Development
### Development Mode

View File

@@ -10,6 +10,7 @@ import { runMigrations } from './lib/services/storage/migrations/migrate.js';
import { ensureDemoUserExists, ensureAdminUserExists } from './lib/services/storage/userStorage.js';
import { initTrackerCron } from './lib/services/crons/tracker-cron.js';
import logger from './lib/services/logger.js';
import { reloadEnabledFromSettings } from './lib/services/debug/debugLogStorage.js';
import { initActiveCheckerCron } from './lib/services/crons/listing-alive-cron.js';
import { initGeocodingCron } from './lib/services/crons/geocoding-cron.js';
import { getSettings } from './lib/services/storage/settingsStorage.js';
@@ -42,6 +43,12 @@ await runMigrations();
const settings = await getSettings();
// Restore the persisted on/off flag for opt-in DB log capture so it survives a
// Fredy restart. reloadEnabledFromSettings() also (un)wires the logger sink based
// on the restored flag, so the logger hot path stays cost-free when nobody enabled
// the feature.
await reloadEnabledFromSettings();
// Ensure the sqlite directory exists before loading anything else (based on config.sqlitepath)
const { dir: sqliteDir } = await computeDbPath();
if (!fs.existsSync(sqliteDir)) {

View File

@@ -38,11 +38,15 @@ import { formatListing } from './utils/formatListing.js';
* 3) Normalize listings to the provider schema
* 4) Filter out incomplete/blacklisted listings
* 5) Identify new listings (vs. previously stored hashes)
* 6) Persist new listings
* 7) Filter out entries similar to already seen ones
* 8) Filter out entries that do not match the job's specFilter
* 9) Filter out entries that do not match the job's spatialFilter
* 10) Dispatch notifications
* 6) Optionally enrich new listings via provider.fetchDetails
* 7) Optionally re-apply the provider blacklist using the (now enriched)
* description — only when the user opted in via
* `blacklist_filter_on_provider_details`
* 8) Persist new listings
* 9) Filter out entries similar to already seen ones
* 10) Filter out entries that do not match the job's specFilter
* 11) Filter out entries that do not match the job's spatialFilter
* 12) Dispatch notifications
*/
class FredyPipelineExecutioner {
/**
@@ -86,6 +90,7 @@ class FredyPipelineExecutioner {
.then(this._filter.bind(this))
.then(this._findNew.bind(this))
.then(this._fetchDetails.bind(this))
.then(this._filterAfterDetails.bind(this))
.then(this._geocode.bind(this))
.then(this._save.bind(this))
.then(this._calculateDistance.bind(this))
@@ -266,6 +271,48 @@ class FredyPipelineExecutioner {
);
}
/**
* Re-apply the provider's blacklist filter after `_fetchDetails` has had a
* chance to enrich the listings (e.g., load the full description from the
* detail page). The initial `_filter` step only sees the truncated snippet
* exposed on the search results page, so a blacklisted term that lives
* deeper in the listing's full description would otherwise slip through.
*
* Opt-in: gated by the user setting `blacklist_filter_on_provider_details`.
* The full detail description tends to contain a lot of boilerplate (legal,
* exposé contact info, generic marketing copy) which can accidentally match
* a blacklist term and remove otherwise relevant listings. Users who want
* the stricter behavior must enable the setting explicitly.
*
* Throws {@link NoNewListingsWarning} when all listings are filtered out
* so the rest of the pipeline (save + notify) is short-circuited.
*
* @param {ParsedListing[]} listings Enriched listings to re-filter.
* @returns {ParsedListing[]} Listings that still pass the provider's filter.
* @throws {NoNewListingsWarning} When every listing is filtered out.
*/
_filterAfterDetails(listings) {
if (typeof this._providerConfig.filter !== 'function') {
return listings;
}
const userId = getJob(this._jobKey)?.userId;
const enabled = getUserSettings(userId)?.blacklist_filter_on_provider_details === true;
if (!enabled) {
return listings;
}
const kept = listings.filter(this._providerConfig.filter);
const removed = listings.length - kept.length;
if (removed > 0) {
logger.debug(
`Re-filter after detail enrichment removed ${removed} listing(s) by blacklist (Provider: '${this._providerId}')`,
);
}
if (kept.length === 0) {
throw new NoNewListingsWarning();
}
return kept;
}
/**
* Determine which listings are new by comparing their IDs against stored hashes.
*

View File

@@ -24,6 +24,7 @@ import userSettingsPlugin from './routes/userSettingsRoute.js';
import trackingPlugin from './routes/trackingRoute.js';
import generalSettingsPlugin from './routes/generalSettingsRoute.js';
import backupPlugin from './routes/backupRouter.js';
import debugPlugin, { registerDebugPublicProbe } from './routes/debugRouter.js';
import userPlugin from './routes/userRoute.js';
import notificationAdapterPlugin from './routes/notificationAdapterRouter.js';
import providerPlugin from './routes/providerRouter.js';
@@ -77,6 +78,16 @@ fastify.register(async (app) => {
app.register(userSettingsPlugin, { prefix: '/api/user/settings' });
app.register(trackingPlugin, { prefix: '/api/tracking' });
app.register(generalSettingsPlugin, { prefix: '/api/admin/generalSettings' });
// The lightweight /api/debug/active probe used by the app-wide red banner. Lives
// here (under authHook, NOT adminHook) so non-admin users also see the warning
// banner when an admin has enabled the feature, without exposing the rest of the
// settings payload.
app.register(
async (sub) => {
registerDebugPublicProbe(sub);
},
{ prefix: '/api/debug' },
);
});
// Admin-only routes
@@ -84,6 +95,7 @@ fastify.register(async (app) => {
app.addHook('preHandler', authHook);
app.addHook('preHandler', adminHook);
app.register(backupPlugin, { prefix: '/api/admin/backup' });
app.register(debugPlugin, { prefix: '/api/admin/debug' });
app.register(userPlugin, { prefix: '/api/admin/users' });
});

View File

@@ -20,6 +20,28 @@ function cap(val) {
return String(val).charAt(0).toUpperCase() + String(val).slice(1);
}
/**
* Compute the most recent job trigger timestamp across the given jobs.
*
* Returns `null` when none of the jobs has ever been triggered. The value is
* persisted per-job via `jobs.last_run_at`, so the dashboard reflects the
* scope visible to the current user (own + shared, or all for admins) rather
* than a process-wide in-memory value.
*
* @param {Array<{lastRunAt?: number|null}>} jobs
* @returns {number|null}
*/
function computeLastRun(jobs) {
let lastRun = null;
for (const job of jobs) {
const ts = job.lastRunAt;
if (typeof ts === 'number' && (lastRun == null || ts > lastRun)) {
lastRun = ts;
}
}
return lastRun;
}
/**
* @param {import('fastify').FastifyInstance} fastify
*/
@@ -46,11 +68,13 @@ export default async function dashboardPlugin(fastify) {
}
: { labels: [], values: [] };
const lastRun = computeLastRun(jobs);
return {
general: {
interval: settings.interval,
lastRun: settings.lastRun || null,
nextRun: settings.lastRun == null ? 0 : settings.lastRun + settings.interval * 60000,
lastRun,
nextRun: lastRun == null ? 0 : lastRun + settings.interval * 60000,
},
kpis: {
totalJobs,

View File

@@ -0,0 +1,93 @@
/*
* Copyright (c) 2026 by Christian Kellner.
* Licensed under Apache-2.0 with Commons Clause and Attribution/Naming Clause
*/
import {
isEnabled,
enableDebugLogging,
disableDebugLogging,
getCurrentSize,
getMaxSize,
hasAnyLogs,
wasEverEnabled,
clearAllDebugLogs,
} from '../../services/debug/debugLogStorage.js';
import { buildDebugBundleFileName, buildDebugBundleZip } from '../../services/debug/debugBundleService.js';
import { getSettings } from '../../services/storage/settingsStorage.js';
/**
* Build the JSON status payload returned by /status and after each enable/disable.
* @returns {Promise<{enabled:boolean, size:number, max:number, hasLogs:boolean, everEnabled:boolean}>}
*/
async function buildStatus() {
return {
enabled: isEnabled(),
size: await getCurrentSize(),
max: getMaxSize(),
hasLogs: hasAnyLogs(),
everEnabled: await wasEverEnabled(),
};
}
/**
* Register the lightweight /active probe used by the app-wide red banner. Exposed
* to every authenticated user (not just admins) so non-admin users see the warning
* banner too. Returns only a single boolean so it cannot be repurposed to leak any
* other state.
*
* @param {import('fastify').FastifyInstance} fastify
*/
export async function registerDebugPublicProbe(fastify) {
fastify.get('/active', async () => ({ enabled: isEnabled() }));
}
/**
* Admin-only debug logging endpoints.
*
* Routes (all relative to the registered prefix /api/admin/debug):
* GET /status → current feature status (used by the UI polling).
* POST /enable → turn debug logging on. Body: { clearPrevious?:boolean }.
* POST /disable → turn debug logging off (existing logs are kept on disk).
* GET /download → ZIP with logs.txt + sys.txt. 409 when the feature has
* never been enabled OR there are no logs to export.
* DELETE /logs → drop every stored debug log row (does NOT change the
* enabled flag — useful to free space while keeping
* recording on).
*
* @param {import('fastify').FastifyInstance} fastify
*/
export default async function debugPlugin(fastify) {
fastify.get('/status', async () => buildStatus());
fastify.post('/enable', async (request) => {
const clearPrevious = request.body?.clearPrevious === true;
await enableDebugLogging({ clearPrevious });
return buildStatus();
});
fastify.post('/disable', async () => {
await disableDebugLogging();
return buildStatus();
});
fastify.delete('/logs', async () => {
clearAllDebugLogs();
return buildStatus();
});
fastify.get('/download', async (request, reply) => {
const ever = await wasEverEnabled();
if (!ever || !hasAnyLogs()) {
return reply.code(409).send({
error: 'Debug logging has never produced any data on this Fredy installation.',
});
}
const settings = await getSettings();
const zipBuffer = await buildDebugBundleZip({ settings });
const fileName = await buildDebugBundleFileName();
reply.header('Content-Type', 'application/zip');
reply.header('Content-Disposition', `attachment; filename="${fileName}"`);
return reply.send(zipBuffer);
});
}

View File

@@ -26,6 +26,7 @@ export default async function listingsPlugin(fastify) {
providerFilter,
watchListFilter,
statusFilter,
hiddenOnly,
sortfield = null,
sortdir = 'asc',
freeTextFilter,
@@ -38,6 +39,7 @@ export default async function listingsPlugin(fastify) {
};
const normalizedActivity = toBool(activityFilter);
const normalizedWatch = toBool(watchListFilter);
const normalizedHidden = toBool(hiddenOnly) === true;
const allowedStatuses = ['applied', 'rejected', 'accepted', 'none'];
const normalizedStatus =
typeof statusFilter === 'string' && allowedStatuses.includes(statusFilter.toLowerCase())
@@ -62,6 +64,7 @@ export default async function listingsPlugin(fastify) {
providerFilter,
watchListFilter: normalizedWatch,
statusFilter: normalizedStatus,
hiddenOnly: normalizedHidden,
sortField: sortfield || null,
sortDir: sortdir === 'desc' ? 'desc' : 'asc',
userId: request.session.currentUser,
@@ -192,4 +195,21 @@ export default async function listingsPlugin(fastify) {
}
return reply.send();
});
fastify.post('/restore', async (request, reply) => {
const { ids } = request.body || {};
const settings = await getSettings();
try {
if (settings.demoMode && !isAdminFn(request)) {
return reply.code(403).send({ error: 'Sorry, but you cannot restore listings in demo mode ;)' });
}
if (Array.isArray(ids) && ids.length > 0) {
listingStorage.restoreListingsById(ids);
}
} catch (error) {
logger.error(error);
return reply.code(500).send({ error: error.message });
}
return reply.send();
});
}

View File

@@ -103,6 +103,28 @@ export default async function userSettingsPlugin(fastify) {
}
});
fastify.post('/blacklist-filter-on-details', async (request, reply) => {
const userId = request.session.currentUser;
const { blacklist_filter_on_provider_details } = request.body;
const globalSettings = await getSettings();
if (globalSettings.demoMode && !isAdmin(request)) {
return reply.code(403).send({ error: 'In demo mode, it is not allowed to change settings.' });
}
if (typeof blacklist_filter_on_provider_details !== 'boolean') {
return reply.code(400).send({ error: 'blacklist_filter_on_provider_details must be a boolean.' });
}
try {
upsertSettings({ blacklist_filter_on_provider_details }, userId);
return { success: true };
} catch (error) {
logger.error('Error updating blacklist-filter-on-details setting', error);
return reply.code(500).send({ error: error.message });
}
});
fastify.post('/listings-view-mode', async (request, reply) => {
const userId = request.session.currentUser;
const { listings_view_mode } = request.body;

View File

@@ -14,7 +14,7 @@ const mapListing = (listing, baseUrl) => ({
size: listing.size,
title: listing.title,
url: listing.link,
fredyUrl: baseUrl && listing.id ? `${baseUrl}/listings/listing/${listing.id}` : null,
fredyUrl: baseUrl && listing.id ? `${baseUrl}/#/listings/listing/${listing.id}` : null,
});
export const send = async ({ serviceName, newListings, notificationConfig, jobKey, baseUrl }) => {

View File

@@ -53,7 +53,7 @@ const mapListingsWithCid = async (serviceName, jobKey, listings, baseUrl) => {
jobKey,
hasImage: false,
imageCid: '',
fredyUrl: baseUrl && l.id ? `${baseUrl}/listings/listing/${l.id}` : null,
fredyUrl: baseUrl && l.id ? `${baseUrl}/#/listings/listing/${l.id}` : null,
};
if (imgUrl) {

View File

@@ -25,7 +25,7 @@ const mapListings = (serviceName, jobKey, listings, baseUrl) =>
price: l.price || '',
image,
hasImage: Boolean(image),
fredyUrl: baseUrl && l.id ? `${baseUrl}/listings/listing/${l.id}` : null,
fredyUrl: baseUrl && l.id ? `${baseUrl}/#/listings/listing/${l.id}` : null,
serviceName,
jobKey,
};

View File

@@ -20,7 +20,7 @@ const mapListings = (serviceName, jobKey, listings, baseUrl) =>
hasImage: Boolean(image),
// optional plain text snippet
snippet: [l.address, l.price, l.size].filter(Boolean).join(' | '),
fredyUrl: baseUrl && l.id ? `${baseUrl}/listings/listing/${l.id}` : null,
fredyUrl: baseUrl && l.id ? `${baseUrl}/#/listings/listing/${l.id}` : null,
serviceName,
jobKey,
};

View File

@@ -25,7 +25,7 @@ const mapListings = (serviceName, jobKey, listings, baseUrl) =>
price: l.price || '',
image,
hasImage: Boolean(image),
fredyUrl: baseUrl && l.id ? `${baseUrl}/listings/listing/${l.id}` : null,
fredyUrl: baseUrl && l.id ? `${baseUrl}/#/listings/listing/${l.id}` : null,
serviceName,
jobKey,
};

View File

@@ -198,7 +198,9 @@ function normalize(o) {
* @returns {boolean}
*/
function applyBlacklist(o) {
return !isOneOf(o.title, appliedBlackList);
const titleNotBlacklisted = !isOneOf(o.title, appliedBlackList);
const descNotBlacklisted = !isOneOf(o.description, appliedBlackList);
return titleNotBlacklisted && descNotBlacklisted;
}
/** @type {ProviderConfig} */
const config = {

View File

@@ -42,7 +42,9 @@ function normalize(o) {
* @returns {boolean}
*/
function applyBlacklist(o) {
return !isOneOf(o.title, appliedBlackList);
const titleNotBlacklisted = !isOneOf(o.title, appliedBlackList);
const descNotBlacklisted = !isOneOf(o.description, appliedBlackList);
return titleNotBlacklisted && descNotBlacklisted;
}
/** @type {ProviderConfig} */

View File

@@ -0,0 +1,263 @@
/*
* Copyright (c) 2026 by Christian Kellner.
* Licensed under Apache-2.0 with Commons Clause and Attribution/Naming Clause
*/
import fs from 'fs';
import os from 'os';
import { getAllDebugLogs } from './debugLogStorage.js';
import { getPackageVersion } from '../../utils.js';
const LOGS_FILE_NAME = 'logs.txt';
const SYSTEM_INFO_FILE_NAME = 'sys.txt';
const DEBUG_FILE_PREFIX = 'FredyDebug-';
/**
* Lazily resolve AdmZip via dynamic import so tests can swap it via globalThis.
* Mirrors the pattern used by backupRestoreService.js for consistency.
* @returns {Promise<any>}
*/
let _AdmZipSingleton = null;
async function getAdmZip() {
if (_AdmZipSingleton) return _AdmZipSingleton;
if (globalThis && globalThis.__TEST_ADM_ZIP__) {
_AdmZipSingleton = globalThis.__TEST_ADM_ZIP__;
return _AdmZipSingleton;
}
const mod = await import('adm-zip');
_AdmZipSingleton = (mod && mod.default) || mod;
return _AdmZipSingleton;
}
/**
* Format a Date as YYYY-MM-DD using local time. Used for the download filename.
* @param {Date} date
* @returns {string}
*/
function formatDateOnly(date) {
const yyyy = date.getFullYear();
const mm = String(date.getMonth() + 1).padStart(2, '0');
const dd = String(date.getDate()).padStart(2, '0');
return `${yyyy}-${mm}-${dd}`;
}
/**
* Build the debug bundle filename, e.g. "2026-06-08-FredyDebug-22.5.0.zip".
* @returns {Promise<string>}
*/
export async function buildDebugBundleFileName() {
const version = await getPackageVersion();
return `${formatDateOnly(new Date())}-${DEBUG_FILE_PREFIX}${version}.zip`;
}
/**
* Format a stored debug_logs row into a single text line. The format mirrors the
* console layout from logger.js so support staff sees familiar output:
* [YYYY-MM-DD HH:MM:SS] LEVEL: message
*
* @param {{ts:number, level:string, message:string}} row
* @returns {string}
*/
function formatLogLine(row) {
const d = new Date(row.ts);
const yyyy = d.getFullYear();
const mm = String(d.getMonth() + 1).padStart(2, '0');
const dd = String(d.getDate()).padStart(2, '0');
const hh = String(d.getHours()).padStart(2, '0');
const mi = String(d.getMinutes()).padStart(2, '0');
const ss = String(d.getSeconds()).padStart(2, '0');
const level = String(row.level || 'info').toUpperCase();
return `[${yyyy}-${mm}-${dd} ${hh}:${mi}:${ss}] ${level}: ${row.message}`;
}
/**
* Render every stored debug log row into a single newline-delimited text blob.
* Returns an empty string when there are no rows.
*
* @returns {string}
*/
export function renderLogsTxt() {
const rows = getAllDebugLogs();
if (!rows || rows.length === 0) return '';
return rows.map(formatLogLine).join('\n') + '\n';
}
/**
* Best-effort Docker detection. Used as a context hint in sys.txt so issue triage
* knows whether the user runs the official container image.
*
* @returns {{inDocker:boolean, evidence:string[]}}
*/
function detectDocker() {
const evidence = [];
let inDocker = false;
if (process.env.FREDY_IN_DOCKER === 'true' || process.env.FREDY_IN_DOCKER === '1') {
inDocker = true;
evidence.push('FREDY_IN_DOCKER env var is set');
}
try {
if (fs.existsSync('/.dockerenv')) {
inDocker = true;
evidence.push('/.dockerenv exists');
}
} catch {
// ignore
}
try {
if (fs.existsSync('/proc/1/cgroup')) {
const cgroup = fs.readFileSync('/proc/1/cgroup', 'utf-8');
if (/docker|containerd|kubepods/i.test(cgroup)) {
inDocker = true;
evidence.push('/proc/1/cgroup mentions a container runtime');
}
}
} catch {
// ignore
}
return { inDocker, evidence };
}
/**
* Strip credentials from URL-like strings so they can safely appear in sys.txt.
* Returns the input unchanged for non-URL values.
* @param {string} value
* @returns {string}
*/
function sanitizeUrlLike(value) {
if (typeof value !== 'string' || value.length === 0) return value;
try {
const u = new URL(value);
if (u.username || u.password) {
u.username = '***';
u.password = '***';
}
return u.toString();
} catch {
return value;
}
}
function formatBytes(bytes) {
if (!Number.isFinite(bytes)) return String(bytes);
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(2)} KiB`;
if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(2)} MiB`;
return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GiB`;
}
function formatDuration(seconds) {
if (!Number.isFinite(seconds)) return String(seconds);
const s = Math.floor(seconds);
const days = Math.floor(s / 86400);
const hours = Math.floor((s % 86400) / 3600);
const minutes = Math.floor((s % 3600) / 60);
const secs = s % 60;
return `${days}d ${hours}h ${minutes}m ${secs}s`;
}
/**
* Build a plaintext system / runtime report for inclusion in the debug zip. Settings
* are sanitized, proxy URL credentials and session secrets are stripped before
* serialization.
*
* @param {object} [options]
* @param {object} [options.settings]
* @returns {Promise<string>}
*/
export async function buildSystemInfo({ settings = null } = {}) {
const fredyVersion = await getPackageVersion();
const docker = detectDocker();
const cpus = os.cpus() || [];
const procMem = process.memoryUsage();
const lines = [];
lines.push('# Fredy Debug Report');
lines.push(`Generated at: ${new Date().toISOString()}`);
lines.push('');
lines.push('## Application');
lines.push(`Fredy version: ${fredyVersion}`);
lines.push(`Node.js version: ${process.version}`);
lines.push(`Process uptime: ${formatDuration(process.uptime())}`);
lines.push(`PID: ${process.pid}`);
lines.push(`Env (NODE_ENV): ${process.env.NODE_ENV || 'development'}`);
lines.push('');
lines.push('## Operating System');
lines.push(`Platform: ${process.platform}`);
lines.push(`Architecture: ${process.arch}`);
lines.push(`OS type: ${os.type()}`);
lines.push(`OS release: ${os.release()}`);
lines.push(`OS version: ${typeof os.version === 'function' ? os.version() : 'n/a'}`);
lines.push(`Hostname: ${os.hostname()}`);
lines.push(`System uptime: ${formatDuration(os.uptime())}`);
lines.push('');
lines.push('## Container');
lines.push(`Running in Docker: ${docker.inDocker ? 'yes' : 'no'}`);
if (docker.evidence.length > 0) {
lines.push(`Evidence: ${docker.evidence.join('; ')}`);
}
if (process.env.FREDY_IMAGE_TAG) {
lines.push(`Image tag: ${process.env.FREDY_IMAGE_TAG}`);
}
lines.push('');
lines.push('## Hardware');
lines.push(`CPU count: ${cpus.length}`);
lines.push(`CPU model: ${cpus[0]?.model || 'unknown'}`);
lines.push(`Total memory: ${formatBytes(os.totalmem())}`);
lines.push(`Free memory: ${formatBytes(os.freemem())}`);
lines.push(`Process RSS: ${formatBytes(procMem.rss)}`);
lines.push(`Process heapUsed: ${formatBytes(procMem.heapUsed)}`);
lines.push(`Process heapTotal: ${formatBytes(procMem.heapTotal)}`);
lines.push('');
if (settings && typeof settings === 'object') {
lines.push('## Settings (sanitized)');
const safe = { ...settings };
if (safe.proxyUrl) safe.proxyUrl = sanitizeUrlLike(safe.proxyUrl);
delete safe.session_secret;
delete safe.sessionSecret;
for (const [key, value] of Object.entries(safe)) {
let printed;
if (value == null) {
printed = 'null';
} else if (typeof value === 'object') {
try {
printed = JSON.stringify(value);
} catch {
printed = String(value);
}
} else {
printed = String(value);
}
lines.push(`${key}: ${printed}`);
}
lines.push('');
}
return lines.join('\n');
}
/**
* Build the final debug bundle zip buffer (logs.txt + sys.txt). The caller is
* responsible for checking wasEverEnabled() before invoking this, we still produce
* a valid zip even when there are zero log rows (logs.txt will contain a placeholder)
* because the route layer handles the user-friendly 409 case.
*
* @param {object} [options]
* @param {object} [options.settings] Runtime settings to embed in sys.txt.
* @returns {Promise<Buffer>}
*/
export async function buildDebugBundleZip({ settings = null } = {}) {
const logsContent = renderLogsTxt() || 'No debug log entries are currently stored.\n';
const sysContent = await buildSystemInfo({ settings });
const AdmZip = await getAdmZip();
const zip = new AdmZip();
zip.addFile(LOGS_FILE_NAME, Buffer.from(logsContent, 'utf-8'));
zip.addFile(SYSTEM_INFO_FILE_NAME, Buffer.from(sysContent, 'utf-8'));
return zip.toBuffer();
}

View File

@@ -0,0 +1,346 @@
/*
* Copyright (c) 2026 by Christian Kellner.
* Licensed under Apache-2.0 with Commons Clause and Attribution/Naming Clause
*/
import SqliteConnection from '../storage/SqliteConnection.js';
import { upsertSettings, getSettings } from '../storage/settingsStorage.js';
import logger from '../logger.js';
/**
* Hard cap on the total UTF-8 byte length of stored log MESSAGES (5 MiB).
*
* Note: this measures the payload bytes (message strings only); SQLite per-row
* overhead (id, ts, level, byte_size columns + page housekeeping) means the actual
* sqlite_master page count for debug_logs can be larger than this cap by a constant
* factor. The cap is intentionally about user-visible payload to keep the math
* predictable and to align with what ends up in logs.txt.
*
* The cap is enforced via a rolling buffer: when the live size exceeds it, the
* oldest rows are removed until the size falls below the limit again.
* @type {number}
*/
export const MAX_DEBUG_LOG_BYTES = 5 * 1024 * 1024;
/** Settings key persisting the active on/off flag. */
const SETTING_ENABLED = 'debug_logging_enabled';
/**
* Settings key persisting "this feature has been turned on at least once". Used to
* decide whether the download endpoint returns 409 (never enabled) or whether the
* "delete previous logs?" confirm dialog should be shown on (re)enable.
*/
const SETTING_EVER_ENABLED = 'debug_logging_ever_enabled';
/**
* Cached live byte size of all rows in debug_logs. Initialized lazily from the DB on
* the first call and kept in sync by append / clear / trim. Storing this in-memory
* avoids running SUM() on every single insert (logger writes can be very frequent).
* @type {number|null}
*/
let cachedSize = null;
/**
* Cached value of debug_logging_enabled. Reflects DB state; flipped by enable() /
* disable() so the logger hot-path does not have to hit the settings cache for every
* log line.
* @type {boolean|null}
*/
let cachedEnabled = null;
/**
* Compute the UTF-8 byte length of a string. Falls back to character count for
* environments where Buffer is not available (vitest covers Node, so it always is).
* @param {string} str
* @returns {number}
*/
function byteLengthOf(str) {
if (typeof str !== 'string') return 0;
if (typeof Buffer !== 'undefined' && typeof Buffer.byteLength === 'function') {
return Buffer.byteLength(str, 'utf-8');
}
return str.length;
}
/**
* Read the current total byte size from the DB and update the local cache.
* @returns {number}
*/
function refreshSizeFromDb() {
const rows = SqliteConnection.query('SELECT COALESCE(SUM(byte_size), 0) AS total FROM debug_logs');
cachedSize = Number(rows?.[0]?.total ?? 0);
return cachedSize;
}
/**
* Lazily ensure the cached enabled/size values are up to date. Called by every public
* method that needs to know either value, so external init is not required.
* @returns {Promise<void>}
*/
async function ensureCachesInitialized() {
if (cachedEnabled == null) {
const settings = await getSettings();
cachedEnabled = settings[SETTING_ENABLED] === true;
}
if (cachedSize == null) {
refreshSizeFromDb();
}
}
/**
* Cached prepared statements used by trimToFit(). Initialized on first use so we do
* not pay the prepare cost on every overflow event, and skipped entirely when the
* feature is never activated.
* @type {{select:any, del:any}|null}
*/
let trimStatements = null;
/**
* Drop the oldest rows from debug_logs until the cached size falls below
* MAX_DEBUG_LOG_BYTES. Implements the rolling buffer behavior chosen for the feature.
*
* The deletion is performed in batches of up to 100 oldest rows wrapped in a single
* transaction. The size cache is updated only after the transaction commits, so a
* mid-batch failure (rolled back by SQLite) cannot leave cachedSize out of sync with
* the on-disk reality. A defensive resync via SUM() is performed on transaction
* failure to recover from any unexpected drift.
*
* @returns {void}
*/
function trimToFit() {
if (cachedSize == null || cachedSize <= MAX_DEBUG_LOG_BYTES) return;
const db = SqliteConnection.getConnection();
if (trimStatements == null) {
trimStatements = {
select: db.prepare('SELECT id, byte_size FROM debug_logs ORDER BY id ASC LIMIT 100'),
del: db.prepare('DELETE FROM debug_logs WHERE id = @id'),
};
}
while (cachedSize > MAX_DEBUG_LOG_BYTES) {
const oldest = trimStatements.select.all();
if (oldest.length === 0) {
// Table is empty but the cache still claims we are over the cap. That can only
// happen if cachedSize drifted (e.g. external DB modification, zero-byte
// messages that never contributed to SUM(byte_size), or a previous trim that
// partially succeeded). Resync from the source of truth and bail out.
refreshSizeFromDb();
break;
}
// Pick exactly enough oldest rows to bring the cache back under the cap. We do
// NOT delete the entire 100-row batch unconditionally, that would over-trim in
// edge cases where just one or two rows are enough.
const needToFree = cachedSize - MAX_DEBUG_LOG_BYTES;
let freed = 0;
const idsToDelete = [];
for (const row of oldest) {
idsToDelete.push(row.id);
freed += Number(row.byte_size) || 0;
if (freed >= needToFree) break;
}
try {
const tx = db.transaction((ids) => {
for (const id of ids) {
trimStatements.del.run({ id });
}
});
tx(idsToDelete);
// Only decrement after the transaction has committed; a mid-batch failure
// would roll the DELETEs back and leave cachedSize untouched.
cachedSize -= freed;
if (freed === 0) {
// We deleted rows but they all had byte_size <= 0, so cachedSize did not
// move. Without intervention the outer loop would spin again with the same
// condition. Resync from the DB and bail to prevent that.
refreshSizeFromDb();
break;
}
} catch {
// SQLite rolled the batch back; resync cachedSize from the DB to recover from
// any unexpected drift, then bail out so we do not spin forever on a persistent
// failure (e.g. database is locked or read-only).
refreshSizeFromDb();
break;
}
}
if (cachedSize < 0) cachedSize = 0;
}
/**
* Whether debug logging is currently enabled. Synchronous and cheap so the logger
* hot-path can call it on every log line.
*
* @returns {boolean} True if logs should be persisted to the debug_logs table.
*/
export function isEnabled() {
return cachedEnabled === true;
}
/**
* Append a single log entry to debug_logs (if enabled) and trim the rolling buffer if
* the new row pushes the live size above the cap.
*
* Safe to call even when logging is disabled, it becomes a no-op. Any storage error
* is swallowed so the logger never breaks the calling code; bookkeeping for cachedSize
* stays consistent because we update it only after a successful insert.
*
* @param {{ts:number, level:string, message:string}} entry
* @returns {void}
*/
export function appendLogEntry(entry) {
if (!isEnabled()) return;
if (!entry || typeof entry.message !== 'string') return;
try {
const ts = Number.isFinite(entry.ts) ? entry.ts : Date.now();
const level = String(entry.level || 'info');
const message = entry.message;
const byte_size = byteLengthOf(message);
SqliteConnection.execute(
'INSERT INTO debug_logs (ts, level, message, byte_size) VALUES (@ts, @level, @message, @byte_size)',
{ ts, level, message, byte_size },
);
if (cachedSize == null) {
refreshSizeFromDb();
} else {
cachedSize += byte_size;
}
trimToFit();
} catch {
// Logging must never break the application. Swallow storage errors silently.
}
}
/**
* Remove every row from debug_logs and reset the cached size to zero. Used by both
* the "clear previous logs" path on (re)enable and by explicit clear actions.
*
* @returns {void}
*/
export function clearAllDebugLogs() {
SqliteConnection.execute('DELETE FROM debug_logs');
cachedSize = 0;
}
/**
* Return the cached live byte size of the debug_logs table contents.
* @returns {Promise<number>}
*/
export async function getCurrentSize() {
await ensureCachesInitialized();
return cachedSize ?? 0;
}
/**
* Return the configured maximum size for the debug_logs table.
* @returns {number}
*/
export function getMaxSize() {
return MAX_DEBUG_LOG_BYTES;
}
/**
* Check whether the debug_logs table contains at least one row.
* @returns {boolean}
*/
export function hasAnyLogs() {
const row = SqliteConnection.query('SELECT 1 AS one FROM debug_logs LIMIT 1');
return Array.isArray(row) && row.length > 0;
}
/**
* Has debug logging ever been enabled in this installation? Used by the download
* endpoint to distinguish "no logs yet" (empty table) from "feature never used"
* (which returns 409 to surface a friendlier UI error).
*
* @returns {Promise<boolean>}
*/
export async function wasEverEnabled() {
const settings = await getSettings();
return settings[SETTING_EVER_ENABLED] === true;
}
/**
* Turn debug logging on. Persists both the active flag and the "ever enabled" flag,
* optionally clearing previous logs when the caller passes clearPrevious=true (this
* is the path taken when the UI confirm dialog "Delete previous logs?" is accepted).
*
* @param {object} [options]
* @param {boolean} [options.clearPrevious=false]
* @returns {Promise<void>}
*/
export async function enableDebugLogging({ clearPrevious = false } = {}) {
if (clearPrevious) {
clearAllDebugLogs();
}
upsertSettings({ [SETTING_ENABLED]: true, [SETTING_EVER_ENABLED]: true });
cachedEnabled = true;
if (cachedSize == null) {
refreshSizeFromDb();
}
// Attach the logger sink only while recording is on so the logger hot path pays
// no per-call cost (Date.now + stringifyArgs) when nobody enabled the feature.
logger.setDebugLogSink(appendLogEntry);
}
/**
* Turn debug logging off. Previous logs are kept on disk so the user can still
* download them; they are only cleared when the user re-enables and chooses "delete
* previous logs".
*
* @returns {Promise<void>}
*/
export async function disableDebugLogging() {
upsertSettings({ [SETTING_ENABLED]: false });
cachedEnabled = false;
// Detach the sink so the logger hot path returns immediately on its `if (sink)`
// check instead of paying the no-op cost on every log line.
logger.setDebugLogSink(null);
}
/**
* Return all stored log entries ordered chronologically. Used by the bundle builder
* when assembling logs.txt.
*
* @returns {{id:number, ts:number, level:string, message:string}[]}
*/
export function getAllDebugLogs() {
return SqliteConnection.query('SELECT id, ts, level, message FROM debug_logs ORDER BY id ASC');
}
/**
* Reload the cached enabled flag from settings storage. Called from the logger at
* startup so the cache reflects the persisted state after a Fredy restart.
*
* @returns {Promise<boolean>} The active enabled flag.
*/
export async function reloadEnabledFromSettings() {
const settings = await getSettings();
cachedEnabled = settings[SETTING_ENABLED] === true;
// (Un)wire the sink to match the persisted state. Note: startup work that runs
// before index.js calls this (CloakBrowser binary check, runMigrations) still
// logs to stdout only, since the sink is not attached yet at that point.
if (cachedEnabled) {
logger.setDebugLogSink(appendLogEntry);
} else {
logger.setDebugLogSink(null);
}
return cachedEnabled;
}
/**
* Test-only helper to drop in-memory caches between unit tests. Resets every piece
* of module-scoped mutable state so a test that swaps the underlying DB does not
* inherit stale prepared statements from a previous run.
* @returns {void}
*/
export function _resetForTests() {
cachedSize = null;
cachedEnabled = null;
trimStatements = null;
}

View File

@@ -103,6 +103,13 @@ const EQUIPMENT_MAP = {
lodgerflat: 'lodgerflat',
};
// The web UI uses "swapflat", but the mobile API only understands "swap_flat".
// An unknown value is not ignored: the API silently returns 0 results for the
// whole search. Other values (e.g. "projectlisting") are identical on both APIs.
const EXCLUSION_CRITERIA_MAP = {
swapflat: 'swap_flat',
};
const REAL_ESTATE_TYPE = {
'haus-mieten': 'houserent',
'wohnung-mieten': 'apartmentrent',
@@ -251,6 +258,9 @@ export function convertWebToMobile(webUrl) {
...(currentEquipmentParams ?? []),
...items.map((item) => EQUIPMENT_MAP[item.toLowerCase()]).filter(Boolean),
];
} else if (key === 'exclusioncriteria') {
const items = [].concat(val).flatMap((v) => `${v}`.split(','));
mobileParams[PARAM_NAME_MAP[key]] = items.map((item) => EXCLUSION_CRITERIA_MAP[item.toLowerCase()] ?? item);
} else {
mobileParams[PARAM_NAME_MAP[key]] = val;
}

View File

@@ -104,7 +104,6 @@ export function initJobExecutionService({ providers, settings, intervalMs }) {
logger.debug('Working hours set. Skipping as outside of working hours.');
return;
}
settings.lastRun = now;
const jobs = jobStorage.getJobs().filter((job) => {
if (!context) return true; // startup/cron → all
if (context.isAdmin) return true; // admin → all
@@ -150,6 +149,13 @@ export function initJobExecutionService({ providers, settings, intervalMs }) {
}
const acquired = markRunning(job.id);
if (!acquired) return;
// Persist the trigger time so the dashboard "last search" KPI can be
// derived per accessible user without an in-memory cache.
try {
jobStorage.updateJobLastRunAt(job.id, Date.now());
} catch (err) {
logger.warn('Failed to persist last_run_at for job', job.id, err);
}
// notify listeners (SSE) that the job started
try {
bus.emit('jobs:status', { jobId: job.id, running: true });

View File

@@ -14,6 +14,20 @@ const COLORS = {
const env = process.env.NODE_ENV || 'development';
const useColor = process.stdout.isTTY || process.stderr.isTTY;
/**
* Optional sink that forwards formatted log entries to the opt-in "Debug Logging"
* DB storage. Wired and unwired by debugLogStorage as the feature is toggled, so
* when nobody enabled the feature this stays null and the logger hot path skips
* the Date.now + stringifyArgs work entirely.
*
* We deliberately do NOT import debugLogStorage here, because that would create a
* cycle (debugLogStorage → SqliteConnection → utils → logger → debugLogStorage).
* Inversion of control via setDebugLogSink() keeps the dependency one-way.
*
* @type {((entry:{ts:number, level:string, message:string}) => void)|null}
*/
let debugLogSink = null;
function ts() {
const d = new Date();
const yyyy = d.getFullYear();
@@ -31,10 +45,50 @@ function lvl(level) {
return `${COLORS[level] || ''}${upper}${COLORS.reset}`;
}
/**
* Build a colour-free plain text representation of variadic console args. Errors
* are unwrapped to their stack/message, objects are JSON-serialized. Used when
* forwarding to the DB sink so the stored text is portable across terminals.
*
* @param {any[]} args
* @returns {string}
*/
function stringifyArgs(args) {
return args
.map((a) => {
if (a == null) return String(a);
if (a instanceof Error) return a.stack || a.message;
if (typeof a === 'object') {
try {
return JSON.stringify(a);
} catch {
return String(a);
}
}
return String(a);
})
.join(' ');
}
/* eslint-disable no-console */
function log(level, ...args) {
// Forward to the DB sink first (regardless of console suppression rules) so the
// recorded debug bundle truly contains every level, including debug entries that
// would otherwise be silenced in production.
if (debugLogSink) {
try {
debugLogSink({
ts: Date.now(),
level,
message: `${stringifyArgs(args)}`,
});
} catch {
// never break the caller because of logging
}
}
if (level === 'debug' && env !== 'development') {
return; // Skip debug logs in non-development environments
return; // Skip debug logs in non-development environments (console only)
}
const prefix = `[${ts()}] ${lvl(level)}:`;
@@ -56,9 +110,28 @@ function log(level, ...args) {
}
}
/**
* Register a sink function that receives every log entry the logger sees, regardless
* of console suppression rules. debugLogStorage attaches its sink only while the
* feature is enabled and detaches it on disable, so the logger's hot path can use
* the null check as a cheap on/off gate and skip stringification when off.
*
* Pass null to remove the sink (used both by the storage module on disable and by
* tests to reset state between cases).
*
* @param {((entry:{ts:number, level:string, message:string}) => void)|null} sink
* @returns {void}
*/
function setDebugLogSink(sink) {
debugLogSink = typeof sink === 'function' ? sink : null;
}
export { setDebugLogSink };
export default {
debug: (...a) => log('debug', ...a),
info: (...a) => log('info', ...a),
warn: (...a) => log('warn', ...a),
error: (...a) => log('error', ...a),
setDebugLogSink,
};

View File

@@ -97,6 +97,7 @@ export const getJob = (jobId) => {
j.notification_adapter AS notificationAdapter,
j.spatial_filter AS spatialFilter,
j.spec_filter AS specFilter,
j.last_run_at AS lastRunAt,
(SELECT COUNT(1) FROM listings l WHERE l.job_id = j.id AND l.is_active = 1 AND l.manually_deleted = 0) AS numberOfFoundListings
FROM jobs j
WHERE j.id = @id
@@ -116,6 +117,24 @@ export const getJob = (jobId) => {
};
};
/**
* Record the timestamp at which a job was last triggered.
*
* Called from the job execution service when a job starts running. The value
* is persisted so that the dashboard "last search" KPI survives restarts and
* can be computed per accessible user.
*
* @param {string} jobId - Job primary key.
* @param {number} timestamp - Epoch milliseconds.
* @returns {void}
*/
export const updateJobLastRunAt = (jobId, timestamp) => {
SqliteConnection.execute(`UPDATE jobs SET last_run_at = @timestamp WHERE id = @id`, {
id: jobId,
timestamp,
});
};
/**
* Update job enabled status.
* @param {{jobId: string, status: boolean}} params - Parameters.
@@ -164,6 +183,7 @@ export const getJobs = () => {
j.notification_adapter AS notificationAdapter,
j.spatial_filter AS spatialFilter,
j.spec_filter AS specFilter,
j.last_run_at AS lastRunAt,
(SELECT COUNT(1) FROM listings l WHERE l.job_id = j.id AND l.is_active = 1 AND l.manually_deleted = 0) AS numberOfFoundListings
FROM jobs j
WHERE j.enabled = 1
@@ -269,6 +289,7 @@ export const queryJobs = ({
j.notification_adapter AS notificationAdapter,
j.spatial_filter AS spatialFilter,
j.spec_filter AS specFilter,
j.last_run_at AS lastRunAt,
(SELECT COUNT(1) FROM listings l WHERE l.job_id = j.id AND l.is_active = 1 AND l.manually_deleted = 0) AS numberOfFoundListings
FROM jobs j
${whereSql}

View File

@@ -264,6 +264,7 @@ export const storeListings = (jobId, providerId, listings) => {
* @param {number} [params.createdBefore] - Only include listings created at or before this unix timestamp (ms).
* @param {string} [params.userId] - Current user id used to scope listings (ignored for admins).
* @param {boolean} [params.isAdmin=false] - When true, returns all listings.
* @param {boolean} [params.hiddenOnly=false] - When true, returns only soft-deleted (manually_deleted = 1) listings.
* @returns {{ totalNumber:number, page:number, result:Object[] }}
*/
export const queryListings = ({
@@ -284,6 +285,7 @@ export const queryListings = ({
maxPrice = null,
userId = null,
isAdmin = false,
hiddenOnly = false,
} = {}) => {
// sanitize inputs
const safePageSize = Number.isFinite(pageSize) && pageSize > 0 ? Math.min(1000, Math.floor(pageSize)) : 50;
@@ -365,8 +367,8 @@ export const queryListings = ({
whereParts.push('(l.price <= @maxPrice)');
}
// Build whereSql (filtering by manually_deleted = 0)
whereParts.push('(l.manually_deleted = 0)');
// Build whereSql: in normal mode hide soft-deleted; in hiddenOnly mode show only soft-deleted.
whereParts.push(hiddenOnly ? '(l.manually_deleted = 1)' : '(l.manually_deleted = 0)');
const whereSqlWithAlias = whereParts.length ? `WHERE ${whereParts.join(' AND ')}` : '';
@@ -463,6 +465,23 @@ export const deleteListingsById = (ids, hardDelete = false) => {
);
};
/**
* Restore previously soft-deleted listings by clearing their `manually_deleted` flag.
*
* @param {string[]} ids - Array of DB row IDs to restore.
* @returns {any} The result from SqliteConnection.execute.
*/
export const restoreListingsById = (ids) => {
if (!Array.isArray(ids) || ids.length === 0) return;
const placeholders = ids.map(() => '?').join(',');
return SqliteConnection.execute(
`UPDATE listings
SET manually_deleted = 0
WHERE id IN (${placeholders})`,
ids,
);
};
/**
* Return all listings that are active, have an address, and do not yet have geocoordinates.
*

View File

@@ -0,0 +1,32 @@
/*
* Copyright (c) 2026 by Christian Kellner.
* Licensed under Apache-2.0 with Commons Clause and Attribution/Naming Clause
*/
/**
* Migration: create the debug_logs table used by the opt-in "Debug Logging" feature.
*
* Each row is a single log line (timestamp + level + message) captured by the in-app
* logger while debug logging is enabled. We store the UTF-8 byte size of the message
* alongside the row so the debugLogStorage can maintain a rolling 5 MB cap without
* having to run length() / SUM() on every insert.
*
* The "debug_logging_enabled" and "debug_logging_ever_enabled" flags are persisted in
* the existing settings table (no schema change needed there) and are managed by
* debugLogStorage.js at runtime.
*/
export function up(db) {
// id is INTEGER PRIMARY KEY AUTOINCREMENT, which is an alias for SQLite's rowid and
// is implicitly indexed. No additional index needed; selecting / deleting by id and
// ordering by id ASC (rolling buffer) both use the existing rowid index.
db.exec(`
CREATE TABLE IF NOT EXISTS debug_logs
(
id INTEGER PRIMARY KEY AUTOINCREMENT,
ts INTEGER NOT NULL,
level TEXT NOT NULL,
message TEXT NOT NULL,
byte_size INTEGER NOT NULL
);
`);
}

View File

@@ -0,0 +1,20 @@
/*
* Copyright (c) 2026 by Christian Kellner.
* Licensed under Apache-2.0 with Commons Clause and Attribution/Naming Clause
*/
/**
* Migration: add `last_run_at` to the `jobs` table.
*
* Stores the epoch-ms timestamp at which a job was last triggered. Used by the
* dashboard "last search" KPI so the value survives restarts and reflects the
* actual jobs the requesting user can see (own, shared, or all for admins),
* replacing the previous in-memory `settings.lastRun` value.
*
* NULL means the job has not yet been triggered since this column was added.
*/
export function up(db) {
db.exec(`
ALTER TABLE jobs ADD COLUMN last_run_at INTEGER
`);
}

View File

@@ -18,6 +18,7 @@
* @property {SpatialFilter | null} [spatialFilter] Optional spatial filter configuration as GeoJSON FeatureCollection.
* @property {SpecFilter | null} [specFilter] Optional listing specifications.
* @property {number} [numberOfFoundListings] Count of active listings for this job.
* @property {number | null} [lastRunAt] Epoch ms at which the job was last triggered, or null if never triggered.
*/
export {};

View File

@@ -1,6 +1,6 @@
{
"name": "fredy",
"version": "22.4.0",
"version": "22.8.0",
"description": "[F]ind [R]eal [E]states [d]amn eas[y].",
"scripts": {
"prepare": "husky",
@@ -62,9 +62,9 @@
"Firefox ESR"
],
"dependencies": {
"@douyinfe/semi-icons": "^2.99.3",
"@douyinfe/semi-ui": "2.99.3",
"@douyinfe/semi-ui-19": "^2.99.3",
"@douyinfe/semi-icons": "^2.100.0",
"@douyinfe/semi-ui": "2.100.0",
"@douyinfe/semi-ui-19": "^2.100.0",
"@fastify/cookie": "^11.0.2",
"@fastify/helmet": "^13.0.2",
"@fastify/session": "^11.1.1",
@@ -86,7 +86,7 @@
"node-cron": "^4.2.1",
"node-fetch": "3.3.2",
"node-mailjet": "6.0.11",
"nodemailer": "^8.0.10",
"nodemailer": "^8.0.11",
"p-throttle": "^8.1.0",
"package-up": "^5.0.0",
"puppeteer-core": "^25.1.0",
@@ -95,10 +95,10 @@
"react-chartjs-2": "^5.3.1",
"react-dom": "19.2.7",
"react-range-slider-input": "^3.3.5",
"react-router": "7.16.0",
"react-router-dom": "7.16.0",
"react-router": "7.17.0",
"react-router-dom": "7.17.0",
"resend": "^6.12.4",
"semver": "^7.8.1",
"semver": "^7.8.4",
"slack": "11.0.2",
"vite": "8.0.16",
"x-var": "^3.0.1",
@@ -120,7 +120,7 @@
"less": "4.6.4",
"lint-staged": "17.0.7",
"nodemon": "^3.1.14",
"prettier": "3.8.3",
"prettier": "3.8.4",
"vitest": "^4.1.8"
}
}

View File

@@ -17,8 +17,12 @@ export const getGeocoordinatesByAddress = (any) => {
return null;
};
let userSettings = null;
export function setUserSettings(settings) {
userSettings = settings;
}
export function getUserSettings(userId) {
return null;
return userSettings;
}
export async function getSettings() {

View File

@@ -3,9 +3,10 @@
* Licensed under Apache-2.0 with Commons Clause and Attribution/Naming Clause
*/
import { expect } from 'vitest';
import { afterEach, expect } from 'vitest';
import { mockFredy } from './utils.js';
import * as mockStore from './mocks/mockStore.js';
import { get as getLastNotification } from './mocks/mockNotification.js';
describe('Issue reproduction: listings filtered by similarity or area should be marked as manually deleted', () => {
it('should call deleteListingsById when listings are filtered by similarity', async () => {
@@ -113,3 +114,223 @@ describe('Issue reproduction: listings filtered by similarity or area should be
expect(mockStore.deletedIds).toContain('2');
});
});
describe('Blacklist is re-applied after detail enrichment', () => {
afterEach(() => {
mockStore.setUserSettings(null);
});
it('filters out a listing whose blacklisted term only appears in the enriched description', async () => {
const Fredy = await mockFredy();
const providerId = 'test-provider';
mockStore.setUserSettings({
provider_details: [providerId],
blacklist_filter_on_provider_details: true,
});
const mockSimilarityCache = {
checkAndAddEntry: () => false,
};
const blacklist = ['allkauf'];
// The search results page returns a clean snippet (no blacklisted term).
// fetchDetails simulates loading the full detail page and discovers the
// blacklisted term hidden deep in the description.
const providerConfig = {
url: 'http://example.com',
getListings: () =>
Promise.resolve([
{
id: 'kept',
title: 'Nice house',
address: 'Some street',
price: '500000',
link: 'http://example.com/kept',
description: 'Cozy home with garden',
},
{
id: 'blacklisted',
title: 'Eleganz trifft Raumkomfort',
address: 'Other street',
price: '600000',
link: 'http://example.com/blacklisted',
description: 'Eleganz trifft Raumkomfort',
},
]),
normalize: (l) => l,
filter: (l) => {
const text = `${l.title ?? ''} ${l.description ?? ''}`.toLowerCase();
return !blacklist.some((term) => text.includes(term));
},
fetchDetails: (listing) => {
if (listing.id === 'blacklisted') {
return Promise.resolve({
...listing,
description: 'Mit allkauf Haus wird dein Traum vom Eigenheim wahr.',
});
}
return Promise.resolve(listing);
},
crawlFields: {
id: 'id',
title: 'title',
address: 'address',
price: 'price',
link: 'link',
description: 'description',
},
requiredFieldNames: ['id', 'title', 'address', 'price', 'link', 'description'],
};
const mockedJob = {
id: 'blacklist-test-job',
notificationAdapter: null,
specFilter: null,
spatialFilter: null,
};
const fredy = new Fredy(providerConfig, mockedJob, providerId, mockSimilarityCache, undefined);
const result = await fredy.execute();
expect(result).toBeInstanceOf(Array);
const ids = result.map((l) => l.id);
expect(ids).toContain('kept');
expect(ids).not.toContain('blacklisted');
const notification = getLastNotification();
const notifiedIds = (notification?.payload ?? []).map((p) => p.id);
expect(notifiedIds).not.toContain('blacklisted');
});
it('short-circuits the pipeline when all listings get blacklisted after enrichment', async () => {
const Fredy = await mockFredy();
const providerId = 'all-blacklisted-provider';
mockStore.setUserSettings({
provider_details: [providerId],
blacklist_filter_on_provider_details: true,
});
const mockSimilarityCache = {
checkAndAddEntry: () => false,
};
const blacklist = ['allkauf'];
const providerConfig = {
url: 'http://example.com',
getListings: () =>
Promise.resolve([
{
id: 'only',
title: 'Eleganz trifft Raumkomfort',
address: 'Some street',
price: '700000',
link: 'http://example.com/only',
description: 'Eleganz trifft Raumkomfort',
},
]),
normalize: (l) => l,
filter: (l) => {
const text = `${l.title ?? ''} ${l.description ?? ''}`.toLowerCase();
return !blacklist.some((term) => text.includes(term));
},
fetchDetails: (listing) =>
Promise.resolve({
...listing,
description: 'Mit allkauf Haus wird dein Traum vom Eigenheim wahr.',
}),
crawlFields: {
id: 'id',
title: 'title',
address: 'address',
price: 'price',
link: 'link',
description: 'description',
},
requiredFieldNames: ['id', 'title', 'address', 'price', 'link', 'description'],
};
const mockedJob = {
id: 'all-blacklisted-job',
notificationAdapter: null,
specFilter: null,
spatialFilter: null,
};
const fredy = new Fredy(providerConfig, mockedJob, providerId, mockSimilarityCache, undefined);
// Should resolve to undefined (NoNewListingsWarning is caught in _handleError).
const result = await fredy.execute();
expect(result).toBeUndefined();
});
it('does NOT re-filter when blacklist_filter_on_provider_details is disabled', async () => {
const Fredy = await mockFredy();
const providerId = 'opt-out-provider';
// provider_details enabled (so fetchDetails runs) but blacklist re-filter NOT enabled.
mockStore.setUserSettings({
provider_details: [providerId],
blacklist_filter_on_provider_details: false,
});
const mockSimilarityCache = {
checkAndAddEntry: () => false,
};
const blacklist = ['allkauf'];
const providerConfig = {
url: 'http://example.com',
getListings: () =>
Promise.resolve([
{
id: 'leaks-through',
title: 'Eleganz trifft Raumkomfort',
address: 'Other street',
price: '600000',
link: 'http://example.com/leaks-through',
description: 'Eleganz trifft Raumkomfort',
},
]),
normalize: (l) => l,
filter: (l) => {
const text = `${l.title ?? ''} ${l.description ?? ''}`.toLowerCase();
return !blacklist.some((term) => text.includes(term));
},
fetchDetails: (listing) =>
Promise.resolve({
...listing,
description: 'Mit allkauf Haus wird dein Traum vom Eigenheim wahr.',
}),
crawlFields: {
id: 'id',
title: 'title',
address: 'address',
price: 'price',
link: 'link',
description: 'description',
},
requiredFieldNames: ['id', 'title', 'address', 'price', 'link', 'description'],
};
const mockedJob = {
id: 'opt-out-job',
notificationAdapter: null,
specFilter: null,
spatialFilter: null,
};
const fredy = new Fredy(providerConfig, mockedJob, providerId, mockSimilarityCache, undefined);
const result = await fredy.execute();
// Listing leaks through because user has not opted in to the stricter check.
expect(result).toBeInstanceOf(Array);
expect(result.map((l) => l.id)).toContain('leaks-through');
});
});

View File

@@ -0,0 +1,129 @@
/*
* Copyright (c) 2026 by Christian Kellner.
* Licensed under Apache-2.0 with Commons Clause and Attribution/Naming Clause
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import path from 'node:path';
describe('services/debug/debugBundleService.js', () => {
let svc;
let storedLogs;
let addedZipEntries;
beforeEach(async () => {
storedLogs = [];
addedZipEntries = [];
/**
* Minimal AdmZip stand-in that records the in-memory entry names + payloads so we
* can assert what made it into the bundle without spinning up real zip parsing.
*/
class MockAdmZip {
constructor() {
this.entries = [];
}
addFile(name, buf) {
this.entries.push({ entryName: name, data: buf });
addedZipEntries.push({ entryName: name, content: buf.toString('utf-8') });
}
toBuffer() {
return Buffer.from(JSON.stringify(this.entries.map((e) => e.entryName)));
}
}
globalThis.__TEST_ADM_ZIP__ = MockAdmZip;
const ROOT = path.resolve('.');
const storagePath = path.join(ROOT, 'lib', 'services', 'debug', 'debugLogStorage.js');
const utilsPath = path.join(ROOT, 'lib', 'utils.js');
const storageMock = {
getAllDebugLogs: () => storedLogs,
};
const utilsMock = { getPackageVersion: async () => '22.5.0' };
vi.resetModules();
vi.doMock(storagePath, () => storageMock);
vi.doMock(utilsPath, () => utilsMock);
svc = await import(path.join(ROOT, 'lib', 'services', 'debug', 'debugBundleService.js'));
});
afterEach(() => {
delete globalThis.__TEST_ADM_ZIP__;
});
describe('renderLogsTxt', () => {
it('returns an empty string when there are no rows', () => {
expect(svc.renderLogsTxt()).toBe('');
});
it('formats each row as [date] LEVEL: message and keeps order', () => {
storedLogs.push({ id: 1, ts: 1717855200000, level: 'info', message: 'first line' });
storedLogs.push({ id: 2, ts: 1717855201000, level: 'warn', message: 'second line' });
const out = svc.renderLogsTxt();
expect(out).toMatch(/\[\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\] INFO: first line/);
expect(out).toMatch(/\[\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\] WARN: second line/);
expect(out.indexOf('first line')).toBeLessThan(out.indexOf('second line'));
expect(out.endsWith('\n')).toBe(true);
});
});
describe('buildSystemInfo', () => {
it('contains Fredy version, Node version and OS platform', async () => {
const sys = await svc.buildSystemInfo({ settings: null });
expect(sys).toMatch(/Fredy version:\s+22\.5\.0/);
expect(sys).toContain(`Node.js version: ${process.version}`);
expect(sys).toContain(`Platform: ${process.platform}`);
});
it('redacts proxy URL credentials', async () => {
const sys = await svc.buildSystemInfo({
settings: { proxyUrl: 'http://secret:hunter2@proxy.example:8080', port: 9998 },
});
expect(sys).not.toContain('hunter2');
expect(sys).not.toContain('secret');
expect(sys).toContain('proxy.example');
expect(sys).toContain('port: 9998');
});
it('strips session secrets from sanitized settings output', async () => {
const sys = await svc.buildSystemInfo({
settings: { session_secret: 'top-secret', sessionSecret: 'other-secret', port: 9998 },
});
expect(sys).not.toContain('top-secret');
expect(sys).not.toContain('other-secret');
});
});
describe('buildDebugBundleFileName', () => {
it('matches YYYY-MM-DD-FredyDebug-<version>.zip', async () => {
const name = await svc.buildDebugBundleFileName();
expect(name).toMatch(/^\d{4}-\d{2}-\d{2}-FredyDebug-22\.5\.0\.zip$/);
});
});
describe('buildDebugBundleZip', () => {
it('always emits both logs.txt and sys.txt entries', async () => {
storedLogs.push({ id: 1, ts: 1717855200000, level: 'info', message: 'recorded line' });
await svc.buildDebugBundleZip({ settings: { port: 9998 } });
const names = addedZipEntries.map((e) => e.entryName).sort();
expect(names).toEqual(['logs.txt', 'sys.txt']);
const logs = addedZipEntries.find((e) => e.entryName === 'logs.txt');
const sys = addedZipEntries.find((e) => e.entryName === 'sys.txt');
expect(logs.content).toContain('recorded line');
expect(sys.content).toMatch(/Fredy version:\s+22\.5\.0/);
expect(sys.content).toContain('port: 9998');
});
it('includes a placeholder message when no logs are stored', async () => {
await svc.buildDebugBundleZip({ settings: null });
const logs = addedZipEntries.find((e) => e.entryName === 'logs.txt');
expect(logs.content).toMatch(/no debug log entries/i);
});
});
});

View File

@@ -0,0 +1,278 @@
/*
* Copyright (c) 2026 by Christian Kellner.
* Licensed under Apache-2.0 with Commons Clause and Attribution/Naming Clause
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import path from 'node:path';
import Database from 'better-sqlite3';
/**
* Wire up an in-memory better-sqlite3 instance plus a stubbed settings module so the
* storage module under test can exercise real SQL while the rest of the dependency
* graph stays inert.
*/
async function bootstrap() {
const db = new Database(':memory:');
db.exec(`
CREATE TABLE debug_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ts INTEGER NOT NULL,
level TEXT NOT NULL,
message TEXT NOT NULL,
byte_size INTEGER NOT NULL
);
`);
const settings = { debug_logging_enabled: false, debug_logging_ever_enabled: false };
const ROOT = path.resolve('.');
const sqlitePath = path.join(ROOT, 'lib', 'services', 'storage', 'SqliteConnection.js');
const settingsPath = path.join(ROOT, 'lib', 'services', 'storage', 'settingsStorage.js');
const sqliteMock = {
default: {
getConnection: () => db,
execute: (sql, params = {}) => db.prepare(sql).run(params),
query: (sql, params = {}) => db.prepare(sql).all(params),
},
};
const settingsMock = {
getSettings: async () => ({ ...settings }),
upsertSettings: (entries) => {
const map = Array.isArray(entries) ? Object.fromEntries(entries) : entries;
for (const [k, v] of Object.entries(map)) {
settings[k] = v;
}
},
};
vi.resetModules();
vi.doMock(sqlitePath, () => sqliteMock);
vi.doMock(settingsPath, () => settingsMock);
const storage = await import(path.join(ROOT, 'lib', 'services', 'debug', 'debugLogStorage.js'));
storage._resetForTests();
return { storage, db, settings };
}
describe('services/debug/debugLogStorage.js', () => {
let ctx;
beforeEach(async () => {
ctx = await bootstrap();
});
afterEach(() => {
try {
ctx.db.close();
} catch {
// ignore
}
});
it('isEnabled is false before enableDebugLogging is called', async () => {
expect(ctx.storage.isEnabled()).toBe(false);
});
it('enableDebugLogging flips the cached flag and persists ever-enabled', async () => {
await ctx.storage.enableDebugLogging();
expect(ctx.storage.isEnabled()).toBe(true);
expect(ctx.settings.debug_logging_enabled).toBe(true);
expect(ctx.settings.debug_logging_ever_enabled).toBe(true);
});
it('reloadEnabledFromSettings picks up persisted state after restart', async () => {
ctx.settings.debug_logging_enabled = true;
const enabled = await ctx.storage.reloadEnabledFromSettings();
expect(enabled).toBe(true);
expect(ctx.storage.isEnabled()).toBe(true);
});
it('appendLogEntry writes only while enabled', async () => {
ctx.storage.appendLogEntry({ ts: 1, level: 'info', message: 'before-enable' });
expect(ctx.db.prepare('SELECT COUNT(*) AS c FROM debug_logs').get().c).toBe(0);
await ctx.storage.enableDebugLogging();
ctx.storage.appendLogEntry({ ts: 2, level: 'warn', message: 'after-enable' });
expect(ctx.db.prepare('SELECT COUNT(*) AS c FROM debug_logs').get().c).toBe(1);
const row = ctx.db.prepare('SELECT level, message, byte_size FROM debug_logs').get();
expect(row.level).toBe('warn');
expect(row.message).toBe('after-enable');
expect(row.byte_size).toBe(Buffer.byteLength('after-enable', 'utf-8'));
});
it('disableDebugLogging stops writes but keeps existing rows', async () => {
await ctx.storage.enableDebugLogging();
ctx.storage.appendLogEntry({ ts: 1, level: 'info', message: 'keep-me' });
await ctx.storage.disableDebugLogging();
ctx.storage.appendLogEntry({ ts: 2, level: 'info', message: 'never-written' });
const rows = ctx.db.prepare('SELECT message FROM debug_logs ORDER BY id').all();
expect(rows).toHaveLength(1);
expect(rows[0].message).toBe('keep-me');
});
it('enableDebugLogging clears previous logs only when asked', async () => {
await ctx.storage.enableDebugLogging();
ctx.storage.appendLogEntry({ ts: 1, level: 'info', message: 'pre-existing' });
await ctx.storage.disableDebugLogging();
await ctx.storage.enableDebugLogging({ clearPrevious: false });
expect(ctx.db.prepare('SELECT COUNT(*) AS c FROM debug_logs').get().c).toBe(1);
await ctx.storage.disableDebugLogging();
await ctx.storage.enableDebugLogging({ clearPrevious: true });
expect(ctx.db.prepare('SELECT COUNT(*) AS c FROM debug_logs').get().c).toBe(0);
});
it('hasAnyLogs / wasEverEnabled report correctly', async () => {
expect(ctx.storage.hasAnyLogs()).toBe(false);
expect(await ctx.storage.wasEverEnabled()).toBe(false);
await ctx.storage.enableDebugLogging();
ctx.storage.appendLogEntry({ ts: 1, level: 'info', message: 'hi' });
expect(ctx.storage.hasAnyLogs()).toBe(true);
expect(await ctx.storage.wasEverEnabled()).toBe(true);
});
it('getCurrentSize reflects the on-disk byte total', async () => {
await ctx.storage.enableDebugLogging();
ctx.storage.appendLogEntry({ ts: 1, level: 'info', message: 'hello' }); // 5 bytes
ctx.storage.appendLogEntry({ ts: 2, level: 'info', message: 'world!' }); // 6 bytes
expect(await ctx.storage.getCurrentSize()).toBe(11);
});
it('rolling buffer drops oldest rows once the cap is exceeded', async () => {
await ctx.storage.enableDebugLogging();
const cap = ctx.storage.getMaxSize();
// Insert one row whose payload exceeds the entire cap. trimToFit must drop the
// oldest row(s) until the live size falls back under the cap. With a single
// oversized row, the only outcome is "table empty".
const giantText = 'X'.repeat(cap + 1024);
ctx.storage.appendLogEntry({ ts: 10, level: 'info', message: giantText });
const remaining = await ctx.storage.getCurrentSize();
expect(remaining).toBeLessThanOrEqual(cap);
expect(remaining).toBe(0);
expect(ctx.db.prepare('SELECT COUNT(*) AS c FROM debug_logs').get().c).toBe(0);
});
it('rolling buffer keeps newer rows when only the oldest need to go', async () => {
await ctx.storage.enableDebugLogging();
const cap = ctx.storage.getMaxSize();
// Push the size just over the cap with one big row, then a smaller "newer" row
// that should survive the trim because it is not at the head of the queue.
const bigText = 'A'.repeat(cap - 10); // ~5 MiB - 10 bytes
ctx.storage.appendLogEntry({ ts: 1, level: 'info', message: bigText });
// At this point we are just under the cap. Pushing one more row will tip us over.
ctx.storage.appendLogEntry({ ts: 2, level: 'warn', message: 'tip-over message which keeps us above cap' });
const remainingRows = ctx.db.prepare('SELECT message FROM debug_logs ORDER BY id ASC').all();
// The oldest (big) row must be gone; the newer one survives.
expect(remainingRows).toHaveLength(1);
expect(remainingRows[0].message).toContain('tip-over');
const remainingSize = await ctx.storage.getCurrentSize();
expect(remainingSize).toBeLessThanOrEqual(cap);
// And the cache must match what SQLite reports, verifies no drift after trim.
const dbSize = ctx.db.prepare('SELECT COALESCE(SUM(byte_size),0) AS s FROM debug_logs').get().s;
expect(remainingSize).toBe(dbSize);
});
it('cachedSize stays consistent across enable → append → disable → re-enable(clear) cycles', async () => {
await ctx.storage.enableDebugLogging();
ctx.storage.appendLogEntry({ ts: 1, level: 'info', message: 'one' });
ctx.storage.appendLogEntry({ ts: 2, level: 'info', message: 'two' });
const sizeAfterFirst = await ctx.storage.getCurrentSize();
await ctx.storage.disableDebugLogging();
expect(await ctx.storage.getCurrentSize()).toBe(sizeAfterFirst);
await ctx.storage.enableDebugLogging({ clearPrevious: true });
expect(await ctx.storage.getCurrentSize()).toBe(0);
ctx.storage.appendLogEntry({ ts: 3, level: 'info', message: 'fresh' });
const dbSize = ctx.db.prepare('SELECT COALESCE(SUM(byte_size),0) AS s FROM debug_logs').get().s;
expect(await ctx.storage.getCurrentSize()).toBe(dbSize);
});
it('clearAllDebugLogs empties the table and resets cached size', async () => {
await ctx.storage.enableDebugLogging();
ctx.storage.appendLogEntry({ ts: 1, level: 'info', message: 'foo' });
ctx.storage.appendLogEntry({ ts: 2, level: 'info', message: 'bar' });
expect(await ctx.storage.getCurrentSize()).toBeGreaterThan(0);
ctx.storage.clearAllDebugLogs();
expect(ctx.db.prepare('SELECT COUNT(*) AS c FROM debug_logs').get().c).toBe(0);
expect(await ctx.storage.getCurrentSize()).toBe(0);
});
it('getAllDebugLogs returns rows ordered chronologically', async () => {
await ctx.storage.enableDebugLogging();
ctx.storage.appendLogEntry({ ts: 1, level: 'info', message: 'first' });
ctx.storage.appendLogEntry({ ts: 2, level: 'warn', message: 'second' });
ctx.storage.appendLogEntry({ ts: 3, level: 'error', message: 'third' });
const rows = ctx.storage.getAllDebugLogs();
expect(rows.map((r) => r.message)).toEqual(['first', 'second', 'third']);
expect(rows.map((r) => r.level)).toEqual(['info', 'warn', 'error']);
});
describe('logger sink wiring', () => {
let logger;
let consoleSpies;
beforeEach(async () => {
// Storage imports the same logger module; vi.resetModules() ensured both share
// the same fresh instance for this test. Spies silence console output so the
// vitest report stays clean while we exercise real logger.info() calls.
logger = (await import(path.resolve('lib/services/logger.js'))).default;
consoleSpies = {
debug: vi.spyOn(console, 'debug').mockImplementation(() => {}),
info: vi.spyOn(console, 'info').mockImplementation(() => {}),
warn: vi.spyOn(console, 'warn').mockImplementation(() => {}),
error: vi.spyOn(console, 'error').mockImplementation(() => {}),
};
});
afterEach(() => {
// Detach sink between tests to prevent cross-test pollution from the shared
// logger module instance.
logger.setDebugLogSink(null);
for (const spy of Object.values(consoleSpies)) spy.mockRestore();
});
it('routes logger calls into debug_logs once enabled', async () => {
await ctx.storage.enableDebugLogging();
logger.info('captured-via-logger');
const rows = ctx.db.prepare('SELECT level, message FROM debug_logs').all();
expect(rows).toHaveLength(1);
expect(rows[0].level).toBe('info');
expect(rows[0].message).toContain('captured-via-logger');
});
it('detaches the sink on disable so logger calls no longer hit the DB', async () => {
await ctx.storage.enableDebugLogging();
await ctx.storage.disableDebugLogging();
logger.info('not-captured');
expect(ctx.db.prepare('SELECT COUNT(*) AS c FROM debug_logs').get().c).toBe(0);
});
it('restores the sink on reloadEnabledFromSettings when persisted state is on', async () => {
ctx.settings.debug_logging_enabled = true;
await ctx.storage.reloadEnabledFromSettings();
logger.warn('captured-after-restart');
const rows = ctx.db.prepare('SELECT level, message FROM debug_logs').all();
expect(rows).toHaveLength(1);
expect(rows[0].level).toBe('warn');
expect(rows[0].message).toContain('captured-after-restart');
});
});
});

View File

@@ -0,0 +1,250 @@
/*
* Copyright (c) 2026 by Christian Kellner.
* Licensed under Apache-2.0 with Commons Clause and Attribution/Naming Clause
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import path from 'node:path';
import Fastify from 'fastify';
describe('api/routes/debugRouter.js', () => {
let app;
let state;
beforeEach(async () => {
state = {
enabled: false,
hasLogs: false,
everEnabled: false,
size: 0,
max: 5 * 1024 * 1024,
};
const ROOT = path.resolve('.');
const storagePath = path.join(ROOT, 'lib', 'services', 'debug', 'debugLogStorage.js');
const bundlePath = path.join(ROOT, 'lib', 'services', 'debug', 'debugBundleService.js');
const settingsStoragePath = path.join(ROOT, 'lib', 'services', 'storage', 'settingsStorage.js');
const storageMock = {
isEnabled: () => state.enabled,
enableDebugLogging: async ({ clearPrevious = false } = {}) => {
state.enabled = true;
state.everEnabled = true;
if (clearPrevious) {
state.hasLogs = false;
state.size = 0;
}
},
disableDebugLogging: async () => {
state.enabled = false;
},
getCurrentSize: async () => state.size,
getMaxSize: () => state.max,
hasAnyLogs: () => state.hasLogs,
wasEverEnabled: async () => state.everEnabled,
clearAllDebugLogs: () => {
state.hasLogs = false;
state.size = 0;
},
};
const bundleMock = {
buildDebugBundleFileName: async () => '2026-06-08-FredyDebug-22.5.0.zip',
buildDebugBundleZip: async () => Buffer.from('FAKEZIP'),
};
const settingsMock = {
getSettings: async () => ({ port: 9998 }),
};
vi.resetModules();
vi.doMock(storagePath, () => storageMock);
vi.doMock(bundlePath, () => bundleMock);
vi.doMock(settingsStoragePath, () => settingsMock);
const mod = await import(path.join(ROOT, 'lib', 'api', 'routes', 'debugRouter.js'));
const plugin = mod.default;
app = Fastify({ logger: false });
await app.register(plugin, { prefix: '/api/admin/debug' });
await app.register(
async (sub) => {
mod.registerDebugPublicProbe(sub);
},
{ prefix: '/api/debug' },
);
await app.ready();
});
afterEach(async () => {
if (app) await app.close();
});
it('GET /status returns the current snapshot', async () => {
const res = await app.inject({ method: 'GET', url: '/api/admin/debug/status' });
expect(res.statusCode).toBe(200);
expect(res.json()).toEqual({
enabled: false,
size: 0,
max: state.max,
hasLogs: false,
everEnabled: false,
});
});
it('POST /enable flips the feature on and returns updated status', async () => {
const res = await app.inject({
method: 'POST',
url: '/api/admin/debug/enable',
payload: {},
});
expect(res.statusCode).toBe(200);
const json = res.json();
expect(json.enabled).toBe(true);
expect(json.everEnabled).toBe(true);
});
it('POST /enable with clearPrevious=true wipes existing logs first', async () => {
state.hasLogs = true;
state.size = 1234;
state.everEnabled = true;
const res = await app.inject({
method: 'POST',
url: '/api/admin/debug/enable',
payload: { clearPrevious: true },
});
expect(res.statusCode).toBe(200);
const json = res.json();
expect(json.enabled).toBe(true);
expect(json.hasLogs).toBe(false);
expect(json.size).toBe(0);
});
it('POST /disable turns the feature off without losing existing logs', async () => {
state.enabled = true;
state.hasLogs = true;
state.everEnabled = true;
state.size = 99;
const res = await app.inject({ method: 'POST', url: '/api/admin/debug/disable' });
expect(res.statusCode).toBe(200);
const json = res.json();
expect(json.enabled).toBe(false);
expect(json.hasLogs).toBe(true);
expect(json.size).toBe(99);
});
it('GET /download returns 409 when the feature was never enabled', async () => {
const res = await app.inject({ method: 'GET', url: '/api/admin/debug/download' });
expect(res.statusCode).toBe(409);
expect(res.json().error).toMatch(/never produced any data/i);
});
it('GET /download returns 409 when ever-enabled but no logs are stored', async () => {
state.everEnabled = true;
state.hasLogs = false;
const res = await app.inject({ method: 'GET', url: '/api/admin/debug/download' });
expect(res.statusCode).toBe(409);
});
it('GET /download streams a zip with the expected headers when logs exist', async () => {
state.everEnabled = true;
state.hasLogs = true;
const res = await app.inject({ method: 'GET', url: '/api/admin/debug/download' });
expect(res.statusCode).toBe(200);
expect(res.headers['content-type']).toBe('application/zip');
expect(res.headers['content-disposition']).toContain('FredyDebug');
expect(res.rawPayload.toString('utf-8')).toBe('FAKEZIP');
});
it('DELETE /logs wipes stored logs without touching the enabled flag', async () => {
state.enabled = true;
state.hasLogs = true;
state.everEnabled = true;
state.size = 1234;
const res = await app.inject({ method: 'DELETE', url: '/api/admin/debug/logs' });
expect(res.statusCode).toBe(200);
const json = res.json();
expect(json.enabled).toBe(true);
expect(json.hasLogs).toBe(false);
expect(json.size).toBe(0);
// everEnabled must stay true so the download button does not change semantics.
expect(json.everEnabled).toBe(true);
});
it('GET /api/debug/active returns only the enabled boolean (no other settings)', async () => {
state.enabled = false;
let res = await app.inject({ method: 'GET', url: '/api/debug/active' });
expect(res.statusCode).toBe(200);
expect(res.json()).toEqual({ enabled: false });
state.enabled = true;
res = await app.inject({ method: 'GET', url: '/api/debug/active' });
expect(res.statusCode).toBe(200);
expect(res.json()).toEqual({ enabled: true });
});
});
describe('api/routes/debugRouter.js - admin-only enforcement', () => {
let app;
beforeEach(async () => {
const ROOT = path.resolve('.');
const storagePath = path.join(ROOT, 'lib', 'services', 'debug', 'debugLogStorage.js');
const bundlePath = path.join(ROOT, 'lib', 'services', 'debug', 'debugBundleService.js');
const settingsStoragePath = path.join(ROOT, 'lib', 'services', 'storage', 'settingsStorage.js');
vi.resetModules();
vi.doMock(storagePath, () => ({
isEnabled: () => false,
enableDebugLogging: async () => {},
disableDebugLogging: async () => {},
getCurrentSize: async () => 0,
getMaxSize: () => 5 * 1024 * 1024,
hasAnyLogs: () => false,
wasEverEnabled: async () => false,
clearAllDebugLogs: () => {},
}));
vi.doMock(bundlePath, () => ({
buildDebugBundleFileName: async () => 'x.zip',
buildDebugBundleZip: async () => Buffer.from(''),
}));
vi.doMock(settingsStoragePath, () => ({
getSettings: async () => ({}),
}));
const plugin = (await import(path.join(ROOT, 'lib', 'api', 'routes', 'debugRouter.js'))).default;
app = Fastify({ logger: false });
await app.register(
async (sub) => {
// Same wiring shape as lib/api/api.js: apply adminHook before the plugin.
sub.addHook('preHandler', async (request, reply) => {
reply.code(401).send();
});
sub.register(plugin, { prefix: '/api/admin/debug' });
},
{ prefix: '/' },
);
await app.ready();
});
afterEach(async () => {
if (app) await app.close();
});
it('rejects non-admin callers with 401 on every endpoint', async () => {
for (const route of [
['GET', '/api/admin/debug/status'],
['POST', '/api/admin/debug/enable'],
['POST', '/api/admin/debug/disable'],
['GET', '/api/admin/debug/download'],
['DELETE', '/api/admin/debug/logs'],
]) {
const [method, url] = route;
const res = await app.inject({ method, url, payload: method === 'POST' ? {} : undefined });
expect(res.statusCode, `${method} ${url}`).toBe(401);
}
});
});

View File

@@ -31,12 +31,35 @@ describe('#immoscout-mobile URL conversion', () => {
const webUrl =
'https://www.immobilienscout24.de/Suche/de/berlin/berlin/wohnung-mieten?heatingtypes=central,selfcontainedcentral&haspromotion=false&numberofrooms=2.0-5.0&livingspace=10.0-25.0&energyefficiencyclasses=a,b,c,d,e,f,g,h,a_plus&exclusioncriteria=projectlisting,swapflat&equipment=parking,cellar,builtinkitchen,lift,garden,guesttoilet,balcony&petsallowedtypes=no,yes,negotiable&price=10.0-100.0&constructionyear=1920-2026&apartmenttypes=halfbasement,penthouse,other,loft,groundfloor,terracedflat,raisedgroundfloor,roofstorey,apartment,maisonette&pricetype=calculatedtotalrent&floor=2-7&enteredFrom=result_list';
const expectedMobileUrl =
'https://api.mobile.immobilienscout24.de/search/list?apartmenttypes=halfbasement,penthouse,other,loft,groundfloor,terracedflat,raisedgroundfloor,roofstorey,apartment,maisonette&constructionyear=1920-2026&energyefficiencyclasses=a,b,c,d,e,f,g,h,a_plus&equipment=parking,cellar,builtInKitchen,lift,garden,guestToilet,balcony&exclusioncriteria=projectlisting,swapflat&floor=2-7&geocodes=%2Fde%2Fberlin%2Fberlin&haspromotion=false&heatingtypes=central,selfcontainedcentral&livingspace=10.0-25.0&numberofrooms=2.0-5.0&petsallowedtypes=no,yes,negotiable&price=10.0-100.0&pricetype=calculatedtotalrent&realestatetype=apartmentrent&searchType=region';
'https://api.mobile.immobilienscout24.de/search/list?apartmenttypes=halfbasement,penthouse,other,loft,groundfloor,terracedflat,raisedgroundfloor,roofstorey,apartment,maisonette&constructionyear=1920-2026&energyefficiencyclasses=a,b,c,d,e,f,g,h,a_plus&equipment=parking,cellar,builtInKitchen,lift,garden,guestToilet,balcony&exclusioncriteria=projectlisting,swap_flat&floor=2-7&geocodes=%2Fde%2Fberlin%2Fberlin&haspromotion=false&heatingtypes=central,selfcontainedcentral&livingspace=10.0-25.0&numberofrooms=2.0-5.0&petsallowedtypes=no,yes,negotiable&price=10.0-100.0&pricetype=calculatedtotalrent&realestatetype=apartmentrent&searchType=region';
const actualMobileUrl = convertWebToMobile(webUrl);
expect(actualMobileUrl).toBe(expectedMobileUrl);
});
// The web UI encodes "no swap flats" as exclusioncriteria=swapflat, but the
// mobile API only understands swap_flat. Unknown values are not ignored by the
// API - the search silently returns 0 results, so the mapping is essential.
it('should map exclusioncriteria=swapflat to the mobile API value swap_flat', () => {
const webUrl =
'https://www.immobilienscout24.de/Suche/de/berlin/berlin/wohnung-mieten?exclusioncriteria=swapflat&price=-1500.0';
const converted = convertWebToMobile(webUrl);
const queryParams = new URL(converted).searchParams;
expect(queryParams.get('exclusioncriteria')).toBe('swap_flat');
});
// Values the mobile API shares with the web API (e.g. projectlisting) must
// pass through unchanged, in any combination with mapped values.
it('should keep other exclusioncriteria values untouched', () => {
const webUrl =
'https://www.immobilienscout24.de/Suche/de/berlin/berlin/wohnung-mieten?exclusioncriteria=projectlisting,swapflat';
const converted = convertWebToMobile(webUrl);
const queryParams = new URL(converted).searchParams;
expect(queryParams.get('exclusioncriteria')).toBe('projectlisting,swap_flat');
});
// Test URL conversion of web-only SEO path
it('should convert a SEO web path to the correct query params', () => {
const webUrl = 'https://www.immobilienscout24.de/Suche/de/berlin/berlin/wohnung-mit-balkon-mieten?equipment=garden';

View File

@@ -0,0 +1,110 @@
/*
* Copyright (c) 2026 by Christian Kellner.
* Licensed under Apache-2.0 with Commons Clause and Attribution/Naming Clause
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import path from 'node:path';
import Fastify from 'fastify';
describe('api/routes/dashboardRouter.js', () => {
let app;
let state;
async function buildApp() {
const ROOT = path.resolve('.');
const jobStoragePath = path.join(ROOT, 'lib', 'services', 'storage', 'jobStorage.js');
const listingsStoragePath = path.join(ROOT, 'lib', 'services', 'storage', 'listingsStorage.js');
const settingsStoragePath = path.join(ROOT, 'lib', 'services', 'storage', 'settingsStorage.js');
const securityPath = path.join(ROOT, 'lib', 'api', 'security.js');
vi.resetModules();
vi.doMock(jobStoragePath, () => ({
getJobs: () => state.jobs.slice(),
}));
vi.doMock(listingsStoragePath, () => ({
getListingsKpisForJobIds: () => ({ numberOfActiveListings: 0, medianPriceOfListings: 0 }),
getProviderDistributionForJobIds: () => [],
}));
vi.doMock(settingsStoragePath, () => ({
getSettings: async () => ({ interval: 30 }),
}));
vi.doMock(securityPath, () => ({
isAdmin: () => state.admin,
}));
const mod = await import(path.join(ROOT, 'lib', 'api', 'routes', 'dashboardRouter.js'));
const plugin = mod.default;
const instance = Fastify({ logger: false });
instance.addHook('onRequest', async (request) => {
request.session = { currentUser: state.currentUser, createdAt: Date.now() };
});
await instance.register(plugin, { prefix: '/api/dashboard' });
await instance.ready();
return instance;
}
beforeEach(() => {
state = {
currentUser: 'u1',
admin: false,
jobs: [],
};
});
afterEach(async () => {
if (app) await app.close();
app = null;
});
it('derives lastRun from the most recent accessible job for a regular user', async () => {
state.jobs = [
{ id: 'a', userId: 'u1', shared_with_user: [], lastRunAt: 1000 },
{ id: 'b', userId: 'u1', shared_with_user: [], lastRunAt: 5000 },
{ id: 'c', userId: 'someone-else', shared_with_user: [], lastRunAt: 9999 },
];
app = await buildApp();
const res = await app.inject({ method: 'GET', url: '/api/dashboard/' });
expect(res.statusCode).toBe(200);
const body = res.json();
expect(body.general.lastRun).toBe(5000);
expect(body.general.nextRun).toBe(5000 + 30 * 60000);
});
it('includes shared jobs in the lastRun calculation', async () => {
state.jobs = [
{ id: 'mine', userId: 'u1', shared_with_user: [], lastRunAt: 1000 },
{ id: 'shared', userId: 'someone-else', shared_with_user: ['u1'], lastRunAt: 4000 },
];
app = await buildApp();
const res = await app.inject({ method: 'GET', url: '/api/dashboard/' });
expect(res.json().general.lastRun).toBe(4000);
});
it('admins see lastRun across all jobs', async () => {
state.admin = true;
state.jobs = [
{ id: 'a', userId: 'someone', shared_with_user: [], lastRunAt: 1000 },
{ id: 'b', userId: 'another', shared_with_user: [], lastRunAt: 7000 },
];
app = await buildApp();
const res = await app.inject({ method: 'GET', url: '/api/dashboard/' });
expect(res.json().general.lastRun).toBe(7000);
});
it('returns null lastRun and 0 nextRun when no accessible job has ever run', async () => {
state.jobs = [
{ id: 'a', userId: 'u1', shared_with_user: [], lastRunAt: null },
{ id: 'b', userId: 'someone-else', shared_with_user: [], lastRunAt: 9999 },
];
app = await buildApp();
const res = await app.inject({ method: 'GET', url: '/api/dashboard/' });
const body = res.json();
expect(body.general.lastRun).toBeNull();
expect(body.general.nextRun).toBe(0);
});
});

View File

@@ -29,6 +29,7 @@ describe('services/jobs/jobExecutionService', () => {
vi.doMock(jobStoragePath, () => ({
getJob: (id) => state.jobsById[id] || null,
getJobs: () => state.jobsList.slice(),
updateJobLastRunAt: (id, timestamp) => calls.lastRunUpdates.push({ id, timestamp }),
}));
vi.doMock(userStoragePath, () => ({
getUsers: () => state.users.slice(),
@@ -65,7 +66,7 @@ describe('services/jobs/jobExecutionService', () => {
beforeEach(() => {
bus = new EventEmitter();
calls = { sent: [], markRunning: [] };
calls = { sent: [], markRunning: [], lastRunUpdates: [] };
state = {
jobsById: {},
jobsList: [],
@@ -119,4 +120,23 @@ describe('services/jobs/jobExecutionService', () => {
await new Promise((r) => setTimeout(r, 0));
expect(new Set(calls.markRunning)).toEqual(new Set(['j1', 'j2']));
});
it('persists last_run_at when a job is executed', async () => {
state.jobsById['j1'] = { id: 'j1', enabled: true, userId: 'u1', provider: [] };
state.jobsList = [state.jobsById['j1']];
state.users = [{ id: 'u1', isAdmin: false }];
await initService();
const before = Date.now();
bus.emit('jobs:runOne', { jobId: 'j1' });
await new Promise((r) => setTimeout(r, 0));
const after = Date.now();
expect(calls.lastRunUpdates.length).toBe(1);
const [update] = calls.lastRunUpdates;
expect(update.id).toBe('j1');
expect(update.timestamp).toBeGreaterThanOrEqual(before);
expect(update.timestamp).toBeLessThanOrEqual(after);
});
});

View File

@@ -0,0 +1,89 @@
/*
* Copyright (c) 2026 by Christian Kellner.
* Licensed under Apache-2.0 with Commons Clause and Attribution/Naming Clause
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import path from 'node:path';
describe('services/logger.js - debug log sink', () => {
let logger;
let setDebugLogSink;
let consoleSpies;
beforeEach(async () => {
vi.resetModules();
const mod = await import(path.resolve('lib/services/logger.js'));
logger = mod.default;
setDebugLogSink = mod.setDebugLogSink;
// Silence console output so test runner stdout stays readable while still
// letting us inspect what the logger emitted if a test wants to.
consoleSpies = {
debug: vi.spyOn(console, 'debug').mockImplementation(() => {}),
info: vi.spyOn(console, 'info').mockImplementation(() => {}),
warn: vi.spyOn(console, 'warn').mockImplementation(() => {}),
error: vi.spyOn(console, 'error').mockImplementation(() => {}),
};
});
afterEach(() => {
setDebugLogSink(null);
for (const spy of Object.values(consoleSpies)) spy.mockRestore();
});
it('is a no-op for the sink when none is registered', () => {
// Just make sure nothing throws.
expect(() => logger.info('hello')).not.toThrow();
expect(() => logger.error(new Error('boom'))).not.toThrow();
});
it('forwards every log level (including debug) to the registered sink', () => {
const captured = [];
setDebugLogSink((entry) => captured.push(entry));
logger.debug('debug-line');
logger.info('info-line');
logger.warn('warn-line');
logger.error('error-line');
expect(captured).toHaveLength(4);
expect(captured.map((c) => c.level)).toEqual(['debug', 'info', 'warn', 'error']);
expect(captured[0].message).toContain('debug-line');
expect(captured[1].message).toContain('info-line');
expect(captured[2].message).toContain('warn-line');
expect(captured[3].message).toContain('error-line');
for (const c of captured) {
expect(typeof c.ts).toBe('number');
}
});
it('serializes Error stacks for the sink instead of "[object Object]"', () => {
const captured = [];
setDebugLogSink((entry) => captured.push(entry));
logger.error(new Error('boom'));
expect(captured).toHaveLength(1);
expect(captured[0].message).toContain('Error: boom');
});
it('stops forwarding once the sink is unregistered', () => {
const captured = [];
setDebugLogSink((entry) => captured.push(entry));
logger.info('one');
setDebugLogSink(null);
logger.info('two');
expect(captured).toHaveLength(1);
expect(captured[0].message).toContain('one');
});
it('does not break the caller when the sink throws', () => {
setDebugLogSink(() => {
throw new Error('sink exploded');
});
expect(() => logger.info('still works')).not.toThrow();
expect(consoleSpies.info).toHaveBeenCalled();
});
});

View File

@@ -120,6 +120,57 @@ describe('listingsStorage.queryListings statusFilter', () => {
});
});
describe('listingsStorage.queryListings hiddenOnly', () => {
let listingsStorage;
beforeEach(async () => {
calls.execute.length = 0;
calls.query.length = 0;
sqliteMock.__queryHandler = (sql) => {
if (/COUNT\(1\)/.test(sql)) return [{ cnt: 0 }];
return [];
};
listingsStorage = await import('../../lib/services/storage/listingsStorage.js');
});
it('filters by manually_deleted = 0 by default', () => {
listingsStorage.queryListings({ userId: 'u1', isAdmin: true });
const pageQuery = calls.query.find((c) => !/COUNT\(1\)/.test(c.sql));
expect(pageQuery.sql).toMatch(/\(l\.manually_deleted = 0\)/);
});
it('filters by manually_deleted = 1 when hiddenOnly is true', () => {
listingsStorage.queryListings({ userId: 'u1', isAdmin: true, hiddenOnly: true });
const pageQuery = calls.query.find((c) => !/COUNT\(1\)/.test(c.sql));
expect(pageQuery.sql).toMatch(/\(l\.manually_deleted = 1\)/);
expect(pageQuery.sql).not.toMatch(/\(l\.manually_deleted = 0\)/);
});
});
describe('listingsStorage.restoreListingsById', () => {
let listingsStorage;
beforeEach(async () => {
calls.execute.length = 0;
calls.query.length = 0;
sqliteMock.__queryHandler = null;
listingsStorage = await import('../../lib/services/storage/listingsStorage.js');
});
it('clears the manually_deleted flag for the given ids', () => {
listingsStorage.restoreListingsById(['a', 'b']);
expect(calls.execute).toHaveLength(1);
expect(calls.execute[0].sql).toMatch(/UPDATE listings\s+SET manually_deleted = 0\s+WHERE id IN \(\?,\?\)/);
expect(calls.execute[0].params).toEqual(['a', 'b']);
});
it('is a no-op when ids are missing or empty', () => {
listingsStorage.restoreListingsById([]);
listingsStorage.restoreListingsById(undefined);
expect(calls.execute).toHaveLength(0);
});
});
describe('listingsStorage.getListingById', () => {
let listingsStorage;

View File

@@ -11,7 +11,7 @@ import GeneralSettings from './views/generalSettings/GeneralSettings';
import JobMutation from './views/jobs/mutation/JobMutation';
import UserMutator from './views/user/mutation/UserMutator';
import { useActions, useSelector } from './services/state/store';
import { Routes, Route, Navigate } from 'react-router-dom';
import { Routes, Route, Navigate, useLocation } from 'react-router-dom';
import Login from './views/login/Login';
import Users from './views/user/Users';
import Jobs from './views/jobs/Jobs';
@@ -30,6 +30,7 @@ import Dashboard from './views/dashboard/Dashboard.jsx';
import ListingDetail from './views/listings/ListingDetail.jsx';
import NewsModal from './components/news/NewsModal.jsx';
import { I18nProvider, availableLanguages } from './services/i18n/i18n.jsx';
import DebugLoggingBanner from './components/debug/DebugLoggingBanner.jsx';
const semiLocaleModules = import.meta.glob('/node_modules/@douyinfe/semi-ui-19/lib/es/locale/source/*.js', {
eager: true,
@@ -42,6 +43,7 @@ for (const [path, mod] of Object.entries(semiLocaleModules)) {
}
export default function FredyApp() {
const location = useLocation();
const actions = useActions();
const [loading, setLoading] = React.useState(true);
const currentUser = useSelector((state) => state.user.currentUser);
@@ -85,7 +87,7 @@ export default function FredyApp() {
{needsLogin() ? (
<Routes>
<Route path="/login" element={<Login />} />
<Route path="*" element={<Navigate to="/login" replace />} />
<Route path="*" element={<Navigate state={{ from: location }} to="/login" replace />} />
</Routes>
) : (
<Layout className="app">
@@ -95,6 +97,7 @@ export default function FredyApp() {
<Layout className="app__main">
<Content className="app__content">
{versionUpdate?.newVersion && <VersionBanner />}
<DebugLoggingBanner />
{settings.demoMode && (
<>
<Banner

View File

@@ -0,0 +1,58 @@
/*
* Copyright (c) 2026 by Christian Kellner.
* Licensed under Apache-2.0 with Commons Clause and Attribution/Naming Clause
*/
import { useEffect, useState } from 'react';
import { Banner } from '@douyinfe/semi-ui-19';
import { useTranslation } from '../../services/i18n/i18n.jsx';
import { fetchDebugActive } from '../../services/debugLoggingClient.js';
const POLL_INTERVAL_MS = 15000;
/**
* Persistent, non-dismissable red banner shown on every page while the admin opt-in
* "Debug Logging" feature is active. Polls the lightweight `/api/debug/active` probe
* so every authenticated user (not just admins) sees the warning, without exposing
* the rest of the settings payload.
*
* Polling interval is intentionally generous (15s) because the value only changes
* when an admin toggles the feature, which happens at human speeds. The Debug tab
* itself uses its own 3s polling for the live progress bar inside Settings.
*
* @returns {JSX.Element|null}
*/
export default function DebugLoggingBanner() {
const t = useTranslation();
const [active, setActive] = useState(false);
useEffect(() => {
let cancelled = false;
const tick = async () => {
try {
const res = await fetchDebugActive();
if (!cancelled) setActive(Boolean(res?.enabled));
} catch {
// Best-effort probe: an unauthenticated 401 (e.g. session expired) simply
// hides the banner until the next successful poll.
}
};
tick();
const id = window.setInterval(tick, POLL_INTERVAL_MS);
return () => {
cancelled = true;
window.clearInterval(id);
};
}, []);
if (!active) return null;
return (
<>
<Banner fullMode={true} type="danger" bordered closeIcon={null} description={t('app.debugLoggingBanner')} />
<br />
</>
);
}
DebugLoggingBanner.displayName = 'DebugLoggingBanner';

View File

@@ -22,9 +22,9 @@ import './ListingsGrid.less';
import { useTranslation, useLocale } from '../../../services/i18n/i18n.jsx';
/**
* @param {{ listings: object[], onWatch: Function, onNavigate: Function, onDelete: Function, onStatusChange: Function }} props
* @param {{ listings: object[], onWatch: Function, onNavigate: Function, onDelete: Function, onRestore?: Function, isHiddenView?: boolean, onStatusChange: Function }} props
*/
const ListingsGrid = ({ listings, onWatch, onNavigate, onDelete, onStatusChange }) => {
const ListingsGrid = ({ listings, onWatch, onNavigate, onDelete, onRestore, isHiddenView = false, onStatusChange }) => {
const t = useTranslation();
const locale = useLocale();
return (
@@ -126,18 +126,38 @@ const ListingsGrid = ({ listings, onWatch, onNavigate, onDelete, onStatusChange
}}
/>
</Tooltip>
<Tooltip content={t('listings.tooltipRemove')}>
<Button
size="small"
icon={<IconDelete />}
style={{ color: '#fb7185' }}
theme="borderless"
onClick={(e) => {
e.stopPropagation();
onDelete(item.id);
}}
/>
</Tooltip>
{isHiddenView ? (
<Tooltip content={t('listings.tooltipUndelete')}>
<Button
size="small"
icon={
<span className="listingsGrid__strike" aria-hidden="true">
<IconDelete />
</span>
}
style={{ color: '#34d399' }}
theme="borderless"
onClick={(e) => {
e.stopPropagation();
onRestore?.(item.id);
}}
aria-label={t('listings.tooltipUndelete')}
/>
</Tooltip>
) : (
<Tooltip content={t('listings.tooltipRemove')}>
<Button
size="small"
icon={<IconDelete />}
style={{ color: '#fb7185' }}
theme="borderless"
onClick={(e) => {
e.stopPropagation();
onDelete(item.id);
}}
/>
</Tooltip>
)}
</div>
</div>
))}

View File

@@ -139,4 +139,23 @@
border-radius: @radius-chip !important;
}
}
&__strike {
position: relative;
display: inline-flex;
align-items: center;
justify-content: center;
&::after {
content: '';
position: absolute;
left: -2px;
right: -2px;
top: 50%;
height: 2px;
background: currentColor;
transform: rotate(-45deg);
pointer-events: none;
}
}
}

View File

@@ -10,7 +10,18 @@ import {
parseString,
parseNullableBoolean,
} from '../../hooks/useSearchParamState.js';
import { Button, Pagination, Toast, Input, Select, Empty, Radio, RadioGroup, Tooltip } from '@douyinfe/semi-ui-19';
import {
Button,
Pagination,
Toast,
Input,
Select,
Empty,
Radio,
RadioGroup,
Tooltip,
Banner,
} from '@douyinfe/semi-ui-19';
import { IconSearch, IconArrowUp, IconArrowDown, IconGridView, IconList } from '@douyinfe/semi-icons';
import { useNavigate, useSearchParams } from 'react-router-dom';
import ListingDeletionModal from '../ListingDeletionModal.jsx';
@@ -50,9 +61,12 @@ const ListingsOverview = ({ mode = 'all' }) => {
const [activityFilter, setActivityFilter] = useSearchParamState(sp, 'active', null, parseNullableBoolean);
const [providerFilter, setProviderFilter] = useSearchParamState(sp, 'provider', null, parseString);
const [statusFilter, setStatusFilter] = useSearchParamState(sp, 'status', null, parseString);
const [hiddenOnly, setHiddenOnly] = useSearchParamState(sp, 'hidden', false, parseNullableBoolean);
const [deleteModalVisible, setDeleteModalVisible] = useState(false);
const [listingToDelete, setListingToDelete] = useState(null);
const isHiddenView = hiddenOnly === true;
// In watchlist mode the watch filter is forced to "watched only" — regardless of the URL.
const effectiveWatchListFilter = isWatchlistMode ? true : watchListFilter;
@@ -66,9 +80,10 @@ const ListingsOverview = ({ mode = 'all' }) => {
filter: {
watchListFilter: effectiveWatchListFilter,
jobNameFilter,
activityFilter,
activityFilter: isHiddenView ? null : activityFilter,
providerFilter,
statusFilter,
hiddenOnly: isHiddenView ? true : undefined,
},
});
};
@@ -85,6 +100,7 @@ const ListingsOverview = ({ mode = 'all' }) => {
jobNameFilter,
watchListFilter,
statusFilter,
hiddenOnly,
isWatchlistMode,
]);
@@ -138,7 +154,21 @@ const ListingsOverview = ({ mode = 'all' }) => {
setDeleteModalVisible(true);
};
const handleNavigate = (id) => navigate(`/listings/listing/${id}`);
const handleRestore = async (id) => {
try {
await actions.listingsData.restoreListings([id]);
Toast.success(t('listings.toastRestored'));
loadData();
} catch (e) {
console.error(e);
Toast.error(t('listings.toastRestoreError'));
}
};
const handleNavigate = (id) => {
if (isHiddenView) return;
navigate(`/listings/listing/${id}`);
};
const confirmDeletion = async (hardDelete, remember, id = listingToDelete) => {
try {
@@ -158,118 +188,161 @@ const ListingsOverview = ({ mode = 'all' }) => {
const listings = listingsData?.result || [];
const activityRadioValue = isHiddenView ? 'hidden' : activityFilter === null ? 'all' : String(activityFilter);
return (
<div className="listingsOverview">
<div className="listingsOverview__topbar">
<Input
className="listingsOverview__topbar__search"
prefix={<IconSearch />}
showClear
placeholder={t('listings.searchPlaceholder')}
defaultValue={freeTextFilter ?? ''}
onChange={handleFilterChange}
/>
<Tooltip content={t('listings.filterSearchHelp')} trigger="hover" position="top">
<span className="listingsOverview__topbar__tooltipWrap listingsOverview__topbar__search">
<Input
prefix={<IconSearch />}
showClear
placeholder={t('listings.searchPlaceholder')}
defaultValue={freeTextFilter ?? ''}
onChange={handleFilterChange}
/>
</span>
</Tooltip>
<RadioGroup
type="button"
buttonSize="middle"
value={activityFilter === null ? 'all' : String(activityFilter)}
onChange={(e) => {
const v = e.target.value;
setActivityFilter(v === 'all' ? null : v === 'true');
setPage(1);
}}
>
<Radio value="all">{t('listings.filterAll')}</Radio>
<Radio value="true">{t('listings.filterActive')}</Radio>
<Radio value="false">{t('listings.filterInactive')}</Radio>
</RadioGroup>
<Tooltip content={t('listings.filterActivityHelp')} trigger="hover" position="top">
<span className="listingsOverview__topbar__tooltipWrap">
<RadioGroup
type="button"
buttonSize="middle"
value={activityRadioValue}
onChange={(e) => {
const v = e.target.value;
if (v === 'hidden') {
setHiddenOnly(true);
setActivityFilter(null);
} else {
setHiddenOnly(false);
setActivityFilter(v === 'all' ? null : v === 'true');
}
setPage(1);
}}
>
<Radio value="all">{t('listings.filterAll')}</Radio>
<Radio value="true">{t('listings.filterActive')}</Radio>
<Radio value="false">{t('listings.filterInactive')}</Radio>
<Radio value="hidden">{t('listings.filterHidden')}</Radio>
</RadioGroup>
</span>
</Tooltip>
{!isWatchlistMode && (
<RadioGroup
type="button"
buttonSize="middle"
value={watchListFilter === null ? 'all' : String(watchListFilter)}
onChange={(e) => {
const v = e.target.value;
setWatchListFilter(v === 'all' ? null : v === 'true');
setPage(1);
}}
>
<Radio value="all">{t('listings.filterAll')}</Radio>
<Radio value="true">{t('listings.filterWatched')}</Radio>
<Radio value="false">{t('listings.filterUnwatched')}</Radio>
</RadioGroup>
<Tooltip content={t('listings.filterWatchHelp')} trigger="hover" position="top">
<span className="listingsOverview__topbar__tooltipWrap">
<RadioGroup
type="button"
buttonSize="middle"
value={watchListFilter === null ? 'all' : String(watchListFilter)}
onChange={(e) => {
const v = e.target.value;
setWatchListFilter(v === 'all' ? null : v === 'true');
setPage(1);
}}
>
<Radio value="all">{t('listings.filterAll')}</Radio>
<Radio value="true">{t('listings.filterWatched')}</Radio>
<Radio value="false">{t('listings.filterUnwatched')}</Radio>
</RadioGroup>
</span>
</Tooltip>
)}
<Select
placeholder={t('listings.filterStatusPlaceholder')}
showClear
onChange={(val) => {
setStatusFilter(val ?? null);
setPage(1);
}}
value={statusFilter}
style={{ width: 150 }}
>
<Select.Option value="applied">{t('listings.filterStatusApplied')}</Select.Option>
<Select.Option value="rejected">{t('listings.filterStatusRejected')}</Select.Option>
<Select.Option value="accepted">{t('listings.filterStatusAccepted')}</Select.Option>
<Select.Option value="none">{t('listings.filterStatusNone')}</Select.Option>
</Select>
<Tooltip content={t('listings.filterStatusHelp')} trigger="hover" position="top">
<span className="listingsOverview__topbar__tooltipWrap">
<Select
placeholder={t('listings.filterStatusPlaceholder')}
showClear
onChange={(val) => {
setStatusFilter(val ?? null);
setPage(1);
}}
value={statusFilter}
style={{ width: 150 }}
>
<Select.Option value="applied">{t('listings.filterStatusApplied')}</Select.Option>
<Select.Option value="rejected">{t('listings.filterStatusRejected')}</Select.Option>
<Select.Option value="accepted">{t('listings.filterStatusAccepted')}</Select.Option>
<Select.Option value="none">{t('listings.filterStatusNone')}</Select.Option>
</Select>
</span>
</Tooltip>
<Select
placeholder={t('listings.filterProviderPlaceholder')}
showClear
onChange={(val) => {
setProviderFilter(val);
setPage(1);
}}
value={providerFilter}
style={{ width: 130 }}
>
{providers?.map((p) => (
<Select.Option key={p.id} value={p.id}>
{p.name}
</Select.Option>
))}
</Select>
<Tooltip content={t('listings.filterProviderHelp')} trigger="hover" position="top">
<span className="listingsOverview__topbar__tooltipWrap">
<Select
placeholder={t('listings.filterProviderPlaceholder')}
showClear
onChange={(val) => {
setProviderFilter(val);
setPage(1);
}}
value={providerFilter}
style={{ width: 130 }}
>
{providers?.map((p) => (
<Select.Option key={p.id} value={p.id}>
{p.name}
</Select.Option>
))}
</Select>
</span>
</Tooltip>
<Select
placeholder={t('listings.filterJobPlaceholder')}
showClear
onChange={(val) => {
setJobNameFilter(val);
setPage(1);
}}
value={jobNameFilter}
style={{ width: 130 }}
>
{jobs?.map((j) => (
<Select.Option key={j.id} value={j.id}>
{j.name}
</Select.Option>
))}
</Select>
<Tooltip content={t('listings.filterJobHelp')} trigger="hover" position="top">
<span className="listingsOverview__topbar__tooltipWrap">
<Select
placeholder={t('listings.filterJobPlaceholder')}
showClear
onChange={(val) => {
setJobNameFilter(val);
setPage(1);
}}
value={jobNameFilter}
style={{ width: 130 }}
>
{jobs?.map((j) => (
<Select.Option key={j.id} value={j.id}>
{j.name}
</Select.Option>
))}
</Select>
</span>
</Tooltip>
<Select
prefix={t('listings.sortPrefix')}
className="listingsOverview__topbar__sort"
style={{ width: 220 }}
value={sortField}
onChange={(val) => setSortField(val)}
>
<Select.Option value="job_name">{t('listings.sortByJobName')}</Select.Option>
<Select.Option value="created_at">{t('listings.sortByDate')}</Select.Option>
<Select.Option value="price">{t('listings.sortByPrice')}</Select.Option>
<Select.Option value="provider">{t('listings.sortByProvider')}</Select.Option>
</Select>
<Tooltip content={t('listings.filterSortHelp')} trigger="hover" position="top">
<span className="listingsOverview__topbar__tooltipWrap listingsOverview__topbar__sort">
<Select
prefix={t('listings.sortPrefix')}
style={{ width: 220 }}
value={sortField}
onChange={(val) => setSortField(val)}
>
<Select.Option value="job_name">{t('listings.sortByJobName')}</Select.Option>
<Select.Option value="created_at">{t('listings.sortByDate')}</Select.Option>
<Select.Option value="price">{t('listings.sortByPrice')}</Select.Option>
<Select.Option value="provider">{t('listings.sortByProvider')}</Select.Option>
</Select>
</span>
</Tooltip>
<Button
icon={sortDir === 'asc' ? <IconArrowUp /> : <IconArrowDown />}
onClick={() => setSortDir(sortDir === 'asc' ? 'desc' : 'asc')}
title={sortDir === 'asc' ? t('listings.sortAscending') : t('listings.sortDescending')}
/>
<Tooltip
content={sortDir === 'asc' ? t('listings.sortAscending') : t('listings.sortDescending')}
trigger="hover"
position="top"
>
<span className="listingsOverview__topbar__tooltipWrap">
<Button
icon={sortDir === 'asc' ? <IconArrowUp /> : <IconArrowDown />}
onClick={() => setSortDir(sortDir === 'asc' ? 'desc' : 'asc')}
aria-label={sortDir === 'asc' ? t('listings.sortAscending') : t('listings.sortDescending')}
/>
</span>
</Tooltip>
<div className="listingsOverview__topbar__view-toggle">
<Tooltip content={t('listings.tooltipGridView')}>
@@ -293,6 +366,16 @@ const ListingsOverview = ({ mode = 'all' }) => {
</div>
</div>
{isHiddenView && (
<Banner
type="info"
fullMode={false}
closeIcon={null}
description={t('listings.hiddenViewBanner')}
style={{ marginBottom: 12 }}
/>
)}
{listings.length === 0 && (
<Empty
image={<IllustrationNoResult />}
@@ -307,6 +390,8 @@ const ListingsOverview = ({ mode = 'all' }) => {
onWatch={handleWatch}
onNavigate={handleNavigate}
onDelete={handleDelete}
onRestore={handleRestore}
isHiddenView={isHiddenView}
onStatusChange={handleStatusChange}
/>
) : (
@@ -315,6 +400,8 @@ const ListingsOverview = ({ mode = 'all' }) => {
onWatch={handleWatch}
onNavigate={handleNavigate}
onDelete={handleDelete}
onRestore={handleRestore}
isHiddenView={isHiddenView}
onStatusChange={handleStatusChange}
/>
)}

View File

@@ -8,6 +8,15 @@
margin-bottom: @space-4;
flex-wrap: wrap;
&__tooltipWrap {
display: inline-flex;
align-items: center;
> * {
width: 100%;
}
}
&__search {
min-width: 200px;
flex: 1;

View File

@@ -22,9 +22,17 @@ import './ListingsTable.less';
import { useTranslation, useLocale } from '../../services/i18n/i18n.jsx';
/**
* @param {{ listings: object[], onWatch: Function, onNavigate: Function, onDelete: Function, onStatusChange: Function }} props
* @param {{ listings: object[], onWatch: Function, onNavigate: Function, onDelete: Function, onRestore?: Function, isHiddenView?: boolean, onStatusChange: Function }} props
*/
const ListingsTable = ({ listings, onWatch, onNavigate, onDelete, onStatusChange }) => {
const ListingsTable = ({
listings,
onWatch,
onNavigate,
onDelete,
onRestore,
isHiddenView = false,
onStatusChange,
}) => {
const t = useTranslation();
const locale = useLocale();
return (
@@ -123,18 +131,38 @@ const ListingsTable = ({ listings, onWatch, onNavigate, onDelete, onStatusChange
}}
/>
</Tooltip>
<Tooltip content={t('listings.tooltipRemove')}>
<Button
size="small"
icon={<IconDelete />}
style={{ color: '#fb7185' }}
theme="borderless"
onClick={(e) => {
e.stopPropagation();
onDelete(item.id);
}}
/>
</Tooltip>
{isHiddenView ? (
<Tooltip content={t('listings.tooltipUndelete')}>
<Button
size="small"
icon={
<span className="listingsTable__strike" aria-hidden="true">
<IconDelete />
</span>
}
style={{ color: '#34d399' }}
theme="borderless"
onClick={(e) => {
e.stopPropagation();
onRestore?.(item.id);
}}
aria-label={t('listings.tooltipUndelete')}
/>
</Tooltip>
) : (
<Tooltip content={t('listings.tooltipRemove')}>
<Button
size="small"
icon={<IconDelete />}
style={{ color: '#fb7185' }}
theme="borderless"
onClick={(e) => {
e.stopPropagation();
onDelete(item.id);
}}
/>
</Tooltip>
)}
</div>
</div>
))}

View File

@@ -5,6 +5,25 @@
flex-direction: column;
gap: 4px;
&__strike {
position: relative;
display: inline-flex;
align-items: center;
justify-content: center;
&::after {
content: '';
position: absolute;
left: -2px;
right: -2px;
top: 50%;
height: 2px;
background: currentColor;
transform: rotate(-45deg);
pointer-events: none;
}
}
&__row {
display: grid;
grid-template-columns: 56px 1fr 140px 200px 120px 110px auto;

View File

@@ -135,6 +135,7 @@
"listings.filterAll": "Alle",
"listings.filterActive": "Aktiv",
"listings.filterInactive": "Inaktiv",
"listings.filterHidden": "Versteckt",
"listings.filterWatched": "Beobachtet",
"listings.filterUnwatched": "Nicht beobachtet",
"listings.filterStatusPlaceholder": "Status",
@@ -144,6 +145,17 @@
"listings.filterStatusNone": "Kein Status",
"listings.filterProviderPlaceholder": "Anbieter",
"listings.filterJobPlaceholder": "Job",
"listings.filterSearchHelp": "Volltextsuche über Titel, Adresse, Anbieter und Link.",
"listings.filterActivityHelp": "Filtert nach Inseratsstatus: 'Alle' zeigt jedes Inserat, 'Aktiv' nur noch online verfügbare, 'Inaktiv' beim Anbieter verschwundene, 'Versteckt' zeigt deine manuell gelöschten (soft-deleted) Inserate, damit du sie wiederherstellen kannst.",
"listings.filterWatchHelp": "Filtert nach Watchlist-Zugehörigkeit: 'Alle' zeigt jedes Inserat, 'Beobachtet' nur die auf deiner Watchlist gespeicherten, 'Nicht beobachtet' die anderen.",
"listings.filterStatusHelp": "Filtert nach dem persönlichen Status (Beworben, Abgelehnt, Angenommen) oder zeigt nur Inserate ohne Status.",
"listings.filterProviderHelp": "Zeigt nur Inserate des ausgewählten Anbieters (ImmoScout24, Kleinanzeigen, ...).",
"listings.filterJobHelp": "Zeigt nur Inserate des ausgewählten Jobs.",
"listings.filterSortHelp": "Wählt das Sortierkriterium. Mit dem Pfeil-Button schaltet man zwischen aufsteigend und absteigend.",
"listings.hiddenViewBanner": "Du siehst gerade versteckte (soft-gelöschte) Inserate. Sie werden in den normalen Ansichten ausgeblendet. Über den Wiederherstellen-Button kannst du sie zurückholen.",
"listings.toastRestored": "Inserat wiederhergestellt",
"listings.toastRestoreError": "Wiederherstellung fehlgeschlagen",
"listings.tooltipUndelete": "Inserat wiederherstellen",
"listings.sortByJobName": "Job-Name",
"listings.sortByDate": "Inserat-Datum",
"listings.sortByPrice": "Preis",
@@ -295,6 +307,7 @@
"settings.tabExecution": "Ausführung",
"settings.tabUserSettings": "Benutzereinstellungen",
"settings.tabBackup": "Backup & Wiederherstellung",
"settings.tabDebug": "Debug",
"settings.save": "Speichern",
"settings.port": "Port",
"settings.portHelp": "Der Port, auf dem Fredy läuft.",
@@ -333,6 +346,11 @@
"settings.providerDetailsPlaceholder": "Anbieter für Detail-Abruf auswählen...",
"settings.providerDetailsUpdated": "Anbieter-Detail-Einstellung aktualisiert.",
"settings.providerDetailsUpdateError": "Einstellung konnte nicht aktualisiert werden.",
"settings.blacklistFilterOnProviderDetails": "Blacklist-Filter auf Anbieter-Details anwenden",
"settings.blacklistFilterOnProviderDetailsHelp": "Wenn aktiv, wird die Blacklist zusätzlich gegen die vollständige Beschreibung geprüft, die durch den obigen Anbieter-Details-Schritt geladen wurde. Damit lassen sich Spam-Anbieter (z. B. 'allkauf', 'massa') herausfiltern, die nur tief in der Detail-Seite auftauchen und nicht im kurzen Vorschau-Text der Suchergebnisse stehen. Standardmäßig aus, weil die vollständige Beschreibung oft generischen Boilerplate-Text (Kontaktdaten, rechtliche Hinweise) enthält, der ein Blacklist-Wort versehentlich auslösen und passende Inserate entfernen kann. Hat keine Wirkung auf Anbieter, für die Anbieter-Details nicht aktiviert sind.",
"settings.blacklistFilterOnProviderDetailsEnable": "Blacklist auf die vollständige Detail-Beschreibung anwenden",
"settings.blacklistFilterOnProviderDetailsUpdated": "Einstellung Blacklist-auf-Details aktualisiert.",
"settings.blacklistFilterOnProviderDetailsUpdateError": "Einstellung konnte nicht aktualisiert werden.",
"settings.listingDeletion": "Inserate löschen",
"settings.listingDeletionHelp": "Wähle den Standard-Löschmodus. Soft Delete blendet Inserate aus ohne erneutes Scraping; Hard Delete entfernt sie aus der Datenbank.",
"settings.listingDeletionSoftLabel": "Als gelöscht markieren (Soft Delete)",
@@ -365,6 +383,36 @@
"settings.toastSqlitePathEmpty": "Der SQLite-Datenbankpfad darf nicht leer sein.",
"settings.toastSavedReloading": "Einstellungen erfolgreich gespeichert. Der Browser wird in 3 Sekunden neu geladen.",
"settings.toastSaveError": "Fehler beim Speichern der Einstellungen.",
"settings.debugSectionName": "Debug-Logging",
"settings.debugInfoTitle": "Was wird aufgezeichnet?",
"settings.debugInfoDescription": "Wenn aktiviert, schreibt Fredy jede Log-Zeile (debug, info, warn und error) in seine Datenbank. Maximal 5 MB werden gespeichert; sobald die Grenze erreicht ist, werden die ältesten Einträge automatisch gelöscht. Die Konsolen-Ausgabe bleibt unverändert.",
"settings.debugEnableButton": "Debug-Logging aktivieren",
"settings.debugDisableButton": "Debug-Logging deaktivieren",
"settings.debugDownloadButton": "Debug Informationen herunterladen",
"settings.debugUsedLabel": "Belegt:",
"settings.debugUsedValue": "{{used}} von {{max}} ({{percent}}%)",
"settings.debugStatusActive": "Debug-Logging ist aktiv!",
"settings.debugStatusInactive": "Debug-Logging ist inaktiv.",
"settings.debugConfirmReenableTitle": "Vorherige Logs löschen?",
"settings.debugConfirmReenableMessage": "Es sind noch Debug-Logs aus einer vorherigen Sitzung gespeichert. Möchtest du sie löschen, bevor das Debug-Logging erneut aktiviert wird?",
"settings.debugConfirmKeep": "Behalten & fortfahren",
"settings.debugConfirmDelete": "Löschen & aktivieren",
"settings.debugToastEnabled": "Debug-Logging aktiviert.",
"settings.debugToastDisabled": "Debug-Logging deaktiviert.",
"settings.debugToastEnableError": "Debug-Logging konnte nicht aktiviert werden.",
"settings.debugToastDisableError": "Debug-Logging konnte nicht deaktiviert werden.",
"settings.debugToastDownloadError": "Debug-Paket konnte nicht heruntergeladen werden.",
"settings.debugToastNoLogs": "Es sind noch keine Debug-Logs vorhanden. Aktiviere das Debug-Logging und reproduziere das Problem.",
"settings.debugClearButton": "Gespeicherte Debug-Logs löschen",
"settings.debugClearConfirmTitle": "Alle gespeicherten Debug-Logs löschen?",
"settings.debugClearConfirmMessage": "Damit werden alle gespeicherten Debug-Log-Einträge dauerhaft aus der Datenbank entfernt. Die Aufzeichnung selbst bleibt {{recordingState}}. Diese Aktion kann nicht rückgängig gemacht werden.",
"settings.debugClearConfirmRecordingOn": "Aktiv",
"settings.debugClearConfirmRecordingOff": "Inaktiv",
"settings.debugClearConfirmDelete": "Ja, Logs löschen",
"settings.debugClearConfirmCancel": "Abbrechen",
"settings.debugToastCleared": "Gespeicherte Debug-Logs wurden gelöscht.",
"settings.debugToastClearError": "Gespeicherte Debug-Logs konnten nicht gelöscht werden.",
"app.debugLoggingBanner": "Debug-Logging ist aktiv! Alles was Fredy loggt, wird in der Datenbank gespeichert. Deaktiviere es unter Einstellungen → Debug, sobald du fertig bist.",
"watchlist.sectionName": "Benachrichtigung für Watchlist",
"watchlist.sectionHelp": "Du kannst bei Änderungen an Inseraten auf deiner Watchlist benachrichtigt werden.",

View File

@@ -135,6 +135,7 @@
"listings.filterAll": "All",
"listings.filterActive": "Active",
"listings.filterInactive": "Inactive",
"listings.filterHidden": "Hidden",
"listings.filterWatched": "Watched",
"listings.filterUnwatched": "Unwatched",
"listings.filterStatusPlaceholder": "Status",
@@ -144,6 +145,17 @@
"listings.filterStatusNone": "No status",
"listings.filterProviderPlaceholder": "Provider",
"listings.filterJobPlaceholder": "Job",
"listings.filterSearchHelp": "Free-text search across title, address, provider and link.",
"listings.filterActivityHelp": "Filter by listing activity: All shows every listing, Active only those still online, Inactive those that disappeared from the provider, Hidden shows your manually deleted (soft-deleted) listings so you can restore them.",
"listings.filterWatchHelp": "Filter by watchlist membership: All shows every listing, Watched only those you saved to your watchlist, Unwatched only those you have not saved.",
"listings.filterStatusHelp": "Filter by the personal status you set on a listing (Applied, Rejected, Accepted) or show only listings with no status yet.",
"listings.filterProviderHelp": "Show only listings coming from the selected real-estate provider (ImmoScout24, Kleinanzeigen, ...).",
"listings.filterJobHelp": "Show only listings produced by the selected job.",
"listings.filterSortHelp": "Choose the column to sort listings by. Use the arrow button to toggle ascending and descending order.",
"listings.hiddenViewBanner": "You are viewing hidden (soft-deleted) listings. They are excluded from the regular views. Use the restore button on a card to bring it back.",
"listings.toastRestored": "Listing restored",
"listings.toastRestoreError": "Failed to restore listing",
"listings.tooltipUndelete": "Restore Listing",
"listings.sortByJobName": "Job Name",
"listings.sortByDate": "Listing Date",
"listings.sortByPrice": "Price",
@@ -295,6 +307,7 @@
"settings.tabExecution": "Execution",
"settings.tabUserSettings": "User Settings",
"settings.tabBackup": "Backup & Restore",
"settings.tabDebug": "Debug",
"settings.save": "Save",
"settings.port": "Port",
"settings.portHelp": "The port on which Fredy is running.",
@@ -333,6 +346,11 @@
"settings.providerDetailsPlaceholder": "Select providers to fetch details from...",
"settings.providerDetailsUpdated": "Provider details setting updated.",
"settings.providerDetailsUpdateError": "Failed to update setting.",
"settings.blacklistFilterOnProviderDetails": "Blacklist-Filtering on Provider Details",
"settings.blacklistFilterOnProviderDetailsHelp": "When enabled, the blacklist is re-checked against the full description loaded by the Provider Details step above. This catches spam advertisers (e.g. 'allkauf', 'massa') that only appear deep in the detail page and not in the short search-result snippet. Off by default, because the full description often contains generic boilerplate (contact info, legal text) that may accidentally trigger a blacklist term and remove otherwise relevant listings. Has no effect on providers for which Provider Details is not enabled.",
"settings.blacklistFilterOnProviderDetailsEnable": "Apply blacklist to the full detail description",
"settings.blacklistFilterOnProviderDetailsUpdated": "Blacklist-on-details setting updated.",
"settings.blacklistFilterOnProviderDetailsUpdateError": "Failed to update setting.",
"settings.listingDeletion": "Listing deletion",
"settings.listingDeletionHelp": "Choose the default deletion mode. Soft delete hides them without re-scraping; hard delete removes them from the database.",
"settings.listingDeletionSoftLabel": "Mark as deleted (Soft Delete)",
@@ -365,6 +383,36 @@
"settings.toastSqlitePathEmpty": "SQLite db path cannot be empty.",
"settings.toastSavedReloading": "Settings stored successfully. We will reload your browser in 3 seconds.",
"settings.toastSaveError": "Error while trying to store settings.",
"settings.debugSectionName": "Debug Logging",
"settings.debugInfoTitle": "What gets recorded?",
"settings.debugInfoDescription": "When enabled, Fredy records every log line (debug, info, warn and error) into its database. A maximum of 5 MB is kept; once the cap is reached, the oldest entries are dropped automatically. Console output is unaffected.",
"settings.debugEnableButton": "Enable debug logging",
"settings.debugDisableButton": "Disable debug logging",
"settings.debugDownloadButton": "Download debug information",
"settings.debugUsedLabel": "Used:",
"settings.debugUsedValue": "{{used}} of {{max}} ({{percent}}%)",
"settings.debugStatusActive": "Debug logging is currently active.",
"settings.debugStatusInactive": "Debug logging is currently inactive.",
"settings.debugConfirmReenableTitle": "Delete previous logs?",
"settings.debugConfirmReenableMessage": "Debug logs from a previous session are still stored. Do you want to delete them before enabling debug logging again?",
"settings.debugConfirmKeep": "Keep & continue",
"settings.debugConfirmDelete": "Delete & enable",
"settings.debugToastEnabled": "Debug logging enabled.",
"settings.debugToastDisabled": "Debug logging disabled.",
"settings.debugToastEnableError": "Could not enable debug logging.",
"settings.debugToastDisableError": "Could not disable debug logging.",
"settings.debugToastDownloadError": "Could not download the debug bundle.",
"settings.debugToastNoLogs": "No debug logs available yet. Enable debug logging first and reproduce the issue.",
"settings.debugClearButton": "Delete stored debug logs",
"settings.debugClearConfirmTitle": "Delete all stored debug logs?",
"settings.debugClearConfirmMessage": "This permanently removes every stored debug log entry from the database. Recording itself will stay {{recordingState}}. This action cannot be undone.",
"settings.debugClearConfirmRecordingOn": "ON",
"settings.debugClearConfirmRecordingOff": "OFF",
"settings.debugClearConfirmDelete": "Yes, delete logs",
"settings.debugClearConfirmCancel": "Cancel",
"settings.debugToastCleared": "Stored debug logs were deleted.",
"settings.debugToastClearError": "Could not delete the stored debug logs.",
"app.debugLoggingBanner": "Debug logging is active! Everything Fredy logs is being stored in its database. Disable it in Settings → Debug once you're done.",
"watchlist.sectionName": "Notification for Watch List",
"watchlist.sectionHelp": "You can get notified for changes on listings from your watch list.",

View File

@@ -0,0 +1,124 @@
/*
* Copyright (c) 2026 by Christian Kellner.
* Licensed under Apache-2.0 with Commons Clause and Attribution/Naming Clause
*/
/**
* Tiny client wrapping the /api/admin/debug endpoints.
*
* The server returns the same status payload from every mutation endpoint so the UI
* does not need to re-fetch after enable/disable, it can apply the response payload
* directly.
*/
function extractFileNameFromDisposition(disposition) {
const dispo = disposition || '';
// RFC 6266 says the UTF-8 encoded `filename*=` form takes precedence over the
// legacy `filename=` form when both are present. Match each form independently
// and prefer the UTF-8 one so we cannot accidentally pick the wrong encoding.
const utf8Match = dispo.match(/filename\*=UTF-8''([^;]+)/);
if (utf8Match) {
try {
return decodeURIComponent(utf8Match[1]);
} catch {
// malformed percent-encoding; fall through to the legacy form
}
}
const legacyMatch = dispo.match(/filename="?([^";]+)"?/);
if (legacyMatch) return legacyMatch[1];
return 'FredyDebug.zip';
}
/**
* Fetch the current feature status. Requires admin auth.
* @returns {Promise<{enabled:boolean, size:number, max:number, hasLogs:boolean, everEnabled:boolean}>}
*/
export async function fetchDebugStatus() {
const resp = await fetch('/api/admin/debug/status', { credentials: 'include' });
if (!resp.ok) throw new Error('Failed to load debug logging status');
return resp.json();
}
/**
* Lightweight "is debug logging active right now?" probe usable by any authenticated
* user. Used by the app-wide red banner so non-admin users also see the warning. The
* payload is intentionally a single boolean, no other settings are exposed.
*
* @returns {Promise<{enabled:boolean}>}
*/
export async function fetchDebugActive() {
const resp = await fetch('/api/debug/active', { credentials: 'include' });
if (!resp.ok) throw new Error('Failed to load debug active flag');
return resp.json();
}
/**
* Enable the feature. When clearPrevious is true, existing log rows are dropped
* before the new collection starts.
* @param {{clearPrevious?:boolean}} [options]
* @returns {Promise<object>}
*/
export async function enableDebugLogging({ clearPrevious = false } = {}) {
const resp = await fetch('/api/admin/debug/enable', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ clearPrevious }),
});
if (!resp.ok) throw new Error('Failed to enable debug logging');
return resp.json();
}
/**
* Disable the feature. Existing logs remain on disk so they can still be downloaded.
* @returns {Promise<object>}
*/
export async function disableDebugLogging() {
const resp = await fetch('/api/admin/debug/disable', {
method: 'POST',
credentials: 'include',
});
if (!resp.ok) throw new Error('Failed to disable debug logging');
return resp.json();
}
/**
* Drop every stored debug log row. Does NOT change the enabled flag: if recording
* was on, it stays on and the table simply starts filling again. Returns the new
* status payload.
* @returns {Promise<object>}
*/
export async function clearDebugLogs() {
const resp = await fetch('/api/admin/debug/logs', {
method: 'DELETE',
credentials: 'include',
});
if (!resp.ok) throw new Error('Failed to clear debug logs');
return resp.json();
}
/**
* Trigger the debug bundle download. Throws when there is nothing to export (server
* returns 409 in that case) or any other non-2xx response.
* @returns {Promise<void>}
*/
export async function downloadDebugBundle() {
const resp = await fetch('/api/admin/debug/download', { credentials: 'include' });
if (resp.status === 409) {
const data = await resp.json().catch(() => ({}));
const err = new Error(data?.error || 'No debug logs available yet');
err.code = 'NO_LOGS';
throw err;
}
if (!resp.ok) throw new Error('Failed to download debug bundle');
const blob = await resp.blob();
const fileName = extractFileNameFromDisposition(resp.headers.get('Content-Disposition'));
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = fileName;
document.body.appendChild(a);
a.click();
a.remove();
window.URL.revokeObjectURL(url);
}

View File

@@ -276,6 +276,14 @@ export const useFredyState = create(
throw Exception;
}
},
async restoreListings(ids) {
try {
await xhrPost('/api/listings/restore', { ids });
} catch (Exception) {
console.error('Error while trying to restore listings. Error:', Exception);
throw Exception;
}
},
},
userSettings: {
async getUserSettings() {
@@ -337,6 +345,28 @@ export const useFredyState = create(
throw Exception;
}
},
async setBlacklistFilterOnProviderDetails(enabled) {
try {
await xhrPost('/api/user/settings/blacklist-filter-on-details', {
blacklist_filter_on_provider_details: enabled,
});
set((state) => ({
userSettings: {
...state.userSettings,
settings: {
...state.userSettings.settings,
blacklist_filter_on_provider_details: enabled,
},
},
}));
} catch (Exception) {
console.error(
'Error while trying to update blacklist-filter-on-provider-details setting. Error:',
Exception,
);
throw Exception;
}
},
async setListingsViewMode(listings_view_mode) {
try {
await xhrPost('/api/user/settings/listings-view-mode', { listings_view_mode });

View File

@@ -22,6 +22,7 @@ import {
Radio,
RadioGroup,
Typography,
Progress,
} from '@douyinfe/semi-ui-19';
import { InputNumber } from '@douyinfe/semi-ui-19';
import { xhrPost, xhrGet } from '../../services/xhr';
@@ -32,7 +33,14 @@ import {
precheckRestore as clientPrecheckRestore,
restore as clientRestore,
} from '../../services/backupRestoreClient';
import { IconSave, IconRefresh, IconSignal, IconHome, IconFolder } from '@douyinfe/semi-icons';
import {
fetchDebugStatus,
enableDebugLogging as apiEnableDebugLogging,
disableDebugLogging as apiDisableDebugLogging,
downloadDebugBundle,
clearDebugLogs as apiClearDebugLogs,
} from '../../services/debugLoggingClient';
import { IconSave, IconRefresh, IconSignal, IconHome, IconFolder, IconAlertTriangle } from '@douyinfe/semi-icons';
import { debounce } from '../../utils';
import Headline from '../../components/headline/Headline.jsx';
import './GeneralSettings.less';
@@ -55,6 +63,32 @@ function formatFromTBackend(time) {
return date.getTime();
}
/**
* Human-readable byte formatter used by the Debug tab's usage label.
* @param {number} bytes
* @returns {string}
*/
function formatBytes(bytes) {
if (!Number.isFinite(bytes)) return String(bytes);
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KiB`;
return `${(bytes / (1024 * 1024)).toFixed(2)} MiB`;
}
/**
* Compute the integer percentage that `used` represents of `total`, clamped to [0, 100].
* @param {number} used
* @param {number} total
* @returns {number}
*/
function percentOf(used, total) {
if (!total || total <= 0) return 0;
const pct = Math.round((used / total) * 100);
if (pct < 0) return 0;
if (pct > 100) return 100;
return pct;
}
const GeneralSettings = function GeneralSettings() {
const actions = useActions();
const t = useTranslation();
@@ -79,9 +113,26 @@ const GeneralSettings = function GeneralSettings() {
const [restoreBusy, setRestoreBusy] = React.useState(false);
const [selectedRestoreFile, setSelectedRestoreFile] = React.useState(null);
// Debug-logging tab state. status is fetched on mount + polled every 3s while the
// feature is active so the progress bar reflects the live byte budget.
// debugStatusSeq monotonically increases with every applied status update so we can
// discard stale polling responses that arrive after a manual enable/disable.
const [debugStatus, setDebugStatus] = React.useState(null);
const [debugBusy, setDebugBusy] = React.useState(false);
const [debugConfirmVisible, setDebugConfirmVisible] = React.useState(false);
const [debugClearConfirmVisible, setDebugClearConfirmVisible] = React.useState(false);
const debugStatusSeqRef = React.useRef(0);
const applyDebugStatus = React.useCallback((fresh) => {
debugStatusSeqRef.current += 1;
setDebugStatus(fresh);
}, []);
// User settings state
const homeAddress = useSelector((state) => state.userSettings.settings.home_address);
const providerDetails = useSelector((state) => state.userSettings.settings.provider_details);
const blacklistFilterOnProviderDetails = useSelector(
(state) => state.userSettings.settings.blacklist_filter_on_provider_details,
);
const listingDeletionPreference = useSelector((state) => state.userSettings.settings.listing_deletion_preference);
const allProviders = useSelector((state) => state.provider);
const [address, setAddress] = useState(homeAddress?.address || '');
@@ -127,6 +178,45 @@ const GeneralSettings = function GeneralSettings() {
setListingDeleteSkipPrompt(listingDeletionPreference?.skipPrompt ?? false);
}, [listingDeletionPreference]);
// Initial debug-status load. Subsequent updates flow through applyDebugStatus()
// (called by polling + after every enable/disable action), so this effect only
// needs to fire once on mount.
useEffect(() => {
let cancelled = false;
fetchDebugStatus()
.then((s) => {
if (!cancelled) applyDebugStatus(s);
})
.catch((e) => {
// Non-fatal: tab is still usable, polling will retry.
console.error('Failed to load debug status', e);
});
return () => {
cancelled = true;
};
}, [applyDebugStatus]);
// Live polling while the feature is active so the progress bar reflects new entries
// as they are written. We intentionally do NOT poll while inactive — the size stays
// constant and there's no Banner to update. Stale poll responses (where a manual
// enable/disable bumped the sequence in the meantime) are discarded so the UI does
// not flicker back to the previous state for ~3s.
useEffect(() => {
if (!debugStatus?.enabled) return undefined;
const id = window.setInterval(async () => {
const seqAtStart = debugStatusSeqRef.current;
try {
const fresh = await fetchDebugStatus();
if (debugStatusSeqRef.current === seqAtStart) {
applyDebugStatus(fresh);
}
} catch {
// ignore transient errors; next tick will retry
}
}, 3000);
return () => window.clearInterval(id);
}, [debugStatus?.enabled, applyDebugStatus]);
const nullOrEmpty = (val) => val == null || val.length === 0;
const handleStore = async () => {
@@ -231,6 +321,89 @@ const GeneralSettings = function GeneralSettings() {
}
}, []);
// ── Debug-logging actions ────────────────────────────────────────────────────
// performEnableDebug() centralizes the actual enable call so both branches of the
// confirm dialog ("delete" vs. "keep") plus the no-confirm fast-path can share it.
const performEnableDebug = React.useCallback(
async ({ clearPrevious }) => {
setDebugBusy(true);
try {
const fresh = await apiEnableDebugLogging({ clearPrevious });
applyDebugStatus(fresh);
// Keep the global generalSettings store in sync so the app-wide red banner
// (which reads settings.debug_logging_enabled) updates immediately.
await actions.generalSettings.getGeneralSettings();
Toast.success(t('settings.debugToastEnabled'));
} catch (e) {
console.error(e);
Toast.error(t('settings.debugToastEnableError'));
} finally {
setDebugBusy(false);
setDebugConfirmVisible(false);
}
},
[actions.generalSettings, applyDebugStatus, t],
);
const handleToggleDebugLogging = React.useCallback(async () => {
// Guard against the initial-load race: if status hasn't arrived yet, ignore the
// click. The button is also disabled when debugStatus == null, this is belt &
// braces for the case where the click somehow reached the handler anyway.
if (debugStatus == null) return;
if (debugStatus.enabled) {
setDebugBusy(true);
try {
const fresh = await apiDisableDebugLogging();
applyDebugStatus(fresh);
await actions.generalSettings.getGeneralSettings();
Toast.success(t('settings.debugToastDisabled'));
} catch (e) {
console.error(e);
Toast.error(t('settings.debugToastDisableError'));
} finally {
setDebugBusy(false);
}
return;
}
// Enabling: if logs from a previous session are still around, ask first.
if (debugStatus.hasLogs) {
setDebugConfirmVisible(true);
return;
}
await performEnableDebug({ clearPrevious: false });
}, [debugStatus, performEnableDebug, actions.generalSettings, applyDebugStatus, t]);
const handleDownloadDebugBundle = React.useCallback(async () => {
try {
await downloadDebugBundle();
} catch (e) {
console.error(e);
if (e?.code === 'NO_LOGS') {
Toast.error(t('settings.debugToastNoLogs'));
} else {
Toast.error(t('settings.debugToastDownloadError'));
}
}
}, [t]);
// Deleting stored logs is a separate action from disabling the feature: the user can
// free up the rolling buffer mid-recording without turning off collection. The
// confirmation dialog makes the destructive nature explicit.
const performClearDebugLogs = React.useCallback(async () => {
setDebugBusy(true);
try {
const fresh = await apiClearDebugLogs();
applyDebugStatus(fresh);
Toast.success(t('settings.debugToastCleared'));
} catch (e) {
console.error(e);
Toast.error(t('settings.debugToastClearError'));
} finally {
setDebugBusy(false);
setDebugClearConfirmVisible(false);
}
}, [applyDebugStatus, t]);
const handleSaveUserSettings = async () => {
try {
const responseJson = await actions.userSettings.setHomeAddress(address);
@@ -477,6 +650,25 @@ const GeneralSettings = function GeneralSettings() {
/>
</SegmentPart>
<SegmentPart
name={t('settings.blacklistFilterOnProviderDetails')}
helpText={t('settings.blacklistFilterOnProviderDetailsHelp')}
>
<Checkbox
checked={blacklistFilterOnProviderDetails === true}
onChange={async (e) => {
try {
await actions.userSettings.setBlacklistFilterOnProviderDetails(e.target.checked);
Toast.success(t('settings.blacklistFilterOnProviderDetailsUpdated'));
} catch {
Toast.error(t('settings.blacklistFilterOnProviderDetailsUpdateError'));
}
}}
>
{t('settings.blacklistFilterOnProviderDetailsEnable')}
</Checkbox>
</SegmentPart>
<SegmentPart name={t('settings.listingDeletion')} helpText={t('settings.listingDeletionHelp')}>
<RadioGroup
value={listingDeleteHard ? 'hard' : 'soft'}
@@ -572,6 +764,98 @@ const GeneralSettings = function GeneralSettings() {
</SegmentPart>
</div>
</TabPane>
{currentUser?.isAdmin && (
<TabPane
tab={
<span>
<IconAlertTriangle
size="small"
style={{
marginRight: 6,
color: debugStatus?.enabled ? 'var(--semi-color-danger)' : undefined,
}}
/>
{t('settings.tabDebug')}
</span>
}
itemKey="debug"
>
<div className="generalSettings__tab-content">
<SegmentPart name={t('settings.debugSectionName')}>
<Banner
type="info"
fullMode={false}
closeIcon={null}
style={{ marginBottom: 12 }}
title={<div style={{ fontWeight: 600, fontSize: '14px' }}>{t('settings.debugInfoTitle')}</div>}
description={t('settings.debugInfoDescription')}
/>
{debugStatus?.enabled ? (
<Banner
type="danger"
fullMode={false}
closeIcon={null}
style={{ marginBottom: 12 }}
description={
<div>
<div style={{ fontWeight: 600 }}>{t('settings.debugStatusActive')}</div>
<div style={{ marginTop: 8 }}>
<Text type="secondary" style={{ marginRight: 8 }}>
{t('settings.debugUsedLabel')}
</Text>
<Text>
{t('settings.debugUsedValue', {
used: formatBytes(debugStatus.size),
max: formatBytes(debugStatus.max),
percent: percentOf(debugStatus.size, debugStatus.max),
})}
</Text>
<Progress
percent={percentOf(debugStatus.size, debugStatus.max)}
stroke="var(--semi-color-danger)"
aria-label="debug log storage"
style={{ marginTop: 6 }}
/>
</div>
</div>
}
/>
) : (
<div style={{ marginBottom: 12 }}>
<Text type="secondary">{t('settings.debugStatusInactive')}</Text>
</div>
)}
<div style={{ display: 'flex', gap: '0.5rem', flexWrap: 'wrap' }}>
<Button
theme="solid"
type={debugStatus?.enabled ? 'danger' : 'primary'}
loading={debugBusy}
disabled={debugStatus == null}
onClick={handleToggleDebugLogging}
>
{debugStatus?.enabled ? t('settings.debugDisableButton') : t('settings.debugEnableButton')}
</Button>
<Button
theme="light"
icon={<IconSave />}
disabled={debugStatus == null || !debugStatus?.everEnabled || !debugStatus?.hasLogs}
onClick={handleDownloadDebugBundle}
>
{t('settings.debugDownloadButton')}
</Button>
{debugStatus?.hasLogs && (
<Button theme="solid" type="warning" onClick={() => setDebugClearConfirmVisible(true)}>
{t('settings.debugClearButton')}
</Button>
)}
</div>
</SegmentPart>
</div>
</TabPane>
)}
</Tabs>
</>
)}
@@ -621,6 +905,65 @@ const GeneralSettings = function GeneralSettings() {
</div>
</Modal>
)}
{debugConfirmVisible && (
<Modal
title={t('settings.debugConfirmReenableTitle')}
visible={debugConfirmVisible}
onCancel={() => {
// Defensive reset in case a network blip left debugBusy stuck while the
// user dismissed the dialog via the X / backdrop.
setDebugBusy(false);
setDebugConfirmVisible(false);
}}
footer={
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
<Button onClick={() => performEnableDebug({ clearPrevious: false })} loading={debugBusy}>
{t('settings.debugConfirmKeep')}
</Button>
<Button
type="danger"
theme="solid"
onClick={() => performEnableDebug({ clearPrevious: true })}
loading={debugBusy}
>
{t('settings.debugConfirmDelete')}
</Button>
</div>
}
>
<div>{t('settings.debugConfirmReenableMessage')}</div>
</Modal>
)}
{debugClearConfirmVisible && (
<Modal
title={t('settings.debugClearConfirmTitle')}
visible={debugClearConfirmVisible}
onCancel={() => {
setDebugBusy(false);
setDebugClearConfirmVisible(false);
}}
footer={
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
<Button onClick={() => setDebugClearConfirmVisible(false)} disabled={debugBusy}>
{t('settings.debugClearConfirmCancel')}
</Button>
<Button type="warning" theme="solid" onClick={performClearDebugLogs} loading={debugBusy}>
{t('settings.debugClearConfirmDelete')}
</Button>
</div>
}
>
<div>
{t('settings.debugClearConfirmMessage', {
recordingState: debugStatus?.enabled
? t('settings.debugClearConfirmRecordingOn')
: t('settings.debugClearConfirmRecordingOff'),
})}
</div>
</Modal>
)}
</div>
);
};

View File

@@ -8,7 +8,7 @@ import React, { useEffect } from 'react';
import cityBackground from '../../assets/city_background.jpg';
import Logo from '../../components/logo/Logo';
import { xhrPost } from '../../services/xhr';
import { useNavigate } from 'react-router-dom';
import { useLocation, useNavigate } from 'react-router-dom';
import { useActions, useSelector } from '../../services/state/store';
import { Input, Button, Banner } from '@douyinfe/semi-ui-19';
@@ -24,6 +24,7 @@ export default function Login() {
const [error, setError] = React.useState(null);
const demoMode = useSelector((state) => state.demoMode.demoMode || false);
const navigate = useNavigate();
const location = useLocation();
useEffect(() => {
async function init() {
@@ -52,7 +53,7 @@ export default function Login() {
}
await actions.user.getCurrentUser();
navigate('/dashboard');
navigate(location.state?.from?.pathname || '/dashboard');
};
return (

View File

@@ -7,7 +7,10 @@ import react from '@vitejs/plugin-react';
import { defineConfig } from 'vite';
// https://vitejs.dev/config/
export default defineConfig({
base: '',
// Must be absolute: with a relative base, asset URLs in index.html break on
// deep links like /listings/listing/:id (the SPA fallback serves index.html,
// but ./assets/* then resolves below the route path and loads HTML as JS).
base: '/',
build: {
chunkSizeWarningLimit: 9999999,
outDir: './ui/public',

154
yarn.lock
View File

@@ -950,34 +950,34 @@
dependencies:
tslib "^2.0.0"
"@douyinfe/semi-animation-react@2.99.3":
version "2.99.3"
resolved "https://registry.yarnpkg.com/@douyinfe/semi-animation-react/-/semi-animation-react-2.99.3.tgz#504e45896db45761d173be8a68cb2aa43157e8cd"
integrity sha512-0iUWQRO1t838Q1VaPE7DwOnYWeAuuu98MrNnaFkbD8JncYsct2K/2A5TDfa56DwSZ5iVz53jz2En8dMi7oF8sw==
"@douyinfe/semi-animation-react@2.100.0":
version "2.100.0"
resolved "https://registry.yarnpkg.com/@douyinfe/semi-animation-react/-/semi-animation-react-2.100.0.tgz#f53cb41a259f4dfefafd68cab76964635a215736"
integrity sha512-zp224kBejXu+28z56uxLNasaijDJN55w0Ll+/JN+NaksTeKoUteEa93hx2SZVt6GGwZAM3H3mfDwF1UcE+fvLA==
dependencies:
"@douyinfe/semi-animation" "2.99.3"
"@douyinfe/semi-animation-styled" "2.99.3"
"@douyinfe/semi-animation" "2.100.0"
"@douyinfe/semi-animation-styled" "2.100.0"
classnames "^2.2.6"
"@douyinfe/semi-animation-styled@2.99.3":
version "2.99.3"
resolved "https://registry.yarnpkg.com/@douyinfe/semi-animation-styled/-/semi-animation-styled-2.99.3.tgz#d810fd4fb1e2fa6c617b479b3bcbf6ef91d1e4d8"
integrity sha512-38/ui6SoIJFWRs2jHv1IiNV2CKHaQKhYB4WftCVXCaYYQGL24+0oQ3iLo6qUeaHEWiQK3EcK2Rt7pxtJCJxVOA==
"@douyinfe/semi-animation-styled@2.100.0":
version "2.100.0"
resolved "https://registry.yarnpkg.com/@douyinfe/semi-animation-styled/-/semi-animation-styled-2.100.0.tgz#20a3fde32b94feb4d1fdf7eba037b19ad74c99ba"
integrity sha512-UHluoWLAHPSVYK2OpdreaSHQI3bh300rrp/dP0UCjsl3FngTUHhsOHVqdWPJ3flTWnc3Mg1Flqr2gUmFjHplhw==
"@douyinfe/semi-animation@2.99.3":
version "2.99.3"
resolved "https://registry.yarnpkg.com/@douyinfe/semi-animation/-/semi-animation-2.99.3.tgz#3544687b8bc1f287c60a0f116494ce23adb42893"
integrity sha512-Uva9MLF+EjC+m6eBYnX9PFZIQKLxD+iKV6ps/nX/P1FWy17DCDxIsga/cByF0PIsVRLzrSdkCsddj3XETcDw9A==
"@douyinfe/semi-animation@2.100.0":
version "2.100.0"
resolved "https://registry.yarnpkg.com/@douyinfe/semi-animation/-/semi-animation-2.100.0.tgz#2f96f57d5c60d732eae5bd02a90ee1e6ec4d23b4"
integrity sha512-X9AxxUrrHWhgxxLkM4oJw8ZM/VAXsu7/fkr4dyIkkZHDhQcnMfMc2YtughqaVqkaicm3SV9zRx9npjYe/S5nVw==
dependencies:
bezier-easing "^2.1.0"
"@douyinfe/semi-foundation@2.99.3":
version "2.99.3"
resolved "https://registry.yarnpkg.com/@douyinfe/semi-foundation/-/semi-foundation-2.99.3.tgz#ac7f9afd4d141711a5aca14b0a1b6e4ffba70417"
integrity sha512-HKzrcdNGYoEZD81CKI6fj8jU2MWNrZx8HZ0NDHym+smBxSyhpoE/b0FrVo0PmLjCzbCDnySDdJ31GsK5GScmuw==
"@douyinfe/semi-foundation@2.100.0":
version "2.100.0"
resolved "https://registry.yarnpkg.com/@douyinfe/semi-foundation/-/semi-foundation-2.100.0.tgz#e503dbc31bbc18c2f8862653bcbdc1d5a330fd65"
integrity sha512-D2pjhpqOMOpjgw4M4Hg0Pj8KSnxl/jVsfynrIji5TwW7V2bGgt/aWOnBqdTXlrTLk4CHDmfAXKyr+rxY9aihhw==
dependencies:
"@douyinfe/semi-animation" "2.99.3"
"@douyinfe/semi-json-viewer-core" "2.99.3"
"@douyinfe/semi-animation" "2.100.0"
"@douyinfe/semi-json-viewer-core" "2.100.0"
"@mdx-js/mdx" "^3.0.1"
async-validator "^3.5.0"
classnames "^2.2.6"
@@ -991,44 +991,44 @@
remark-gfm "^4.0.0"
scroll-into-view-if-needed "^2.2.24"
"@douyinfe/semi-icons@2.99.3", "@douyinfe/semi-icons@^2.99.3":
version "2.99.3"
resolved "https://registry.yarnpkg.com/@douyinfe/semi-icons/-/semi-icons-2.99.3.tgz#295d4fd79b2bf987bbcd34c0a4e3fb364f96e509"
integrity sha512-Pm5H3Ua/PDumUCCsnJWwN+znVoKiyFCqag6DJy9/cuF6OOdd1+QUnvi0NHNg6+0fx/LHH088UwKFoOiZRkbaSw==
"@douyinfe/semi-icons@2.100.0", "@douyinfe/semi-icons@^2.100.0":
version "2.100.0"
resolved "https://registry.yarnpkg.com/@douyinfe/semi-icons/-/semi-icons-2.100.0.tgz#b0853f230bfa993acbf90a1c2e9fcbb97321819b"
integrity sha512-S/UZAOgzhbk2Dpwn0mUz/SrjswRpSTjSupzluLO0QmM8mCVuLSetmJ0Y/HO4MGM1eY9rEUrXON/FV3+SukFzxQ==
dependencies:
classnames "^2.2.6"
"@douyinfe/semi-illustrations@2.99.3":
version "2.99.3"
resolved "https://registry.yarnpkg.com/@douyinfe/semi-illustrations/-/semi-illustrations-2.99.3.tgz#e97d6c30830d44b7ec299d7e05f1a6e3c4938bf7"
integrity sha512-z1rQPgWOV2xtZS8NkmL8JCK1DltQ8FGiL1qYlXbSHjEs1XkNYruq4W3dKv0IJEpTVLIlPsbDg4VmPAuuwLCCkQ==
"@douyinfe/semi-illustrations@2.100.0":
version "2.100.0"
resolved "https://registry.yarnpkg.com/@douyinfe/semi-illustrations/-/semi-illustrations-2.100.0.tgz#4ca6623eedd1944817f1b7c8eba0095a6a7d2985"
integrity sha512-SN7plpE328WGBohLHOVpYe6FwWSO6RLS7Xf6LhqEdtarwK52ircr4C/b+OyRqIwcLOzRYMgIoqcWnAQGmowcUw==
"@douyinfe/semi-json-viewer-core@2.99.3":
version "2.99.3"
resolved "https://registry.yarnpkg.com/@douyinfe/semi-json-viewer-core/-/semi-json-viewer-core-2.99.3.tgz#a8dee4ea6cbf1bcac85c723696a9430b4faf3152"
integrity sha512-KEbZEyyM2qqGv9K+Yw/ZvAn4CEgcY2lQfL6a2ASEt80FlPoDAIWA7tGjpYxxM9/NcX9omNtsM/HLgDmrCjjBXQ==
"@douyinfe/semi-json-viewer-core@2.100.0":
version "2.100.0"
resolved "https://registry.yarnpkg.com/@douyinfe/semi-json-viewer-core/-/semi-json-viewer-core-2.100.0.tgz#c0c3bf50f722aa51008a8e6acf17ac7842baceeb"
integrity sha512-iQ6rX04YBngrsMz7Eds8zBI+W0MXb0mAICvfTaiX8RpoAwau9yFwbyHiCPKOVPSzI0hS8GwdMLSIYxdCOQPNqQ==
dependencies:
jsonc-parser "^3.3.1"
"@douyinfe/semi-theme-default@2.99.3":
version "2.99.3"
resolved "https://registry.yarnpkg.com/@douyinfe/semi-theme-default/-/semi-theme-default-2.99.3.tgz#e5ee0e4a8eec413ea3f58ed12f93415729c47251"
integrity sha512-r0IIjrN6vQE1bqbky7FIRi4HQ03x4ykzSIRMf4Za04BFp76IFV6CclyYyUg6cLJ6GjWCnEPMFtwTLKP+b8dAYA==
"@douyinfe/semi-theme-default@2.100.0":
version "2.100.0"
resolved "https://registry.yarnpkg.com/@douyinfe/semi-theme-default/-/semi-theme-default-2.100.0.tgz#919bb12307f6b3258016cf36e320c607717eb8c2"
integrity sha512-7tJjg5NiuUYtChWr/E5rQ4Kcko3izz8rTxlNDWSS4YR3RQg3S+lQTgG5bD7LMnBqX399erf3wgE35KLwQZKWTg==
"@douyinfe/semi-ui-19@^2.99.3":
version "2.99.3"
resolved "https://registry.yarnpkg.com/@douyinfe/semi-ui-19/-/semi-ui-19-2.99.3.tgz#236a8894ea38ac3cd9d4a4d9c784dc9712b2105a"
integrity sha512-HrXK1xIXfzS7OYzkrS+3PQKlMnx6J5HEw7wfYtDvGSIN/riSbjeD8vciHeIvP1tvhEAubFY8DMFwT07ZdmqfxA==
"@douyinfe/semi-ui-19@^2.100.0":
version "2.100.0"
resolved "https://registry.yarnpkg.com/@douyinfe/semi-ui-19/-/semi-ui-19-2.100.0.tgz#bee76e0a0eec57b49b64f8dd2d73b9039b7a2c1b"
integrity sha512-eL4DTJm4CPopWgr4d278dXIa2UwNgUundRJ37ksQ7Ev1TZnWr8SxCWLcmi4exl8kymZurAWV7j2w1sv7BHqtAA==
dependencies:
"@dnd-kit/core" "^6.0.8"
"@dnd-kit/sortable" "^7.0.2"
"@dnd-kit/utilities" "^3.2.1"
"@douyinfe/semi-animation" "2.99.3"
"@douyinfe/semi-animation-react" "2.99.3"
"@douyinfe/semi-foundation" "2.99.3"
"@douyinfe/semi-icons" "2.99.3"
"@douyinfe/semi-illustrations" "2.99.3"
"@douyinfe/semi-theme-default" "2.99.3"
"@douyinfe/semi-animation" "2.100.0"
"@douyinfe/semi-animation-react" "2.100.0"
"@douyinfe/semi-foundation" "2.100.0"
"@douyinfe/semi-icons" "2.100.0"
"@douyinfe/semi-illustrations" "2.100.0"
"@douyinfe/semi-theme-default" "2.100.0"
"@tiptap/core" "^3.10.7"
"@tiptap/extension-document" "^3.10.7"
"@tiptap/extension-hard-break" "^3.10.7"
@@ -1057,20 +1057,20 @@
scroll-into-view-if-needed "^2.2.24"
utility-types "^3.10.0"
"@douyinfe/semi-ui@2.99.3":
version "2.99.3"
resolved "https://registry.yarnpkg.com/@douyinfe/semi-ui/-/semi-ui-2.99.3.tgz#a183ecc4db0e96c48c714d8733a6d30e9395bc4a"
integrity sha512-6NkeijjZZWzD31omteNVLz+oZuuMKQm3nEcwLI8+44Vv+VUSJPb87WnSFSD3F6eUIt/hZp2vJbCXHWW9SbCpDw==
"@douyinfe/semi-ui@2.100.0":
version "2.100.0"
resolved "https://registry.yarnpkg.com/@douyinfe/semi-ui/-/semi-ui-2.100.0.tgz#2964299a4c4da2501c4ba1fd2699fbfd2daef106"
integrity sha512-fTaqS6B1gHLjwMKgcWTcJWdMk9gY96h94I71Y3z9ee6qIXJyjAO8XiE8G6bihEIeVO3vTKXp1DOKiGhlgMVJKQ==
dependencies:
"@dnd-kit/core" "^6.0.8"
"@dnd-kit/sortable" "^7.0.2"
"@dnd-kit/utilities" "^3.2.1"
"@douyinfe/semi-animation" "2.99.3"
"@douyinfe/semi-animation-react" "2.99.3"
"@douyinfe/semi-foundation" "2.99.3"
"@douyinfe/semi-icons" "2.99.3"
"@douyinfe/semi-illustrations" "2.99.3"
"@douyinfe/semi-theme-default" "2.99.3"
"@douyinfe/semi-animation" "2.100.0"
"@douyinfe/semi-animation-react" "2.100.0"
"@douyinfe/semi-foundation" "2.100.0"
"@douyinfe/semi-icons" "2.100.0"
"@douyinfe/semi-illustrations" "2.100.0"
"@douyinfe/semi-theme-default" "2.100.0"
"@tiptap/core" "^3.10.7"
"@tiptap/extension-document" "^3.10.7"
"@tiptap/extension-hard-break" "^3.10.7"
@@ -5795,10 +5795,10 @@ node-releases@^2.0.27:
resolved "https://registry.npmjs.org/node-releases/-/node-releases-2.0.27.tgz"
integrity sha512-nmh3lCkYZ3grZvqcCH+fjmQ7X+H0OeZgP40OierEaAptX4XofMh5kwNbWh7lBduUzCcV/8kZ+NDLCwm2iorIlA==
nodemailer@^8.0.10:
version "8.0.10"
resolved "https://registry.yarnpkg.com/nodemailer/-/nodemailer-8.0.10.tgz#009d4deaa06f54b6bd7ddc6cac1bf78e3bcb0bf2"
integrity sha512-BLFuSth7QtHOkBzyqTehWWyub0NTRDuK2Q2SQfnGLsrJnzyU+Yeh4WpV1eZGuARFj1xQJHIdnTuJZLP+b9R1GQ==
nodemailer@^8.0.11:
version "8.0.11"
resolved "https://registry.yarnpkg.com/nodemailer/-/nodemailer-8.0.11.tgz#ce46b7c2c8bbf17b0408122fbfb4e47f4bffc688"
integrity sha512-nrO/pDAUKl+wXX+lx16tDLbnm0fW6sK/x8mgohaCpg+CdCEl482bD4tCuAZk2DyliruiNTIZxRCoWkDqJEnAiA==
nodemon@^3.1.14:
version "3.1.14"
@@ -6180,10 +6180,10 @@ prelude-ls@^1.2.1:
resolved "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz"
integrity sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==
prettier@3.8.3:
version "3.8.3"
resolved "https://registry.yarnpkg.com/prettier/-/prettier-3.8.3.tgz#560f2de55bf01b4c0503bc629d5df99b9a1d09b0"
integrity sha512-7igPTM53cGHMW8xWuVTydi2KO233VFiTNyF5hLJqpilHfmn8C8gPf+PS7dUT64YcXFbiMGZxS9pCSxL/Dxm/Jw==
prettier@3.8.4:
version "3.8.4"
resolved "https://registry.yarnpkg.com/prettier/-/prettier-3.8.4.tgz#f334f013ac04a96676f24dabc23c1c4ae1bae411"
integrity sha512-N2MylSdi48+5N/6S5j+maeHbUSIzzZ5uOcX5Hm4QpV8Dkb1HFjfAKTKX6yNPJQD9AhcT3ifHNB66tWTTJDi11Q==
prismjs@^1.29.0:
version "1.30.0"
@@ -6525,17 +6525,17 @@ react-resizable@^3.0.5:
prop-types "15.x"
react-draggable "^4.0.3"
react-router-dom@7.16.0:
version "7.16.0"
resolved "https://registry.yarnpkg.com/react-router-dom/-/react-router-dom-7.16.0.tgz#284a7cd021052aa7d0a9240dca4a02eec24eceb5"
integrity sha512-kMUAbimWB5FVbF4Bce4bJsiKJWLIUHq/mEG8+CFDnCSgltptBiG5nguducmsJeGKytlCvQud9Qhzpn49iduTlA==
react-router-dom@7.17.0:
version "7.17.0"
resolved "https://registry.yarnpkg.com/react-router-dom/-/react-router-dom-7.17.0.tgz#e77527b4b7862f7b47ff26dd5b9315fb897b82a7"
integrity sha512-fyU2yjGups/hE6Xz0I5ZYbVL8Gx29eCjgpHaRaTaVU+OOAdfRX05KsvyRm0GO8YQwOkhpU3MurW1jyMUJn+zSw==
dependencies:
react-router "7.16.0"
react-router "7.17.0"
react-router@7.16.0:
version "7.16.0"
resolved "https://registry.yarnpkg.com/react-router/-/react-router-7.16.0.tgz#fb41536aef2ccc2c7be12ea6be819a1e56eb6343"
integrity sha512-wArC8lVyJb3+jM9OpDyW6hLCizACWkvQR/sSGqSs+o5uEXEtGlqdZ4v8hENR3Jad6i+LRkK93q/+bQAcvl6V1A==
react-router@7.17.0:
version "7.17.0"
resolved "https://registry.yarnpkg.com/react-router/-/react-router-7.17.0.tgz#88bbe817c6e37ab36faf140623b5d4678bf81e41"
integrity sha512-FDELK7rTMlCHO5+reyXsPlmfr7N1F91lPHsWYfMEGQm/KQ+F4JFM8jGoeQDmDvdTs93Fw9aSilH+uKRb4/jXvQ==
dependencies:
cookie "^1.0.1"
set-cookie-parser "^2.6.0"
@@ -6974,10 +6974,10 @@ semver@^7.6.0:
resolved "https://registry.yarnpkg.com/semver/-/semver-7.7.4.tgz#28464e36060e991fa7a11d0279d2d3f3b57a7e8a"
integrity sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==
semver@^7.8.1:
version "7.8.1"
resolved "https://registry.yarnpkg.com/semver/-/semver-7.8.1.tgz#bf4970b5e70fda0686363cc18bfe8805d5ed957e"
integrity sha512-rkVq3IXh+4FDGch+KwzX3aV9W3kO54GyEgpvBzSyctDA6Xtd7RJQV1xmXbeQp5v7+VzLOfVqiutSE6GICgPFvg==
semver@^7.8.4:
version "7.8.4"
resolved "https://registry.yarnpkg.com/semver/-/semver-7.8.4.tgz#c73eceebae0616934be8dff28a7fd70757c8e696"
integrity sha512-rUCObTnP32Q08R2uuIrt7r9PlEonuTmtuXYcW6s5kjdlj3xbnwe+21yXptAUYcMAABLkYYTtnmzb3w3EDZfueA==
send@^1.1.0:
version "1.2.1"