refactor(auth): replace dashboard sessions with stateless tokens and session control (#6329)

* refactor(auth): replace dashboard sessions with stateless tokens

* feat(auth): harden session issuance and distributed enforcement

* fix(proxy): preserve trusted proxy compatibility defaults

* refactor: address dashboard auth review feedback

* refactor: remove classic frontend and flatten web app
This commit is contained in:
Calcium-Ion
2026-07-20 16:48:43 +08:00
committed by GitHub
parent 5a6c53d496
commit 31d70fca39
1605 changed files with 17511 additions and 147913 deletions
+52
View File
@@ -0,0 +1,52 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
/**
* Column definitions factory
*/
import type { ColumnDef } from '@tanstack/react-table'
import { useCommonLogsColumns } from '../components/columns/common-logs-columns'
import { useDrawingLogsColumns } from '../components/columns/drawing-logs-columns'
import { useTaskLogsColumns } from '../components/columns/task-logs-columns'
import type { LogCategory } from '../types'
/**
* Get column definitions based on log category
* Returns any[] due to different log types (UsageLog, MjProxy log, TaskLog)
*/
export function useColumnsByCategory(
logCategory: LogCategory,
isAdmin: boolean
// eslint-disable-next-line @typescript-eslint/no-explicit-any
): ColumnDef<any>[] {
const commonColumns = useCommonLogsColumns(isAdmin)
const drawingColumns = useDrawingLogsColumns(isAdmin)
const taskColumns = useTaskLogsColumns(isAdmin)
switch (logCategory) {
case 'common':
return commonColumns
case 'drawing':
return drawingColumns
case 'task':
return taskColumns
default:
return commonColumns
}
}
+87
View File
@@ -0,0 +1,87 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
/**
* Utility functions for usage logs filters
*/
import { LOG_CATEGORY_LABELS } from '../constants'
import type {
LogCategory,
LogFilters,
CommonLogFilters,
DrawingLogFilters,
TaskLogFilters,
} from '../types'
// ============================================================================
// Filter Building Functions
// ============================================================================
/**
* Build search params from filters based on log category
*/
export function buildSearchParams(
filters: LogFilters,
logCategory: LogCategory
): Record<string, unknown> {
const baseParams: Record<string, unknown> = {
...(filters.startTime && { startTime: filters.startTime.getTime() }),
...(filters.endTime && { endTime: filters.endTime.getTime() }),
...(filters.channel && { channel: filters.channel }),
}
switch (logCategory) {
case 'common': {
const commonFilters = filters as CommonLogFilters
return {
...baseParams,
...(commonFilters.model && { model: commonFilters.model }),
...(commonFilters.token && { token: commonFilters.token }),
...(commonFilters.group && { group: commonFilters.group }),
...(commonFilters.username && { username: commonFilters.username }),
...(commonFilters.requestId && { requestId: commonFilters.requestId }),
...(commonFilters.upstreamRequestId && {
upstreamRequestId: commonFilters.upstreamRequestId,
}),
}
}
case 'drawing': {
const drawingFilters = filters as DrawingLogFilters
return {
...baseParams,
...(drawingFilters.mjId && { filter: drawingFilters.mjId }),
}
}
case 'task': {
const taskFilters = filters as TaskLogFilters
return {
...baseParams,
...(taskFilters.taskId && { filter: taskFilters.taskId }),
}
}
default:
return baseParams
}
}
/**
* Get log category display name
*/
export function getLogCategoryLabel(category: LogCategory): string {
return LOG_CATEGORY_LABELS[category]
}
+408
View File
@@ -0,0 +1,408 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import type { StatusBadgeProps } from '@/components/status-badge'
import {
BILLING_PRICING_VARS,
normalizeTierLabel,
parseTiersFromExpr,
type ParsedTier,
} from '@/features/pricing/lib/billing-expr'
import type { UsageLog } from '../data/schema'
import type { LogOtherData } from '../types'
export { normalizeTierLabel }
const PARAM_OVERRIDE_ACTION_MAP: Record<string, string> = {
set: 'Set',
delete: 'Delete',
copy: 'Copy',
move: 'Move',
append: 'Append',
prepend: 'Prepend',
trim_prefix: 'Trim Prefix',
trim_suffix: 'Trim Suffix',
ensure_prefix: 'Ensure Prefix',
ensure_suffix: 'Ensure Suffix',
trim_space: 'Trim Space',
to_lower: 'To Lower',
to_upper: 'To Upper',
replace: 'Replace',
regex_replace: 'Regex Replace',
set_header: 'Set Header',
delete_header: 'Delete Header',
copy_header: 'Copy Header',
move_header: 'Move Header',
pass_headers: 'Pass Headers',
sync_fields: 'Sync Fields',
return_error: 'Return Error',
}
/**
* Get localized label for a param override action
*/
export function getParamOverrideActionLabel(
action: string,
t: (key: string) => string
): string {
const key = PARAM_OVERRIDE_ACTION_MAP[action.toLowerCase()]
return key ? t(key) : action
}
/**
* Parse a param override audit line into action and content
*/
export function parseAuditLine(
line: string
): { action: string; content: string } | null {
if (typeof line !== 'string') return null
const firstSpace = line.indexOf(' ')
if (firstSpace <= 0) return { action: line, content: line }
return {
action: line.slice(0, firstSpace),
content: line.slice(firstSpace + 1),
}
}
/**
* Check if the log is a violation fee log
*/
export function isViolationFeeLog(other: LogOtherData | null): boolean {
if (!other) return false
return (
other.violation_fee === true ||
Boolean(other.violation_fee_code) ||
Boolean(other.violation_fee_marker)
)
}
/**
* Parse the 'other' field from JSON string to object
*/
export function parseLogOther(other: string): LogOtherData | null {
if (!other) return null
try {
return JSON.parse(other) as LogOtherData
} catch (error) {
// eslint-disable-next-line no-console
console.error('Failed to parse log other field:', error)
return null
}
}
/**
* Get time color based on duration (in seconds)
*/
export function getTimeColor(
seconds: number
): 'success' | 'warning' | 'danger' {
if (seconds < 10) return 'success'
if (seconds < 30) return 'warning'
return 'danger'
}
/**
* Get first-response-token color based on latency (in seconds)
*/
export function getFirstResponseTimeColor(
seconds: number
): 'success' | 'warning' | 'danger' {
if (seconds < 5) return 'success'
if (seconds < 10) return 'warning'
return 'danger'
}
/**
* Get throughput color based on generated tokens per second
*/
export function getThroughputColor(
tokensPerSecond: number
): 'success' | 'warning' | 'danger' {
if (tokensPerSecond >= 30) return 'success'
if (tokensPerSecond >= 15) return 'warning'
return 'danger'
}
/**
* Get response color using throughput only when enough output tokens exist.
*/
export function getResponseTimeColor(
seconds: number,
completionTokens: number
): 'success' | 'warning' | 'danger' {
if (completionTokens < 100 || seconds <= 0) return getTimeColor(seconds)
return getThroughputColor(completionTokens / seconds)
}
/**
* Format model name with mapping indicator
*/
export function formatModelName(log: UsageLog): {
name: string
isMapped: boolean
actualModel?: string
} {
const other = parseLogOther(log.other)
const isMapped = !!(
other?.is_model_mapped &&
other?.upstream_model_name &&
other.upstream_model_name !== ''
)
return {
name: log.model_name,
isMapped,
actualModel: isMapped ? other.upstream_model_name : undefined,
}
}
/**
* Decode a base64-encoded billing expression. Safely returns an empty string
* when the input is missing or malformed (e.g. legacy logs without expr_b64).
*/
export function decodeBillingExprB64(exprB64: string | undefined): string {
if (!exprB64) return ''
try {
const binaryString =
typeof window !== 'undefined'
? window.atob(exprB64)
: Buffer.from(exprB64, 'base64').toString('binary')
const bytes = new Uint8Array(binaryString.length)
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i)
}
if (typeof TextDecoder !== 'undefined') {
return new TextDecoder().decode(bytes)
}
return decodeURIComponent(
Array.prototype.map
.call(bytes, (byte: number) => `%${byte.toString(16).padStart(2, '0')}`)
.join('')
)
} catch {
return ''
}
}
/**
* Resolve which parsed tier corresponds to the matched_tier label in a log
* entry. Missing or unknown labels do not fall back to another tier because
* that would display guessed unit prices.
*/
export function resolveMatchedTier(
tiers: ParsedTier[],
matchedLabel: string | undefined
): ParsedTier | null {
if (tiers.length === 0) return null
if (!matchedLabel) return null
const found = tiers.find((tier) => {
const l1 = normalizeTierLabel(tier.label)
const l2 = normalizeTierLabel(matchedLabel)
return l1 === l2 && l1 !== ''
})
return found || null
}
/**
* Tiered pricing summary derived from an `other` log payload using the
* billing-expression library. Returns null when the entry is not a tiered
* billing log or the expression failed to parse.
*/
export interface TieredBillingSummary {
tiers: ParsedTier[]
tier: ParsedTier
priceEntries: Array<{ field: string; shortLabel: string; price: number }>
}
/**
* Whether the request payload reports any cache-related token usage. Used to
* suppress cache pricing rows from the tiered breakdown when the request did
* not exercise the cache path.
*/
export function hasAnyCacheTokens(
other: LogOtherData | null | undefined
): boolean {
if (!other) return false
return (
(other.cache_tokens || 0) > 0 ||
(other.cache_creation_tokens || 0) > 0 ||
(other.cache_creation_tokens_5m || 0) > 0 ||
(other.cache_creation_tokens_1h || 0) > 0
)
}
export function getTieredBillingSummary(
other: LogOtherData | null
): TieredBillingSummary | null {
if (!other || other.billing_mode !== 'tiered_expr') return null
const exprStr = decodeBillingExprB64(other.expr_b64)
if (!exprStr) return null
const tiers = parseTiersFromExpr(exprStr)
const tier = resolveMatchedTier(tiers, other.matched_tier)
if (!tier) return null
const cacheTokensPresent = hasAnyCacheTokens(other)
const priceEntries: TieredBillingSummary['priceEntries'] = []
for (const v of BILLING_PRICING_VARS) {
if (!v.field) continue
if (v.group === 'cache' && !cacheTokensPresent) continue
const raw = tier[v.field as keyof ParsedTier]
const price = Number(raw)
if (Number.isFinite(price) && price > 0) {
priceEntries.push({
field: v.field,
shortLabel: v.shortLabel,
price,
})
}
}
return { tiers, tier, priceEntries }
}
/**
* Calculate duration and return formatted result with color variant
* @param submitTime - Submit timestamp
* @param finishTime - Finish timestamp
* @param unit - Unit of the timestamps ('seconds' or 'milliseconds')
*/
export function formatDuration(
submitTime?: number,
finishTime?: number,
unit: 'seconds' | 'milliseconds' = 'milliseconds'
): { durationSec: number; variant: StatusBadgeProps['variant'] } | null {
if (!submitTime || !finishTime) return null
const durationSec =
unit === 'milliseconds'
? (finishTime - submitTime) / 1000
: finishTime - submitTime
return { durationSec, variant: durationSec > 60 ? 'red' : 'green' }
}
/**
* Maps a language-independent audit/login operation `action` to an i18n
* template string (the template itself is the i18n key, with {{placeholders}}).
*
* The backend stores only `action` + structured `params` in `other.op`; the UI
* renders localized content at display time so audit/login logs are fully
* translatable instead of being frozen to whatever language was written to DB.
*/
const AUDIT_TEMPLATES: Record<string, string> = {
login: 'Logged in successfully via {{method}}',
// User management
'user.create': 'Created user {{username}} (role {{role}})',
'user.update': 'Updated user {{username}} (ID: {{id}})',
'user.delete': 'Deleted user {{username}} (ID: {{id}})',
'user.manage': 'Performed {{action}} on user {{username}} (ID: {{id}})',
'user.quota_add': 'Increased user quota by {{quota}}',
'user.quota_subtract': 'Decreased user quota by {{quota}}',
'user.quota_override': 'Overrode user quota from {{from}} to {{to}}',
'user.binding_clear': 'Cleared {{bindingType}} binding for user {{username}}',
'user.2fa_disable': 'Force-disabled two-factor authentication for the user',
'user.passkey_register': 'Registered a passkey',
'user.passkey_delete': 'Deleted a passkey',
'user.topup_complete': 'Completed top-up order for the user',
'user.reset_passkey': 'Reset the user passkey',
'user.oauth_unbind': 'Removed an OAuth binding for the user',
// System settings
'option.update': 'Updated system setting {{key}}',
'option.payment_compliance': 'Confirmed payment compliance',
'option.reset_ratio': 'Reset model ratios',
'option.clear_affinity_cache': 'Cleared channel affinity cache',
// Custom OAuth
'custom_oauth.create': 'Created a custom OAuth provider',
'custom_oauth.update': 'Updated a custom OAuth provider',
'custom_oauth.delete': 'Deleted a custom OAuth provider',
// Performance / cache
'performance.clear_disk_cache': 'Cleared disk cache',
'performance.gc': 'Triggered garbage collection',
'performance.clear_logs': 'Cleared log files',
// Channel
'channel.create': 'Created channel {{name}} (type {{type}}, count {{count}})',
'channel.update': 'Updated channel {{name}} (ID: {{id}})',
'channel.delete': 'Deleted channel {{name}} (ID: {{id}})',
'channel.delete_batch': 'Batch deleted {{count}} channels',
'channel.delete_disabled': 'Deleted all disabled channels ({{count}})',
'channel.key_view': 'Viewed channel key {{name}} (ID: {{id}})',
'channel.tag_disable': 'Disabled channels with tag {{tag}}',
'channel.tag_enable': 'Enabled channels with tag {{tag}}',
'channel.tag_edit': 'Edited channels with tag {{tag}}',
'channel.tag_batch_set': 'Batch set tag for {{count}} channels',
'channel.copy':
'Copied channel (source ID: {{sourceId}}) to {{name}} (new ID: {{id}})',
'channel.multi_key_manage':
'Multi-key management {{action}} on channel (ID: {{id}})',
'channel.upstream_apply':
'Applied upstream model changes to channel (ID: {{id}})',
'channel.upstream_apply_all':
'Applied upstream model changes to {{count}} channels',
// Redemption codes
'redemption.create':
'Created {{count}} redemption codes named {{name}} ({{quota}} each)',
'redemption.update': 'Updated a redemption code',
'redemption.delete': 'Deleted a redemption code',
'redemption.delete_invalid': 'Deleted invalid redemption codes',
// Prefill groups
'prefill_group.create': 'Created a prefill group',
'prefill_group.update': 'Updated a prefill group',
'prefill_group.delete': 'Deleted a prefill group',
// Vendors
'vendor.create': 'Created a vendor',
'vendor.update': 'Updated a vendor',
'vendor.delete': 'Deleted a vendor',
// Model metadata
'model.create': 'Created a model',
'model.update': 'Updated a model',
'model.delete': 'Deleted a model',
'model.sync_upstream': 'Synced upstream models',
// Deployments
'deployment.create': 'Created a deployment',
'deployment.update': 'Updated a deployment',
'deployment.delete': 'Deleted a deployment',
// Subscriptions
'subscription.plan_create': 'Created a subscription plan',
'subscription.plan_update': 'Updated a subscription plan',
'subscription.bind': 'Bound a subscription',
// Logs
'log.clear': 'Cleared historical logs',
'log.cleanup_start': 'Log cleanup task started.',
// Generic middleware fallback
generic: '{{method}} {{route}}',
}
/**
* Render the localized content of an audit/login log from its structured
* `other.op` descriptor. Returns null when the log has no recognized action,
* letting callers fall back to the raw `content` field.
*/
export function renderAuditContent(
other: LogOtherData | null | undefined,
t: (key: string, opts?: Record<string, unknown>) => string
): string | null {
const op = other?.op
if (!op?.action) return null
const template = AUDIT_TEMPLATES[op.action]
if (!template) return null
return t(template, (op.params ?? {}) as Record<string, unknown>)
}
+63
View File
@@ -0,0 +1,63 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
/**
* Central export point for all lib utilities
*/
// Format utilities (usage-logs specific)
export {
parseLogOther,
getTimeColor,
formatModelName,
formatDuration,
getParamOverrideActionLabel,
parseAuditLine,
isViolationFeeLog,
} from './format'
// Filter utilities
export { buildSearchParams, getLogCategoryLabel } from './filter'
// General utilities
export {
isDisplayableLogType,
isTimingLogType,
getLogTypeConfig,
isPerCallBilling,
getDefaultTimeRange,
buildQueryParams,
buildBaseParams,
buildApiParams,
fetchLogsByCategory,
} from './utils'
// Status mapper utilities
export { createStatusMapper } from './status'
// Mappers
export {
mjTaskTypeMapper,
mjStatusMapper,
taskActionMapper,
taskStatusMapper,
taskPlatformMapper,
} from './mappers'
// Column utilities
export { useColumnsByCategory } from './columns'
+71
View File
@@ -0,0 +1,71 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
/**
* Status mappers for different log types
* Centralized mapper instances for consistent usage across components
*/
import {
MJ_TASK_TYPE_MAPPINGS,
MJ_STATUS_MAPPINGS,
MJ_SUBMIT_RESULT_MAPPINGS,
TASK_ACTION_MAPPINGS,
TASK_STATUS_MAPPINGS,
TASK_PLATFORM_MAPPINGS,
} from '../constants'
import { createStatusMapper } from './status'
// ============================================================================
// MjProxy (Drawing) Logs Mappers
// ============================================================================
/**
* MjProxy task type mapper
*/
export const mjTaskTypeMapper = createStatusMapper(MJ_TASK_TYPE_MAPPINGS)
/**
* MjProxy task status mapper
*/
export const mjStatusMapper = createStatusMapper(MJ_STATUS_MAPPINGS)
/**
* MjProxy submit result mapper
*/
export const mjSubmitResultMapper = createStatusMapper(
MJ_SUBMIT_RESULT_MAPPINGS
)
// ============================================================================
// Task Logs Mappers
// ============================================================================
/**
* Task action type mapper
*/
export const taskActionMapper = createStatusMapper(TASK_ACTION_MAPPINGS)
/**
* Task status mapper
*/
export const taskStatusMapper = createStatusMapper(TASK_STATUS_MAPPINGS)
/**
* Task platform mapper
*/
export const taskPlatformMapper = createStatusMapper(TASK_PLATFORM_MAPPINGS)
+39
View File
@@ -0,0 +1,39 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import type { StatusBadgeProps } from '@/components/status-badge'
/**
* Generic status mapping utility
* Creates a function to map status values to labels and variants
*/
export function createStatusMapper<T extends string>(mapping: {
[key in T]?: { label: string; variant: StatusBadgeProps['variant'] }
}) {
return {
getLabel: (status: string, defaultLabel = 'Unknown'): string => {
return mapping[status as T]?.label ?? defaultLabel
},
getVariant: (
status: string,
defaultVariant: StatusBadgeProps['variant'] = 'neutral'
): StatusBadgeProps['variant'] => {
return mapping[status as T]?.variant ?? defaultVariant
},
}
}
+304
View File
@@ -0,0 +1,304 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
/**
* Utility functions for usage logs feature
*/
import {
getAllLogs,
getUserLogs,
getAllMidjourneyLogs,
getUserMidjourneyLogs,
getAllTaskLogs,
getUserTaskLogs,
} from '../api'
import {
LOG_TYPES,
DISPLAYABLE_LOG_TYPES,
TIMING_LOG_TYPES,
} from '../constants'
import type {
GetLogsParams,
GetLogsResponse,
FetchLogsConfig,
GetMidjourneyLogsParams,
GetTaskLogsParams,
} from '../types'
// ============================================================================
// Type Checkers & Utilities
// ============================================================================
/**
* Check if log type is displayable (has detailed info)
*/
export function isDisplayableLogType(type: number): boolean {
return (DISPLAYABLE_LOG_TYPES as readonly number[]).includes(type)
}
/**
* Check if log type shows timing info
*/
export function isTimingLogType(type: number): boolean {
return (TIMING_LOG_TYPES as readonly number[]).includes(type)
}
/**
* Get log type configuration by type number
*/
export function getLogTypeConfig(type: number) {
return LOG_TYPES.find((t) => t.value === type) || LOG_TYPES[0]
}
/**
* Check if log uses per-call billing
*/
export function isPerCallBilling(modelPrice?: number): boolean {
return (modelPrice ?? 0) > 0
}
/**
* Get default time range (today 00:00:00 to now + 1 hour)
*/
export function getDefaultTimeRange(): { start: Date; end: Date } {
const now = new Date()
const start = new Date(now)
start.setHours(0, 0, 0, 0)
const end = new Date(now.getTime() + 3600 * 1000) // +1 hour
return { start, end }
}
/**
* Convert milliseconds timestamp to seconds for API
*/
function timestampToSeconds(ms: number): number {
return Math.floor(ms / 1000)
}
/**
* Build query parameters from filters
*/
export function buildQueryParams(
params: Record<string, unknown>
): URLSearchParams {
const queryParams = new URLSearchParams()
Object.entries(params).forEach(([key, value]) => {
// Keep 0 as a valid value, only filter out undefined, null, and empty string
if (value !== undefined && value !== null && value !== '') {
queryParams.append(key, String(value))
}
})
return queryParams
}
/**
* Build time range parameters with default values
* Shared logic for all log types
*/
function buildTimeRangeParams(
searchParams: Record<string, unknown>,
useMilliseconds: boolean
): { start_timestamp?: number; end_timestamp?: number } {
const hasTimeParams = searchParams.startTime ?? searchParams.endTime
const defaultTimeRange = !hasTimeParams ? getDefaultTimeRange() : null
const convertTimestamp = (timestamp: number) =>
useMilliseconds ? timestamp : timestampToSeconds(timestamp)
const getTimestamp = (paramTime?: unknown, defaultTime?: Date) => {
const time = (paramTime as number) || defaultTime?.getTime()
return time ? convertTimestamp(time) : undefined
}
return {
start_timestamp: getTimestamp(
searchParams.startTime,
defaultTimeRange?.start
),
end_timestamp: getTimestamp(searchParams.endTime, defaultTimeRange?.end),
}
}
/**
* Build base parameters with time range (for drawing and task logs)
* @param useMilliseconds - Whether to use millisecond timestamps (true for drawing logs, false for task logs)
*/
export function buildBaseParams(config: {
page: number
pageSize: number
searchParams: Record<string, unknown>
useMilliseconds?: boolean
}): {
p: number
page_size: number
channel_id?: string
start_timestamp?: number
end_timestamp?: number
} {
const { page, pageSize, searchParams, useMilliseconds = false } = config
return {
p: page,
page_size: pageSize,
...(searchParams.channel
? {
channel_id: String(searchParams.channel),
}
: {}),
...buildTimeRangeParams(searchParams, useMilliseconds),
}
}
/**
* Build API params from search params and column filters (for common logs)
*/
export function buildApiParams(config: {
page: number
pageSize: number
searchParams: Record<string, unknown>
columnFilters?: Array<{ id: string; value: unknown }>
isAdmin: boolean
}): GetLogsParams {
const { page, pageSize, searchParams, columnFilters = [], isAdmin } = config
// Helper to process type parameter (single value from array)
const processType = (value: unknown): number | undefined => {
const parseType = (raw: unknown): number | undefined => {
const type = Number(raw)
return Number.isFinite(type) ? type : undefined
}
if (Array.isArray(value) && value.length === 1) {
return parseType(value[0])
}
if (typeof value === 'string' && value !== '') {
return parseType(value)
}
return undefined
}
// Build base params from search params
const params: GetLogsParams = {
p: page,
page_size: pageSize,
...(searchParams.type ? { type: processType(searchParams.type) } : {}),
...(searchParams.model ? { model_name: String(searchParams.model) } : {}),
...(searchParams.token ? { token_name: String(searchParams.token) } : {}),
...(searchParams.group ? { group: String(searchParams.group) } : {}),
...(isAdmin && searchParams.channel
? { channel: Number(searchParams.channel) || 0 }
: {}),
...(isAdmin && searchParams.username
? { username: String(searchParams.username) }
: {}),
...(searchParams.requestId
? { request_id: String(searchParams.requestId) }
: {}),
...(searchParams.upstreamRequestId
? { upstream_request_id: String(searchParams.upstreamRequestId) }
: {}),
...buildTimeRangeParams(searchParams, false),
}
// Override with column filters if present
if (columnFilters.length > 0) {
columnFilters.forEach(({ id, value }) => {
if (value === undefined || value === null || value === '') return
switch (id) {
case 'type':
params.type = processType(value)
break
case 'model_name':
params.model_name = String(value)
break
case 'token_name':
params.token_name = String(value)
break
case 'group':
params.group = String(value)
break
case 'channel':
if (isAdmin) params.channel = Number(value) || 0
break
case 'username':
if (isAdmin) params.username = String(value)
break
}
})
}
return params
}
// ============================================================================
// Data Fetching
// ============================================================================
/**
* Fetch logs based on category type
*/
export async function fetchLogsByCategory(
config: FetchLogsConfig
): Promise<GetLogsResponse> {
const { logCategory, isAdmin, page, pageSize, searchParams, columnFilters } =
config
if (logCategory === 'common') {
const params = buildApiParams({
page,
pageSize,
searchParams,
columnFilters,
isAdmin,
})
return isAdmin ? await getAllLogs(params) : await getUserLogs(params)
}
// For drawing and task logs
const baseParams = buildBaseParams({
page,
pageSize,
searchParams,
useMilliseconds: logCategory === 'drawing',
})
const paramsWithFilter = {
...baseParams,
...(logCategory === 'drawing'
? { mj_id: searchParams.filter as string | undefined }
: {}),
...(logCategory === 'task'
? { task_id: searchParams.filter as string | undefined }
: {}),
}
if (logCategory === 'drawing') {
return isAdmin
? await getAllMidjourneyLogs(paramsWithFilter as GetMidjourneyLogsParams)
: await getUserMidjourneyLogs(paramsWithFilter as GetMidjourneyLogsParams)
}
// task logs
return isAdmin
? await getAllTaskLogs(paramsWithFilter as GetTaskLogsParams)
: await getUserTaskLogs(paramsWithFilter as GetTaskLogsParams)
}