First commit

This commit is contained in:
shaw
2025-12-18 13:50:39 +08:00
parent 569f4882e5
commit 642842c29e
218 changed files with 86902 additions and 0 deletions

View File

@@ -0,0 +1,176 @@
<template>
<div v-if="siteKey" class="turnstile-wrapper">
<div ref="containerRef" class="turnstile-container"></div>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue';
interface TurnstileRenderOptions {
sitekey: string;
callback: (token: string) => void;
'expired-callback'?: () => void;
'error-callback'?: () => void;
theme?: 'light' | 'dark' | 'auto';
size?: 'normal' | 'compact' | 'flexible';
}
interface TurnstileAPI {
render: (container: HTMLElement, options: TurnstileRenderOptions) => string;
reset: (widgetId?: string) => void;
remove: (widgetId?: string) => void;
}
declare global {
interface Window {
turnstile?: TurnstileAPI;
onTurnstileLoad?: () => void;
}
}
const props = withDefaults(defineProps<{
siteKey: string;
theme?: 'light' | 'dark' | 'auto';
size?: 'normal' | 'compact' | 'flexible';
}>(), {
theme: 'auto',
size: 'flexible',
});
const emit = defineEmits<{
(e: 'verify', token: string): void;
(e: 'expire'): void;
(e: 'error'): void;
}>();
const containerRef = ref<HTMLElement | null>(null);
const widgetId = ref<string | null>(null);
const scriptLoaded = ref(false);
const loadScript = (): Promise<void> => {
return new Promise((resolve, reject) => {
if (window.turnstile) {
scriptLoaded.value = true;
resolve();
return;
}
// Check if script is already loading
const existingScript = document.querySelector('script[src*="turnstile"]');
if (existingScript) {
window.onTurnstileLoad = () => {
scriptLoaded.value = true;
resolve();
};
return;
}
const script = document.createElement('script');
script.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js?onload=onTurnstileLoad';
script.async = true;
script.defer = true;
window.onTurnstileLoad = () => {
scriptLoaded.value = true;
resolve();
};
script.onerror = () => {
reject(new Error('Failed to load Turnstile script'));
};
document.head.appendChild(script);
});
};
const renderWidget = () => {
if (!window.turnstile || !containerRef.value || !props.siteKey) {
return;
}
// Remove existing widget if any
if (widgetId.value) {
try {
window.turnstile.remove(widgetId.value);
} catch {
// Ignore errors when removing
}
widgetId.value = null;
}
// Clear container
containerRef.value.innerHTML = '';
widgetId.value = window.turnstile.render(containerRef.value, {
sitekey: props.siteKey,
callback: (token: string) => {
emit('verify', token);
},
'expired-callback': () => {
emit('expire');
},
'error-callback': () => {
emit('error');
},
theme: props.theme,
size: props.size,
});
};
const reset = () => {
if (window.turnstile && widgetId.value) {
window.turnstile.reset(widgetId.value);
}
};
// Expose reset method to parent
defineExpose({ reset });
onMounted(async () => {
if (!props.siteKey) {
return;
}
try {
await loadScript();
renderWidget();
} catch (error) {
console.error('Failed to initialize Turnstile:', error);
emit('error');
}
});
onUnmounted(() => {
if (window.turnstile && widgetId.value) {
try {
window.turnstile.remove(widgetId.value);
} catch {
// Ignore errors when removing
}
}
});
// Re-render when siteKey changes
watch(() => props.siteKey, (newKey) => {
if (newKey && scriptLoaded.value) {
renderWidget();
}
});
</script>
<style scoped>
.turnstile-wrapper {
width: 100%;
}
.turnstile-container {
width: 100%;
min-height: 65px;
}
/* Make the Turnstile iframe fill the container width */
.turnstile-container :deep(iframe) {
width: 100% !important;
}
</style>

View File

@@ -0,0 +1,120 @@
<template>
<div class="flex items-center gap-2">
<!-- Main Status Badge -->
<span
:class="[
'badge text-xs',
statusClass
]"
>
{{ statusText }}
</span>
<!-- Error Info Indicator -->
<div v-if="hasError && account.error_message" class="relative group/error">
<svg class="w-4 h-4 text-red-500 dark:text-red-400 cursor-help hover:text-red-600 dark:hover:text-red-300 transition-colors" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M9.879 7.519c1.171-1.025 3.071-1.025 4.242 0 1.172 1.025 1.172 2.687 0 3.712-.203.179-.43.326-.67.442-.745.361-1.45.999-1.45 1.827v.75M21 12a9 9 0 11-18 0 9 9 0 0118 0zm-9 5.25h.008v.008H12v-.008z" />
</svg>
<!-- Tooltip - 向下显示 -->
<div class="absolute top-full left-0 mt-1.5 px-3 py-2 bg-gray-800 dark:bg-gray-900 text-white text-xs rounded-lg shadow-xl opacity-0 invisible group-hover/error:opacity-100 group-hover/error:visible transition-all duration-200 z-[100] min-w-[200px] max-w-[300px]">
<div class="text-gray-300 break-words whitespace-pre-wrap leading-relaxed">{{ account.error_message }}</div>
<!-- 上方小三角 -->
<div class="absolute bottom-full left-3 border-[6px] border-transparent border-b-gray-800 dark:border-b-gray-900"></div>
</div>
</div>
<!-- Rate Limit Indicator (429) -->
<div v-if="isRateLimited" class="relative group">
<span class="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs font-medium bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400">
<svg class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
</svg>
429
</span>
<!-- Tooltip -->
<div class="absolute bottom-full left-1/2 -translate-x-1/2 mb-2 px-2 py-1 bg-gray-900 dark:bg-gray-700 text-white text-xs rounded whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-50">
Rate limited until {{ formatTime(account.rate_limit_reset_at) }}
<div class="absolute top-full left-1/2 -translate-x-1/2 border-4 border-transparent border-t-gray-900 dark:border-t-gray-700"></div>
</div>
</div>
<!-- Overload Indicator (529) -->
<div v-if="isOverloaded" class="relative group">
<span class="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs font-medium bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400">
<svg class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
</svg>
529
</span>
<!-- Tooltip -->
<div class="absolute bottom-full left-1/2 -translate-x-1/2 mb-2 px-2 py-1 bg-gray-900 dark:bg-gray-700 text-white text-xs rounded whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-50">
Overloaded until {{ formatTime(account.overload_until) }}
<div class="absolute top-full left-1/2 -translate-x-1/2 border-4 border-transparent border-t-gray-900 dark:border-t-gray-700"></div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import type { Account } from '@/types'
const props = defineProps<{
account: Account
}>()
// Computed: is rate limited (429)
const isRateLimited = computed(() => {
if (!props.account.rate_limit_reset_at) return false
return new Date(props.account.rate_limit_reset_at) > new Date()
})
// Computed: is overloaded (529)
const isOverloaded = computed(() => {
if (!props.account.overload_until) return false
return new Date(props.account.overload_until) > new Date()
})
// Computed: has error status
const hasError = computed(() => {
return props.account.status === 'error'
})
// Computed: status badge class
const statusClass = computed(() => {
if (!props.account.schedulable || isRateLimited.value || isOverloaded.value) {
return 'badge-gray'
}
switch (props.account.status) {
case 'active':
return 'badge-success'
case 'inactive':
return 'badge-gray'
case 'error':
return 'badge-danger'
default:
return 'badge-gray'
}
})
// Computed: status text
const statusText = computed(() => {
if (!props.account.schedulable) {
return 'Paused'
}
if (isRateLimited.value || isOverloaded.value) {
return 'Limited'
}
return props.account.status
})
// Format time helper
const formatTime = (dateStr: string | null | undefined) => {
if (!dateStr) return 'N/A'
const date = new Date(dateStr)
return date.toLocaleTimeString('en-US', {
hour: '2-digit',
minute: '2-digit'
})
}
</script>

View File

@@ -0,0 +1,342 @@
<template>
<Modal
:show="show"
:title="t('admin.accounts.testAccountConnection')"
size="md"
@close="handleClose"
>
<div class="space-y-4">
<!-- Account Info Card -->
<div v-if="account" class="flex items-center justify-between p-3 bg-gradient-to-r from-gray-50 to-gray-100 dark:from-dark-700 dark:to-dark-600 rounded-xl border border-gray-200 dark:border-dark-500">
<div class="flex items-center gap-3">
<div class="w-10 h-10 rounded-lg bg-gradient-to-br from-primary-500 to-primary-600 flex items-center justify-center">
<svg class="w-5 h-5 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5.121 17.804A13.937 13.937 0 0112 16c2.5 0 4.847.655 6.879 1.804M15 10a3 3 0 11-6 0 3 3 0 016 0zm6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
</div>
<div>
<div class="font-semibold text-gray-900 dark:text-gray-100">{{ account.name }}</div>
<div class="text-xs text-gray-500 dark:text-gray-400 flex items-center gap-1.5">
<span class="px-1.5 py-0.5 bg-gray-200 dark:bg-dark-500 rounded text-[10px] font-medium uppercase">
{{ account.type }}
</span>
<span>{{ t('admin.accounts.account') }}</span>
</div>
</div>
</div>
<span
:class="[
'px-2.5 py-1 text-xs font-semibold rounded-full',
account.status === 'active'
? 'bg-green-100 text-green-700 dark:bg-green-500/20 dark:text-green-400'
: 'bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-400'
]"
>
{{ account.status }}
</span>
</div>
<!-- Terminal Output -->
<div class="relative group">
<div
ref="terminalRef"
class="bg-gray-900 dark:bg-black rounded-xl p-4 min-h-[120px] max-h-[240px] overflow-y-auto font-mono text-sm border border-gray-700 dark:border-gray-800"
>
<!-- Status Line -->
<div v-if="status === 'idle'" class="text-gray-500 flex items-center gap-2">
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
</svg>
<span>{{ t('admin.accounts.readyToTest') }}</span>
</div>
<div v-else-if="status === 'connecting'" class="text-yellow-400 flex items-center gap-2">
<svg class="animate-spin w-4 h-4" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
<span>{{ t('admin.accounts.connectingToApi') }}</span>
</div>
<!-- Output Lines -->
<div v-for="(line, index) in outputLines" :key="index" :class="line.class">
{{ line.text }}
</div>
<!-- Streaming Content -->
<div v-if="streamingContent" class="text-green-400">
{{ streamingContent }}<span class="animate-pulse">_</span>
</div>
<!-- Result Status -->
<div v-if="status === 'success'" class="text-green-400 mt-3 pt-3 border-t border-gray-700 flex items-center gap-2">
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<span>{{ t('admin.accounts.testCompleted') }}</span>
</div>
<div v-else-if="status === 'error'" class="text-red-400 mt-3 pt-3 border-t border-gray-700 flex items-center gap-2">
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<span>{{ errorMessage }}</span>
</div>
</div>
<!-- Copy Button -->
<button
v-if="outputLines.length > 0"
@click="copyOutput"
class="absolute top-2 right-2 p-1.5 text-gray-400 hover:text-white bg-gray-800/80 hover:bg-gray-700 rounded-lg transition-all opacity-0 group-hover:opacity-100"
:title="t('admin.accounts.copyOutput')"
>
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
</svg>
</button>
</div>
<!-- Test Info -->
<div class="flex items-center justify-between text-xs text-gray-500 dark:text-gray-400 px-1">
<div class="flex items-center gap-3">
<span class="flex items-center gap-1">
<svg class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 3v2m6-2v2M9 19v2m6-2v2M5 9H3m2 6H3m18-6h-2m2 6h-2M7 19h10a2 2 0 002-2V7a2 2 0 00-2-2H7a2 2 0 00-2 2v10a2 2 0 002 2zM9 9h6v6H9V9z" />
</svg>
{{ t('admin.accounts.testModel') }}
</span>
</div>
<span class="flex items-center gap-1">
<svg class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z" />
</svg>
{{ t('admin.accounts.testPrompt') }}
</span>
</div>
</div>
<template #footer>
<div class="flex justify-end gap-3">
<button
@click="handleClose"
class="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-dark-600 hover:bg-gray-200 dark:hover:bg-dark-500 rounded-lg transition-colors"
:disabled="status === 'connecting'"
>
{{ t('common.close') }}
</button>
<button
@click="startTest"
:disabled="status === 'connecting'"
:class="[
'px-4 py-2 text-sm font-medium rounded-lg transition-all flex items-center gap-2',
status === 'connecting'
? 'bg-primary-400 text-white cursor-not-allowed'
: status === 'success'
? 'bg-green-500 hover:bg-green-600 text-white'
: status === 'error'
? 'bg-orange-500 hover:bg-orange-600 text-white'
: 'bg-primary-500 hover:bg-primary-600 text-white'
]"
>
<svg v-if="status === 'connecting'" class="animate-spin h-4 w-4" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
<svg v-else-if="status === 'idle'" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z" />
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<svg v-else class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
</svg>
<span>
{{ status === 'connecting' ? t('admin.accounts.testing') : status === 'idle' ? t('admin.accounts.startTest') : t('admin.accounts.retry') }}
</span>
</button>
</div>
</template>
</Modal>
</template>
<script setup lang="ts">
import { ref, watch, nextTick } from 'vue'
import { useI18n } from 'vue-i18n'
import Modal from '@/components/common/Modal.vue'
import type { Account } from '@/types'
const { t } = useI18n()
interface OutputLine {
text: string
class: string
}
const props = defineProps<{
show: boolean
account: Account | null
}>()
const emit = defineEmits<{
(e: 'close'): void
}>()
const terminalRef = ref<HTMLElement | null>(null)
const status = ref<'idle' | 'connecting' | 'success' | 'error'>('idle')
const outputLines = ref<OutputLine[]>([])
const streamingContent = ref('')
const errorMessage = ref('')
let eventSource: EventSource | null = null
// Reset state when modal opens
watch(() => props.show, (newVal) => {
if (newVal) {
resetState()
} else {
closeEventSource()
}
})
const resetState = () => {
status.value = 'idle'
outputLines.value = []
streamingContent.value = ''
errorMessage.value = ''
}
const handleClose = () => {
closeEventSource()
emit('close')
}
const closeEventSource = () => {
if (eventSource) {
eventSource.close()
eventSource = null
}
}
const addLine = (text: string, className: string = 'text-gray-300') => {
outputLines.value.push({ text, class: className })
scrollToBottom()
}
const scrollToBottom = async () => {
await nextTick()
if (terminalRef.value) {
terminalRef.value.scrollTop = terminalRef.value.scrollHeight
}
}
const startTest = async () => {
if (!props.account) return
resetState()
status.value = 'connecting'
addLine(t('admin.accounts.startingTestForAccount', { name: props.account.name }), 'text-blue-400')
addLine(t('admin.accounts.testAccountTypeLabel', { type: props.account.type }), 'text-gray-400')
addLine('', 'text-gray-300')
closeEventSource()
try {
// Create EventSource for SSE
const url = `/api/v1/admin/accounts/${props.account.id}/test`
// Use fetch with streaming for SSE since EventSource doesn't support POST
const response = await fetch(url, {
method: 'POST',
headers: {
'Authorization': `Bearer ${localStorage.getItem('auth_token')}`,
'Content-Type': 'application/json'
}
})
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`)
}
const reader = response.body?.getReader()
if (!reader) {
throw new Error('No response body')
}
const decoder = new TextDecoder()
let buffer = ''
while (true) {
const { done, value } = await reader.read()
if (done) break
buffer += decoder.decode(value, { stream: true })
const lines = buffer.split('\n')
buffer = lines.pop() || ''
for (const line of lines) {
if (line.startsWith('data: ')) {
const jsonStr = line.slice(6).trim()
if (jsonStr) {
try {
const event = JSON.parse(jsonStr)
handleEvent(event)
} catch (e) {
console.error('Failed to parse SSE event:', e)
}
}
}
}
}
} catch (error: any) {
status.value = 'error'
errorMessage.value = error.message || 'Unknown error'
addLine(`Error: ${errorMessage.value}`, 'text-red-400')
}
}
const handleEvent = (event: { type: string; text?: string; model?: string; success?: boolean; error?: string }) => {
switch (event.type) {
case 'test_start':
addLine(t('admin.accounts.connectedToApi'), 'text-green-400')
if (event.model) {
addLine(t('admin.accounts.usingModel', { model: event.model }), 'text-cyan-400')
}
addLine(t('admin.accounts.sendingTestMessage'), 'text-gray-400')
addLine('', 'text-gray-300')
addLine(t('admin.accounts.response'), 'text-yellow-400')
break
case 'content':
if (event.text) {
streamingContent.value += event.text
scrollToBottom()
}
break
case 'test_complete':
// Move streaming content to output lines
if (streamingContent.value) {
addLine(streamingContent.value, 'text-green-300')
streamingContent.value = ''
}
if (event.success) {
status.value = 'success'
} else {
status.value = 'error'
errorMessage.value = event.error || 'Test failed'
}
break
case 'error':
status.value = 'error'
errorMessage.value = event.error || 'Unknown error'
if (streamingContent.value) {
addLine(streamingContent.value, 'text-green-300')
streamingContent.value = ''
}
break
}
}
const copyOutput = () => {
const text = outputLines.value.map(l => l.text).join('\n')
navigator.clipboard.writeText(text)
}
</script>

View File

@@ -0,0 +1,82 @@
<template>
<div>
<!-- Loading state -->
<div v-if="loading" class="space-y-0.5">
<div class="h-3 w-12 bg-gray-200 dark:bg-gray-700 rounded animate-pulse"></div>
<div class="h-3 w-16 bg-gray-200 dark:bg-gray-700 rounded animate-pulse"></div>
<div class="h-3 w-10 bg-gray-200 dark:bg-gray-700 rounded animate-pulse"></div>
</div>
<!-- Error state -->
<div v-else-if="error" class="text-xs text-red-500">
{{ error }}
</div>
<!-- Stats data -->
<div v-else-if="stats" class="space-y-0.5 text-xs">
<!-- Requests -->
<div class="flex items-center gap-1">
<span class="text-gray-500 dark:text-gray-400">Req:</span>
<span class="font-medium text-gray-700 dark:text-gray-300">{{ formatNumber(stats.requests) }}</span>
</div>
<!-- Tokens -->
<div class="flex items-center gap-1">
<span class="text-gray-500 dark:text-gray-400">Tok:</span>
<span class="font-medium text-gray-700 dark:text-gray-300">{{ formatTokens(stats.tokens) }}</span>
</div>
<!-- Cost -->
<div class="flex items-center gap-1">
<span class="text-gray-500 dark:text-gray-400">Cost:</span>
<span class="font-medium text-emerald-600 dark:text-emerald-400">{{ formatCurrency(stats.cost) }}</span>
</div>
</div>
<!-- No data -->
<div v-else class="text-xs text-gray-400">
-
</div>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { adminAPI } from '@/api/admin'
import type { Account, WindowStats } from '@/types'
import { formatNumber, formatCurrency } from '@/utils/format'
const props = defineProps<{
account: Account
}>()
const loading = ref(false)
const error = ref<string | null>(null)
const stats = ref<WindowStats | null>(null)
// Format large token numbers (e.g., 1234567 -> 1.23M)
const formatTokens = (tokens: number): string => {
if (tokens >= 1000000) {
return `${(tokens / 1000000).toFixed(2)}M`
} else if (tokens >= 1000) {
return `${(tokens / 1000).toFixed(1)}K`
}
return tokens.toString()
}
const loadStats = async () => {
loading.value = true
error.value = null
try {
stats.value = await adminAPI.accounts.getTodayStats(props.account.id)
} catch (e: any) {
error.value = 'Failed'
console.error('Failed to load today stats:', e)
} finally {
loading.value = false
}
}
onMounted(() => {
loadStats()
})
</script>

View File

@@ -0,0 +1,113 @@
<template>
<div v-if="account.type === 'oauth' || account.type === 'setup-token'">
<!-- OAuth accounts: fetch real usage data -->
<template v-if="account.type === 'oauth'">
<!-- Loading state -->
<div v-if="loading" class="space-y-1.5">
<div class="flex items-center gap-1">
<div class="w-[32px] h-3 bg-gray-200 dark:bg-gray-700 rounded animate-pulse"></div>
<div class="w-8 h-1.5 bg-gray-200 dark:bg-gray-700 rounded-full animate-pulse"></div>
<div class="w-[32px] h-3 bg-gray-200 dark:bg-gray-700 rounded animate-pulse"></div>
</div>
<div class="flex items-center gap-1">
<div class="w-[32px] h-3 bg-gray-200 dark:bg-gray-700 rounded animate-pulse"></div>
<div class="w-8 h-1.5 bg-gray-200 dark:bg-gray-700 rounded-full animate-pulse"></div>
<div class="w-[32px] h-3 bg-gray-200 dark:bg-gray-700 rounded animate-pulse"></div>
</div>
<div class="flex items-center gap-1">
<div class="w-[32px] h-3 bg-gray-200 dark:bg-gray-700 rounded animate-pulse"></div>
<div class="w-8 h-1.5 bg-gray-200 dark:bg-gray-700 rounded-full animate-pulse"></div>
<div class="w-[32px] h-3 bg-gray-200 dark:bg-gray-700 rounded animate-pulse"></div>
</div>
</div>
<!-- Error state -->
<div v-else-if="error" class="text-xs text-red-500">
{{ error }}
</div>
<!-- Usage data -->
<div v-else-if="usageInfo" class="space-y-1">
<!-- 5h Window -->
<UsageProgressBar
v-if="usageInfo.five_hour"
label="5h"
:utilization="usageInfo.five_hour.utilization"
:resets-at="usageInfo.five_hour.resets_at"
:window-stats="usageInfo.five_hour.window_stats"
color="indigo"
/>
<!-- 7d Window -->
<UsageProgressBar
v-if="usageInfo.seven_day"
label="7d"
:utilization="usageInfo.seven_day.utilization"
:resets-at="usageInfo.seven_day.resets_at"
color="emerald"
/>
<!-- 7d Sonnet Window -->
<UsageProgressBar
v-if="usageInfo.seven_day_sonnet"
label="7d S"
:utilization="usageInfo.seven_day_sonnet.utilization"
:resets-at="usageInfo.seven_day_sonnet.resets_at"
color="purple"
/>
</div>
<!-- No data yet -->
<div v-else class="text-xs text-gray-400">
-
</div>
</template>
<!-- Setup Token accounts: show time-based window progress -->
<template v-else-if="account.type === 'setup-token'">
<SetupTokenTimeWindow :account="account" />
</template>
</div>
<!-- Non-OAuth accounts -->
<div v-else class="text-xs text-gray-400">
-
</div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { adminAPI } from '@/api/admin'
import type { Account, AccountUsageInfo } from '@/types'
import UsageProgressBar from './UsageProgressBar.vue'
import SetupTokenTimeWindow from './SetupTokenTimeWindow.vue'
const props = defineProps<{
account: Account
}>()
const loading = ref(false)
const error = ref<string | null>(null)
const usageInfo = ref<AccountUsageInfo | null>(null)
const loadUsage = async () => {
// Only fetch usage for OAuth accounts (Setup Token uses local time-based calculation)
if (props.account.type !== 'oauth') return
loading.value = true
error.value = null
try {
usageInfo.value = await adminAPI.accounts.getUsage(props.account.id)
} catch (e: any) {
error.value = 'Failed'
console.error('Failed to load usage:', e)
} finally {
loading.value = false
}
}
onMounted(() => {
loadUsage()
})
</script>

View File

@@ -0,0 +1,929 @@
<template>
<Modal
:show="show"
:title="t('admin.accounts.createAccount')"
size="lg"
@close="handleClose"
>
<!-- Step Indicator for OAuth accounts -->
<div v-if="isOAuthFlow" class="mb-6 flex items-center justify-center">
<div class="flex items-center space-x-4">
<div class="flex items-center">
<div
:class="[
'flex h-8 w-8 items-center justify-center rounded-full text-sm font-semibold',
step >= 1 ? 'bg-primary-500 text-white' : 'bg-gray-200 text-gray-500 dark:bg-dark-600'
]"
>
1
</div>
<span class="ml-2 text-sm font-medium text-gray-700 dark:text-gray-300">{{ t('admin.accounts.oauth.authMethod') }}</span>
</div>
<div class="h-0.5 w-8 bg-gray-300 dark:bg-dark-600" />
<div class="flex items-center">
<div
:class="[
'flex h-8 w-8 items-center justify-center rounded-full text-sm font-semibold',
step >= 2 ? 'bg-primary-500 text-white' : 'bg-gray-200 text-gray-500 dark:bg-dark-600'
]"
>
2
</div>
<span class="ml-2 text-sm font-medium text-gray-700 dark:text-gray-300">{{ t('admin.accounts.oauth.title') }}</span>
</div>
</div>
</div>
<!-- Step 1: Basic Info -->
<form v-if="step === 1" @submit.prevent="handleSubmit" class="space-y-5">
<div>
<label class="input-label">{{ t('admin.accounts.accountName') }}</label>
<input
v-model="form.name"
type="text"
required
class="input"
:placeholder="t('admin.accounts.enterAccountName')"
/>
</div>
<div>
<label class="input-label">{{ t('admin.accounts.accountType') }}</label>
<div class="grid grid-cols-2 gap-3 mt-2">
<label
:class="[
'relative flex cursor-pointer rounded-lg border-2 p-4 transition-all',
accountCategory === 'oauth-based'
? 'border-primary-500 bg-primary-50 dark:bg-primary-900/20'
: 'border-gray-200 dark:border-dark-600 hover:border-primary-300'
]"
>
<input
v-model="accountCategory"
type="radio"
value="oauth-based"
class="sr-only"
/>
<div class="flex items-center gap-3">
<div class="flex h-10 w-10 items-center justify-center rounded-lg bg-gradient-to-br from-orange-500 to-orange-600">
<svg class="w-5 h-5 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
<path stroke-linecap="round" stroke-linejoin="round" d="M9.813 15.904L9 18.75l-.813-2.846a4.5 4.5 0 00-3.09-3.09L2.25 12l2.846-.813a4.5 4.5 0 003.09-3.09L9 5.25l.813 2.846a4.5 4.5 0 003.09 3.09L15.75 12l-2.846.813a4.5 4.5 0 00-3.09 3.09zM18.259 8.715L18 9.75l-.259-1.035a3.375 3.375 0 00-2.455-2.456L14.25 6l1.036-.259a3.375 3.375 0 002.455-2.456L18 2.25l.259 1.035a3.375 3.375 0 002.456 2.456L21.75 6l-1.035.259a3.375 3.375 0 00-2.456 2.456z" />
</svg>
</div>
<div>
<span class="block text-sm font-semibold text-gray-900 dark:text-white">{{ t('admin.accounts.claudeCode') }}</span>
<span class="text-xs text-gray-500 dark:text-gray-400">{{ t('admin.accounts.oauthSetupToken') }}</span>
</div>
</div>
<div
v-if="accountCategory === 'oauth-based'"
class="absolute right-2 top-2 flex h-5 w-5 items-center justify-center rounded-full bg-primary-500"
>
<svg class="w-3 h-3 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="3">
<path stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5" />
</svg>
</div>
</label>
<label
:class="[
'relative flex cursor-pointer rounded-lg border-2 p-4 transition-all',
accountCategory === 'apikey'
? 'border-primary-500 bg-primary-50 dark:bg-primary-900/20'
: 'border-gray-200 dark:border-dark-600 hover:border-primary-300'
]"
>
<input
v-model="accountCategory"
type="radio"
value="apikey"
class="sr-only"
/>
<div class="flex items-center gap-3">
<div class="flex h-10 w-10 items-center justify-center rounded-lg bg-gradient-to-br from-purple-500 to-purple-600">
<svg class="w-5 h-5 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
<path stroke-linecap="round" stroke-linejoin="round" d="M15.75 5.25a3 3 0 013 3m3 0a6 6 0 01-7.029 5.912c-.563-.097-1.159.026-1.563.43L10.5 17.25H8.25v2.25H6v2.25H2.25v-2.818c0-.597.237-1.17.659-1.591l6.499-6.499c.404-.404.527-1 .43-1.563A6 6 0 1121.75 8.25z" />
</svg>
</div>
<div>
<span class="block text-sm font-semibold text-gray-900 dark:text-white">{{ t('admin.accounts.claudeConsole') }}</span>
<span class="text-xs text-gray-500 dark:text-gray-400">{{ t('admin.accounts.apiKey') }}</span>
</div>
</div>
<div
v-if="accountCategory === 'apikey'"
class="absolute right-2 top-2 flex h-5 w-5 items-center justify-center rounded-full bg-primary-500"
>
<svg class="w-3 h-3 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="3">
<path stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5" />
</svg>
</div>
</label>
</div>
</div>
<!-- Add Method (only for OAuth-based type) -->
<div v-if="isOAuthFlow">
<label class="input-label">{{ t('admin.accounts.addMethod') }}</label>
<div class="flex gap-4 mt-2">
<label class="flex cursor-pointer items-center">
<input
v-model="addMethod"
type="radio"
value="oauth"
class="mr-2 text-primary-600 focus:ring-primary-500"
/>
<span class="text-sm text-gray-700 dark:text-gray-300">Oauth</span>
</label>
<label class="flex cursor-pointer items-center">
<input
v-model="addMethod"
type="radio"
value="setup-token"
class="mr-2 text-primary-600 focus:ring-primary-500"
/>
<span class="text-sm text-gray-700 dark:text-gray-300">{{ t('admin.accounts.setupTokenLongLived') }}</span>
</label>
</div>
</div>
<!-- API Key input (only for apikey type) -->
<div v-if="form.type === 'apikey'" class="space-y-4">
<div>
<label class="input-label">{{ t('admin.accounts.baseUrl') }}</label>
<input
v-model="apiKeyBaseUrl"
type="text"
class="input"
placeholder="https://api.anthropic.com"
/>
<p class="input-hint">{{ t('admin.accounts.baseUrlHint') }}</p>
</div>
<div>
<label class="input-label">{{ t('admin.accounts.apiKeyRequired') }}</label>
<input
v-model="apiKeyValue"
type="password"
required
class="input font-mono"
:placeholder="t('admin.accounts.apiKeyPlaceholder')"
/>
<p class="input-hint">{{ t('admin.accounts.apiKeyHint') }}</p>
</div>
<!-- Model Restriction Section -->
<div class="border-t border-gray-200 dark:border-dark-600 pt-4">
<label class="input-label">{{ t('admin.accounts.modelRestriction') }}</label>
<!-- Mode Toggle -->
<div class="flex gap-2 mb-4">
<button
type="button"
@click="modelRestrictionMode = 'whitelist'"
:class="[
'flex-1 rounded-lg px-4 py-2 text-sm font-medium transition-all',
modelRestrictionMode === 'whitelist'
? 'bg-primary-100 text-primary-700 dark:bg-primary-900/30 dark:text-primary-400'
: 'bg-gray-100 text-gray-600 hover:bg-gray-200 dark:bg-dark-600 dark:text-gray-400 dark:hover:bg-dark-500'
]"
>
<svg class="w-4 h-4 inline mr-1.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
{{ t('admin.accounts.modelWhitelist') }}
</button>
<button
type="button"
@click="modelRestrictionMode = 'mapping'"
:class="[
'flex-1 rounded-lg px-4 py-2 text-sm font-medium transition-all',
modelRestrictionMode === 'mapping'
? 'bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400'
: 'bg-gray-100 text-gray-600 hover:bg-gray-200 dark:bg-dark-600 dark:text-gray-400 dark:hover:bg-dark-500'
]"
>
<svg class="w-4 h-4 inline mr-1.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4" />
</svg>
{{ t('admin.accounts.modelMapping') }}
</button>
</div>
<!-- Whitelist Mode -->
<div v-if="modelRestrictionMode === 'whitelist'">
<div class="mb-3 rounded-lg bg-blue-50 dark:bg-blue-900/20 p-3">
<p class="text-xs text-blue-700 dark:text-blue-400">
<svg class="w-4 h-4 inline mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
{{ t('admin.accounts.selectAllowedModels') }}
</p>
</div>
<!-- Model Checkbox List -->
<div class="grid grid-cols-2 gap-2 mb-3">
<label
v-for="model in commonModels"
:key="model.value"
class="flex cursor-pointer items-center rounded-lg border p-3 transition-all hover:bg-gray-50 dark:border-dark-600 dark:hover:bg-dark-700"
:class="allowedModels.includes(model.value) ? 'border-primary-500 bg-primary-50 dark:bg-primary-900/20' : 'border-gray-200'"
>
<input
type="checkbox"
:value="model.value"
v-model="allowedModels"
class="mr-2 rounded border-gray-300 text-primary-600 focus:ring-primary-500"
/>
<span class="text-sm text-gray-700 dark:text-gray-300">{{ model.label }}</span>
</label>
</div>
<p class="text-xs text-gray-500 dark:text-gray-400">
{{ t('admin.accounts.selectedModels', { count: allowedModels.length }) }}
<span v-if="allowedModels.length === 0">{{ t('admin.accounts.supportsAllModels') }}</span>
</p>
</div>
<!-- Mapping Mode -->
<div v-else>
<div class="mb-3 rounded-lg bg-purple-50 dark:bg-purple-900/20 p-3">
<p class="text-xs text-purple-700 dark:text-purple-400">
<svg class="w-4 h-4 inline mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
{{ t('admin.accounts.mapRequestModels') }}
</p>
</div>
<!-- Model Mapping List -->
<div v-if="modelMappings.length > 0" class="space-y-2 mb-3">
<div
v-for="(mapping, index) in modelMappings"
:key="index"
class="flex items-center gap-2"
>
<input
v-model="mapping.from"
type="text"
class="input flex-1"
:placeholder="t('admin.accounts.requestModel')"
/>
<svg class="w-4 h-4 text-gray-400 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14 5l7 7m0 0l-7 7m7-7H3" />
</svg>
<input
v-model="mapping.to"
type="text"
class="input flex-1"
:placeholder="t('admin.accounts.actualModel')"
/>
<button
type="button"
@click="removeModelMapping(index)"
class="p-2 text-red-500 hover:text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors"
>
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
</button>
</div>
</div>
<button
type="button"
@click="addModelMapping"
class="w-full rounded-lg border-2 border-dashed border-gray-300 dark:border-dark-500 px-4 py-2 text-gray-600 dark:text-gray-400 transition-colors hover:border-gray-400 hover:text-gray-700 dark:hover:border-dark-400 dark:hover:text-gray-300 mb-3"
>
<svg class="w-4 h-4 inline mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
</svg>
{{ t('admin.accounts.addMapping') }}
</button>
<!-- Quick Add Buttons -->
<div class="flex flex-wrap gap-2">
<button
v-for="preset in presetMappings"
:key="preset.label"
type="button"
@click="addPresetMapping(preset.from, preset.to)"
:class="[
'rounded-lg px-3 py-1 text-xs transition-colors',
preset.color
]"
>
+ {{ preset.label }}
</button>
</div>
</div>
</div>
<!-- Custom Error Codes Section -->
<div class="border-t border-gray-200 dark:border-dark-600 pt-4">
<div class="flex items-center justify-between mb-3">
<div>
<label class="input-label mb-0">{{ t('admin.accounts.customErrorCodes') }}</label>
<p class="text-xs text-gray-500 dark:text-gray-400 mt-1">{{ t('admin.accounts.customErrorCodesHint') }}</p>
</div>
<button
type="button"
@click="customErrorCodesEnabled = !customErrorCodesEnabled"
:class="[
'relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-primary-500 focus:ring-offset-2',
customErrorCodesEnabled ? 'bg-primary-600' : 'bg-gray-200 dark:bg-dark-600'
]"
>
<span
:class="[
'pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out',
customErrorCodesEnabled ? 'translate-x-5' : 'translate-x-0'
]"
/>
</button>
</div>
<div v-if="customErrorCodesEnabled" class="space-y-3">
<div class="rounded-lg bg-amber-50 dark:bg-amber-900/20 p-3">
<p class="text-xs text-amber-700 dark:text-amber-400">
<svg class="w-4 h-4 inline mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
</svg>
{{ t('admin.accounts.customErrorCodesWarning') }}
</p>
</div>
<!-- Error Code Buttons -->
<div class="flex flex-wrap gap-2">
<button
v-for="code in commonErrorCodes"
:key="code.value"
type="button"
@click="toggleErrorCode(code.value)"
:class="[
'rounded-lg px-3 py-1.5 text-sm font-medium transition-colors',
selectedErrorCodes.includes(code.value)
? 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400 ring-1 ring-red-500'
: 'bg-gray-100 text-gray-600 hover:bg-gray-200 dark:bg-dark-600 dark:text-gray-400 dark:hover:bg-dark-500'
]"
>
{{ code.value }} {{ code.label }}
</button>
</div>
<!-- Manual input -->
<div class="flex items-center gap-2">
<input
v-model="customErrorCodeInput"
type="number"
min="100"
max="599"
class="input flex-1"
:placeholder="t('admin.accounts.enterErrorCode')"
@keyup.enter="addCustomErrorCode"
/>
<button
type="button"
@click="addCustomErrorCode"
class="btn btn-secondary px-3"
>
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
</svg>
</button>
</div>
<!-- Selected codes summary -->
<div class="flex flex-wrap gap-1.5">
<span
v-for="code in selectedErrorCodes.sort((a, b) => a - b)"
:key="code"
class="inline-flex items-center gap-1 rounded-full bg-red-100 dark:bg-red-900/30 px-2.5 py-0.5 text-sm font-medium text-red-700 dark:text-red-400"
>
{{ code }}
<button
type="button"
@click="removeErrorCode(code)"
class="hover:text-red-900 dark:hover:text-red-300"
>
<svg class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</span>
<span v-if="selectedErrorCodes.length === 0" class="text-xs text-gray-400">
{{ t('admin.accounts.noneSelectedUsesDefault') }}
</span>
</div>
</div>
</div>
</div>
<div>
<label class="input-label">{{ t('admin.accounts.proxy') }}</label>
<ProxySelector
v-model="form.proxy_id"
:proxies="proxies"
/>
</div>
<div class="grid grid-cols-2 gap-4">
<div>
<label class="input-label">{{ t('admin.accounts.concurrency') }}</label>
<input
v-model.number="form.concurrency"
type="number"
min="1"
class="input"
/>
</div>
<div>
<label class="input-label">{{ t('admin.accounts.priority') }}</label>
<input
v-model.number="form.priority"
type="number"
min="1"
class="input"
/>
<p class="input-hint">{{ t('admin.accounts.priorityHint') }}</p>
</div>
</div>
<!-- Group Selection -->
<GroupSelector
v-model="form.group_ids"
:groups="groups"
/>
<div class="flex justify-end gap-3 pt-4">
<button
@click="handleClose"
type="button"
class="btn btn-secondary"
>
{{ t('common.cancel') }}
</button>
<button
type="submit"
:disabled="submitting"
class="btn btn-primary"
>
<svg
v-if="submitting"
class="animate-spin -ml-1 mr-2 h-4 w-4"
fill="none"
viewBox="0 0 24 24"
>
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
{{ isOAuthFlow ? t('common.next') : (submitting ? t('admin.accounts.creating') : t('common.create')) }}
</button>
</div>
</form>
<!-- Step 2: OAuth Authorization -->
<div v-else class="space-y-5">
<OAuthAuthorizationFlow
ref="oauthFlowRef"
:add-method="addMethod"
:auth-url="oauth.authUrl.value"
:session-id="oauth.sessionId.value"
:loading="oauth.loading.value"
:error="oauth.error.value"
:show-help="true"
:show-proxy-warning="!!form.proxy_id"
:allow-multiple="true"
@generate-url="handleGenerateUrl"
@cookie-auth="handleCookieAuth"
/>
<div class="flex justify-between gap-3 pt-4">
<button
type="button"
class="btn btn-secondary"
@click="goBackToBasicInfo"
>
{{ t('common.back') }}
</button>
<button
v-if="oauthFlowRef?.inputMethod?.value === 'manual'"
type="button"
:disabled="!canExchangeCode"
class="btn btn-primary"
@click="handleExchangeCode"
>
<svg
v-if="oauth.loading.value"
class="animate-spin -ml-1 mr-2 h-4 w-4"
fill="none"
viewBox="0 0 24 24"
>
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
{{ oauth.loading.value ? t('admin.accounts.oauth.verifying') : t('admin.accounts.oauth.completeAuth') }}
</button>
</div>
</div>
</Modal>
</template>
<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useAppStore } from '@/stores/app'
import { adminAPI } from '@/api/admin'
import { useAccountOAuth, type AddMethod } from '@/composables/useAccountOAuth'
import type { Proxy, Group, AccountPlatform, AccountType } from '@/types'
import Modal from '@/components/common/Modal.vue'
import Select from '@/components/common/Select.vue'
import ProxySelector from '@/components/common/ProxySelector.vue'
import GroupSelector from '@/components/common/GroupSelector.vue'
import OAuthAuthorizationFlow from './OAuthAuthorizationFlow.vue'
const { t } = useI18n()
interface Props {
show: boolean
proxies: Proxy[]
groups: Group[]
}
const props = defineProps<Props>()
const emit = defineEmits<{
close: []
created: []
}>()
const appStore = useAppStore()
// OAuth composable
const oauth = useAccountOAuth()
// Refs
const oauthFlowRef = ref<InstanceType<typeof OAuthAuthorizationFlow> | null>(null)
// Model mapping type
interface ModelMapping {
from: string
to: string
}
// State
const step = ref(1)
const submitting = ref(false)
const accountCategory = ref<'oauth-based' | 'apikey'>('oauth-based') // UI selection for account category
const addMethod = ref<AddMethod>('oauth') // For oauth-based: 'oauth' or 'setup-token'
const apiKeyBaseUrl = ref('https://api.anthropic.com')
const apiKeyValue = ref('')
const modelMappings = ref<ModelMapping[]>([])
const modelRestrictionMode = ref<'whitelist' | 'mapping'>('whitelist')
const allowedModels = ref<string[]>([])
const customErrorCodesEnabled = ref(false)
const selectedErrorCodes = ref<number[]>([])
const customErrorCodeInput = ref<number | null>(null)
// Common models for whitelist
const commonModels = [
{ value: 'claude-opus-4-5-20251101', label: 'Claude Opus 4.5' },
{ value: 'claude-sonnet-4-20250514', label: 'Claude Sonnet 4' },
{ value: 'claude-sonnet-4-5-20250929', label: 'Claude Sonnet 4.5' },
{ value: 'claude-3-5-haiku-20241022', label: 'Claude 3.5 Haiku' },
{ value: 'claude-haiku-4-5-20251001', label: 'Claude Haiku 4.5' },
{ value: 'claude-3-opus-20240229', label: 'Claude 3 Opus' },
{ value: 'claude-3-5-sonnet-20241022', label: 'Claude 3.5 Sonnet' },
{ value: 'claude-3-haiku-20240307', label: 'Claude 3 Haiku' }
]
// Preset mappings for quick add
const presetMappings = [
{ label: 'Sonnet 4', from: 'claude-sonnet-4-20250514', to: 'claude-sonnet-4-20250514', color: 'bg-blue-100 text-blue-700 hover:bg-blue-200 dark:bg-blue-900/30 dark:text-blue-400' },
{ label: 'Sonnet 4.5', from: 'claude-sonnet-4-5-20250929', to: 'claude-sonnet-4-5-20250929', color: 'bg-indigo-100 text-indigo-700 hover:bg-indigo-200 dark:bg-indigo-900/30 dark:text-indigo-400' },
{ label: 'Opus 4.5', from: 'claude-opus-4-5-20251101', to: 'claude-opus-4-5-20251101', color: 'bg-purple-100 text-purple-700 hover:bg-purple-200 dark:bg-purple-900/30 dark:text-purple-400' },
{ label: 'Haiku 3.5', from: 'claude-3-5-haiku-20241022', to: 'claude-3-5-haiku-20241022', color: 'bg-green-100 text-green-700 hover:bg-green-200 dark:bg-green-900/30 dark:text-green-400' },
{ label: 'Haiku 4.5', from: 'claude-haiku-4-5-20251001', to: 'claude-haiku-4-5-20251001', color: 'bg-emerald-100 text-emerald-700 hover:bg-emerald-200 dark:bg-emerald-900/30 dark:text-emerald-400' },
{ label: 'Opus->Sonnet', from: 'claude-opus-4-5-20251101', to: 'claude-sonnet-4-5-20250929', color: 'bg-amber-100 text-amber-700 hover:bg-amber-200 dark:bg-amber-900/30 dark:text-amber-400' }
]
// Common HTTP error codes for quick selection
const commonErrorCodes = [
{ value: 401, label: 'Unauthorized' },
{ value: 403, label: 'Forbidden' },
{ value: 429, label: 'Rate Limit' },
{ value: 500, label: 'Server Error' },
{ value: 502, label: 'Bad Gateway' },
{ value: 503, label: 'Unavailable' },
{ value: 529, label: 'Overloaded' }
]
const form = reactive({
name: '',
platform: 'anthropic' as AccountPlatform,
type: 'oauth' as AccountType, // Will be 'oauth', 'setup-token', or 'apikey'
credentials: {} as Record<string, unknown>,
proxy_id: null as number | null,
concurrency: 10,
priority: 1,
group_ids: [] as number[]
})
// Helper to check if current type needs OAuth flow
const isOAuthFlow = computed(() => accountCategory.value === 'oauth-based')
const canExchangeCode = computed(() => {
const authCode = oauthFlowRef.value?.authCode?.value || ''
return authCode.trim() && oauth.sessionId.value && !oauth.loading.value
})
// Watchers
watch(() => props.show, (newVal) => {
if (!newVal) {
resetForm()
}
})
// Sync form.type based on accountCategory and addMethod
watch([accountCategory, addMethod], ([category, method]) => {
if (category === 'oauth-based') {
form.type = method as AccountType // 'oauth' or 'setup-token'
} else {
form.type = 'apikey'
}
}, { immediate: true })
// Model mapping helpers
const addModelMapping = () => {
modelMappings.value.push({ from: '', to: '' })
}
const removeModelMapping = (index: number) => {
modelMappings.value.splice(index, 1)
}
const addPresetMapping = (from: string, to: string) => {
// Check if mapping already exists
const exists = modelMappings.value.some(m => m.from === from)
if (exists) {
appStore.showInfo(t('admin.accounts.mappingExists', { model: from }))
return
}
modelMappings.value.push({ from, to })
}
// Error code toggle helper
const toggleErrorCode = (code: number) => {
const index = selectedErrorCodes.value.indexOf(code)
if (index === -1) {
selectedErrorCodes.value.push(code)
} else {
selectedErrorCodes.value.splice(index, 1)
}
}
// Add custom error code from input
const addCustomErrorCode = () => {
const code = customErrorCodeInput.value
if (code === null || code < 100 || code > 599) {
appStore.showError(t('admin.accounts.invalidErrorCode'))
return
}
if (selectedErrorCodes.value.includes(code)) {
appStore.showInfo(t('admin.accounts.errorCodeExists'))
return
}
selectedErrorCodes.value.push(code)
customErrorCodeInput.value = null
}
// Remove error code
const removeErrorCode = (code: number) => {
const index = selectedErrorCodes.value.indexOf(code)
if (index !== -1) {
selectedErrorCodes.value.splice(index, 1)
}
}
const buildModelMappingObject = (): Record<string, string> | null => {
const mapping: Record<string, string> = {}
if (modelRestrictionMode.value === 'whitelist') {
// Whitelist mode: map model to itself
for (const model of allowedModels.value) {
mapping[model] = model
}
} else {
// Mapping mode: use custom mappings
for (const m of modelMappings.value) {
const from = m.from.trim()
const to = m.to.trim()
if (from && to) {
mapping[from] = to
}
}
}
return Object.keys(mapping).length > 0 ? mapping : null
}
// Methods
const resetForm = () => {
step.value = 1
form.name = ''
form.platform = 'anthropic'
form.type = 'oauth'
form.credentials = {}
form.proxy_id = null
form.concurrency = 10
form.priority = 1
form.group_ids = []
accountCategory.value = 'oauth-based'
addMethod.value = 'oauth'
apiKeyBaseUrl.value = 'https://api.anthropic.com'
apiKeyValue.value = ''
modelMappings.value = []
modelRestrictionMode.value = 'whitelist'
allowedModels.value = []
customErrorCodesEnabled.value = false
selectedErrorCodes.value = []
customErrorCodeInput.value = null
oauth.resetState()
oauthFlowRef.value?.reset()
}
const handleClose = () => {
emit('close')
}
const handleSubmit = async () => {
// For OAuth-based type, handle OAuth flow (goes to step 2)
if (isOAuthFlow.value) {
if (!form.name.trim()) {
appStore.showError(t('admin.accounts.pleaseEnterAccountName'))
return
}
step.value = 2
return
}
// For apikey type, create directly
if (!apiKeyValue.value.trim()) {
appStore.showError(t('admin.accounts.pleaseEnterApiKey'))
return
}
// Build credentials with optional model mapping
const credentials: Record<string, unknown> = {
base_url: apiKeyBaseUrl.value.trim() || 'https://api.anthropic.com',
api_key: apiKeyValue.value.trim()
}
// Add model mapping if configured
const modelMapping = buildModelMappingObject()
if (modelMapping) {
credentials.model_mapping = modelMapping
}
// Add custom error codes if enabled
if (customErrorCodesEnabled.value) {
credentials.custom_error_codes_enabled = true
credentials.custom_error_codes = [...selectedErrorCodes.value]
}
form.credentials = credentials
submitting.value = true
try {
await adminAPI.accounts.create(form)
appStore.showSuccess(t('admin.accounts.accountCreated'))
emit('created')
handleClose()
} catch (error: any) {
appStore.showError(error.response?.data?.detail || t('admin.accounts.failedToCreate'))
} finally {
submitting.value = false
}
}
const goBackToBasicInfo = () => {
step.value = 1
oauth.resetState()
oauthFlowRef.value?.reset()
}
const handleGenerateUrl = async () => {
await oauth.generateAuthUrl(addMethod.value, form.proxy_id)
}
const handleExchangeCode = async () => {
const authCode = oauthFlowRef.value?.authCode?.value || ''
if (!authCode.trim() || !oauth.sessionId.value) return
oauth.loading.value = true
oauth.error.value = ''
try {
const proxyConfig = form.proxy_id ? { proxy_id: form.proxy_id } : {}
const endpoint = addMethod.value === 'oauth'
? '/admin/accounts/exchange-code'
: '/admin/accounts/exchange-setup-token-code'
const tokenInfo = await adminAPI.accounts.exchangeCode(endpoint, {
session_id: oauth.sessionId.value,
code: authCode.trim(),
...proxyConfig
})
const extra = oauth.buildExtraInfo(tokenInfo)
await adminAPI.accounts.create({
name: form.name,
platform: form.platform,
type: addMethod.value, // Use addMethod as type: 'oauth' or 'setup-token'
credentials: tokenInfo,
extra,
proxy_id: form.proxy_id,
concurrency: form.concurrency,
priority: form.priority
})
appStore.showSuccess(t('admin.accounts.accountCreated'))
emit('created')
handleClose()
} catch (error: any) {
oauth.error.value = error.response?.data?.detail || t('admin.accounts.oauth.authFailed')
appStore.showError(oauth.error.value)
} finally {
oauth.loading.value = false
}
}
const handleCookieAuth = async (sessionKey: string) => {
oauth.loading.value = true
oauth.error.value = ''
try {
const proxyConfig = form.proxy_id ? { proxy_id: form.proxy_id } : {}
const keys = oauth.parseSessionKeys(sessionKey)
if (keys.length === 0) {
oauth.error.value = t('admin.accounts.oauth.pleaseEnterSessionKey')
return
}
const endpoint = addMethod.value === 'oauth'
? '/admin/accounts/cookie-auth'
: '/admin/accounts/setup-token-cookie-auth'
let successCount = 0
let failedCount = 0
const errors: string[] = []
for (let i = 0; i < keys.length; i++) {
try {
const tokenInfo = await adminAPI.accounts.exchangeCode(endpoint, {
session_id: '',
code: keys[i],
...proxyConfig
})
const extra = oauth.buildExtraInfo(tokenInfo)
const accountName = keys.length > 1 ? `${form.name} #${i + 1}` : form.name
await adminAPI.accounts.create({
name: accountName,
platform: form.platform,
type: addMethod.value, // Use addMethod as type: 'oauth' or 'setup-token'
credentials: tokenInfo,
extra,
proxy_id: form.proxy_id,
concurrency: form.concurrency,
priority: form.priority
})
successCount++
} catch (error: any) {
failedCount++
errors.push(t('admin.accounts.oauth.keyAuthFailed', { index: i + 1, error: error.response?.data?.detail || t('admin.accounts.oauth.authFailed') }))
}
}
if (successCount > 0) {
appStore.showSuccess(t('admin.accounts.oauth.successCreated', { count: successCount }))
if (failedCount === 0) {
emit('created')
handleClose()
} else {
emit('created')
}
}
if (failedCount > 0) {
oauth.error.value = errors.join('\n')
}
} catch (error: any) {
oauth.error.value = error.response?.data?.detail || t('admin.accounts.oauth.cookieAuthFailed')
} finally {
oauth.loading.value = false
}
}
</script>

View File

@@ -0,0 +1,646 @@
<template>
<Modal
:show="show"
:title="t('admin.accounts.editAccount')"
size="lg"
@close="handleClose"
>
<form v-if="account" @submit.prevent="handleSubmit" class="space-y-5">
<div>
<label class="input-label">{{ t('common.name') }}</label>
<input
v-model="form.name"
type="text"
required
class="input"
/>
</div>
<!-- API Key fields (only for apikey type) -->
<div v-if="account.type === 'apikey'" class="space-y-4">
<div>
<label class="input-label">{{ t('admin.accounts.baseUrl') }}</label>
<input
v-model="editBaseUrl"
type="text"
class="input"
placeholder="https://api.anthropic.com"
/>
<p class="input-hint">{{ t('admin.accounts.baseUrlHint') }}</p>
</div>
<div>
<label class="input-label">{{ t('admin.accounts.apiKey') }}</label>
<input
v-model="editApiKey"
type="password"
class="input font-mono"
:placeholder="t('admin.accounts.leaveEmptyToKeep')"
/>
<p class="input-hint">{{ t('admin.accounts.leaveEmptyToKeep') }}</p>
</div>
<!-- Model Restriction Section -->
<div class="border-t border-gray-200 dark:border-dark-600 pt-4">
<label class="input-label">{{ t('admin.accounts.modelRestriction') }}</label>
<!-- Mode Toggle -->
<div class="flex gap-2 mb-4">
<button
type="button"
@click="modelRestrictionMode = 'whitelist'"
:class="[
'flex-1 rounded-lg px-4 py-2 text-sm font-medium transition-all',
modelRestrictionMode === 'whitelist'
? 'bg-primary-100 text-primary-700 dark:bg-primary-900/30 dark:text-primary-400'
: 'bg-gray-100 text-gray-600 hover:bg-gray-200 dark:bg-dark-600 dark:text-gray-400 dark:hover:bg-dark-500'
]"
>
<svg class="w-4 h-4 inline mr-1.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
{{ t('admin.accounts.modelWhitelist') }}
</button>
<button
type="button"
@click="modelRestrictionMode = 'mapping'"
:class="[
'flex-1 rounded-lg px-4 py-2 text-sm font-medium transition-all',
modelRestrictionMode === 'mapping'
? 'bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400'
: 'bg-gray-100 text-gray-600 hover:bg-gray-200 dark:bg-dark-600 dark:text-gray-400 dark:hover:bg-dark-500'
]"
>
<svg class="w-4 h-4 inline mr-1.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4" />
</svg>
{{ t('admin.accounts.modelMapping') }}
</button>
</div>
<!-- Whitelist Mode -->
<div v-if="modelRestrictionMode === 'whitelist'">
<div class="mb-3 rounded-lg bg-blue-50 dark:bg-blue-900/20 p-3">
<p class="text-xs text-blue-700 dark:text-blue-400">
<svg class="w-4 h-4 inline mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
{{ t('admin.accounts.selectAllowedModels') }}
</p>
</div>
<!-- Model Checkbox List -->
<div class="grid grid-cols-2 gap-2 mb-3">
<label
v-for="model in commonModels"
:key="model.value"
class="flex cursor-pointer items-center rounded-lg border p-3 transition-all hover:bg-gray-50 dark:border-dark-600 dark:hover:bg-dark-700"
:class="allowedModels.includes(model.value) ? 'border-primary-500 bg-primary-50 dark:bg-primary-900/20' : 'border-gray-200'"
>
<input
type="checkbox"
:value="model.value"
v-model="allowedModels"
class="mr-2 rounded border-gray-300 text-primary-600 focus:ring-primary-500"
/>
<span class="text-sm text-gray-700 dark:text-gray-300">{{ model.label }}</span>
</label>
</div>
<p class="text-xs text-gray-500 dark:text-gray-400">
{{ t('admin.accounts.selectedModels', { count: allowedModels.length }) }}
<span v-if="allowedModels.length === 0">{{ t('admin.accounts.supportsAllModels') }}</span>
</p>
</div>
<!-- Mapping Mode -->
<div v-else>
<div class="mb-3 rounded-lg bg-purple-50 dark:bg-purple-900/20 p-3">
<p class="text-xs text-purple-700 dark:text-purple-400">
<svg class="w-4 h-4 inline mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
{{ t('admin.accounts.mapRequestModels') }}
</p>
</div>
<!-- Model Mapping List -->
<div v-if="modelMappings.length > 0" class="space-y-2 mb-3">
<div
v-for="(mapping, index) in modelMappings"
:key="index"
class="flex items-center gap-2"
>
<input
v-model="mapping.from"
type="text"
class="input flex-1"
:placeholder="t('admin.accounts.requestModel')"
/>
<svg class="w-4 h-4 text-gray-400 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14 5l7 7m0 0l-7 7m7-7H3" />
</svg>
<input
v-model="mapping.to"
type="text"
class="input flex-1"
:placeholder="t('admin.accounts.actualModel')"
/>
<button
type="button"
@click="removeModelMapping(index)"
class="p-2 text-red-500 hover:text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors"
>
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
</button>
</div>
</div>
<button
type="button"
@click="addModelMapping"
class="w-full rounded-lg border-2 border-dashed border-gray-300 dark:border-dark-500 px-4 py-2 text-gray-600 dark:text-gray-400 transition-colors hover:border-gray-400 hover:text-gray-700 dark:hover:border-dark-400 dark:hover:text-gray-300 mb-3"
>
<svg class="w-4 h-4 inline mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
</svg>
{{ t('admin.accounts.addMapping') }}
</button>
<!-- Quick Add Buttons -->
<div class="flex flex-wrap gap-2">
<button
v-for="preset in presetMappings"
:key="preset.label"
type="button"
@click="addPresetMapping(preset.from, preset.to)"
:class="[
'rounded-lg px-3 py-1 text-xs transition-colors',
preset.color
]"
>
+ {{ preset.label }}
</button>
</div>
</div>
</div>
<!-- Custom Error Codes Section -->
<div class="border-t border-gray-200 dark:border-dark-600 pt-4">
<div class="flex items-center justify-between mb-3">
<div>
<label class="input-label mb-0">{{ t('admin.accounts.customErrorCodes') }}</label>
<p class="text-xs text-gray-500 dark:text-gray-400 mt-1">{{ t('admin.accounts.customErrorCodesHint') }}</p>
</div>
<button
type="button"
@click="customErrorCodesEnabled = !customErrorCodesEnabled"
:class="[
'relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-primary-500 focus:ring-offset-2',
customErrorCodesEnabled ? 'bg-primary-600' : 'bg-gray-200 dark:bg-dark-600'
]"
>
<span
:class="[
'pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out',
customErrorCodesEnabled ? 'translate-x-5' : 'translate-x-0'
]"
/>
</button>
</div>
<div v-if="customErrorCodesEnabled" class="space-y-3">
<div class="rounded-lg bg-amber-50 dark:bg-amber-900/20 p-3">
<p class="text-xs text-amber-700 dark:text-amber-400">
<svg class="w-4 h-4 inline mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
</svg>
{{ t('admin.accounts.customErrorCodesWarning') }}
</p>
</div>
<!-- Error Code Buttons -->
<div class="flex flex-wrap gap-2">
<button
v-for="code in commonErrorCodes"
:key="code.value"
type="button"
@click="toggleErrorCode(code.value)"
:class="[
'rounded-lg px-3 py-1.5 text-sm font-medium transition-colors',
selectedErrorCodes.includes(code.value)
? 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400 ring-1 ring-red-500'
: 'bg-gray-100 text-gray-600 hover:bg-gray-200 dark:bg-dark-600 dark:text-gray-400 dark:hover:bg-dark-500'
]"
>
{{ code.value }} {{ code.label }}
</button>
</div>
<!-- Manual input -->
<div class="flex items-center gap-2">
<input
v-model="customErrorCodeInput"
type="number"
min="100"
max="599"
class="input flex-1"
:placeholder="t('admin.accounts.enterErrorCode')"
@keyup.enter="addCustomErrorCode"
/>
<button
type="button"
@click="addCustomErrorCode"
class="btn btn-secondary px-3"
>
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
</svg>
</button>
</div>
<!-- Selected codes summary -->
<div class="flex flex-wrap gap-1.5">
<span
v-for="code in selectedErrorCodes.sort((a, b) => a - b)"
:key="code"
class="inline-flex items-center gap-1 rounded-full bg-red-100 dark:bg-red-900/30 px-2.5 py-0.5 text-sm font-medium text-red-700 dark:text-red-400"
>
{{ code }}
<button
type="button"
@click="removeErrorCode(code)"
class="hover:text-red-900 dark:hover:text-red-300"
>
<svg class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</span>
<span v-if="selectedErrorCodes.length === 0" class="text-xs text-gray-400">
{{ t('admin.accounts.noneSelectedUsesDefault') }}
</span>
</div>
</div>
</div>
</div>
<div>
<label class="input-label">{{ t('admin.accounts.proxy') }}</label>
<ProxySelector
v-model="form.proxy_id"
:proxies="proxies"
/>
</div>
<div class="grid grid-cols-2 gap-4">
<div>
<label class="input-label">{{ t('admin.accounts.concurrency') }}</label>
<input
v-model.number="form.concurrency"
type="number"
min="1"
class="input"
/>
</div>
<div>
<label class="input-label">{{ t('admin.accounts.priority') }}</label>
<input
v-model.number="form.priority"
type="number"
min="1"
class="input"
/>
</div>
</div>
<div>
<label class="input-label">{{ t('common.status') }}</label>
<Select
v-model="form.status"
:options="statusOptions"
/>
</div>
<!-- Group Selection -->
<GroupSelector
v-model="form.group_ids"
:groups="groups"
/>
<div class="flex justify-end gap-3 pt-4">
<button
@click="handleClose"
type="button"
class="btn btn-secondary"
>
{{ t('common.cancel') }}
</button>
<button
type="submit"
:disabled="submitting"
class="btn btn-primary"
>
<svg
v-if="submitting"
class="animate-spin -ml-1 mr-2 h-4 w-4"
fill="none"
viewBox="0 0 24 24"
>
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
{{ submitting ? t('admin.accounts.updating') : t('common.update') }}
</button>
</div>
</form>
</Modal>
</template>
<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useAppStore } from '@/stores/app'
import { adminAPI } from '@/api/admin'
import type { Account, Proxy, Group } from '@/types'
import Modal from '@/components/common/Modal.vue'
import Select from '@/components/common/Select.vue'
import ProxySelector from '@/components/common/ProxySelector.vue'
import GroupSelector from '@/components/common/GroupSelector.vue'
interface Props {
show: boolean
account: Account | null
proxies: Proxy[]
groups: Group[]
}
const props = defineProps<Props>()
const emit = defineEmits<{
close: []
updated: []
}>()
const { t } = useI18n()
const appStore = useAppStore()
// Model mapping type
interface ModelMapping {
from: string
to: string
}
// State
const submitting = ref(false)
const editBaseUrl = ref('https://api.anthropic.com')
const editApiKey = ref('')
const modelMappings = ref<ModelMapping[]>([])
const modelRestrictionMode = ref<'whitelist' | 'mapping'>('whitelist')
const allowedModels = ref<string[]>([])
const customErrorCodesEnabled = ref(false)
const selectedErrorCodes = ref<number[]>([])
const customErrorCodeInput = ref<number | null>(null)
// Common models for whitelist
const commonModels = [
{ value: 'claude-opus-4-5-20251101', label: 'Claude Opus 4.5' },
{ value: 'claude-sonnet-4-20250514', label: 'Claude Sonnet 4' },
{ value: 'claude-sonnet-4-5-20250929', label: 'Claude Sonnet 4.5' },
{ value: 'claude-3-5-haiku-20241022', label: 'Claude 3.5 Haiku' },
{ value: 'claude-haiku-4-5-20251001', label: 'Claude Haiku 4.5' },
{ value: 'claude-3-opus-20240229', label: 'Claude 3 Opus' },
{ value: 'claude-3-5-sonnet-20241022', label: 'Claude 3.5 Sonnet' },
{ value: 'claude-3-haiku-20240307', label: 'Claude 3 Haiku' }
]
// Preset mappings for quick add
const presetMappings = [
{ label: 'Sonnet 4', from: 'claude-sonnet-4-20250514', to: 'claude-sonnet-4-20250514', color: 'bg-blue-100 text-blue-700 hover:bg-blue-200 dark:bg-blue-900/30 dark:text-blue-400' },
{ label: 'Sonnet 4.5', from: 'claude-sonnet-4-5-20250929', to: 'claude-sonnet-4-5-20250929', color: 'bg-indigo-100 text-indigo-700 hover:bg-indigo-200 dark:bg-indigo-900/30 dark:text-indigo-400' },
{ label: 'Opus 4.5', from: 'claude-opus-4-5-20251101', to: 'claude-opus-4-5-20251101', color: 'bg-purple-100 text-purple-700 hover:bg-purple-200 dark:bg-purple-900/30 dark:text-purple-400' },
{ label: 'Haiku 3.5', from: 'claude-3-5-haiku-20241022', to: 'claude-3-5-haiku-20241022', color: 'bg-green-100 text-green-700 hover:bg-green-200 dark:bg-green-900/30 dark:text-green-400' },
{ label: 'Haiku 4.5', from: 'claude-haiku-4-5-20251001', to: 'claude-haiku-4-5-20251001', color: 'bg-emerald-100 text-emerald-700 hover:bg-emerald-200 dark:bg-emerald-900/30 dark:text-emerald-400' },
{ label: 'Opus->Sonnet', from: 'claude-opus-4-5-20251101', to: 'claude-sonnet-4-5-20250929', color: 'bg-amber-100 text-amber-700 hover:bg-amber-200 dark:bg-amber-900/30 dark:text-amber-400' }
]
// Common HTTP error codes for quick selection
const commonErrorCodes = [
{ value: 401, label: 'Unauthorized' },
{ value: 403, label: 'Forbidden' },
{ value: 429, label: 'Rate Limit' },
{ value: 500, label: 'Server Error' },
{ value: 502, label: 'Bad Gateway' },
{ value: 503, label: 'Unavailable' },
{ value: 529, label: 'Overloaded' }
]
const form = reactive({
name: '',
proxy_id: null as number | null,
concurrency: 1,
priority: 1,
status: 'active' as 'active' | 'inactive',
group_ids: [] as number[]
})
const statusOptions = computed(() => [
{ value: 'active', label: t('common.active') },
{ value: 'inactive', label: t('common.inactive') }
])
// Watchers
watch(() => props.account, (newAccount) => {
if (newAccount) {
form.name = newAccount.name
form.proxy_id = newAccount.proxy_id
form.concurrency = newAccount.concurrency
form.priority = newAccount.priority
form.status = newAccount.status as 'active' | 'inactive'
form.group_ids = newAccount.group_ids || []
// Initialize API Key fields for apikey type
if (newAccount.type === 'apikey' && newAccount.credentials) {
const credentials = newAccount.credentials as Record<string, unknown>
editBaseUrl.value = credentials.base_url as string || 'https://api.anthropic.com'
// Load model mappings and detect mode
const existingMappings = credentials.model_mapping as Record<string, string> | undefined
if (existingMappings && typeof existingMappings === 'object') {
const entries = Object.entries(existingMappings)
// Detect if this is whitelist mode (all from === to) or mapping mode
const isWhitelistMode = entries.length > 0 && entries.every(([from, to]) => from === to)
if (isWhitelistMode) {
// Whitelist mode: populate allowedModels
modelRestrictionMode.value = 'whitelist'
allowedModels.value = entries.map(([from]) => from)
modelMappings.value = []
} else {
// Mapping mode: populate modelMappings
modelRestrictionMode.value = 'mapping'
modelMappings.value = entries.map(([from, to]) => ({ from, to }))
allowedModels.value = []
}
} else {
// No mappings: default to whitelist mode with empty selection (allow all)
modelRestrictionMode.value = 'whitelist'
modelMappings.value = []
allowedModels.value = []
}
// Load custom error codes
customErrorCodesEnabled.value = credentials.custom_error_codes_enabled === true
const existingErrorCodes = credentials.custom_error_codes as number[] | undefined
if (existingErrorCodes && Array.isArray(existingErrorCodes)) {
selectedErrorCodes.value = [...existingErrorCodes]
} else {
selectedErrorCodes.value = []
}
} else {
editBaseUrl.value = 'https://api.anthropic.com'
modelRestrictionMode.value = 'whitelist'
modelMappings.value = []
allowedModels.value = []
customErrorCodesEnabled.value = false
selectedErrorCodes.value = []
}
editApiKey.value = ''
}
}, { immediate: true })
// Model mapping helpers
const addModelMapping = () => {
modelMappings.value.push({ from: '', to: '' })
}
const removeModelMapping = (index: number) => {
modelMappings.value.splice(index, 1)
}
const addPresetMapping = (from: string, to: string) => {
const exists = modelMappings.value.some(m => m.from === from)
if (exists) {
appStore.showInfo(t('admin.accounts.mappingExists', { model: from }))
return
}
modelMappings.value.push({ from, to })
}
// Error code toggle helper
const toggleErrorCode = (code: number) => {
const index = selectedErrorCodes.value.indexOf(code)
if (index === -1) {
selectedErrorCodes.value.push(code)
} else {
selectedErrorCodes.value.splice(index, 1)
}
}
// Add custom error code from input
const addCustomErrorCode = () => {
const code = customErrorCodeInput.value
if (code === null || code < 100 || code > 599) {
appStore.showError(t('admin.accounts.invalidErrorCode'))
return
}
if (selectedErrorCodes.value.includes(code)) {
appStore.showInfo(t('admin.accounts.errorCodeExists'))
return
}
selectedErrorCodes.value.push(code)
customErrorCodeInput.value = null
}
// Remove error code
const removeErrorCode = (code: number) => {
const index = selectedErrorCodes.value.indexOf(code)
if (index !== -1) {
selectedErrorCodes.value.splice(index, 1)
}
}
const buildModelMappingObject = (): Record<string, string> | null => {
const mapping: Record<string, string> = {}
if (modelRestrictionMode.value === 'whitelist') {
// Whitelist mode: model maps to itself
for (const model of allowedModels.value) {
mapping[model] = model
}
} else {
// Mapping mode: use the mapping entries
for (const m of modelMappings.value) {
const from = m.from.trim()
const to = m.to.trim()
if (from && to) {
mapping[from] = to
}
}
}
return Object.keys(mapping).length > 0 ? mapping : null
}
// Methods
const handleClose = () => {
emit('close')
}
const handleSubmit = async () => {
if (!props.account) return
submitting.value = true
try {
const updatePayload: Record<string, unknown> = { ...form }
// For apikey type, handle credentials update
if (props.account.type === 'apikey') {
const currentCredentials = props.account.credentials as Record<string, unknown> || {}
const newBaseUrl = editBaseUrl.value.trim() || 'https://api.anthropic.com'
const modelMapping = buildModelMappingObject()
// Always update credentials for apikey type to handle model mapping changes
const newCredentials: Record<string, unknown> = {
base_url: newBaseUrl
}
// Handle API key
if (editApiKey.value.trim()) {
// User provided a new API key
newCredentials.api_key = editApiKey.value.trim()
} else if (currentCredentials.api_key) {
// Preserve existing api_key
newCredentials.api_key = currentCredentials.api_key
} else {
appStore.showError(t('admin.accounts.apiKeyIsRequired'))
submitting.value = false
return
}
// Add model mapping if configured
if (modelMapping) {
newCredentials.model_mapping = modelMapping
}
// Add custom error codes if enabled
if (customErrorCodesEnabled.value) {
newCredentials.custom_error_codes_enabled = true
newCredentials.custom_error_codes = [...selectedErrorCodes.value]
}
updatePayload.credentials = newCredentials
}
await adminAPI.accounts.update(props.account.id, updatePayload)
appStore.showSuccess(t('admin.accounts.accountUpdated'))
emit('updated')
handleClose()
} catch (error: any) {
appStore.showError(error.response?.data?.detail || t('admin.accounts.failedToUpdate'))
} finally {
submitting.value = false
}
}
</script>

View File

@@ -0,0 +1,364 @@
<template>
<div class="rounded-lg border border-blue-200 bg-blue-50 dark:border-blue-700 dark:bg-blue-900/30 p-6">
<div class="flex items-start gap-4">
<div class="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-lg bg-blue-500">
<svg class="w-5 h-5 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
<path stroke-linecap="round" stroke-linejoin="round" d="M13.19 8.688a4.5 4.5 0 011.242 7.244l-4.5 4.5a4.5 4.5 0 01-6.364-6.364l1.757-1.757m13.35-.622l1.757-1.757a4.5 4.5 0 00-6.364-6.364l-4.5 4.5a4.5 4.5 0 001.242 7.244" />
</svg>
</div>
<div class="flex-1">
<h4 class="mb-3 font-semibold text-blue-900 dark:text-blue-200">{{ t('admin.accounts.oauth.title') }}</h4>
<!-- Auth Method Selection -->
<div class="mb-4">
<label class="mb-2 block text-sm font-medium text-blue-800 dark:text-blue-300">
{{ methodLabel }}
</label>
<div class="flex gap-4">
<label class="flex cursor-pointer items-center gap-2">
<input
v-model="inputMethod"
type="radio"
value="manual"
class="text-blue-600 focus:ring-blue-500"
/>
<span class="text-sm text-blue-900 dark:text-blue-200">{{ t('admin.accounts.oauth.manualAuth') }}</span>
</label>
<label class="flex cursor-pointer items-center gap-2">
<input
v-model="inputMethod"
type="radio"
value="cookie"
class="text-blue-600 focus:ring-blue-500"
/>
<span class="text-sm text-blue-900 dark:text-blue-200">{{ t('admin.accounts.oauth.cookieAutoAuth') }}</span>
</label>
</div>
</div>
<!-- Cookie Auto-Auth Form -->
<div v-if="inputMethod === 'cookie'" class="space-y-4">
<div class="rounded-lg border border-blue-300 dark:border-blue-600 bg-white/80 dark:bg-gray-800/80 p-4">
<p class="mb-3 text-sm text-blue-700 dark:text-blue-300">
{{ t('admin.accounts.oauth.cookieAutoAuthDesc') }}
</p>
<!-- sessionKey Input -->
<div class="mb-4">
<label class="mb-2 flex items-center gap-2 text-sm font-semibold text-gray-700 dark:text-gray-300">
<svg class="w-4 h-4 text-blue-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
<path stroke-linecap="round" stroke-linejoin="round" d="M15.75 5.25a3 3 0 013 3m3 0a6 6 0 01-7.029 5.912c-.563-.097-1.159.026-1.563.43L10.5 17.25H8.25v2.25H6v2.25H2.25v-2.818c0-.597.237-1.17.659-1.591l6.499-6.499c.404-.404.527-1 .43-1.563A6 6 0 1121.75 8.25z" />
</svg>
{{ t('admin.accounts.oauth.sessionKey') }}
<span
v-if="parsedKeyCount > 1 && allowMultiple"
class="rounded-full bg-blue-500 px-2 py-0.5 text-xs text-white"
>
{{ t('admin.accounts.oauth.keysCount', { count: parsedKeyCount }) }}
</span>
<button
v-if="showHelp"
type="button"
class="text-blue-500 hover:text-blue-600"
@click="showHelpDialog = !showHelpDialog"
>
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
<path stroke-linecap="round" stroke-linejoin="round" d="M9.879 7.519c1.171-1.025 3.071-1.025 4.242 0 1.172 1.025 1.172 2.687 0 3.712-.203.179-.43.326-.67.442-.745.361-1.45.999-1.45 1.827v.75M21 12a9 9 0 11-18 0 9 9 0 0118 0zm-9 5.25h.008v.008H12v-.008z" />
</svg>
</button>
</label>
<textarea
v-model="sessionKeyInput"
rows="3"
class="input w-full font-mono text-sm resize-y"
:placeholder="allowMultiple ? t('admin.accounts.oauth.sessionKeyPlaceholder') : t('admin.accounts.oauth.sessionKeyPlaceholderSingle')"
></textarea>
<p
v-if="parsedKeyCount > 1 && allowMultiple"
class="mt-1 text-xs text-blue-600 dark:text-blue-400"
>
{{ t('admin.accounts.oauth.batchCreateAccounts', { count: parsedKeyCount }) }}
</p>
</div>
<!-- Help Section -->
<div
v-if="showHelpDialog && showHelp"
class="mb-4 rounded-lg border border-amber-200 bg-amber-50 dark:border-amber-700 dark:bg-amber-900/30 p-3"
>
<h5 class="mb-2 font-semibold text-amber-800 dark:text-amber-200">
{{ t('admin.accounts.oauth.howToGetSessionKey') }}
</h5>
<ol class="list-inside list-decimal space-y-1 text-xs text-amber-700 dark:text-amber-300">
<li v-html="t('admin.accounts.oauth.step1')"></li>
<li v-html="t('admin.accounts.oauth.step2')"></li>
<li v-html="t('admin.accounts.oauth.step3')"></li>
<li v-html="t('admin.accounts.oauth.step4')"></li>
<li v-html="t('admin.accounts.oauth.step5')"></li>
<li v-html="t('admin.accounts.oauth.step6')"></li>
</ol>
<p class="mt-2 text-xs text-amber-600 dark:text-amber-400" v-html="t('admin.accounts.oauth.sessionKeyFormat')"></p>
</div>
<!-- Error Message -->
<div
v-if="error"
class="mb-4 rounded-lg border border-red-200 bg-red-50 dark:border-red-700 dark:bg-red-900/30 p-3"
>
<p class="text-sm text-red-600 dark:text-red-400 whitespace-pre-line">
{{ error }}
</p>
</div>
<!-- Auth Button -->
<button
type="button"
class="btn btn-primary w-full"
:disabled="loading || !sessionKeyInput.trim()"
@click="handleCookieAuth"
>
<svg v-if="loading" class="animate-spin -ml-1 mr-2 h-4 w-4" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
<svg v-else class="w-4 h-4 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
<path stroke-linecap="round" stroke-linejoin="round" d="M9.813 15.904L9 18.75l-.813-2.846a4.5 4.5 0 00-3.09-3.09L2.25 12l2.846-.813a4.5 4.5 0 003.09-3.09L9 5.25l.813 2.846a4.5 4.5 0 003.09 3.09L15.75 12l-2.846.813a4.5 4.5 0 00-3.09 3.09z" />
</svg>
{{ loading ? t('admin.accounts.oauth.authorizing') : t('admin.accounts.oauth.startAutoAuth') }}
</button>
</div>
</div>
<!-- Manual Authorization Flow -->
<div v-else class="space-y-4">
<p class="mb-4 text-sm text-blue-800 dark:text-blue-300">
{{ t('admin.accounts.oauth.followSteps') }}
</p>
<!-- Step 1: Generate Auth URL -->
<div class="rounded-lg border border-blue-300 dark:border-blue-600 bg-white/80 dark:bg-gray-800/80 p-4">
<div class="flex items-start gap-3">
<div class="flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-full bg-blue-600 text-xs font-bold text-white">
1
</div>
<div class="flex-1">
<p class="mb-2 font-medium text-blue-900 dark:text-blue-200">
{{ t('admin.accounts.oauth.step1GenerateUrl') }}
</p>
<button
v-if="!authUrl"
type="button"
:disabled="loading"
class="btn btn-primary text-sm"
@click="handleGenerateUrl"
>
<svg v-if="loading" class="animate-spin -ml-1 mr-2 h-4 w-4" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
<svg v-else class="w-4 h-4 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
<path stroke-linecap="round" stroke-linejoin="round" d="M13.19 8.688a4.5 4.5 0 011.242 7.244l-4.5 4.5a4.5 4.5 0 01-6.364-6.364l1.757-1.757m13.35-.622l1.757-1.757a4.5 4.5 0 00-6.364-6.364l-4.5 4.5a4.5 4.5 0 001.242 7.244" />
</svg>
{{ loading ? t('admin.accounts.oauth.generating') : t('admin.accounts.oauth.generateAuthUrl') }}
</button>
<div v-else class="space-y-3">
<div class="flex items-center gap-2">
<input
:value="authUrl"
readonly
type="text"
class="input flex-1 bg-gray-50 dark:bg-gray-700 font-mono text-xs"
/>
<button
type="button"
class="btn btn-secondary p-2"
title="Copy URL"
@click="handleCopyUrl"
>
<svg v-if="!copied" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
<path stroke-linecap="round" stroke-linejoin="round" d="M15.666 3.888A2.25 2.25 0 0013.5 2.25h-3c-1.03 0-1.9.693-2.166 1.638m7.332 0c.055.194.084.4.084.612v0a.75.75 0 01-.75.75H9a.75.75 0 01-.75-.75v0c0-.212.03-.418.084-.612m7.332 0c.646.049 1.288.11 1.927.184 1.1.128 1.907 1.077 1.907 2.185V19.5a2.25 2.25 0 01-2.25 2.25H6.75A2.25 2.25 0 014.5 19.5V6.257c0-1.108.806-2.057 1.907-2.185a48.208 48.208 0 011.927-.184" />
</svg>
<svg v-else class="w-4 h-4 text-green-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5" />
</svg>
</button>
</div>
<button
type="button"
class="text-xs text-blue-600 hover:text-blue-700 dark:text-blue-400"
@click="handleRegenerate"
>
<svg class="w-3 h-3 inline mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
<path stroke-linecap="round" stroke-linejoin="round" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7M4.031 9.865a8.25 8.25 0 0113.803-3.7l3.181 3.182m0-4.991v4.99" />
</svg>
{{ t('admin.accounts.oauth.regenerate') }}
</button>
</div>
</div>
</div>
</div>
<!-- Step 2: Open URL and authorize -->
<div class="rounded-lg border border-blue-300 dark:border-blue-600 bg-white/80 dark:bg-gray-800/80 p-4">
<div class="flex items-start gap-3">
<div class="flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-full bg-blue-600 text-xs font-bold text-white">
2
</div>
<div class="flex-1">
<p class="mb-2 font-medium text-blue-900 dark:text-blue-200">
{{ t('admin.accounts.oauth.step2OpenUrl') }}
</p>
<p class="text-sm text-blue-700 dark:text-blue-300">
{{ t('admin.accounts.oauth.openUrlDesc') }}
</p>
<div v-if="showProxyWarning" class="mt-2 rounded border border-yellow-300 dark:border-yellow-700 bg-yellow-50 dark:bg-yellow-900/30 p-3">
<p class="text-xs text-yellow-800 dark:text-yellow-300" v-html="t('admin.accounts.oauth.proxyWarning')">
</p>
</div>
</div>
</div>
</div>
<!-- Step 3: Enter authorization code -->
<div class="rounded-lg border border-blue-300 dark:border-blue-600 bg-white/80 dark:bg-gray-800/80 p-4">
<div class="flex items-start gap-3">
<div class="flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-full bg-blue-600 text-xs font-bold text-white">
3
</div>
<div class="flex-1">
<p class="mb-2 font-medium text-blue-900 dark:text-blue-200">
{{ t('admin.accounts.oauth.step3EnterCode') }}
</p>
<p class="mb-3 text-sm text-blue-700 dark:text-blue-300" v-html="t('admin.accounts.oauth.authCodeDesc')">
</p>
<div>
<label class="input-label">
<svg class="w-4 h-4 inline mr-1 text-blue-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
<path stroke-linecap="round" stroke-linejoin="round" d="M15.75 5.25a3 3 0 013 3m3 0a6 6 0 01-7.029 5.912c-.563-.097-1.159.026-1.563.43L10.5 17.25H8.25v2.25H6v2.25H2.25v-2.818c0-.597.237-1.17.659-1.591l6.499-6.499c.404-.404.527-1 .43-1.563A6 6 0 1121.75 8.25z" />
</svg>
{{ t('admin.accounts.oauth.authCode') }}
</label>
<textarea
v-model="authCodeInput"
rows="3"
class="input w-full font-mono text-sm resize-none"
:placeholder="t('admin.accounts.oauth.authCodePlaceholder')"
></textarea>
<p class="mt-2 text-xs text-gray-500 dark:text-gray-400">
<svg class="w-3 h-3 inline mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
<path stroke-linecap="round" stroke-linejoin="round" d="M11.25 11.25l.041-.02a.75.75 0 011.063.852l-.708 2.836a.75.75 0 001.063.853l.041-.021M21 12a9 9 0 11-18 0 9 9 0 0118 0zm-9-3.75h.008v.008H12V8.25z" />
</svg>
{{ t('admin.accounts.oauth.authCodeHint') }}
</p>
</div>
<!-- Error Message -->
<div
v-if="error"
class="mt-3 rounded-lg border border-red-200 bg-red-50 dark:border-red-700 dark:bg-red-900/30 p-3"
>
<p class="text-sm text-red-600 dark:text-red-400 whitespace-pre-line">
{{ error }}
</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useClipboard } from '@/composables/useClipboard'
import type { AddMethod, AuthInputMethod } from '@/composables/useAccountOAuth'
interface Props {
addMethod: AddMethod
authUrl?: string
sessionId?: string
loading?: boolean
error?: string
showHelp?: boolean
showProxyWarning?: boolean
allowMultiple?: boolean
methodLabel?: string
}
const props = withDefaults(defineProps<Props>(), {
authUrl: '',
sessionId: '',
loading: false,
error: '',
showHelp: true,
showProxyWarning: true,
allowMultiple: false,
methodLabel: 'Authorization Method'
})
const emit = defineEmits<{
'generate-url': []
'exchange-code': [code: string]
'cookie-auth': [sessionKey: string]
'update:inputMethod': [method: AuthInputMethod]
}>()
const { t } = useI18n()
// Local state
const inputMethod = ref<AuthInputMethod>('manual')
const authCodeInput = ref('')
const sessionKeyInput = ref('')
const showHelpDialog = ref(false)
// Clipboard
const { copied, copyToClipboard } = useClipboard()
// Computed
const parsedKeyCount = computed(() => {
return sessionKeyInput.value.split('\n').map(k => k.trim()).filter(k => k).length
})
// Watchers
watch(inputMethod, (newVal) => {
emit('update:inputMethod', newVal)
})
// Methods
const handleGenerateUrl = () => {
emit('generate-url')
}
const handleCopyUrl = () => {
if (props.authUrl) {
copyToClipboard(props.authUrl, 'URL copied to clipboard')
}
}
const handleRegenerate = () => {
authCodeInput.value = ''
emit('generate-url')
}
const handleCookieAuth = () => {
if (sessionKeyInput.value.trim()) {
emit('cookie-auth', sessionKeyInput.value)
}
}
// Expose methods and state
defineExpose({
authCode: authCodeInput,
sessionKey: sessionKeyInput,
inputMethod,
reset: () => {
authCodeInput.value = ''
sessionKeyInput.value = ''
inputMethod.value = 'manual'
showHelpDialog.value = false
}
})
</script>

View File

@@ -0,0 +1,240 @@
<template>
<Modal
:show="show"
:title="t('admin.accounts.reAuthorizeAccount')"
size="lg"
@close="handleClose"
>
<div v-if="account" class="space-y-5">
<!-- Account Info -->
<div class="rounded-lg border border-gray-200 dark:border-dark-600 bg-gray-50 dark:bg-dark-700 p-4">
<div class="flex items-center gap-3">
<div class="flex h-10 w-10 items-center justify-center rounded-lg bg-gradient-to-br from-orange-500 to-orange-600">
<svg class="w-5 h-5 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
<path stroke-linecap="round" stroke-linejoin="round" d="M9.813 15.904L9 18.75l-.813-2.846a4.5 4.5 0 00-3.09-3.09L2.25 12l2.846-.813a4.5 4.5 0 003.09-3.09L9 5.25l.813 2.846a4.5 4.5 0 003.09 3.09L15.75 12l-2.846.813a4.5 4.5 0 00-3.09 3.09z" />
</svg>
</div>
<div>
<span class="block font-semibold text-gray-900 dark:text-white">{{ account.name }}</span>
<span class="text-sm text-gray-500 dark:text-gray-400">{{ t('admin.accounts.claudeCodeAccount') }}</span>
</div>
</div>
</div>
<!-- Add Method Selection -->
<div>
<label class="input-label">{{ t('admin.accounts.oauth.authMethod') }}</label>
<div class="flex gap-4 mt-2">
<label class="flex cursor-pointer items-center">
<input
v-model="addMethod"
type="radio"
value="oauth"
class="mr-2 text-primary-600 focus:ring-primary-500"
/>
<span class="text-sm text-gray-700 dark:text-gray-300">Oauth</span>
</label>
<label class="flex cursor-pointer items-center">
<input
v-model="addMethod"
type="radio"
value="setup-token"
class="mr-2 text-primary-600 focus:ring-primary-500"
/>
<span class="text-sm text-gray-700 dark:text-gray-300">{{ t('admin.accounts.setupTokenLongLived') }}</span>
</label>
</div>
</div>
<!-- OAuth Authorization Section -->
<OAuthAuthorizationFlow
ref="oauthFlowRef"
:add-method="addMethod"
:auth-url="oauth.authUrl.value"
:session-id="oauth.sessionId.value"
:loading="oauth.loading.value"
:error="oauth.error.value"
:show-help="false"
:show-proxy-warning="false"
:allow-multiple="false"
:method-label="t('admin.accounts.inputMethod')"
@generate-url="handleGenerateUrl"
@cookie-auth="handleCookieAuth"
/>
<div class="flex justify-between gap-3 pt-4">
<button
type="button"
class="btn btn-secondary"
@click="handleClose"
>
{{ t('common.cancel') }}
</button>
<button
v-if="oauthFlowRef?.inputMethod?.value === 'manual'"
type="button"
:disabled="!canExchangeCode"
class="btn btn-primary"
@click="handleExchangeCode"
>
<svg
v-if="oauth.loading.value"
class="animate-spin -ml-1 mr-2 h-4 w-4"
fill="none"
viewBox="0 0 24 24"
>
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
{{ oauth.loading.value ? t('admin.accounts.oauth.verifying') : t('admin.accounts.oauth.completeAuth') }}
</button>
</div>
</div>
</Modal>
</template>
<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useAppStore } from '@/stores/app'
import { adminAPI } from '@/api/admin'
import { useAccountOAuth, type AddMethod } from '@/composables/useAccountOAuth'
import type { Account } from '@/types'
import Modal from '@/components/common/Modal.vue'
import OAuthAuthorizationFlow from './OAuthAuthorizationFlow.vue'
interface Props {
show: boolean
account: Account | null
}
const props = defineProps<Props>()
const emit = defineEmits<{
close: []
reauthorized: []
}>()
const appStore = useAppStore()
const { t } = useI18n()
// OAuth composable
const oauth = useAccountOAuth()
// Refs
const oauthFlowRef = ref<InstanceType<typeof OAuthAuthorizationFlow> | null>(null)
// State
const addMethod = ref<AddMethod>('oauth')
// Computed
const canExchangeCode = computed(() => {
const authCode = oauthFlowRef.value?.authCode?.value || ''
return authCode.trim() && oauth.sessionId.value && !oauth.loading.value
})
// Watchers
watch(() => props.show, (newVal) => {
if (newVal && props.account) {
// Initialize addMethod based on current account type
if (props.account.type === 'oauth' || props.account.type === 'setup-token') {
addMethod.value = props.account.type as AddMethod
}
} else {
resetState()
}
})
// Methods
const resetState = () => {
addMethod.value = 'oauth'
oauth.resetState()
oauthFlowRef.value?.reset()
}
const handleClose = () => {
emit('close')
}
const handleGenerateUrl = async () => {
if (!props.account) return
await oauth.generateAuthUrl(addMethod.value, props.account.proxy_id)
}
const handleExchangeCode = async () => {
if (!props.account) return
const authCode = oauthFlowRef.value?.authCode?.value || ''
if (!authCode.trim() || !oauth.sessionId.value) return
oauth.loading.value = true
oauth.error.value = ''
try {
const proxyConfig = props.account.proxy_id ? { proxy_id: props.account.proxy_id } : {}
const endpoint = addMethod.value === 'oauth'
? '/admin/accounts/exchange-code'
: '/admin/accounts/exchange-setup-token-code'
const tokenInfo = await adminAPI.accounts.exchangeCode(endpoint, {
session_id: oauth.sessionId.value,
code: authCode.trim(),
...proxyConfig
})
const extra = oauth.buildExtraInfo(tokenInfo)
// Update account with new credentials and type
await adminAPI.accounts.update(props.account.id, {
type: addMethod.value, // Update type based on selected method
credentials: tokenInfo,
extra
})
appStore.showSuccess(t('admin.accounts.reAuthorizedSuccess'))
emit('reauthorized')
handleClose()
} catch (error: any) {
oauth.error.value = error.response?.data?.detail || t('admin.accounts.oauth.authFailed')
appStore.showError(oauth.error.value)
} finally {
oauth.loading.value = false
}
}
const handleCookieAuth = async (sessionKey: string) => {
if (!props.account) return
oauth.loading.value = true
oauth.error.value = ''
try {
const proxyConfig = props.account.proxy_id ? { proxy_id: props.account.proxy_id } : {}
const endpoint = addMethod.value === 'oauth'
? '/admin/accounts/cookie-auth'
: '/admin/accounts/setup-token-cookie-auth'
const tokenInfo = await adminAPI.accounts.exchangeCode(endpoint, {
session_id: '',
code: sessionKey.trim(),
...proxyConfig
})
const extra = oauth.buildExtraInfo(tokenInfo)
// Update account with new credentials and type
await adminAPI.accounts.update(props.account.id, {
type: addMethod.value, // Update type based on selected method
credentials: tokenInfo,
extra
})
appStore.showSuccess(t('admin.accounts.reAuthorizedSuccess'))
emit('reauthorized')
handleClose()
} catch (error: any) {
oauth.error.value = error.response?.data?.detail || t('admin.accounts.oauth.cookieAuthFailed')
} finally {
oauth.loading.value = false
}
}
</script>

View File

@@ -0,0 +1,200 @@
<template>
<div class="space-y-1">
<!-- 5h Time Window Progress -->
<div v-if="hasWindowInfo" class="flex items-center gap-1">
<!-- Label badge -->
<span class="text-[10px] font-medium px-1 rounded w-[32px] text-center shrink-0 bg-indigo-100 text-indigo-700 dark:bg-indigo-900/40 dark:text-indigo-300">
5h
</span>
<!-- Progress bar container -->
<div class="w-8 h-1.5 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden shrink-0">
<div
:class="['h-full transition-all duration-300', barColorClass]"
:style="{ width: progressWidth }"
></div>
</div>
<!-- Percentage -->
<span :class="['text-[10px] font-medium w-[32px] text-right shrink-0', textColorClass]">
{{ displayPercent }}
</span>
<!-- Reset time -->
<span class="text-[10px] text-gray-400 shrink-0">
{{ formatResetTime }}
</span>
</div>
<!-- No recent activity (had activity but window expired > 1 hour) -->
<div v-else-if="hasExpiredWindow" class="flex items-center gap-1">
<span class="text-[10px] font-medium px-1 rounded w-[32px] text-center shrink-0 bg-indigo-100 text-indigo-700 dark:bg-indigo-900/40 dark:text-indigo-300">
5h
</span>
<span class="text-[10px] text-gray-400 italic">
No recent activity
</span>
</div>
<!-- No window info yet (never had activity) -->
<div v-else class="flex items-center gap-1">
<span class="text-[10px] font-medium px-1 rounded w-[32px] text-center shrink-0 bg-indigo-100 text-indigo-700 dark:bg-indigo-900/40 dark:text-indigo-300">
5h
</span>
<span class="text-[10px] text-gray-400 italic">
No activity yet
</span>
</div>
<!-- Hint -->
<div class="text-[10px] text-gray-400 italic">
Setup Token (time-based)
</div>
</div>
</template>
<script setup lang="ts">
import { computed, ref, onMounted, onUnmounted } from 'vue'
import type { Account } from '@/types'
const props = defineProps<{
account: Account
}>()
// Update timer
const currentTime = ref(new Date())
let timer: ReturnType<typeof setInterval> | null = null
onMounted(() => {
// Update every second for more accurate countdown
timer = setInterval(() => {
currentTime.value = new Date()
}, 1000)
})
onUnmounted(() => {
if (timer) {
clearInterval(timer)
}
})
// Check if we have window information but it's been expired for more than 1 hour
const hasExpiredWindow = computed(() => {
if (!props.account.session_window_start || !props.account.session_window_end) {
return false
}
const end = new Date(props.account.session_window_end).getTime()
const now = currentTime.value.getTime()
const expiredMs = now - end
// Window exists and expired more than 1 hour ago
return expiredMs > 1000 * 60 * 60
})
// Check if we have valid window information (not expired for more than 1 hour)
const hasWindowInfo = computed(() => {
if (!props.account.session_window_start || !props.account.session_window_end) {
return false
}
// If window is expired more than 1 hour, don't show progress bar
if (hasExpiredWindow.value) {
return false
}
return true
})
// Calculate time-based progress (0-100)
const timeProgress = computed(() => {
if (!props.account.session_window_start || !props.account.session_window_end) {
return 0
}
const start = new Date(props.account.session_window_start).getTime()
const end = new Date(props.account.session_window_end).getTime()
const now = currentTime.value.getTime()
// Window hasn't started yet
if (now < start) {
return 0
}
// Window has ended
if (now >= end) {
return 100
}
// Calculate progress within window
const total = end - start
const elapsed = now - start
return Math.round((elapsed / total) * 100)
})
// Progress bar width
const progressWidth = computed(() => {
return `${Math.min(timeProgress.value, 100)}%`
})
// Display percentage
const displayPercent = computed(() => {
return `${timeProgress.value}%`
})
// Progress bar color based on progress
const barColorClass = computed(() => {
if (timeProgress.value >= 100) {
return 'bg-red-500'
} else if (timeProgress.value >= 80) {
return 'bg-amber-500'
} else {
return 'bg-green-500'
}
})
// Text color based on progress
const textColorClass = computed(() => {
if (timeProgress.value >= 100) {
return 'text-red-600 dark:text-red-400'
} else if (timeProgress.value >= 80) {
return 'text-amber-600 dark:text-amber-400'
} else {
return 'text-gray-600 dark:text-gray-400'
}
})
// Format reset time (time remaining until window end)
const formatResetTime = computed(() => {
if (!props.account.session_window_end) {
return 'N/A'
}
const end = new Date(props.account.session_window_end)
const now = currentTime.value
const diffMs = end.getTime() - now.getTime()
if (diffMs <= 0) {
// 窗口已过期,计算过期了多久
const expiredMs = Math.abs(diffMs)
const expiredHours = Math.floor(expiredMs / (1000 * 60 * 60))
if (expiredHours >= 1) {
return 'No recent activity'
}
return 'Window expired'
}
const diffHours = Math.floor(diffMs / (1000 * 60 * 60))
const diffMins = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60))
const diffSecs = Math.floor((diffMs % (1000 * 60)) / 1000)
if (diffHours > 0) {
return `${diffHours}h ${diffMins}m`
} else if (diffMins > 0) {
return `${diffMins}m ${diffSecs}s`
} else {
return `${diffSecs}s`
}
})
</script>

View File

@@ -0,0 +1,129 @@
<template>
<div class="flex items-center gap-1">
<!-- Label badge (fixed width for alignment) -->
<span
:class="[
'text-[10px] font-medium px-1 rounded w-[32px] text-center shrink-0',
labelClass
]"
>
{{ label }}
</span>
<!-- Progress bar container -->
<div class="w-8 h-1.5 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden shrink-0">
<div
:class="['h-full transition-all duration-300', barClass]"
:style="{ width: barWidth }"
></div>
</div>
<!-- Percentage -->
<span :class="['text-[10px] font-medium w-[32px] text-right shrink-0', textClass]">
{{ displayPercent }}
</span>
<!-- Reset time -->
<span v-if="resetsAt" class="text-[10px] text-gray-400 shrink-0">
{{ formatResetTime }}
</span>
<!-- Window stats (only for 5h window) -->
<span v-if="windowStats" class="text-[10px] text-gray-400 shrink-0 ml-1">
({{ formatStats }})
</span>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import type { WindowStats } from '@/types'
const props = defineProps<{
label: string
utilization: number // Percentage (0-100+)
resetsAt?: string | null
color: 'indigo' | 'emerald' | 'purple'
windowStats?: WindowStats | null
}>()
// Label background colors
const labelClass = computed(() => {
const colors = {
indigo: 'bg-indigo-100 text-indigo-700 dark:bg-indigo-900/40 dark:text-indigo-300',
emerald: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300',
purple: 'bg-purple-100 text-purple-700 dark:bg-purple-900/40 dark:text-purple-300'
}
return colors[props.color]
})
// Progress bar color based on utilization
const barClass = computed(() => {
if (props.utilization >= 100) {
return 'bg-red-500'
} else if (props.utilization >= 80) {
return 'bg-amber-500'
} else {
return 'bg-green-500'
}
})
// Text color based on utilization
const textClass = computed(() => {
if (props.utilization >= 100) {
return 'text-red-600 dark:text-red-400'
} else if (props.utilization >= 80) {
return 'text-amber-600 dark:text-amber-400'
} else {
return 'text-gray-600 dark:text-gray-400'
}
})
// Bar width (capped at 100%)
const barWidth = computed(() => {
return `${Math.min(props.utilization, 100)}%`
})
// Display percentage (cap at 999% for readability)
const displayPercent = computed(() => {
const percent = Math.round(props.utilization)
return percent > 999 ? '>999%' : `${percent}%`
})
// Format reset time
const formatResetTime = computed(() => {
if (!props.resetsAt) return 'N/A'
const date = new Date(props.resetsAt)
const now = new Date()
const diffMs = date.getTime() - now.getTime()
if (diffMs <= 0) return 'Now'
const diffHours = Math.floor(diffMs / (1000 * 60 * 60))
const diffMins = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60))
if (diffHours >= 24) {
const days = Math.floor(diffHours / 24)
return `${days}d ${diffHours % 24}h`
} else if (diffHours > 0) {
return `${diffHours}h ${diffMins}m`
} else {
return `${diffMins}m`
}
})
// Format window stats
const formatStats = computed(() => {
if (!props.windowStats) return ''
const { requests, tokens, cost } = props.windowStats
// Format tokens (e.g., 1234567 -> 1.2M)
const formatTokens = (t: number): string => {
if (t >= 1000000) return `${(t / 1000000).toFixed(1)}M`
if (t >= 1000) return `${(t / 1000).toFixed(1)}K`
return t.toString()
}
return `${requests}req ${formatTokens(tokens)}tok $${cost.toFixed(2)}`
})
</script>

View File

@@ -0,0 +1,7 @@
export { default as CreateAccountModal } from './CreateAccountModal.vue'
export { default as EditAccountModal } from './EditAccountModal.vue'
export { default as ReAuthAccountModal } from './ReAuthAccountModal.vue'
export { default as OAuthAuthorizationFlow } from './OAuthAuthorizationFlow.vue'
export { default as AccountStatusIndicator } from './AccountStatusIndicator.vue'
export { default as AccountUsageCell } from './AccountUsageCell.vue'
export { default as UsageProgressBar } from './UsageProgressBar.vue'

View File

@@ -0,0 +1,65 @@
<template>
<Modal :show="show" :title="title" size="sm" @close="handleCancel">
<div class="space-y-4">
<p class="text-sm text-gray-600 dark:text-gray-400">{{ message }}</p>
</div>
<template #footer>
<div class="flex justify-end space-x-3">
<button
@click="handleCancel"
type="button"
class="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-200 bg-white dark:bg-dark-700 border border-gray-300 dark:border-dark-600 rounded-md hover:bg-gray-50 dark:hover:bg-dark-600 focus:outline-none focus:ring-2 focus:ring-offset-2 dark:focus:ring-offset-dark-800 focus:ring-primary-500"
>
{{ cancelText }}
</button>
<button
@click="handleConfirm"
type="button"
:class="[
'px-4 py-2 text-sm font-medium text-white rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 dark:focus:ring-offset-dark-800',
danger
? 'bg-red-600 hover:bg-red-700 focus:ring-red-500'
: 'bg-primary-600 hover:bg-primary-700 focus:ring-primary-500'
]"
>
{{ confirmText }}
</button>
</div>
</template>
</Modal>
</template>
<script setup lang="ts">
import Modal from './Modal.vue'
interface Props {
show: boolean
title: string
message: string
confirmText?: string
cancelText?: string
danger?: boolean
}
interface Emits {
(e: 'confirm'): void
(e: 'cancel'): void
}
const props = withDefaults(defineProps<Props>(), {
confirmText: 'Confirm',
cancelText: 'Cancel',
danger: false
})
const emit = defineEmits<Emits>()
const handleConfirm = () => {
emit('confirm')
}
const handleCancel = () => {
emit('cancel')
}
</script>

View File

@@ -0,0 +1,134 @@
<template>
<div class="overflow-x-auto">
<table class="min-w-full divide-y divide-gray-200 dark:divide-dark-700">
<thead class="bg-gray-50 dark:bg-dark-800">
<tr>
<th
v-for="column in columns"
:key="column.key"
scope="col"
class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-dark-400 uppercase tracking-wider"
:class="{ 'cursor-pointer hover:bg-gray-100 dark:hover:bg-dark-700': column.sortable }"
@click="column.sortable && handleSort(column.key)"
>
<div class="flex items-center space-x-1">
<span>{{ column.label }}</span>
<span v-if="column.sortable" class="text-gray-400 dark:text-dark-500">
<svg
v-if="sortKey === column.key"
class="w-4 h-4"
:class="{ 'transform rotate-180': sortOrder === 'desc' }"
fill="currentColor"
viewBox="0 0 20 20"
>
<path
fill-rule="evenodd"
d="M14.707 12.707a1 1 0 01-1.414 0L10 9.414l-3.293 3.293a1 1 0 01-1.414-1.414l4-4a1 1 0 011.414 0l4 4a1 1 0 010 1.414z"
clip-rule="evenodd"
/>
</svg>
<svg v-else class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
<path
d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z"
/>
</svg>
</span>
</div>
</th>
</tr>
</thead>
<tbody class="bg-white dark:bg-dark-900 divide-y divide-gray-200 dark:divide-dark-700">
<!-- Loading skeleton -->
<tr v-if="loading" v-for="i in 5" :key="i">
<td v-for="column in columns" :key="column.key" class="px-6 py-4 whitespace-nowrap">
<div class="animate-pulse">
<div class="h-4 bg-gray-200 dark:bg-dark-700 rounded w-3/4"></div>
</div>
</td>
</tr>
<!-- Empty state -->
<tr v-else-if="!data || data.length === 0">
<td :colspan="columns.length" class="px-6 py-12 text-center text-gray-500 dark:text-dark-400">
<slot name="empty">
<div class="flex flex-col items-center">
<svg class="w-12 h-12 text-gray-400 dark:text-dark-500 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4"
/>
</svg>
<p class="text-lg font-medium text-gray-900 dark:text-gray-100">{{ t('empty.noData') }}</p>
</div>
</slot>
</td>
</tr>
<!-- Data rows -->
<tr v-else v-for="(row, index) in sortedData" :key="index" class="hover:bg-gray-50 dark:hover:bg-dark-800">
<td
v-for="column in columns"
:key="column.key"
class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100"
>
<slot :name="`cell-${column.key}`" :row="row" :value="row[column.key]">
{{ column.formatter ? column.formatter(row[column.key], row) : row[column.key] }}
</slot>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script setup lang="ts">
import { computed, ref } from 'vue'
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
export interface Column {
key: string
label: string
sortable?: boolean
formatter?: (value: any, row: any) => string
}
interface Props {
columns: Column[]
data: any[]
loading?: boolean
}
const props = withDefaults(defineProps<Props>(), {
loading: false
})
const sortKey = ref<string>('')
const sortOrder = ref<'asc' | 'desc'>('asc')
const handleSort = (key: string) => {
if (sortKey.value === key) {
sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc'
} else {
sortKey.value = key
sortOrder.value = 'asc'
}
}
const sortedData = computed(() => {
if (!sortKey.value || !props.data) return props.data
return [...props.data].sort((a, b) => {
const aVal = a[sortKey.value]
const bVal = b[sortKey.value]
if (aVal === bVal) return 0
const comparison = aVal > bVal ? 1 : -1
return sortOrder.value === 'asc' ? comparison : -comparison
})
})
</script>

View File

@@ -0,0 +1,415 @@
<template>
<div class="relative" ref="containerRef">
<button
type="button"
@click="toggle"
:class="[
'date-picker-trigger',
isOpen && 'date-picker-trigger-open'
]"
>
<span class="date-picker-icon">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="1.5">
<path stroke-linecap="round" stroke-linejoin="round" d="M6.75 3v2.25M17.25 3v2.25M3 18.75V7.5a2.25 2.25 0 012.25-2.25h13.5A2.25 2.25 0 0121 7.5v11.25m-18 0A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75m-18 0v-7.5A2.25 2.25 0 015.25 9h13.5A2.25 2.25 0 0121 11.25v7.5" />
</svg>
</span>
<span class="date-picker-value">
{{ displayValue }}
</span>
<span class="date-picker-chevron">
<svg
:class="['w-4 h-4 transition-transform duration-200', isOpen && 'rotate-180']"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
stroke-width="1.5"
>
<path stroke-linecap="round" stroke-linejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" />
</svg>
</span>
</button>
<Transition name="date-picker-dropdown">
<div
v-if="isOpen"
class="date-picker-dropdown"
>
<!-- Quick presets -->
<div class="date-picker-presets">
<button
v-for="preset in presets"
:key="preset.value"
@click="selectPreset(preset)"
:class="[
'date-picker-preset',
isPresetActive(preset) && 'date-picker-preset-active'
]"
>
{{ t(preset.labelKey) }}
</button>
</div>
<div class="date-picker-divider"></div>
<!-- Custom date range inputs -->
<div class="date-picker-custom">
<div class="date-picker-field">
<label class="date-picker-label">{{ t('dates.startDate') }}</label>
<input
type="date"
v-model="localStartDate"
:max="localEndDate || today"
class="date-picker-input"
@change="onDateChange"
/>
</div>
<div class="date-picker-separator">
<svg class="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="1.5">
<path stroke-linecap="round" stroke-linejoin="round" d="M17.25 8.25L21 12m0 0l-3.75 3.75M21 12H3" />
</svg>
</div>
<div class="date-picker-field">
<label class="date-picker-label">{{ t('dates.endDate') }}</label>
<input
type="date"
v-model="localEndDate"
:min="localStartDate"
:max="today"
class="date-picker-input"
@change="onDateChange"
/>
</div>
</div>
<!-- Apply button -->
<div class="date-picker-actions">
<button
@click="apply"
class="date-picker-apply"
>
{{ t('dates.apply') }}
</button>
</div>
</div>
</Transition>
</div>
</template>
<script setup lang="ts">
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import { useI18n } from 'vue-i18n'
interface DatePreset {
labelKey: string
value: string
getRange: () => { start: string; end: string }
}
interface Props {
startDate: string
endDate: string
}
interface Emits {
(e: 'update:startDate', value: string): void
(e: 'update:endDate', value: string): void
(e: 'change', range: { startDate: string; endDate: string; preset: string | null }): void
}
const props = defineProps<Props>()
const emit = defineEmits<Emits>()
const { t, locale } = useI18n()
const isOpen = ref(false)
const containerRef = ref<HTMLElement | null>(null)
const localStartDate = ref(props.startDate)
const localEndDate = ref(props.endDate)
const activePreset = ref<string | null>('7days')
const today = computed(() => new Date().toISOString().split('T')[0])
const presets: DatePreset[] = [
{
labelKey: 'dates.today',
value: 'today',
getRange: () => {
const t = today.value
return { start: t, end: t }
}
},
{
labelKey: 'dates.yesterday',
value: 'yesterday',
getRange: () => {
const d = new Date()
d.setDate(d.getDate() - 1)
const yesterday = d.toISOString().split('T')[0]
return { start: yesterday, end: yesterday }
}
},
{
labelKey: 'dates.last7Days',
value: '7days',
getRange: () => {
const end = today.value
const d = new Date()
d.setDate(d.getDate() - 6)
const start = d.toISOString().split('T')[0]
return { start, end }
}
},
{
labelKey: 'dates.last14Days',
value: '14days',
getRange: () => {
const end = today.value
const d = new Date()
d.setDate(d.getDate() - 13)
const start = d.toISOString().split('T')[0]
return { start, end }
}
},
{
labelKey: 'dates.last30Days',
value: '30days',
getRange: () => {
const end = today.value
const d = new Date()
d.setDate(d.getDate() - 29)
const start = d.toISOString().split('T')[0]
return { start, end }
}
},
{
labelKey: 'dates.thisMonth',
value: 'thisMonth',
getRange: () => {
const now = new Date()
const start = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]
return { start, end: today.value }
}
},
{
labelKey: 'dates.lastMonth',
value: 'lastMonth',
getRange: () => {
const now = new Date()
const start = new Date(now.getFullYear(), now.getMonth() - 1, 1).toISOString().split('T')[0]
const end = new Date(now.getFullYear(), now.getMonth(), 0).toISOString().split('T')[0]
return { start, end }
}
}
]
const displayValue = computed(() => {
if (activePreset.value) {
const preset = presets.find(p => p.value === activePreset.value)
if (preset) return t(preset.labelKey)
}
if (localStartDate.value && localEndDate.value) {
if (localStartDate.value === localEndDate.value) {
return formatDate(localStartDate.value)
}
return `${formatDate(localStartDate.value)} - ${formatDate(localEndDate.value)}`
}
return t('dates.selectDateRange')
})
const formatDate = (dateStr: string): string => {
const date = new Date(dateStr + 'T00:00:00')
const dateLocale = locale.value === 'zh' ? 'zh-CN' : 'en-US'
return date.toLocaleDateString(dateLocale, { month: 'short', day: 'numeric' })
}
const isPresetActive = (preset: DatePreset): boolean => {
return activePreset.value === preset.value
}
const selectPreset = (preset: DatePreset) => {
const range = preset.getRange()
localStartDate.value = range.start
localEndDate.value = range.end
activePreset.value = preset.value
}
const onDateChange = () => {
// Check if current dates match any preset
activePreset.value = null
for (const preset of presets) {
const range = preset.getRange()
if (range.start === localStartDate.value && range.end === localEndDate.value) {
activePreset.value = preset.value
break
}
}
}
const toggle = () => {
isOpen.value = !isOpen.value
}
const apply = () => {
emit('update:startDate', localStartDate.value)
emit('update:endDate', localEndDate.value)
emit('change', {
startDate: localStartDate.value,
endDate: localEndDate.value,
preset: activePreset.value
})
isOpen.value = false
}
const handleClickOutside = (event: MouseEvent) => {
if (containerRef.value && !containerRef.value.contains(event.target as Node)) {
isOpen.value = false
}
}
const handleEscape = (event: KeyboardEvent) => {
if (event.key === 'Escape' && isOpen.value) {
isOpen.value = false
}
}
// Sync local state with props
watch(() => props.startDate, (val) => {
localStartDate.value = val
onDateChange()
})
watch(() => props.endDate, (val) => {
localEndDate.value = val
onDateChange()
})
onMounted(() => {
document.addEventListener('click', handleClickOutside)
document.addEventListener('keydown', handleEscape)
// Initialize active preset detection
onDateChange()
})
onUnmounted(() => {
document.removeEventListener('click', handleClickOutside)
document.removeEventListener('keydown', handleEscape)
})
</script>
<style scoped>
.date-picker-trigger {
@apply flex items-center gap-2;
@apply px-3 py-2 rounded-lg text-sm;
@apply bg-white dark:bg-dark-800;
@apply border border-gray-200 dark:border-dark-600;
@apply text-gray-700 dark:text-gray-300;
@apply transition-all duration-200;
@apply focus:outline-none focus:ring-2 focus:ring-primary-500/30 focus:border-primary-500;
@apply hover:border-gray-300 dark:hover:border-dark-500;
@apply cursor-pointer;
}
.date-picker-trigger-open {
@apply ring-2 ring-primary-500/30 border-primary-500;
}
.date-picker-icon {
@apply text-gray-400 dark:text-dark-400;
}
.date-picker-value {
@apply font-medium;
}
.date-picker-chevron {
@apply text-gray-400 dark:text-dark-400;
}
.date-picker-dropdown {
@apply absolute z-[100] mt-2 left-0;
@apply bg-white dark:bg-dark-800;
@apply rounded-xl;
@apply border border-gray-200 dark:border-dark-700;
@apply shadow-lg shadow-black/10 dark:shadow-black/30;
@apply overflow-hidden;
@apply min-w-[320px];
}
.date-picker-presets {
@apply grid grid-cols-2 gap-1 p-2;
}
.date-picker-preset {
@apply px-3 py-1.5 text-xs font-medium rounded-md;
@apply text-gray-600 dark:text-gray-400;
@apply hover:bg-gray-100 dark:hover:bg-dark-700;
@apply transition-colors duration-150;
}
.date-picker-preset-active {
@apply bg-primary-100 dark:bg-primary-900/30;
@apply text-primary-700 dark:text-primary-300;
}
.date-picker-divider {
@apply border-t border-gray-100 dark:border-dark-700;
}
.date-picker-custom {
@apply flex items-end gap-2 p-3;
}
.date-picker-field {
@apply flex-1;
}
.date-picker-label {
@apply block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1;
}
.date-picker-input {
@apply w-full px-2 py-1.5 text-sm rounded-md;
@apply bg-gray-50 dark:bg-dark-700;
@apply border border-gray-200 dark:border-dark-600;
@apply text-gray-900 dark:text-gray-100;
@apply focus:outline-none focus:ring-2 focus:ring-primary-500/30 focus:border-primary-500;
}
.date-picker-input::-webkit-calendar-picker-indicator {
@apply cursor-pointer opacity-60 hover:opacity-100;
filter: invert(0.5);
}
.dark .date-picker-input::-webkit-calendar-picker-indicator {
filter: invert(0.7);
}
.date-picker-separator {
@apply flex items-center justify-center pb-1;
}
.date-picker-actions {
@apply flex justify-end p-2 pt-0;
}
.date-picker-apply {
@apply px-4 py-1.5 text-sm font-medium rounded-lg;
@apply bg-primary-600 text-white;
@apply hover:bg-primary-700;
@apply transition-colors duration-150;
}
/* Dropdown animation */
.date-picker-dropdown-enter-active,
.date-picker-dropdown-leave-active {
transition: all 0.2s ease;
}
.date-picker-dropdown-enter-from,
.date-picker-dropdown-leave-to {
opacity: 0;
transform: translateY(-8px);
}
</style>

View File

@@ -0,0 +1,91 @@
<template>
<div class="empty-state">
<!-- Icon -->
<div class="w-20 h-20 mb-5 rounded-2xl bg-gray-100 dark:bg-dark-800 flex items-center justify-center">
<slot name="icon">
<component
v-if="icon"
:is="icon"
class="empty-state-icon w-10 h-10"
aria-hidden="true"
/>
<svg
v-else
class="empty-state-icon w-10 h-10"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
stroke-width="1.5"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4"
/>
</svg>
</slot>
</div>
<!-- Title -->
<h3 class="empty-state-title">
{{ title }}
</h3>
<!-- Description -->
<p class="empty-state-description">
{{ description }}
</p>
<!-- Action -->
<div v-if="actionText || $slots.action" class="mt-6">
<slot name="action">
<component
:is="actionTo ? 'RouterLink' : 'button'"
v-if="actionText"
:to="actionTo"
@click="!actionTo && $emit('action')"
class="btn btn-primary"
>
<svg
v-if="actionIcon"
class="w-5 h-5 mr-2"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
stroke-width="1.5"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M12 4.5v15m7.5-7.5h-15"
/>
</svg>
{{ actionText }}
</component>
</slot>
</div>
</div>
</template>
<script setup lang="ts">
import type { Component } from 'vue'
import { RouterLink } from 'vue-router'
interface Props {
icon?: Component | string
title?: string
description?: string
actionText?: string
actionTo?: string | object
actionIcon?: boolean
message?: string
}
const props = withDefaults(defineProps<Props>(), {
title: 'No data found',
description: '',
actionIcon: true
})
defineEmits(['action'])
</script>

View File

@@ -0,0 +1,50 @@
<template>
<span
:class="[
'inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md text-xs font-medium transition-colors',
isSubscription
? 'bg-violet-100 text-violet-700 dark:bg-violet-900/30 dark:text-violet-400'
: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400'
]"
>
<!-- Subscription type icon (calendar) -->
<svg v-if="isSubscription" class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M6.75 3v2.25M17.25 3v2.25M3 18.75V7.5a2.25 2.25 0 012.25-2.25h13.5A2.25 2.25 0 0121 7.5v11.25m-18 0A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75m-18 0v-7.5A2.25 2.25 0 015.25 9h13.5A2.25 2.25 0 0121 11.25v7.5" />
</svg>
<!-- Standard type icon (wallet) -->
<svg v-else class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M21 12a2.25 2.25 0 00-2.25-2.25H15a3 3 0 11-6 0H5.25A2.25 2.25 0 003 12m18 0v6a2.25 2.25 0 01-2.25 2.25H5.25A2.25 2.25 0 013 18v-6m18 0V9M3 12V9m18 0a2.25 2.25 0 00-2.25-2.25H5.25A2.25 2.25 0 003 9m18 0V6a2.25 2.25 0 00-2.25-2.25H5.25A2.25 2.25 0 003 6v3" />
</svg>
<span class="truncate">{{ name }}</span>
<span
v-if="showRate && rateMultiplier !== undefined"
:class="[
'px-1 py-0.5 rounded text-[10px] font-semibold',
isSubscription
? 'bg-violet-200/60 text-violet-800 dark:bg-violet-800/40 dark:text-violet-300'
: 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400'
]"
>
{{ rateMultiplier }}x
</span>
</span>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import type { SubscriptionType } from '@/types'
interface Props {
name: string
subscriptionType?: SubscriptionType
rateMultiplier?: number
showRate?: boolean
}
const props = withDefaults(defineProps<Props>(), {
subscriptionType: 'standard',
showRate: true
})
const isSubscription = computed(() => props.subscriptionType === 'subscription')
</script>

View File

@@ -0,0 +1,61 @@
<template>
<div>
<label class="input-label">
Groups
<span class="text-gray-400 font-normal">({{ modelValue.length }} selected)</span>
</label>
<div
class="grid grid-cols-2 gap-1 max-h-32 overflow-y-auto p-2 border border-gray-200 dark:border-dark-600 rounded-lg bg-gray-50 dark:bg-dark-800"
>
<label
v-for="group in groups"
:key="group.id"
class="flex items-center gap-2 px-2 py-1.5 rounded hover:bg-white dark:hover:bg-dark-700 cursor-pointer transition-colors"
:title="`${group.rate_multiplier}x rate · ${group.account_count || 0} accounts`"
>
<input
type="checkbox"
:value="group.id"
:checked="modelValue.includes(group.id)"
@change="handleChange(group.id, ($event.target as HTMLInputElement).checked)"
class="w-3.5 h-3.5 text-primary-500 border-gray-300 dark:border-dark-500 rounded focus:ring-primary-500 shrink-0"
/>
<GroupBadge
:name="group.name"
:subscription-type="group.subscription_type"
:rate-multiplier="group.rate_multiplier"
class="flex-1 min-w-0"
/>
<span class="text-xs text-gray-400 shrink-0">{{ group.account_count || 0 }}</span>
</label>
<div
v-if="groups.length === 0"
class="col-span-2 text-center text-sm text-gray-500 dark:text-gray-400 py-2"
>
No groups available
</div>
</div>
</div>
</template>
<script setup lang="ts">
import GroupBadge from './GroupBadge.vue'
import type { Group } from '@/types'
interface Props {
modelValue: number[]
groups: Group[]
}
const props = defineProps<Props>()
const emit = defineEmits<{
'update:modelValue': [value: number[]]
}>()
const handleChange = (groupId: number, checked: boolean) => {
const newValue = checked
? [...props.modelValue, groupId]
: props.modelValue.filter(id => id !== groupId)
emit('update:modelValue', newValue)
}
</script>

View File

@@ -0,0 +1,65 @@
<template>
<div
:class="['spinner', sizeClasses, colorClass]"
role="status"
:aria-label="t('common.loading')"
>
<span class="sr-only">{{ t('common.loading') }}</span>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
type SpinnerSize = 'sm' | 'md' | 'lg' | 'xl'
type SpinnerColor = 'primary' | 'secondary' | 'white' | 'gray'
interface Props {
size?: SpinnerSize
color?: SpinnerColor
}
const props = withDefaults(defineProps<Props>(), {
size: 'md',
color: 'primary'
})
const sizeClasses = computed(() => {
const sizes: Record<SpinnerSize, string> = {
sm: 'w-4 h-4 border-2',
md: 'w-8 h-8 border-2',
lg: 'w-12 h-12 border-[3px]',
xl: 'w-16 h-16 border-4'
}
return sizes[props.size]
})
const colorClass = computed(() => {
const colors: Record<SpinnerColor, string> = {
primary: 'text-primary-500',
secondary: 'text-gray-500 dark:text-dark-400',
white: 'text-white',
gray: 'text-gray-400 dark:text-dark-500'
}
return colors[props.color]
})
</script>
<style scoped>
.spinner {
@apply inline-block rounded-full border-solid border-current border-r-transparent;
animation: spin 0.75s linear infinite;
}
@keyframes spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
</style>

View File

@@ -0,0 +1,100 @@
<template>
<div class="relative" ref="dropdownRef">
<button
@click="toggleDropdown"
class="flex items-center gap-1.5 px-2 py-1.5 rounded-lg text-sm font-medium text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-dark-700 transition-colors"
:title="currentLocale?.name"
>
<span class="text-base">{{ currentLocale?.flag }}</span>
<span class="hidden sm:inline">{{ currentLocale?.code.toUpperCase() }}</span>
<svg
class="w-3.5 h-3.5 text-gray-400 transition-transform duration-200"
:class="{ 'rotate-180': isOpen }"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
stroke-width="2"
>
<path stroke-linecap="round" stroke-linejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" />
</svg>
</button>
<transition name="dropdown">
<div
v-if="isOpen"
class="absolute right-0 mt-1 w-32 rounded-lg bg-white dark:bg-dark-800 shadow-lg border border-gray-200 dark:border-dark-700 overflow-hidden z-50"
>
<button
v-for="locale in availableLocales"
:key="locale.code"
@click="selectLocale(locale.code)"
class="w-full flex items-center gap-2 px-3 py-2 text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-dark-700 transition-colors"
:class="{ 'bg-primary-50 dark:bg-primary-900/20 text-primary-600 dark:text-primary-400': locale.code === currentLocaleCode }"
>
<span class="text-base">{{ locale.flag }}</span>
<span>{{ locale.name }}</span>
<svg
v-if="locale.code === currentLocaleCode"
class="w-4 h-4 ml-auto text-primary-500"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
stroke-width="2"
>
<path stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5" />
</svg>
</button>
</div>
</transition>
</div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { useI18n } from 'vue-i18n'
import { setLocale, availableLocales } from '@/i18n'
const { locale } = useI18n()
const isOpen = ref(false)
const dropdownRef = ref<HTMLElement | null>(null)
const currentLocaleCode = computed(() => locale.value)
const currentLocale = computed(() => availableLocales.find(l => l.code === locale.value))
function toggleDropdown() {
isOpen.value = !isOpen.value
}
function selectLocale(code: string) {
setLocale(code)
isOpen.value = false
}
function handleClickOutside(event: MouseEvent) {
if (dropdownRef.value && !dropdownRef.value.contains(event.target as Node)) {
isOpen.value = false
}
}
onMounted(() => {
document.addEventListener('click', handleClickOutside)
})
onBeforeUnmount(() => {
document.removeEventListener('click', handleClickOutside)
})
</script>
<style scoped>
.dropdown-enter-active,
.dropdown-leave-active {
transition: all 0.15s ease;
}
.dropdown-enter-from,
.dropdown-leave-to {
opacity: 0;
transform: scale(0.95) translateY(-4px);
}
</style>

View File

@@ -0,0 +1,122 @@
<template>
<Teleport to="body">
<div
v-if="show"
class="modal-overlay"
aria-labelledby="modal-title"
role="dialog"
aria-modal="true"
@click.self="handleClose"
>
<!-- Modal panel -->
<div
:class="['modal-content', sizeClasses]"
@click.stop
>
<!-- Header -->
<div class="modal-header">
<h3
id="modal-title"
class="modal-title"
>
{{ title }}
</h3>
<button
@click="emit('close')"
class="p-2 -mr-2 rounded-xl text-gray-400 dark:text-dark-500 hover:text-gray-600 dark:hover:text-dark-300 hover:bg-gray-100 dark:hover:bg-dark-700 transition-colors"
aria-label="Close modal"
>
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="1.5">
<path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
<!-- Body -->
<div class="modal-body">
<slot></slot>
</div>
<!-- Footer -->
<div
v-if="$slots.footer"
class="modal-footer"
>
<slot name="footer"></slot>
</div>
</div>
</div>
</Teleport>
</template>
<script setup lang="ts">
import { computed, watch, onMounted, onUnmounted } from 'vue'
type ModalSize = 'sm' | 'md' | 'lg' | 'xl' | 'full'
interface Props {
show: boolean
title: string
size?: ModalSize
closeOnEscape?: boolean
closeOnClickOutside?: boolean
}
interface Emits {
(e: 'close'): void
}
const props = withDefaults(defineProps<Props>(), {
size: 'md',
closeOnEscape: true,
closeOnClickOutside: false
})
const emit = defineEmits<Emits>()
const sizeClasses = computed(() => {
const sizes: Record<ModalSize, string> = {
sm: 'max-w-sm',
md: 'max-w-md',
lg: 'max-w-lg',
xl: 'max-w-xl',
full: 'max-w-4xl'
}
return sizes[props.size]
})
const handleClose = () => {
if (props.closeOnClickOutside) {
emit('close')
}
}
const handleEscape = (event: KeyboardEvent) => {
if (props.show && props.closeOnEscape && event.key === 'Escape') {
emit('close')
}
}
// Prevent body scroll when modal is open
watch(
() => props.show,
(isOpen) => {
console.log('[Modal] show changed to:', isOpen)
if (isOpen) {
document.body.style.overflow = 'hidden'
} else {
document.body.style.overflow = ''
}
},
{ immediate: true }
)
onMounted(() => {
document.addEventListener('keydown', handleEscape)
})
onUnmounted(() => {
document.removeEventListener('keydown', handleEscape)
document.body.style.overflow = ''
})
</script>

View File

@@ -0,0 +1,214 @@
<template>
<div class="flex items-center justify-between px-4 py-3 bg-white dark:bg-dark-800 border-t border-gray-200 dark:border-dark-700 sm:px-6">
<div class="flex items-center justify-between flex-1 sm:hidden">
<!-- Mobile pagination -->
<button
@click="goToPage(page - 1)"
:disabled="page === 1"
class="relative inline-flex items-center px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-200 bg-white dark:bg-dark-700 border border-gray-300 dark:border-dark-600 rounded-md hover:bg-gray-50 dark:hover:bg-dark-600 disabled:opacity-50 disabled:cursor-not-allowed"
>
{{ t('pagination.previous') }}
</button>
<span class="text-sm text-gray-700 dark:text-gray-300">
{{ t('pagination.pageOf', { page, total: totalPages }) }}
</span>
<button
@click="goToPage(page + 1)"
:disabled="page === totalPages"
class="relative inline-flex items-center px-4 py-2 ml-3 text-sm font-medium text-gray-700 dark:text-gray-200 bg-white dark:bg-dark-700 border border-gray-300 dark:border-dark-600 rounded-md hover:bg-gray-50 dark:hover:bg-dark-600 disabled:opacity-50 disabled:cursor-not-allowed"
>
{{ t('pagination.next') }}
</button>
</div>
<div class="hidden sm:flex sm:flex-1 sm:items-center sm:justify-between">
<!-- Desktop pagination info -->
<div class="flex items-center space-x-4">
<p class="text-sm text-gray-700 dark:text-gray-300">
{{ t('pagination.showing') }}
<span class="font-medium">{{ fromItem }}</span>
{{ t('pagination.to') }}
<span class="font-medium">{{ toItem }}</span>
{{ t('pagination.of') }}
<span class="font-medium">{{ total }}</span>
{{ t('pagination.results') }}
</p>
<!-- Page size selector -->
<div class="flex items-center space-x-2">
<span class="text-sm text-gray-700 dark:text-gray-300">{{ t('pagination.perPage') }}:</span>
<div class="w-20 page-size-select">
<Select
:model-value="pageSize"
:options="pageSizeSelectOptions"
@update:model-value="handlePageSizeChange"
/>
</div>
</div>
</div>
<!-- Desktop pagination buttons -->
<nav
class="relative z-0 inline-flex -space-x-px rounded-md shadow-sm"
aria-label="Pagination"
>
<!-- Previous button -->
<button
@click="goToPage(page - 1)"
:disabled="page === 1"
class="relative inline-flex items-center px-2 py-2 text-sm font-medium text-gray-500 dark:text-gray-400 bg-white dark:bg-dark-700 border border-gray-300 dark:border-dark-600 rounded-l-md hover:bg-gray-50 dark:hover:bg-dark-600 disabled:opacity-50 disabled:cursor-not-allowed"
:aria-label="t('pagination.previous')"
>
<svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
<path
fill-rule="evenodd"
d="M12.707 5.293a1 1 0 010 1.414L9.414 10l3.293 3.293a1 1 0 01-1.414 1.414l-4-4a1 1 0 010-1.414l4-4a1 1 0 011.414 0z"
clip-rule="evenodd"
/>
</svg>
</button>
<!-- Page numbers -->
<button
v-for="pageNum in visiblePages"
:key="pageNum"
@click="typeof pageNum === 'number' && goToPage(pageNum)"
:disabled="typeof pageNum !== 'number'"
:class="[
'relative inline-flex items-center px-4 py-2 text-sm font-medium border',
pageNum === page
? 'z-10 bg-primary-50 dark:bg-primary-900/30 border-primary-500 text-primary-600 dark:text-primary-400'
: 'bg-white dark:bg-dark-700 border-gray-300 dark:border-dark-600 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-dark-600',
typeof pageNum !== 'number' && 'cursor-default'
]"
:aria-label="typeof pageNum === 'number' ? t('pagination.goToPage', { page: pageNum }) : undefined"
:aria-current="pageNum === page ? 'page' : undefined"
>
{{ pageNum }}
</button>
<!-- Next button -->
<button
@click="goToPage(page + 1)"
:disabled="page === totalPages"
class="relative inline-flex items-center px-2 py-2 text-sm font-medium text-gray-500 dark:text-gray-400 bg-white dark:bg-dark-700 border border-gray-300 dark:border-dark-600 rounded-r-md hover:bg-gray-50 dark:hover:bg-dark-600 disabled:opacity-50 disabled:cursor-not-allowed"
:aria-label="t('pagination.next')"
>
<svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
<path
fill-rule="evenodd"
d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z"
clip-rule="evenodd"
/>
</svg>
</button>
</nav>
</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import Select from './Select.vue'
const { t } = useI18n()
interface Props {
total: number
page: number
pageSize: number
pageSizeOptions?: number[]
}
interface Emits {
(e: 'update:page', page: number): void
(e: 'update:pageSize', pageSize: number): void
}
const props = withDefaults(defineProps<Props>(), {
pageSizeOptions: () => [10, 20, 50, 100]
})
const emit = defineEmits<Emits>()
const totalPages = computed(() => Math.ceil(props.total / props.pageSize))
const fromItem = computed(() => {
if (props.total === 0) return 0
return (props.page - 1) * props.pageSize + 1
})
const toItem = computed(() => {
const to = props.page * props.pageSize
return to > props.total ? props.total : to
})
const pageSizeSelectOptions = computed(() => {
return props.pageSizeOptions.map(size => ({
value: size,
label: String(size)
}))
})
const visiblePages = computed(() => {
const pages: (number | string)[] = []
const maxVisible = 7
const total = totalPages.value
if (total <= maxVisible) {
// Show all pages if total is small
for (let i = 1; i <= total; i++) {
pages.push(i)
}
} else {
// Always show first page
pages.push(1)
const start = Math.max(2, props.page - 2)
const end = Math.min(total - 1, props.page + 2)
// Add ellipsis before if needed
if (start > 2) {
pages.push('...')
}
// Add middle pages
for (let i = start; i <= end; i++) {
pages.push(i)
}
// Add ellipsis after if needed
if (end < total - 1) {
pages.push('...')
}
// Always show last page
pages.push(total)
}
return pages
})
const goToPage = (newPage: number) => {
if (newPage >= 1 && newPage <= totalPages.value && newPage !== props.page) {
emit('update:page', newPage)
}
}
const handlePageSizeChange = (value: string | number | null) => {
if (value === null) return
const newPageSize = typeof value === 'string' ? parseInt(value) : value
emit('update:pageSize', newPageSize)
// Reset to first page when page size changes
if (props.page !== 1) {
emit('update:page', 1)
}
}
</script>
<style scoped>
.page-size-select :deep(.select-trigger) {
@apply py-1.5 px-3 text-sm;
}
</style>

View File

@@ -0,0 +1,426 @@
<template>
<div class="relative" ref="containerRef">
<button
type="button"
@click="toggle"
:disabled="disabled"
:class="[
'select-trigger',
isOpen && 'select-trigger-open',
disabled && 'select-trigger-disabled'
]"
>
<span class="select-value">
{{ selectedLabel }}
</span>
<span class="select-icon">
<svg
:class="['w-5 h-5 transition-transform duration-200', isOpen && 'rotate-180']"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
stroke-width="1.5"
>
<path stroke-linecap="round" stroke-linejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" />
</svg>
</span>
</button>
<Transition name="select-dropdown">
<div
v-if="isOpen"
class="select-dropdown"
>
<!-- Search and Batch Test Header -->
<div class="select-header">
<div class="select-search">
<svg class="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="1.5">
<path stroke-linecap="round" stroke-linejoin="round" d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z" />
</svg>
<input
ref="searchInputRef"
v-model="searchQuery"
type="text"
:placeholder="t('admin.proxies.searchProxies')"
class="select-search-input"
@click.stop
/>
</div>
<button
v-if="proxies.length > 0"
type="button"
@click.stop="handleBatchTest"
:disabled="batchTesting"
class="batch-test-btn"
:title="t('admin.proxies.batchTest')"
>
<svg v-if="batchTesting" class="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
<svg v-else class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="1.5">
<path stroke-linecap="round" stroke-linejoin="round" d="M5.25 5.653c0-.856.917-1.398 1.667-.986l11.54 6.347a1.125 1.125 0 010 1.972l-11.54 6.347a1.125 1.125 0 01-1.667-.986V5.653z" />
</svg>
</button>
</div>
<!-- Options list -->
<div class="select-options">
<!-- No Proxy option -->
<div
@click="selectOption(null)"
:class="[
'select-option',
modelValue === null && 'select-option-selected'
]"
>
<span class="select-option-label">{{ t('admin.accounts.noProxy') }}</span>
<svg
v-if="modelValue === null"
class="w-4 h-4 text-primary-500"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
stroke-width="2"
>
<path stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5" />
</svg>
</div>
<!-- Proxy options -->
<div
v-for="proxy in filteredProxies"
:key="proxy.id"
@click="selectOption(proxy.id)"
:class="[
'select-option',
modelValue === proxy.id && 'select-option-selected'
]"
>
<div class="flex-1 min-w-0">
<div class="flex items-center gap-2">
<span class="truncate font-medium">{{ proxy.name }}</span>
<!-- Account count badge -->
<span
v-if="proxy.account_count !== undefined"
class="flex-shrink-0 inline-flex items-center px-1.5 py-0.5 rounded text-xs bg-gray-100 dark:bg-dark-600 text-gray-600 dark:text-gray-400"
>
{{ proxy.account_count }}
</span>
<!-- Test result badges -->
<template v-if="testResults[proxy.id]">
<span
v-if="testResults[proxy.id].success"
class="flex-shrink-0 inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs bg-emerald-100 dark:bg-emerald-900/30 text-emerald-700 dark:text-emerald-400"
>
<span v-if="testResults[proxy.id].country">{{ testResults[proxy.id].country }}</span>
<span v-if="testResults[proxy.id].latency_ms">{{ testResults[proxy.id].latency_ms }}ms</span>
</span>
<span
v-else
class="flex-shrink-0 inline-flex items-center px-1.5 py-0.5 rounded text-xs bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-400"
>
{{ t('admin.proxies.testFailed') }}
</span>
</template>
</div>
<div class="text-xs text-gray-500 dark:text-gray-400 truncate">
{{ proxy.protocol }}://{{ proxy.host }}:{{ proxy.port }}
</div>
</div>
<!-- Individual test button -->
<button
type="button"
@click.stop="handleTestProxy(proxy)"
:disabled="testingProxyIds.has(proxy.id)"
class="test-btn"
:title="t('admin.proxies.testConnection')"
>
<svg v-if="testingProxyIds.has(proxy.id)" class="w-3.5 h-3.5 animate-spin" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
<svg v-else class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="1.5">
<path stroke-linecap="round" stroke-linejoin="round" d="M5.25 5.653c0-.856.917-1.398 1.667-.986l11.54 6.347a1.125 1.125 0 010 1.972l-11.54 6.347a1.125 1.125 0 01-1.667-.986V5.653z" />
</svg>
</button>
<svg
v-if="modelValue === proxy.id"
class="w-4 h-4 text-primary-500 flex-shrink-0"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
stroke-width="2"
>
<path stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5" />
</svg>
</div>
<!-- Empty state -->
<div v-if="filteredProxies.length === 0 && searchQuery" class="select-empty">
{{ t('common.noOptionsFound') }}
</div>
</div>
</div>
</Transition>
</div>
</template>
<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { useI18n } from 'vue-i18n'
import { adminAPI } from '@/api/admin'
import type { Proxy } from '@/types'
const { t } = useI18n()
interface ProxyTestResult {
success: boolean
message: string
latency_ms?: number
ip_address?: string
city?: string
region?: string
country?: string
}
interface Props {
modelValue: number | null
proxies: Proxy[]
disabled?: boolean
}
const props = withDefaults(defineProps<Props>(), {
disabled: false,
})
const emit = defineEmits<{
'update:modelValue': [value: number | null]
}>()
const isOpen = ref(false)
const searchQuery = ref('')
const containerRef = ref<HTMLElement | null>(null)
const searchInputRef = ref<HTMLInputElement | null>(null)
// Test state
const testResults = reactive<Record<number, ProxyTestResult>>({})
const testingProxyIds = reactive(new Set<number>())
const batchTesting = ref(false)
const selectedProxy = computed(() => {
if (props.modelValue === null) return null
return props.proxies.find(p => p.id === props.modelValue) || null
})
const selectedLabel = computed(() => {
if (!selectedProxy.value) {
return t('admin.accounts.noProxy')
}
const proxy = selectedProxy.value
return `${proxy.name} (${proxy.protocol}://${proxy.host}:${proxy.port})`
})
const filteredProxies = computed(() => {
if (!searchQuery.value) {
return props.proxies
}
const query = searchQuery.value.toLowerCase()
return props.proxies.filter(proxy => {
const name = proxy.name.toLowerCase()
const host = proxy.host.toLowerCase()
return name.includes(query) || host.includes(query)
})
})
const toggle = () => {
if (props.disabled) return
isOpen.value = !isOpen.value
if (isOpen.value) {
nextTick(() => {
searchInputRef.value?.focus()
})
}
}
const selectOption = (value: number | null) => {
emit('update:modelValue', value)
isOpen.value = false
searchQuery.value = ''
}
const handleTestProxy = async (proxy: Proxy) => {
if (testingProxyIds.has(proxy.id)) return
testingProxyIds.add(proxy.id)
try {
const result = await adminAPI.proxies.testProxy(proxy.id)
testResults[proxy.id] = result
} catch (error: any) {
testResults[proxy.id] = {
success: false,
message: error.response?.data?.detail || 'Test failed'
}
} finally {
testingProxyIds.delete(proxy.id)
}
}
const handleBatchTest = async () => {
if (batchTesting.value || props.proxies.length === 0) return
batchTesting.value = true
// Test all proxies in parallel
const testPromises = props.proxies.map(async (proxy) => {
testingProxyIds.add(proxy.id)
try {
const result = await adminAPI.proxies.testProxy(proxy.id)
testResults[proxy.id] = result
} catch (error: any) {
testResults[proxy.id] = {
success: false,
message: error.response?.data?.detail || 'Test failed'
}
} finally {
testingProxyIds.delete(proxy.id)
}
})
await Promise.all(testPromises)
batchTesting.value = false
}
const handleClickOutside = (event: MouseEvent) => {
if (containerRef.value && !containerRef.value.contains(event.target as Node)) {
isOpen.value = false
searchQuery.value = ''
}
}
const handleEscape = (event: KeyboardEvent) => {
if (event.key === 'Escape' && isOpen.value) {
isOpen.value = false
searchQuery.value = ''
}
}
onMounted(() => {
document.addEventListener('click', handleClickOutside)
document.addEventListener('keydown', handleEscape)
})
onUnmounted(() => {
document.removeEventListener('click', handleClickOutside)
document.removeEventListener('keydown', handleEscape)
})
</script>
<style scoped>
.select-trigger {
@apply w-full flex items-center justify-between gap-2;
@apply px-4 py-2.5 rounded-xl text-sm;
@apply bg-white dark:bg-dark-800;
@apply border border-gray-200 dark:border-dark-600;
@apply text-gray-900 dark:text-gray-100;
@apply transition-all duration-200;
@apply focus:outline-none focus:ring-2 focus:ring-primary-500/30 focus:border-primary-500;
@apply hover:border-gray-300 dark:hover:border-dark-500;
@apply cursor-pointer;
}
.select-trigger-open {
@apply ring-2 ring-primary-500/30 border-primary-500;
}
.select-trigger-disabled {
@apply bg-gray-100 dark:bg-dark-900 cursor-not-allowed opacity-60;
}
.select-value {
@apply flex-1 text-left truncate;
}
.select-icon {
@apply flex-shrink-0 text-gray-400 dark:text-dark-400;
}
.select-dropdown {
@apply absolute z-[100] w-full mt-2;
@apply bg-white dark:bg-dark-800;
@apply rounded-xl;
@apply border border-gray-200 dark:border-dark-700;
@apply shadow-lg shadow-black/10 dark:shadow-black/30;
@apply overflow-hidden;
}
.select-header {
@apply flex items-center gap-2 px-3 py-2;
@apply border-b border-gray-100 dark:border-dark-700;
}
.select-search {
@apply flex-1 flex items-center gap-2;
}
.select-search-input {
@apply flex-1 bg-transparent text-sm;
@apply text-gray-900 dark:text-gray-100;
@apply placeholder:text-gray-400 dark:placeholder:text-dark-400;
@apply focus:outline-none;
}
.batch-test-btn {
@apply flex-shrink-0 p-1.5 rounded-lg;
@apply text-gray-500 hover:text-emerald-600 dark:hover:text-emerald-400;
@apply hover:bg-emerald-50 dark:hover:bg-emerald-900/20;
@apply transition-colors disabled:opacity-50 disabled:cursor-not-allowed;
}
.select-options {
@apply max-h-60 overflow-y-auto py-1;
}
.select-option {
@apply flex items-center justify-between gap-2;
@apply px-4 py-2.5 text-sm;
@apply text-gray-700 dark:text-gray-300;
@apply cursor-pointer transition-colors duration-150;
@apply hover:bg-gray-50 dark:hover:bg-dark-700;
}
.select-option-selected {
@apply bg-primary-50 dark:bg-primary-900/20;
@apply text-primary-700 dark:text-primary-300;
}
.select-option-label {
@apply truncate;
}
.select-empty {
@apply px-4 py-8 text-center text-sm;
@apply text-gray-500 dark:text-dark-400;
}
.test-btn {
@apply flex-shrink-0 p-1 rounded;
@apply text-gray-400 hover:text-emerald-600 dark:hover:text-emerald-400;
@apply hover:bg-emerald-50 dark:hover:bg-emerald-900/20;
@apply transition-colors disabled:opacity-50 disabled:cursor-not-allowed;
}
/* Dropdown animation */
.select-dropdown-enter-active,
.select-dropdown-leave-active {
transition: all 0.2s ease;
}
.select-dropdown-enter-from,
.select-dropdown-leave-to {
opacity: 0;
transform: translateY(-8px);
}
</style>

View File

@@ -0,0 +1,243 @@
# Common Components
This directory contains reusable Vue 3 components built with Composition API, TypeScript, and TailwindCSS.
## Components
### DataTable.vue
A generic data table component with sorting, loading states, and custom cell rendering.
**Props:**
- `columns: Column[]` - Array of column definitions with key, label, sortable, and formatter
- `data: any[]` - Array of data objects to display
- `loading?: boolean` - Show loading skeleton
**Slots:**
- `empty` - Custom empty state content
- `cell-{key}` - Custom cell renderer for specific column (receives `row` and `value`)
**Usage:**
```vue
<DataTable
:columns="[
{ key: 'name', label: 'Name', sortable: true },
{ key: 'email', label: 'Email' },
{ key: 'status', label: 'Status', formatter: (val) => val.toUpperCase() }
]"
:data="users"
:loading="isLoading"
>
<template #cell-actions="{ row }">
<button @click="editUser(row)">Edit</button>
</template>
</DataTable>
```
---
### Pagination.vue
Pagination component with page numbers, navigation, and page size selector.
**Props:**
- `total: number` - Total number of items
- `page: number` - Current page (1-indexed)
- `pageSize: number` - Items per page
- `pageSizeOptions?: number[]` - Available page size options (default: [10, 20, 50, 100])
**Events:**
- `update:page` - Emitted when page changes
- `update:pageSize` - Emitted when page size changes
**Usage:**
```vue
<Pagination
:total="totalUsers"
:page="currentPage"
:pageSize="pageSize"
@update:page="currentPage = $event"
@update:pageSize="pageSize = $event"
/>
```
---
### Modal.vue
Modal dialog with customizable size and close behavior.
**Props:**
- `show: boolean` - Control modal visibility
- `title: string` - Modal title
- `size?: 'sm' | 'md' | 'lg' | 'xl' | 'full'` - Modal size (default: 'md')
- `closeOnEscape?: boolean` - Close on Escape key (default: true)
- `closeOnClickOutside?: boolean` - Close on backdrop click (default: true)
**Events:**
- `close` - Emitted when modal should close
**Slots:**
- `default` - Modal body content
- `footer` - Modal footer content
**Usage:**
```vue
<Modal :show="showModal" title="Edit User" size="lg" @close="showModal = false">
<form @submit.prevent="saveUser">
<!-- Form content -->
</form>
<template #footer>
<button @click="showModal = false">Cancel</button>
<button @click="saveUser">Save</button>
</template>
</Modal>
```
---
### ConfirmDialog.vue
Confirmation dialog built on top of Modal component.
**Props:**
- `show: boolean` - Control dialog visibility
- `title: string` - Dialog title
- `message: string` - Confirmation message
- `confirmText?: string` - Confirm button text (default: 'Confirm')
- `cancelText?: string` - Cancel button text (default: 'Cancel')
- `danger?: boolean` - Use danger/red styling (default: false)
**Events:**
- `confirm` - Emitted when user confirms
- `cancel` - Emitted when user cancels
**Usage:**
```vue
<ConfirmDialog
:show="showDeleteConfirm"
title="Delete User"
message="Are you sure you want to delete this user? This action cannot be undone."
confirm-text="Delete"
cancel-text="Cancel"
danger
@confirm="deleteUser"
@cancel="showDeleteConfirm = false"
/>
```
---
### StatCard.vue
Statistics card component for displaying metrics with optional change indicators.
**Props:**
- `title: string` - Card title
- `value: number | string` - Main value to display
- `icon?: Component` - Icon component
- `change?: number` - Percentage change value
- `changeType?: 'up' | 'down' | 'neutral'` - Change direction (default: 'neutral')
- `formatValue?: (value) => string` - Custom value formatter
**Usage:**
```vue
<StatCard
title="Total Users"
:value="1234"
:icon="UserIcon"
:change="12.5"
change-type="up"
/>
```
---
### Toast.vue
Toast notification component that automatically displays toasts from the app store.
**Usage:**
```vue
<!-- Add once in App.vue or layout -->
<Toast />
```
```typescript
// Trigger toasts from anywhere using the app store
import { useAppStore } from '@/stores/app'
const appStore = useAppStore()
appStore.addToast({
type: 'success',
title: 'Success!',
message: 'User created successfully',
duration: 3000
})
appStore.addToast({
type: 'error',
message: 'Failed to delete user'
})
```
---
### LoadingSpinner.vue
Simple animated loading spinner.
**Props:**
- `size?: 'sm' | 'md' | 'lg' | 'xl'` - Spinner size (default: 'md')
- `color?: 'primary' | 'secondary' | 'white' | 'gray'` - Spinner color (default: 'primary')
**Usage:**
```vue
<LoadingSpinner size="lg" color="primary" />
```
---
### EmptyState.vue
Empty state placeholder with icon, message, and optional action button.
**Props:**
- `icon?: Component` - Icon component
- `title: string` - Empty state title
- `description: string` - Empty state description
- `actionText?: string` - Action button text
- `actionTo?: string | object` - Router link destination
- `actionIcon?: boolean` - Show plus icon in button (default: true)
**Slots:**
- `icon` - Custom icon content
- `action` - Custom action button/link
**Usage:**
```vue
<EmptyState
title="No users found"
description="Get started by creating your first user account."
action-text="Add User"
:action-to="{ name: 'users-create' }"
/>
```
## Import
You can import components individually:
```typescript
import { DataTable, Pagination, Modal } from '@/components/common'
```
Or import specific components:
```typescript
import DataTable from '@/components/common/DataTable.vue'
```
## Features
All components include:
- **TypeScript support** with proper type definitions
- **Accessibility** with ARIA attributes and keyboard navigation
- **Responsive design** with mobile-friendly layouts
- **TailwindCSS styling** for consistent design
- **Vue 3 Composition API** with `<script setup>`
- **Slot support** for customization

View File

@@ -0,0 +1,319 @@
<template>
<div class="relative" ref="containerRef">
<button
type="button"
@click="toggle"
:disabled="disabled"
:class="[
'select-trigger',
isOpen && 'select-trigger-open',
error && 'select-trigger-error',
disabled && 'select-trigger-disabled'
]"
>
<span class="select-value">
<slot name="selected" :option="selectedOption">
{{ selectedLabel }}
</slot>
</span>
<span class="select-icon">
<svg
:class="['w-5 h-5 transition-transform duration-200', isOpen && 'rotate-180']"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
stroke-width="1.5"
>
<path stroke-linecap="round" stroke-linejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" />
</svg>
</span>
</button>
<Transition name="select-dropdown">
<div
v-if="isOpen"
class="select-dropdown"
>
<!-- Search input -->
<div v-if="searchable" class="select-search">
<svg class="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="1.5">
<path stroke-linecap="round" stroke-linejoin="round" d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z" />
</svg>
<input
ref="searchInputRef"
v-model="searchQuery"
type="text"
:placeholder="searchPlaceholderText"
class="select-search-input"
@click.stop
/>
</div>
<!-- Options list -->
<div class="select-options">
<div
v-for="option in filteredOptions"
:key="getOptionValue(option)"
@click="selectOption(option)"
:class="[
'select-option',
isSelected(option) && 'select-option-selected'
]"
>
<slot name="option" :option="option" :selected="isSelected(option)">
<span class="select-option-label">{{ getOptionLabel(option) }}</span>
<svg
v-if="isSelected(option)"
class="w-4 h-4 text-primary-500"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
stroke-width="2"
>
<path stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5" />
</svg>
</slot>
</div>
<!-- Empty state -->
<div v-if="filteredOptions.length === 0" class="select-empty">
{{ emptyTextDisplay }}
</div>
</div>
</div>
</Transition>
</div>
</template>
<script setup lang="ts">
import { ref, computed, watch, onMounted, onUnmounted, nextTick } from 'vue'
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
export interface SelectOption {
value: string | number | null
label: string
disabled?: boolean
[key: string]: unknown
}
interface Props {
modelValue: string | number | null | undefined
options: SelectOption[] | Array<Record<string, unknown>>
placeholder?: string
disabled?: boolean
error?: boolean
searchable?: boolean
searchPlaceholder?: string
emptyText?: string
valueKey?: string
labelKey?: string
}
interface Emits {
(e: 'update:modelValue', value: string | number | null): void
(e: 'change', value: string | number | null, option: SelectOption | null): void
}
const props = withDefaults(defineProps<Props>(), {
disabled: false,
error: false,
searchable: false,
valueKey: 'value',
labelKey: 'label'
})
// Use computed for i18n default values
const placeholderText = computed(() => props.placeholder ?? t('common.selectOption'))
const searchPlaceholderText = computed(() => props.searchPlaceholder ?? t('common.searchPlaceholder'))
const emptyTextDisplay = computed(() => props.emptyText ?? t('common.noOptionsFound'))
const emit = defineEmits<Emits>()
const isOpen = ref(false)
const searchQuery = ref('')
const containerRef = ref<HTMLElement | null>(null)
const searchInputRef = ref<HTMLInputElement | null>(null)
const getOptionValue = (option: SelectOption | Record<string, unknown>): string | number | null => {
if (typeof option === 'object' && option !== null) {
return option[props.valueKey] as string | number | null
}
return option as string | number | null
}
const getOptionLabel = (option: SelectOption | Record<string, unknown>): string => {
if (typeof option === 'object' && option !== null) {
return String(option[props.labelKey] ?? '')
}
return String(option ?? '')
}
const selectedOption = computed(() => {
return props.options.find(opt => getOptionValue(opt) === props.modelValue) || null
})
const selectedLabel = computed(() => {
if (selectedOption.value) {
return getOptionLabel(selectedOption.value)
}
return placeholderText.value
})
const filteredOptions = computed(() => {
if (!props.searchable || !searchQuery.value) {
return props.options
}
const query = searchQuery.value.toLowerCase()
return props.options.filter(opt => {
const label = getOptionLabel(opt).toLowerCase()
return label.includes(query)
})
})
const isSelected = (option: SelectOption | Record<string, unknown>): boolean => {
return getOptionValue(option) === props.modelValue
}
const toggle = () => {
if (props.disabled) return
isOpen.value = !isOpen.value
if (isOpen.value && props.searchable) {
nextTick(() => {
searchInputRef.value?.focus()
})
}
}
const selectOption = (option: SelectOption | Record<string, unknown>) => {
const value = getOptionValue(option)
emit('update:modelValue', value)
emit('change', value, option as SelectOption)
isOpen.value = false
searchQuery.value = ''
}
const handleClickOutside = (event: MouseEvent) => {
if (containerRef.value && !containerRef.value.contains(event.target as Node)) {
isOpen.value = false
searchQuery.value = ''
}
}
const handleEscape = (event: KeyboardEvent) => {
if (event.key === 'Escape' && isOpen.value) {
isOpen.value = false
searchQuery.value = ''
}
}
watch(isOpen, (open) => {
if (!open) {
searchQuery.value = ''
}
})
onMounted(() => {
document.addEventListener('click', handleClickOutside)
document.addEventListener('keydown', handleEscape)
})
onUnmounted(() => {
document.removeEventListener('click', handleClickOutside)
document.removeEventListener('keydown', handleEscape)
})
</script>
<style scoped>
.select-trigger {
@apply w-full flex items-center justify-between gap-2;
@apply px-4 py-2.5 rounded-xl text-sm;
@apply bg-white dark:bg-dark-800;
@apply border border-gray-200 dark:border-dark-600;
@apply text-gray-900 dark:text-gray-100;
@apply transition-all duration-200;
@apply focus:outline-none focus:ring-2 focus:ring-primary-500/30 focus:border-primary-500;
@apply hover:border-gray-300 dark:hover:border-dark-500;
@apply cursor-pointer;
}
.select-trigger-open {
@apply ring-2 ring-primary-500/30 border-primary-500;
}
.select-trigger-error {
@apply border-red-500 focus:ring-red-500/30 focus:border-red-500;
}
.select-trigger-disabled {
@apply bg-gray-100 dark:bg-dark-900 cursor-not-allowed opacity-60;
}
.select-value {
@apply flex-1 text-left truncate;
}
.select-icon {
@apply flex-shrink-0 text-gray-400 dark:text-dark-400;
}
.select-dropdown {
@apply absolute z-[100] w-full mt-2;
@apply bg-white dark:bg-dark-800;
@apply rounded-xl;
@apply border border-gray-200 dark:border-dark-700;
@apply shadow-lg shadow-black/10 dark:shadow-black/30;
@apply overflow-hidden;
}
.select-search {
@apply flex items-center gap-2 px-3 py-2;
@apply border-b border-gray-100 dark:border-dark-700;
}
.select-search-input {
@apply flex-1 bg-transparent text-sm;
@apply text-gray-900 dark:text-gray-100;
@apply placeholder:text-gray-400 dark:placeholder:text-dark-400;
@apply focus:outline-none;
}
.select-options {
@apply max-h-60 overflow-y-auto py-1;
}
.select-option {
@apply flex items-center justify-between gap-2;
@apply px-4 py-2.5 text-sm;
@apply text-gray-700 dark:text-gray-300;
@apply cursor-pointer transition-colors duration-150;
@apply hover:bg-gray-50 dark:hover:bg-dark-700;
}
.select-option-selected {
@apply bg-primary-50 dark:bg-primary-900/20;
@apply text-primary-700 dark:text-primary-300;
}
.select-option-label {
@apply truncate;
}
.select-empty {
@apply px-4 py-8 text-center text-sm;
@apply text-gray-500 dark:text-dark-400;
}
/* Dropdown animation */
.select-dropdown-enter-active,
.select-dropdown-leave-active {
transition: all 0.2s ease;
}
.select-dropdown-enter-from,
.select-dropdown-leave-to {
opacity: 0;
transform: translateY(-8px);
}
</style>

View File

@@ -0,0 +1,94 @@
<template>
<div class="stat-card">
<div :class="['stat-icon', iconClass]">
<component
v-if="icon"
:is="icon"
class="w-6 h-6"
aria-hidden="true"
/>
</div>
<div class="flex-1 min-w-0">
<p class="stat-label truncate">{{ title }}</p>
<div class="flex items-baseline gap-2 mt-1">
<p class="stat-value">{{ formattedValue }}</p>
<span
v-if="change !== undefined"
:class="['stat-trend', trendClass]"
>
<svg
v-if="changeType !== 'neutral'"
:class="['w-3 h-3', changeType === 'down' && 'rotate-180']"
fill="currentColor"
viewBox="0 0 20 20"
>
<path
fill-rule="evenodd"
d="M5.293 9.707a1 1 0 010-1.414l4-4a1 1 0 011.414 0l4 4a1 1 0 01-1.414 1.414L11 7.414V15a1 1 0 11-2 0V7.414L6.707 9.707a1 1 0 01-1.414 0z"
clip-rule="evenodd"
/>
</svg>
{{ formattedChange }}
</span>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import type { Component } from 'vue'
type ChangeType = 'up' | 'down' | 'neutral'
type IconVariant = 'primary' | 'success' | 'warning' | 'danger'
interface Props {
title: string
value: number | string
icon?: Component
iconVariant?: IconVariant
change?: number
changeType?: ChangeType
formatValue?: (value: number | string) => string
}
const props = withDefaults(defineProps<Props>(), {
changeType: 'neutral',
iconVariant: 'primary'
})
const formattedValue = computed(() => {
if (props.formatValue) {
return props.formatValue(props.value)
}
if (typeof props.value === 'number') {
return props.value.toLocaleString()
}
return props.value
})
const formattedChange = computed(() => {
if (props.change === undefined) return ''
const absChange = Math.abs(props.change)
return `${absChange}%`
})
const iconClass = computed(() => {
const classes: Record<IconVariant, string> = {
primary: 'stat-icon-primary',
success: 'stat-icon-success',
warning: 'stat-icon-warning',
danger: 'stat-icon-danger'
}
return classes[props.iconVariant]
})
const trendClass = computed(() => {
const classes: Record<ChangeType, string> = {
up: 'stat-trend-up',
down: 'stat-trend-down',
neutral: 'text-gray-500 dark:text-dark-400'
}
return classes[props.changeType]
})
</script>

View File

@@ -0,0 +1,267 @@
<template>
<div v-if="hasActiveSubscriptions" class="relative" ref="containerRef">
<!-- Mini Progress Display -->
<button
@click="toggleTooltip"
class="flex items-center gap-2 px-3 py-1.5 rounded-xl bg-purple-50 dark:bg-purple-900/20 hover:bg-purple-100 dark:hover:bg-purple-900/30 transition-colors cursor-pointer"
:title="t('subscriptionProgress.viewDetails')"
>
<svg class="w-4 h-4 text-purple-600 dark:text-purple-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
<path stroke-linecap="round" stroke-linejoin="round" d="M2.25 8.25h19.5M2.25 9h19.5m-16.5 5.25h6m-6 2.25h3m-3.75 3h15a2.25 2.25 0 002.25-2.25V6.75A2.25 2.25 0 0019.5 4.5h-15a2.25 2.25 0 00-2.25 2.25v10.5A2.25 2.25 0 004.5 19.5z" />
</svg>
<div class="flex items-center gap-1.5">
<!-- Combined progress indicator -->
<div class="flex items-center gap-0.5">
<div
v-for="(sub, index) in displaySubscriptions.slice(0, 3)"
:key="index"
class="w-2 h-2 rounded-full"
:class="getProgressDotClass(sub)"
></div>
</div>
<span class="text-xs font-medium text-purple-700 dark:text-purple-300">
{{ activeSubscriptions.length }}
</span>
</div>
</button>
<!-- Hover/Click Tooltip -->
<transition name="dropdown">
<div
v-if="tooltipOpen"
class="absolute right-0 mt-2 w-80 bg-white dark:bg-dark-800 rounded-xl shadow-xl border border-gray-200 dark:border-dark-700 z-50"
>
<div class="p-3 border-b border-gray-100 dark:border-dark-700">
<h3 class="text-sm font-semibold text-gray-900 dark:text-white">
{{ t('subscriptionProgress.title') }}
</h3>
<p class="text-xs text-gray-500 dark:text-dark-400 mt-0.5">
{{ t('subscriptionProgress.activeCount', { count: activeSubscriptions.length }) }}
</p>
</div>
<div class="max-h-64 overflow-y-auto">
<div
v-for="subscription in displaySubscriptions"
:key="subscription.id"
class="p-3 border-b border-gray-50 dark:border-dark-700/50 last:border-b-0"
>
<div class="flex items-center justify-between mb-2">
<span class="text-sm font-medium text-gray-900 dark:text-white">
{{ subscription.group?.name || `Group #${subscription.group_id}` }}
</span>
<span
v-if="subscription.expires_at"
class="text-xs"
:class="getDaysRemainingClass(subscription.expires_at)"
>
{{ formatDaysRemaining(subscription.expires_at) }}
</span>
</div>
<!-- Progress bars -->
<div class="space-y-1.5">
<div v-if="subscription.group?.daily_limit_usd" class="flex items-center gap-2">
<span class="text-[10px] text-gray-500 w-8">{{ t('subscriptionProgress.daily') }}</span>
<div class="flex-1 bg-gray-200 dark:bg-dark-600 rounded-full h-1.5">
<div
class="h-1.5 rounded-full transition-all"
:class="getProgressBarClass(subscription.daily_usage_usd, subscription.group?.daily_limit_usd)"
:style="{ width: getProgressWidth(subscription.daily_usage_usd, subscription.group?.daily_limit_usd) }"
></div>
</div>
<span class="text-[10px] text-gray-500 w-16 text-right">
{{ formatUsage(subscription.daily_usage_usd, subscription.group?.daily_limit_usd) }}
</span>
</div>
<div v-if="subscription.group?.weekly_limit_usd" class="flex items-center gap-2">
<span class="text-[10px] text-gray-500 w-8">{{ t('subscriptionProgress.weekly') }}</span>
<div class="flex-1 bg-gray-200 dark:bg-dark-600 rounded-full h-1.5">
<div
class="h-1.5 rounded-full transition-all"
:class="getProgressBarClass(subscription.weekly_usage_usd, subscription.group?.weekly_limit_usd)"
:style="{ width: getProgressWidth(subscription.weekly_usage_usd, subscription.group?.weekly_limit_usd) }"
></div>
</div>
<span class="text-[10px] text-gray-500 w-16 text-right">
{{ formatUsage(subscription.weekly_usage_usd, subscription.group?.weekly_limit_usd) }}
</span>
</div>
<div v-if="subscription.group?.monthly_limit_usd" class="flex items-center gap-2">
<span class="text-[10px] text-gray-500 w-8">{{ t('subscriptionProgress.monthly') }}</span>
<div class="flex-1 bg-gray-200 dark:bg-dark-600 rounded-full h-1.5">
<div
class="h-1.5 rounded-full transition-all"
:class="getProgressBarClass(subscription.monthly_usage_usd, subscription.group?.monthly_limit_usd)"
:style="{ width: getProgressWidth(subscription.monthly_usage_usd, subscription.group?.monthly_limit_usd) }"
></div>
</div>
<span class="text-[10px] text-gray-500 w-16 text-right">
{{ formatUsage(subscription.monthly_usage_usd, subscription.group?.monthly_limit_usd) }}
</span>
</div>
</div>
</div>
</div>
<div class="p-2 border-t border-gray-100 dark:border-dark-700">
<router-link
to="/subscriptions"
@click="closeTooltip"
class="block w-full text-center text-xs text-primary-600 dark:text-primary-400 hover:underline py-1"
>
{{ t('subscriptionProgress.viewAll') }}
</router-link>
</div>
</div>
</transition>
</div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import subscriptionsAPI from '@/api/subscriptions';
import type { UserSubscription } from '@/types';
const { t } = useI18n();
const containerRef = ref<HTMLElement | null>(null);
const tooltipOpen = ref(false);
const activeSubscriptions = ref<UserSubscription[]>([]);
const loading = ref(false);
const hasActiveSubscriptions = computed(() => activeSubscriptions.value.length > 0);
const displaySubscriptions = computed(() => {
// Sort by most usage (highest percentage first)
return [...activeSubscriptions.value].sort((a, b) => {
const aMax = getMaxUsagePercentage(a);
const bMax = getMaxUsagePercentage(b);
return bMax - aMax;
});
});
function getMaxUsagePercentage(sub: UserSubscription): number {
const percentages: number[] = [];
if (sub.group?.daily_limit_usd) {
percentages.push((sub.daily_usage_usd || 0) / sub.group.daily_limit_usd * 100);
}
if (sub.group?.weekly_limit_usd) {
percentages.push((sub.weekly_usage_usd || 0) / sub.group.weekly_limit_usd * 100);
}
if (sub.group?.monthly_limit_usd) {
percentages.push((sub.monthly_usage_usd || 0) / sub.group.monthly_limit_usd * 100);
}
return percentages.length > 0 ? Math.max(...percentages) : 0;
}
function getProgressDotClass(sub: UserSubscription): string {
const maxPercentage = getMaxUsagePercentage(sub);
if (maxPercentage >= 90) return 'bg-red-500';
if (maxPercentage >= 70) return 'bg-orange-500';
return 'bg-green-500';
}
function getProgressBarClass(used: number | undefined, limit: number | null | undefined): string {
if (!limit || limit === 0) return 'bg-gray-400';
const percentage = ((used || 0) / limit) * 100;
if (percentage >= 90) return 'bg-red-500';
if (percentage >= 70) return 'bg-orange-500';
return 'bg-green-500';
}
function getProgressWidth(used: number | undefined, limit: number | null | undefined): string {
if (!limit || limit === 0) return '0%';
const percentage = Math.min(((used || 0) / limit) * 100, 100);
return `${percentage}%`;
}
function formatUsage(used: number | undefined, limit: number | null | undefined): string {
const usedValue = (used || 0).toFixed(2);
const limitValue = limit?.toFixed(2) || '∞';
return `$${usedValue}/$${limitValue}`;
}
function formatDaysRemaining(expiresAt: string): string {
const now = new Date();
const expires = new Date(expiresAt);
const diff = expires.getTime() - now.getTime();
if (diff < 0) return t('subscriptionProgress.expired');
const days = Math.ceil(diff / (1000 * 60 * 60 * 24));
if (days === 0) return t('subscriptionProgress.expirestoday');
if (days === 1) return t('subscriptionProgress.expiresTomorrow');
return t('subscriptionProgress.daysRemaining', { days });
}
function getDaysRemainingClass(expiresAt: string): string {
const now = new Date();
const expires = new Date(expiresAt);
const diff = expires.getTime() - now.getTime();
const days = Math.ceil(diff / (1000 * 60 * 60 * 24));
if (days <= 3) return 'text-red-600 dark:text-red-400';
if (days <= 7) return 'text-orange-600 dark:text-orange-400';
return 'text-gray-500 dark:text-dark-400';
}
function toggleTooltip() {
tooltipOpen.value = !tooltipOpen.value;
}
function closeTooltip() {
tooltipOpen.value = false;
}
function handleClickOutside(event: MouseEvent) {
if (containerRef.value && !containerRef.value.contains(event.target as Node)) {
closeTooltip();
}
}
async function loadSubscriptions() {
try {
loading.value = true;
activeSubscriptions.value = await subscriptionsAPI.getActiveSubscriptions();
} catch (error) {
console.error('Failed to load subscriptions:', error);
activeSubscriptions.value = [];
} finally {
loading.value = false;
}
}
onMounted(() => {
document.addEventListener('click', handleClickOutside);
loadSubscriptions();
});
onBeforeUnmount(() => {
document.removeEventListener('click', handleClickOutside);
});
// Refresh subscriptions periodically (every 5 minutes)
let refreshInterval: ReturnType<typeof setInterval> | null = null;
onMounted(() => {
refreshInterval = setInterval(loadSubscriptions, 5 * 60 * 1000);
});
onBeforeUnmount(() => {
if (refreshInterval) {
clearInterval(refreshInterval);
}
});
</script>
<style scoped>
.dropdown-enter-active,
.dropdown-leave-active {
transition: all 0.2s ease;
}
.dropdown-enter-from,
.dropdown-leave-to {
opacity: 0;
transform: scale(0.95) translateY(-4px);
}
</style>

View File

@@ -0,0 +1,224 @@
<template>
<Teleport to="body">
<div
class="fixed top-4 right-4 z-[9999] space-y-3 pointer-events-none"
aria-live="polite"
aria-atomic="true"
>
<TransitionGroup
enter-active-class="transition ease-out duration-300"
enter-from-class="opacity-0 translate-x-full"
enter-to-class="opacity-100 translate-x-0"
leave-active-class="transition ease-in duration-200"
leave-from-class="opacity-100 translate-x-0"
leave-to-class="opacity-0 translate-x-full"
>
<div
v-for="toast in toasts"
:key="toast.id"
:class="[
'pointer-events-auto min-w-[320px] max-w-md overflow-hidden rounded-lg shadow-lg',
'bg-white dark:bg-dark-800',
'border-l-4',
getBorderColor(toast.type)
]"
>
<div class="p-4">
<div class="flex items-start gap-3">
<!-- Icon -->
<div class="flex-shrink-0 mt-0.5">
<component
:is="getIcon(toast.type)"
:class="['w-5 h-5', getIconColor(toast.type)]"
aria-hidden="true"
/>
</div>
<!-- Content -->
<div class="flex-1 min-w-0">
<p
v-if="toast.title"
class="text-sm font-semibold text-gray-900 dark:text-white"
>
{{ toast.title }}
</p>
<p
:class="[
'text-sm leading-relaxed',
toast.title ? 'mt-1 text-gray-600 dark:text-gray-300' : 'text-gray-900 dark:text-white'
]"
>
{{ toast.message }}
</p>
</div>
<!-- Close button -->
<button
@click="removeToast(toast.id)"
class="flex-shrink-0 p-1 -m-1 text-gray-400 dark:text-gray-500 transition-colors rounded hover:text-gray-600 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-dark-700"
aria-label="Close notification"
>
<svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
<path
fill-rule="evenodd"
d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z"
clip-rule="evenodd"
/>
</svg>
</button>
</div>
</div>
<!-- Progress bar -->
<div
v-if="toast.duration"
class="h-1 bg-gray-100 dark:bg-dark-700"
>
<div
:class="['h-full transition-all', getProgressBarColor(toast.type)]"
:style="{ width: `${getProgress(toast)}%` }"
></div>
</div>
</div>
</TransitionGroup>
</div>
</Teleport>
</template>
<script setup lang="ts">
import { computed, onMounted, onUnmounted, h } from 'vue'
import { useAppStore } from '@/stores/app'
const appStore = useAppStore()
const toasts = computed(() => appStore.toasts)
const getIcon = (type: string) => {
const icons = {
success: () =>
h(
'svg',
{
fill: 'currentColor',
viewBox: '0 0 20 20'
},
[
h('path', {
'fill-rule': 'evenodd',
d: 'M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z',
'clip-rule': 'evenodd'
})
]
),
error: () =>
h(
'svg',
{
fill: 'currentColor',
viewBox: '0 0 20 20'
},
[
h('path', {
'fill-rule': 'evenodd',
d: 'M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z',
'clip-rule': 'evenodd'
})
]
),
warning: () =>
h(
'svg',
{
fill: 'currentColor',
viewBox: '0 0 20 20'
},
[
h('path', {
'fill-rule': 'evenodd',
d: 'M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z',
'clip-rule': 'evenodd'
})
]
),
info: () =>
h(
'svg',
{
fill: 'currentColor',
viewBox: '0 0 20 20'
},
[
h('path', {
'fill-rule': 'evenodd',
d: 'M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z',
'clip-rule': 'evenodd'
})
]
)
}
return icons[type as keyof typeof icons] || icons.info
}
const getIconColor = (type: string): string => {
const colors: Record<string, string> = {
success: 'text-green-500',
error: 'text-red-500',
warning: 'text-yellow-500',
info: 'text-blue-500'
}
return colors[type] || colors.info
}
const getBorderColor = (type: string): string => {
const colors: Record<string, string> = {
success: 'border-green-500',
error: 'border-red-500',
warning: 'border-yellow-500',
info: 'border-blue-500'
}
return colors[type] || colors.info
}
const getProgressBarColor = (type: string): string => {
const colors: Record<string, string> = {
success: 'bg-green-500',
error: 'bg-red-500',
warning: 'bg-yellow-500',
info: 'bg-blue-500'
}
return colors[type] || colors.info
}
const getProgress = (toast: any): number => {
if (!toast.duration || !toast.startTime) return 100
const elapsed = Date.now() - toast.startTime
const progress = Math.max(0, 100 - (elapsed / toast.duration) * 100)
return progress
}
const removeToast = (id: string) => {
appStore.hideToast(id)
}
let intervalId: number | undefined
onMounted(() => {
// Check for expired toasts every 100ms
intervalId = window.setInterval(() => {
const now = Date.now()
toasts.value.forEach((toast) => {
if (toast.duration && toast.startTime) {
if (now - toast.startTime >= toast.duration) {
removeToast(toast.id)
}
}
})
}, 100)
})
onUnmounted(() => {
if (intervalId !== undefined) {
clearInterval(intervalId)
}
})
</script>

View File

@@ -0,0 +1,35 @@
<template>
<button
type="button"
@click="toggle"
class="relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-primary-500 focus:ring-offset-2 dark:focus:ring-offset-dark-800"
:class="[
modelValue
? 'bg-primary-600'
: 'bg-gray-200 dark:bg-dark-600'
]"
role="switch"
:aria-checked="modelValue"
>
<span
class="pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out"
:class="[
modelValue ? 'translate-x-5' : 'translate-x-0'
]"
/>
</button>
</template>
<script setup lang="ts">
const props = defineProps<{
modelValue: boolean;
}>();
const emit = defineEmits<{
(e: 'update:modelValue', value: boolean): void;
}>();
function toggle() {
emit('update:modelValue', !props.modelValue);
}
</script>

View File

@@ -0,0 +1,250 @@
<template>
<div class="relative">
<!-- Admin: Full version badge with dropdown -->
<template v-if="isAdmin">
<button
@click="toggleDropdown"
class="flex items-center gap-1.5 px-2 py-1 text-xs rounded-lg transition-colors"
:class="[
hasUpdate
? 'bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-400 hover:bg-amber-200 dark:hover:bg-amber-900/50'
: 'bg-gray-100 dark:bg-dark-800 text-gray-600 dark:text-dark-400 hover:bg-gray-200 dark:hover:bg-dark-700'
]"
:title="hasUpdate ? 'New version available' : 'Up to date'"
>
<span class="font-medium">v{{ currentVersion }}</span>
<!-- Update indicator -->
<span v-if="hasUpdate" class="relative flex h-2 w-2">
<span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-amber-400 opacity-75"></span>
<span class="relative inline-flex rounded-full h-2 w-2 bg-amber-500"></span>
</span>
</button>
<!-- Dropdown -->
<transition name="dropdown">
<div
v-if="dropdownOpen"
ref="dropdownRef"
class="absolute left-0 mt-2 w-64 bg-white dark:bg-dark-800 rounded-xl shadow-lg border border-gray-200 dark:border-dark-700 z-50 overflow-hidden"
>
<!-- Header with refresh button -->
<div class="flex items-center justify-between px-4 py-3 border-b border-gray-100 dark:border-dark-700">
<span class="text-sm font-medium text-gray-700 dark:text-dark-300">{{ t('version.currentVersion') }}</span>
<button
@click="refreshVersion(true)"
class="p-1.5 rounded-lg text-gray-400 hover:text-gray-600 dark:hover:text-dark-200 hover:bg-gray-100 dark:hover:bg-dark-700 transition-colors"
:disabled="loading"
:title="t('version.refresh')"
>
<svg class="w-4 h-4" :class="{ 'animate-spin': loading }" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7M4.031 9.865a8.25 8.25 0 0113.803-3.7l3.181 3.182m0-4.991v4.99" />
</svg>
</button>
</div>
<div class="p-4">
<!-- Loading state -->
<div v-if="loading" class="flex items-center justify-center py-6">
<svg class="animate-spin h-6 w-6 text-primary-500" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
</div>
<!-- Content -->
<template v-else>
<!-- Version display - centered and prominent -->
<div class="text-center mb-4">
<div class="inline-flex items-center gap-2">
<span class="text-2xl font-bold text-gray-900 dark:text-white">v{{ currentVersion }}</span>
<!-- Show check mark when up to date -->
<span v-if="!hasUpdate" class="flex items-center justify-center w-5 h-5 rounded-full bg-green-100 dark:bg-green-900/30">
<svg class="w-3 h-3 text-green-600 dark:text-green-400" fill="currentColor" viewBox="0 0 20 20">
<path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
</svg>
</span>
</div>
<p class="text-xs text-gray-500 dark:text-dark-400 mt-1">
{{ hasUpdate ? t('version.latestVersion') + ': v' + latestVersion : t('version.upToDate') }}
</p>
</div>
<!-- Update available for source build - show git pull hint -->
<div v-if="hasUpdate && !isReleaseBuild" class="space-y-2">
<a
v-if="releaseInfo?.html_url && releaseInfo.html_url !== '#'"
:href="releaseInfo.html_url"
target="_blank"
rel="noopener noreferrer"
class="flex items-center gap-3 p-3 rounded-lg bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800/50 hover:bg-amber-100 dark:hover:bg-amber-900/30 transition-colors group"
>
<div class="flex-shrink-0 w-8 h-8 rounded-full bg-amber-100 dark:bg-amber-900/50 flex items-center justify-center">
<svg class="w-4 h-4 text-amber-600 dark:text-amber-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
</svg>
</div>
<div class="flex-1 min-w-0">
<p class="text-sm font-medium text-amber-700 dark:text-amber-300">{{ t('version.updateAvailable') }}</p>
<p class="text-xs text-amber-600/70 dark:text-amber-400/70">v{{ latestVersion }}</p>
</div>
<svg class="w-4 h-4 text-amber-500 dark:text-amber-400 group-hover:translate-x-0.5 transition-transform" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7" />
</svg>
</a>
<!-- Source build hint -->
<div class="flex items-center gap-2 p-2 rounded-lg bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800/50">
<svg class="w-3.5 h-3.5 text-blue-500 dark:text-blue-400 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<p class="text-xs text-blue-600 dark:text-blue-400">{{ t('version.sourceModeHint') }}</p>
</div>
</div>
<!-- Update available for release build - show download link -->
<a
v-else-if="hasUpdate && isReleaseBuild && releaseInfo?.html_url && releaseInfo.html_url !== '#'"
:href="releaseInfo.html_url"
target="_blank"
rel="noopener noreferrer"
class="flex items-center gap-3 p-3 rounded-lg bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800/50 hover:bg-amber-100 dark:hover:bg-amber-900/30 transition-colors group"
>
<div class="flex-shrink-0 w-8 h-8 rounded-full bg-amber-100 dark:bg-amber-900/50 flex items-center justify-center">
<svg class="w-4 h-4 text-amber-600 dark:text-amber-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
</svg>
</div>
<div class="flex-1 min-w-0">
<p class="text-sm font-medium text-amber-700 dark:text-amber-300">{{ t('version.updateAvailable') }}</p>
<p class="text-xs text-amber-600/70 dark:text-amber-400/70">v{{ latestVersion }}</p>
</div>
<svg class="w-4 h-4 text-amber-500 dark:text-amber-400 group-hover:translate-x-0.5 transition-transform" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7" />
</svg>
</a>
<!-- GitHub link when up to date -->
<a
v-else-if="releaseInfo?.html_url && releaseInfo.html_url !== '#'"
:href="releaseInfo.html_url"
target="_blank"
rel="noopener noreferrer"
class="flex items-center justify-center gap-2 py-2 text-sm text-gray-500 dark:text-dark-400 hover:text-gray-700 dark:hover:text-dark-200 transition-colors"
>
<svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
<path fill-rule="evenodd" clip-rule="evenodd" d="M12 2C6.477 2 2 6.477 2 12c0 4.42 2.865 8.17 6.839 9.49.5.092.682-.217.682-.482 0-.237-.008-.866-.013-1.7-2.782.604-3.369-1.34-3.369-1.34-.454-1.156-1.11-1.464-1.11-1.464-.908-.62.069-.608.069-.608 1.003.07 1.531 1.03 1.531 1.03.892 1.529 2.341 1.087 2.91.831.092-.646.35-1.086.636-1.336-2.22-.253-4.555-1.11-4.555-4.943 0-1.091.39-1.984 1.029-2.683-.103-.253-.446-1.27.098-2.647 0 0 .84-.269 2.75 1.025A9.578 9.578 0 0112 6.836c.85.004 1.705.114 2.504.336 1.909-1.294 2.747-1.025 2.747-1.025.546 1.377.203 2.394.1 2.647.64.699 1.028 1.592 1.028 2.683 0 3.842-2.339 4.687-4.566 4.935.359.309.678.919.678 1.852 0 1.336-.012 2.415-.012 2.743 0 .267.18.578.688.48C19.138 20.167 22 16.418 22 12c0-5.523-4.477-10-10-10z" />
</svg>
{{ t('version.viewRelease') }}
</a>
</template>
</div>
</div>
</transition>
</template>
<!-- Non-admin: Simple static version text -->
<span
v-else-if="version"
class="text-xs text-gray-500 dark:text-dark-400"
>
v{{ version }}
</span>
</div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
import { useI18n } from 'vue-i18n';
import { useAuthStore } from '@/stores';
import { checkUpdates, type VersionInfo, type ReleaseInfo } from '@/api/admin/system';
const { t } = useI18n();
const props = defineProps<{
version?: string;
}>();
const authStore = useAuthStore();
const isAdmin = computed(() => authStore.isAdmin);
const loading = ref(false);
const dropdownOpen = ref(false);
const dropdownRef = ref<HTMLElement | null>(null);
const currentVersion = ref('0.1.0');
const latestVersion = ref('0.1.0');
const hasUpdate = ref(false);
const releaseInfo = ref<ReleaseInfo | null>(null);
const buildType = ref('source'); // "source" or "release"
// Only show update check for release builds (binary/docker deployment)
const isReleaseBuild = computed(() => buildType.value === 'release');
function toggleDropdown() {
dropdownOpen.value = !dropdownOpen.value;
}
function closeDropdown() {
dropdownOpen.value = false;
}
async function refreshVersion(force = true) {
if (!isAdmin.value) return;
loading.value = true;
try {
const data: VersionInfo = await checkUpdates(force);
currentVersion.value = data.current_version;
latestVersion.value = data.latest_version;
buildType.value = data.build_type || 'source';
// Show update indicator for all build types
hasUpdate.value = data.has_update;
releaseInfo.value = data.release_info || null;
} catch (error) {
console.error('Failed to check updates:', error);
} finally {
loading.value = false;
}
}
function handleClickOutside(event: MouseEvent) {
const target = event.target as Node;
const button = (event.target as Element).closest('button');
if (dropdownRef.value && !dropdownRef.value.contains(target) && !button?.contains(target)) {
closeDropdown();
}
}
onMounted(() => {
if (isAdmin.value) {
refreshVersion(false);
} else if (props.version) {
currentVersion.value = props.version;
}
document.addEventListener('click', handleClickOutside);
});
onBeforeUnmount(() => {
document.removeEventListener('click', handleClickOutside);
});
</script>
<style scoped>
.dropdown-enter-active,
.dropdown-leave-active {
transition: all 0.2s ease;
}
.dropdown-enter-from,
.dropdown-leave-to {
opacity: 0;
transform: scale(0.95) translateY(-4px);
}
.line-clamp-3 {
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
}
</style>

View File

@@ -0,0 +1,13 @@
// Export all common components
export { default as DataTable } from './DataTable.vue'
export { default as Pagination } from './Pagination.vue'
export { default as Modal } from './Modal.vue'
export { default as ConfirmDialog } from './ConfirmDialog.vue'
export { default as StatCard } from './StatCard.vue'
export { default as Toast } from './Toast.vue'
export { default as LoadingSpinner } from './LoadingSpinner.vue'
export { default as EmptyState } from './EmptyState.vue'
export { default as LocaleSwitcher } from './LocaleSwitcher.vue'
// Export types
export type { Column } from './DataTable.vue'

View File

@@ -0,0 +1,200 @@
<template>
<Modal
:show="show"
:title="t('keys.useKeyModal.title')"
size="lg"
@close="emit('close')"
>
<div class="space-y-4">
<!-- Description -->
<p class="text-sm text-gray-600 dark:text-gray-400">
{{ t('keys.useKeyModal.description') }}
</p>
<!-- OS Tabs -->
<div class="border-b border-gray-200 dark:border-dark-700">
<nav class="-mb-px flex space-x-4" aria-label="Tabs">
<button
v-for="tab in tabs"
:key="tab.id"
@click="activeTab = tab.id"
:class="[
'whitespace-nowrap py-2.5 px-1 border-b-2 font-medium text-sm transition-colors',
activeTab === tab.id
? 'border-primary-500 text-primary-600 dark:text-primary-400'
: 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 dark:text-gray-400 dark:hover:text-gray-300'
]"
>
<span class="flex items-center gap-2">
<component :is="tab.icon" class="w-4 h-4" />
{{ tab.label }}
</span>
</button>
</nav>
</div>
<!-- Code Block -->
<div class="relative">
<div class="bg-gray-900 dark:bg-dark-900 rounded-xl overflow-hidden">
<!-- Code Header -->
<div class="flex items-center justify-between px-4 py-2 bg-gray-800 dark:bg-dark-800 border-b border-gray-700 dark:border-dark-700">
<span class="text-xs text-gray-400 font-mono">{{ activeTabConfig?.filename }}</span>
<button
@click="copyConfig"
class="flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded-lg transition-colors"
:class="copied
? 'bg-green-500/20 text-green-400'
: 'bg-gray-700 hover:bg-gray-600 text-gray-300 hover:text-white'"
>
<svg v-if="copied" class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7" />
</svg>
<svg v-else class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="1.5">
<path stroke-linecap="round" stroke-linejoin="round" d="M15.666 3.888A2.25 2.25 0 0013.5 2.25h-3c-1.03 0-1.9.693-2.166 1.638m7.332 0c.055.194.084.4.084.612v0a.75.75 0 01-.75.75H9a.75.75 0 01-.75-.75v0c0-.212.03-.418.084-.612m7.332 0c.646.049 1.288.11 1.927.184 1.1.128 1.907 1.077 1.907 2.185V19.5a2.25 2.25 0 01-2.25 2.25H6.75A2.25 2.25 0 014.5 19.5V6.257c0-1.108.806-2.057 1.907-2.185a48.208 48.208 0 011.927-.184" />
</svg>
{{ copied ? t('keys.useKeyModal.copied') : t('keys.useKeyModal.copy') }}
</button>
</div>
<!-- Code Content -->
<pre class="p-4 text-sm font-mono text-gray-100 overflow-x-auto"><code v-html="highlightedCode"></code></pre>
</div>
</div>
<!-- Usage Note -->
<div class="flex items-start gap-3 p-3 rounded-lg bg-blue-50 dark:bg-blue-900/20 border border-blue-100 dark:border-blue-800">
<svg class="w-5 h-5 text-blue-500 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="1.5">
<path stroke-linecap="round" stroke-linejoin="round" d="M11.25 11.25l.041-.02a.75.75 0 011.063.852l-.708 2.836a.75.75 0 001.063.853l.041-.021M21 12a9 9 0 11-18 0 9 9 0 0118 0zm-9-3.75h.008v.008H12V8.25z" />
</svg>
<p class="text-sm text-blue-700 dark:text-blue-300">
{{ t('keys.useKeyModal.note') }}
</p>
</div>
</div>
<template #footer>
<div class="flex justify-end">
<button
@click="emit('close')"
class="btn btn-secondary"
>
{{ t('common.close') }}
</button>
</div>
</template>
</Modal>
</template>
<script setup lang="ts">
import { ref, computed, h } from 'vue'
import { useI18n } from 'vue-i18n'
import Modal from '@/components/common/Modal.vue'
import { useAppStore } from '@/stores/app'
interface Props {
show: boolean
apiKey: string
baseUrl: string
}
interface Emits {
(e: 'close'): void
}
const props = defineProps<Props>()
const emit = defineEmits<Emits>()
const { t } = useI18n()
const appStore = useAppStore()
const copied = ref(false)
const activeTab = ref<'unix' | 'cmd' | 'powershell'>('unix')
// Icon components
const AppleIcon = {
render() {
return h('svg', {
fill: 'currentColor',
viewBox: '0 0 24 24',
class: 'w-4 h-4'
}, [
h('path', { d: 'M18.71 19.5c-.83 1.24-1.71 2.45-3.05 2.47-1.34.03-1.77-.79-3.29-.79-1.53 0-2 .77-3.27.82-1.31.05-2.3-1.32-3.14-2.53C4.25 17 2.94 12.45 4.7 9.39c.87-1.52 2.43-2.48 4.12-2.51 1.28-.02 2.5.87 3.29.87.78 0 2.26-1.07 3.81-.91.65.03 2.47.26 3.64 1.98-.09.06-2.17 1.28-2.15 3.81.03 3.02 2.65 4.03 2.68 4.04-.03.07-.42 1.44-1.38 2.83M13 3.5c.73-.83 1.94-1.46 2.94-1.5.13 1.17-.34 2.35-1.04 3.19-.69.85-1.83 1.51-2.95 1.42-.15-1.15.41-2.35 1.05-3.11z' })
])
}
}
const WindowsIcon = {
render() {
return h('svg', {
fill: 'currentColor',
viewBox: '0 0 24 24',
class: 'w-4 h-4'
}, [
h('path', { d: 'M3 12V6.75l6-1.32v6.48L3 12zm17-9v8.75l-10 .15V5.21L20 3zM3 13l6 .09v6.81l-6-1.15V13zm7 .25l10 .15V21l-10-1.91v-5.84z' })
])
}
}
const tabs = [
{ id: 'unix' as const, label: 'macOS / Linux', icon: AppleIcon, filename: 'Terminal' },
{ id: 'cmd' as const, label: 'Windows CMD', icon: WindowsIcon, filename: 'Command Prompt' },
{ id: 'powershell' as const, label: 'PowerShell', icon: WindowsIcon, filename: 'PowerShell' }
]
const activeTabConfig = computed(() => tabs.find(tab => tab.id === activeTab.value))
const configCode = computed(() => {
const baseUrl = props.baseUrl || window.location.origin
const apiKey = props.apiKey
switch (activeTab.value) {
case 'unix':
return `export ANTHROPIC_BASE_URL="${baseUrl}"
export ANTHROPIC_AUTH_TOKEN="${apiKey}"`
case 'cmd':
return `set ANTHROPIC_BASE_URL=${baseUrl}
set ANTHROPIC_AUTH_TOKEN=${apiKey}`
case 'powershell':
return `$env:ANTHROPIC_BASE_URL="${baseUrl}"
$env:ANTHROPIC_AUTH_TOKEN="${apiKey}"`
default:
return ''
}
})
const highlightedCode = computed(() => {
const baseUrl = props.baseUrl || window.location.origin
const apiKey = props.apiKey
// Build highlighted code directly to avoid regex replacement conflicts
const keyword = (text: string) => `<span class="text-purple-400">${text}</span>`
const variable = (text: string) => `<span class="text-cyan-400">${text}</span>`
const string = (text: string) => `<span class="text-green-400">${text}</span>`
const operator = (text: string) => `<span class="text-yellow-400">${text}</span>`
switch (activeTab.value) {
case 'unix':
return `${keyword('export')} ${variable('ANTHROPIC_BASE_URL')}${operator('=')}${string(`"${baseUrl}"`)}
${keyword('export')} ${variable('ANTHROPIC_AUTH_TOKEN')}${operator('=')}${string(`"${apiKey}"`)}`
case 'cmd':
return `${keyword('set')} ${variable('ANTHROPIC_BASE_URL')}${operator('=')}${baseUrl}
${keyword('set')} ${variable('ANTHROPIC_AUTH_TOKEN')}${operator('=')}${apiKey}`
case 'powershell':
return `${keyword('$env:')}${variable('ANTHROPIC_BASE_URL')}${operator('=')}${string(`"${baseUrl}"`)}
${keyword('$env:')}${variable('ANTHROPIC_AUTH_TOKEN')}${operator('=')}${string(`"${apiKey}"`)}`
default:
return ''
}
})
const copyConfig = async () => {
try {
await navigator.clipboard.writeText(configCode.value)
copied.value = true
setTimeout(() => {
copied.value = false
}, 2000)
} catch (error) {
appStore.showError(t('common.copyFailed'))
}
}
</script>

View File

@@ -0,0 +1,259 @@
<template>
<header class="sticky top-0 z-30 glass border-b border-gray-200/50 dark:border-dark-700/50">
<div class="flex items-center justify-between h-16 px-4 md:px-6">
<!-- Left: Mobile Menu Toggle + Page Title -->
<div class="flex items-center gap-4">
<button
@click="toggleMobileSidebar"
class="lg:hidden btn-ghost btn-icon"
aria-label="Toggle Menu"
>
<svg class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
<path stroke-linecap="round" stroke-linejoin="round" d="M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5" />
</svg>
</button>
<div class="hidden lg:block">
<h1 class="text-lg font-semibold text-gray-900 dark:text-white">
{{ pageTitle }}
</h1>
<p v-if="pageDescription" class="text-xs text-gray-500 dark:text-dark-400">
{{ pageDescription }}
</p>
</div>
</div>
<!-- Right: Language + Subscriptions + Balance + User Dropdown -->
<div class="flex items-center gap-3">
<!-- Language Switcher -->
<LocaleSwitcher />
<!-- Subscription Progress (for users with active subscriptions) -->
<SubscriptionProgressMini v-if="user" />
<!-- Balance Display -->
<div v-if="user" class="hidden sm:flex items-center gap-2 px-3 py-1.5 rounded-xl bg-primary-50 dark:bg-primary-900/20">
<svg class="w-4 h-4 text-primary-600 dark:text-primary-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
<path stroke-linecap="round" stroke-linejoin="round" d="M2.25 18.75a60.07 60.07 0 0115.797 2.101c.727.198 1.453-.342 1.453-1.096V18.75M3.75 4.5v.75A.75.75 0 013 6h-.75m0 0v-.375c0-.621.504-1.125 1.125-1.125H20.25M2.25 6v9m18-10.5v.75c0 .414.336.75.75.75h.75m-1.5-1.5h.375c.621 0 1.125.504 1.125 1.125v9.75c0 .621-.504 1.125-1.125 1.125h-.375m1.5-1.5H21a.75.75 0 00-.75.75v.75m0 0H3.75m0 0h-.375a1.125 1.125 0 01-1.125-1.125V15m1.5 1.5v-.75A.75.75 0 003 15h-.75M15 10.5a3 3 0 11-6 0 3 3 0 016 0zm3 0h.008v.008H18V10.5zm-12 0h.008v.008H6V10.5z" />
</svg>
<span class="text-sm font-semibold text-primary-700 dark:text-primary-300">
${{ user.balance?.toFixed(2) || '0.00' }}
</span>
</div>
<!-- User Dropdown -->
<div v-if="user" class="relative" ref="dropdownRef">
<button
@click="toggleDropdown"
class="flex items-center gap-2 p-1.5 rounded-xl hover:bg-gray-100 dark:hover:bg-dark-800 transition-colors"
aria-label="User Menu"
>
<div class="w-8 h-8 rounded-xl bg-gradient-to-br from-primary-500 to-primary-600 text-white flex items-center justify-center text-sm font-medium shadow-sm">
{{ userInitials }}
</div>
<div class="hidden md:block text-left">
<div class="text-sm font-medium text-gray-900 dark:text-white">
{{ displayName }}
</div>
<div class="text-xs text-gray-500 dark:text-dark-400 capitalize">
{{ user.role }}
</div>
</div>
<svg class="w-4 h-4 text-gray-400 hidden md:block" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
<path stroke-linecap="round" stroke-linejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" />
</svg>
</button>
<!-- Dropdown Menu -->
<transition name="dropdown">
<div
v-if="dropdownOpen"
class="dropdown right-0 mt-2 w-56"
>
<!-- User Info -->
<div class="px-4 py-3 border-b border-gray-100 dark:border-dark-700">
<div class="text-sm font-medium text-gray-900 dark:text-white">{{ displayName }}</div>
<div class="text-xs text-gray-500 dark:text-dark-400">{{ user.email }}</div>
</div>
<!-- Balance (mobile only) -->
<div class="sm:hidden px-4 py-2 border-b border-gray-100 dark:border-dark-700">
<div class="text-xs text-gray-500 dark:text-dark-400">{{ t('common.balance') }}</div>
<div class="text-sm font-semibold text-primary-600 dark:text-primary-400">
${{ user.balance?.toFixed(2) || '0.00' }}
</div>
</div>
<div class="py-1">
<router-link
to="/profile"
@click="closeDropdown"
class="dropdown-item"
>
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
<path stroke-linecap="round" stroke-linejoin="round" d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z" />
</svg>
{{ t('nav.profile') }}
</router-link>
<router-link
to="/keys"
@click="closeDropdown"
class="dropdown-item"
>
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
<path stroke-linecap="round" stroke-linejoin="round" d="M15.75 5.25a3 3 0 013 3m3 0a6 6 0 01-7.029 5.912c-.563-.097-1.159.026-1.563.43L10.5 17.25H8.25v2.25H6v2.25H2.25v-2.818c0-.597.237-1.17.659-1.591l6.499-6.499c.404-.404.527-1 .43-1.563A6 6 0 1121.75 8.25z" />
</svg>
{{ t('nav.apiKeys') }}
</router-link>
<a
href="https://github.com/fangyuan99/sub2api"
target="_blank"
rel="noopener noreferrer"
@click="closeDropdown"
class="dropdown-item"
>
<svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
<path fill-rule="evenodd" clip-rule="evenodd" d="M12 2C6.477 2 2 6.477 2 12c0 4.42 2.865 8.17 6.839 9.49.5.092.682-.217.682-.482 0-.237-.008-.866-.013-1.7-2.782.604-3.369-1.34-3.369-1.34-.454-1.156-1.11-1.464-1.11-1.464-.908-.62.069-.608.069-.608 1.003.07 1.531 1.03 1.531 1.03.892 1.529 2.341 1.087 2.91.831.092-.646.35-1.086.636-1.336-2.22-.253-4.555-1.11-4.555-4.943 0-1.091.39-1.984 1.029-2.683-.103-.253-.446-1.27.098-2.647 0 0 .84-.269 2.75 1.025A9.578 9.578 0 0112 6.836c.85.004 1.705.114 2.504.336 1.909-1.294 2.747-1.025 2.747-1.025.546 1.377.203 2.394.1 2.647.64.699 1.028 1.592 1.028 2.683 0 3.842-2.339 4.687-4.566 4.935.359.309.678.919.678 1.852 0 1.336-.012 2.415-.012 2.743 0 .267.18.578.688.48C19.138 20.167 22 16.418 22 12c0-5.523-4.477-10-10-10z" />
</svg>
{{ t('nav.github') }}
</a>
</div>
<!-- Contact Support (only show if configured) -->
<div v-if="contactInfo" class="border-t border-gray-100 dark:border-dark-700 px-4 py-2.5">
<div class="flex items-center gap-2 text-xs text-gray-500 dark:text-gray-400">
<svg class="w-3.5 h-3.5 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
<path stroke-linecap="round" stroke-linejoin="round" d="M20.25 8.511c.884.284 1.5 1.128 1.5 2.097v4.286c0 1.136-.847 2.1-1.98 2.193-.34.027-.68.052-1.02.072v3.091l-3-3c-1.354 0-2.694-.055-4.02-.163a2.115 2.115 0 01-.825-.242m9.345-8.334a2.126 2.126 0 00-.476-.095 48.64 48.64 0 00-8.048 0c-1.131.094-1.976 1.057-1.976 2.192v4.286c0 .837.46 1.58 1.155 1.951m9.345-8.334V6.637c0-1.621-1.152-3.026-2.76-3.235A48.455 48.455 0 0011.25 3c-2.115 0-4.198.137-6.24.402-1.608.209-2.76 1.614-2.76 3.235v6.226c0 1.621 1.152 3.026 2.76 3.235.577.075 1.157.14 1.74.194V21l4.155-4.155" />
</svg>
<span>{{ t('common.contactSupport') }}:</span>
<span class="font-medium text-gray-700 dark:text-gray-300">{{ contactInfo }}</span>
</div>
</div>
<div class="border-t border-gray-100 dark:border-dark-700 py-1">
<button
@click="handleLogout"
class="dropdown-item w-full text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20"
>
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
<path stroke-linecap="round" stroke-linejoin="round" d="M15.75 9V5.25A2.25 2.25 0 0013.5 3h-6a2.25 2.25 0 00-2.25 2.25v13.5A2.25 2.25 0 007.5 21h6a2.25 2.25 0 002.25-2.25V15M12 9l-3 3m0 0l3 3m-3-3h12.75" />
</svg>
{{ t('nav.logout') }}
</button>
</div>
</div>
</transition>
</div>
</div>
</div>
</header>
</template>
<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { useAppStore, useAuthStore } from '@/stores';
import { authAPI } from '@/api';
import LocaleSwitcher from '@/components/common/LocaleSwitcher.vue';
import SubscriptionProgressMini from '@/components/common/SubscriptionProgressMini.vue';
const router = useRouter();
const route = useRoute();
const { t } = useI18n();
const appStore = useAppStore();
const authStore = useAuthStore();
const user = computed(() => authStore.user);
const dropdownOpen = ref(false);
const dropdownRef = ref<HTMLElement | null>(null);
const contactInfo = ref('');
const userInitials = computed(() => {
if (!user.value) return '';
// Prefer username, fallback to email
if (user.value.username) {
return user.value.username.substring(0, 2).toUpperCase();
}
if (user.value.email) {
// Get the part before @ and take first 2 chars
const localPart = user.value.email.split('@')[0];
return localPart.substring(0, 2).toUpperCase();
}
return '';
});
const displayName = computed(() => {
if (!user.value) return '';
return user.value.username || user.value.email?.split('@')[0] || '';
});
const pageTitle = computed(() => {
const titleKey = route.meta.titleKey as string;
if (titleKey) {
return t(titleKey);
}
return (route.meta.title as string) || '';
});
const pageDescription = computed(() => {
const descKey = route.meta.descriptionKey as string;
if (descKey) {
return t(descKey);
}
return (route.meta.description as string) || '';
});
function toggleMobileSidebar() {
appStore.toggleSidebar();
}
function toggleDropdown() {
dropdownOpen.value = !dropdownOpen.value;
}
function closeDropdown() {
dropdownOpen.value = false;
}
async function handleLogout() {
closeDropdown();
authStore.logout();
await router.push('/login');
}
function handleClickOutside(event: MouseEvent) {
if (dropdownRef.value && !dropdownRef.value.contains(event.target as Node)) {
closeDropdown();
}
}
onMounted(async () => {
document.addEventListener('click', handleClickOutside);
try {
const settings = await authAPI.getPublicSettings();
contactInfo.value = settings.contact_info || '';
} catch (error) {
console.error('Failed to load contact info:', error);
}
});
onBeforeUnmount(() => {
document.removeEventListener('click', handleClickOutside);
});
</script>
<style scoped>
.dropdown-enter-active,
.dropdown-leave-active {
transition: all 0.2s ease;
}
.dropdown-enter-from,
.dropdown-leave-to {
opacity: 0;
transform: scale(0.95) translateY(-4px);
}
</style>

View File

@@ -0,0 +1,36 @@
<template>
<div class="min-h-screen bg-gray-50 dark:bg-dark-950">
<!-- Background Decoration -->
<div class="fixed inset-0 bg-mesh-gradient pointer-events-none"></div>
<!-- Sidebar -->
<AppSidebar />
<!-- Main Content Area -->
<div
class="relative min-h-screen transition-all duration-300"
:class="[
sidebarCollapsed ? 'lg:ml-[72px]' : 'lg:ml-64',
]"
>
<!-- Header -->
<AppHeader />
<!-- Main Content -->
<main class="p-4 md:p-6 lg:p-8">
<slot />
</main>
</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue';
import { useAppStore } from '@/stores';
import AppSidebar from './AppSidebar.vue';
import AppHeader from './AppHeader.vue';
const appStore = useAppStore();
const sidebarCollapsed = computed(() => appStore.sidebarCollapsed);
</script>

View File

@@ -0,0 +1,331 @@
<template>
<aside
class="sidebar"
:class="[
sidebarCollapsed ? 'w-[72px]' : 'w-64',
{ '-translate-x-full lg:translate-x-0': !mobileOpen }
]"
>
<!-- Logo/Brand -->
<div class="sidebar-header">
<!-- Custom Logo or Default Logo -->
<div class="w-9 h-9 rounded-xl overflow-hidden flex items-center justify-center shadow-glow">
<img :src="siteLogo || '/logo.png'" alt="Logo" class="w-full h-full object-contain" />
</div>
<transition name="fade">
<div v-if="!sidebarCollapsed" class="flex flex-col">
<span class="text-lg font-bold text-gray-900 dark:text-white">
{{ siteName }}
</span>
<!-- Version Badge -->
<VersionBadge :version="siteVersion" />
</div>
</transition>
</div>
<!-- Navigation -->
<nav class="sidebar-nav scrollbar-hide">
<!-- Admin View: Admin menu first, then personal menu -->
<template v-if="isAdmin">
<!-- Admin Section -->
<div class="sidebar-section">
<router-link
v-for="item in adminNavItems"
:key="item.path"
:to="item.path"
class="sidebar-link mb-1"
:class="{ 'sidebar-link-active': isActive(item.path) }"
:title="sidebarCollapsed ? item.label : undefined"
>
<component :is="item.icon" class="w-5 h-5 flex-shrink-0" />
<transition name="fade">
<span v-if="!sidebarCollapsed">{{ item.label }}</span>
</transition>
</router-link>
</div>
<!-- Personal Section for Admin -->
<div class="sidebar-section">
<div v-if="!sidebarCollapsed" class="sidebar-section-title">
{{ t('nav.myAccount') }}
</div>
<div v-else class="h-px bg-gray-200 dark:bg-dark-700 mx-3 my-3"></div>
<router-link
v-for="item in personalNavItems"
:key="item.path"
:to="item.path"
class="sidebar-link mb-1"
:class="{ 'sidebar-link-active': isActive(item.path) }"
:title="sidebarCollapsed ? item.label : undefined"
>
<component :is="item.icon" class="w-5 h-5 flex-shrink-0" />
<transition name="fade">
<span v-if="!sidebarCollapsed">{{ item.label }}</span>
</transition>
</router-link>
</div>
</template>
<!-- Regular User View -->
<template v-else>
<div class="sidebar-section">
<router-link
v-for="item in userNavItems"
:key="item.path"
:to="item.path"
class="sidebar-link mb-1"
:class="{ 'sidebar-link-active': isActive(item.path) }"
:title="sidebarCollapsed ? item.label : undefined"
>
<component :is="item.icon" class="w-5 h-5 flex-shrink-0" />
<transition name="fade">
<span v-if="!sidebarCollapsed">{{ item.label }}</span>
</transition>
</router-link>
</div>
</template>
</nav>
<!-- Bottom Section -->
<div class="mt-auto border-t border-gray-100 dark:border-dark-800 p-3">
<!-- Theme Toggle -->
<button
@click="toggleTheme"
class="sidebar-link w-full mb-2"
:title="sidebarCollapsed ? (isDark ? t('nav.lightMode') : t('nav.darkMode')) : undefined"
>
<SunIcon v-if="isDark" class="w-5 h-5 flex-shrink-0 text-amber-500" />
<MoonIcon v-else class="w-5 h-5 flex-shrink-0" />
<transition name="fade">
<span v-if="!sidebarCollapsed">{{ isDark ? t('nav.lightMode') : t('nav.darkMode') }}</span>
</transition>
</button>
<!-- Collapse Button -->
<button
@click="toggleSidebar"
class="sidebar-link w-full"
:title="sidebarCollapsed ? t('nav.expand') : t('nav.collapse')"
>
<ChevronDoubleLeftIcon v-if="!sidebarCollapsed" class="w-5 h-5 flex-shrink-0" />
<ChevronDoubleRightIcon v-else class="w-5 h-5 flex-shrink-0" />
<transition name="fade">
<span v-if="!sidebarCollapsed">{{ t('nav.collapse') }}</span>
</transition>
</button>
</div>
</aside>
<!-- Mobile Overlay -->
<transition name="fade">
<div
v-if="mobileOpen"
class="fixed inset-0 bg-black/50 z-30 lg:hidden"
@click="closeMobile"
></div>
</transition>
</template>
<script setup lang="ts">
import { computed, h, ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { useAppStore, useAuthStore } from '@/stores';
import { getPublicSettings } from '@/api/auth';
import VersionBadge from '@/components/common/VersionBadge.vue';
const { t } = useI18n();
const route = useRoute();
const appStore = useAppStore();
const authStore = useAuthStore();
const sidebarCollapsed = computed(() => appStore.sidebarCollapsed);
const isAdmin = computed(() => authStore.isAdmin);
const isDark = ref(document.documentElement.classList.contains('dark'));
const mobileOpen = ref(false);
// Site settings
const siteName = ref('Sub2API');
const siteLogo = ref('');
const siteVersion = ref('');
onMounted(async () => {
try {
const settings = await getPublicSettings();
siteName.value = settings.site_name || 'Sub2API';
siteLogo.value = settings.site_logo || '';
siteVersion.value = settings.version || '';
} catch (error) {
console.error('Failed to load public settings:', error);
}
});
// SVG Icon Components
const DashboardIcon = {
render: () => h('svg', { fill: 'none', viewBox: '0 0 24 24', stroke: 'currentColor', 'stroke-width': '1.5' }, [
h('path', { 'stroke-linecap': 'round', 'stroke-linejoin': 'round', d: 'M3.75 6A2.25 2.25 0 016 3.75h2.25A2.25 2.25 0 0110.5 6v2.25a2.25 2.25 0 01-2.25 2.25H6a2.25 2.25 0 01-2.25-2.25V6zM3.75 15.75A2.25 2.25 0 016 13.5h2.25a2.25 2.25 0 012.25 2.25V18a2.25 2.25 0 01-2.25 2.25H6A2.25 2.25 0 013.75 18v-2.25zM13.5 6a2.25 2.25 0 012.25-2.25H18A2.25 2.25 0 0120.25 6v2.25A2.25 2.25 0 0118 10.5h-2.25a2.25 2.25 0 01-2.25-2.25V6zM13.5 15.75a2.25 2.25 0 012.25-2.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-2.25A2.25 2.25 0 0113.5 18v-2.25z' })
])
};
const KeyIcon = {
render: () => h('svg', { fill: 'none', viewBox: '0 0 24 24', stroke: 'currentColor', 'stroke-width': '1.5' }, [
h('path', { 'stroke-linecap': 'round', 'stroke-linejoin': 'round', d: 'M15.75 5.25a3 3 0 013 3m3 0a6 6 0 01-7.029 5.912c-.563-.097-1.159.026-1.563.43L10.5 17.25H8.25v2.25H6v2.25H2.25v-2.818c0-.597.237-1.17.659-1.591l6.499-6.499c.404-.404.527-1 .43-1.563A6 6 0 1121.75 8.25z' })
])
};
const ChartIcon = {
render: () => h('svg', { fill: 'none', viewBox: '0 0 24 24', stroke: 'currentColor', 'stroke-width': '1.5' }, [
h('path', { 'stroke-linecap': 'round', 'stroke-linejoin': 'round', d: 'M3 13.125C3 12.504 3.504 12 4.125 12h2.25c.621 0 1.125.504 1.125 1.125v6.75C7.5 20.496 6.996 21 6.375 21h-2.25A1.125 1.125 0 013 19.875v-6.75zM9.75 8.625c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125v11.25c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 01-1.125-1.125V8.625zM16.5 4.125c0-.621.504-1.125 1.125-1.125h2.25C20.496 3 21 3.504 21 4.125v15.75c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 01-1.125-1.125V4.125z' })
])
};
const GiftIcon = {
render: () => h('svg', { fill: 'none', viewBox: '0 0 24 24', stroke: 'currentColor', 'stroke-width': '1.5' }, [
h('path', { 'stroke-linecap': 'round', 'stroke-linejoin': 'round', d: 'M21 11.25v8.25a1.5 1.5 0 01-1.5 1.5H5.25a1.5 1.5 0 01-1.5-1.5v-8.25M12 4.875A2.625 2.625 0 109.375 7.5H12m0-2.625V7.5m0-2.625A2.625 2.625 0 1114.625 7.5H12m0 0V21m-8.625-9.75h18c.621 0 1.125-.504 1.125-1.125v-1.5c0-.621-.504-1.125-1.125-1.125h-18c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125z' })
])
};
const UserIcon = {
render: () => h('svg', { fill: 'none', viewBox: '0 0 24 24', stroke: 'currentColor', 'stroke-width': '1.5' }, [
h('path', { 'stroke-linecap': 'round', 'stroke-linejoin': 'round', d: 'M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z' })
])
};
const UsersIcon = {
render: () => h('svg', { fill: 'none', viewBox: '0 0 24 24', stroke: 'currentColor', 'stroke-width': '1.5' }, [
h('path', { 'stroke-linecap': 'round', 'stroke-linejoin': 'round', d: 'M15 19.128a9.38 9.38 0 002.625.372 9.337 9.337 0 004.121-.952 4.125 4.125 0 00-7.533-2.493M15 19.128v-.003c0-1.113-.285-2.16-.786-3.07M15 19.128v.106A12.318 12.318 0 018.624 21c-2.331 0-4.512-.645-6.374-1.766l-.001-.109a6.375 6.375 0 0111.964-3.07M12 6.375a3.375 3.375 0 11-6.75 0 3.375 3.375 0 016.75 0zm8.25 2.25a2.625 2.625 0 11-5.25 0 2.625 2.625 0 015.25 0z' })
])
};
const FolderIcon = {
render: () => h('svg', { fill: 'none', viewBox: '0 0 24 24', stroke: 'currentColor', 'stroke-width': '1.5' }, [
h('path', { 'stroke-linecap': 'round', 'stroke-linejoin': 'round', d: 'M2.25 12.75V12A2.25 2.25 0 014.5 9.75h15A2.25 2.25 0 0121.75 12v.75m-8.69-6.44l-2.12-2.12a1.5 1.5 0 00-1.061-.44H4.5A2.25 2.25 0 002.25 6v12a2.25 2.25 0 002.25 2.25h15A2.25 2.25 0 0021.75 18V9a2.25 2.25 0 00-2.25-2.25h-5.379a1.5 1.5 0 01-1.06-.44z' })
])
};
const CreditCardIcon = {
render: () => h('svg', { fill: 'none', viewBox: '0 0 24 24', stroke: 'currentColor', 'stroke-width': '1.5' }, [
h('path', { 'stroke-linecap': 'round', 'stroke-linejoin': 'round', d: 'M2.25 8.25h19.5M2.25 9h19.5m-16.5 5.25h6m-6 2.25h3m-3.75 3h15a2.25 2.25 0 002.25-2.25V6.75A2.25 2.25 0 0019.5 4.5h-15a2.25 2.25 0 00-2.25 2.25v10.5A2.25 2.25 0 004.5 19.5z' })
])
};
const GlobeIcon = {
render: () => h('svg', { fill: 'none', viewBox: '0 0 24 24', stroke: 'currentColor', 'stroke-width': '1.5' }, [
h('path', { 'stroke-linecap': 'round', 'stroke-linejoin': 'round', d: 'M12 21a9.004 9.004 0 008.716-6.747M12 21a9.004 9.004 0 01-8.716-6.747M12 21c2.485 0 4.5-4.03 4.5-9S14.485 3 12 3m0 18c-2.485 0-4.5-4.03-4.5-9S9.515 3 12 3m0 0a8.997 8.997 0 017.843 4.582M12 3a8.997 8.997 0 00-7.843 4.582m15.686 0A11.953 11.953 0 0112 10.5c-2.998 0-5.74-1.1-7.843-2.918m15.686 0A8.959 8.959 0 0121 12c0 .778-.099 1.533-.284 2.253m0 0A17.919 17.919 0 0112 16.5c-3.162 0-6.133-.815-8.716-2.247m0 0A9.015 9.015 0 013 12c0-1.605.42-3.113 1.157-4.418' })
])
};
const ServerIcon = {
render: () => h('svg', { fill: 'none', viewBox: '0 0 24 24', stroke: 'currentColor', 'stroke-width': '1.5' }, [
h('path', { 'stroke-linecap': 'round', 'stroke-linejoin': 'round', d: 'M5.25 14.25h13.5m-13.5 0a3 3 0 01-3-3m3 3a3 3 0 100 6h13.5a3 3 0 100-6m-16.5-3a3 3 0 013-3h13.5a3 3 0 013 3m-19.5 0a4.5 4.5 0 01.9-2.7L5.737 5.1a3.375 3.375 0 012.7-1.35h7.126c1.062 0 2.062.5 2.7 1.35l2.587 3.45a4.5 4.5 0 01.9 2.7m0 0a3 3 0 01-3 3m0 3h.008v.008h-.008v-.008zm0-6h.008v.008h-.008v-.008zm-3 6h.008v.008h-.008v-.008zm0-6h.008v.008h-.008v-.008z' })
])
};
const TicketIcon = {
render: () => h('svg', { fill: 'none', viewBox: '0 0 24 24', stroke: 'currentColor', 'stroke-width': '1.5' }, [
h('path', { 'stroke-linecap': 'round', 'stroke-linejoin': 'round', d: 'M16.5 6v.75m0 3v.75m0 3v.75m0 3V18m-9-5.25h5.25M7.5 15h3M3.375 5.25c-.621 0-1.125.504-1.125 1.125v3.026a2.999 2.999 0 010 5.198v3.026c0 .621.504 1.125 1.125 1.125h17.25c.621 0 1.125-.504 1.125-1.125v-3.026a2.999 2.999 0 010-5.198V6.375c0-.621-.504-1.125-1.125-1.125H3.375z' })
])
};
const CogIcon = {
render: () => h('svg', { fill: 'none', viewBox: '0 0 24 24', stroke: 'currentColor', 'stroke-width': '1.5' }, [
h('path', { 'stroke-linecap': 'round', 'stroke-linejoin': 'round', d: 'M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.324.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 011.37.49l1.296 2.247a1.125 1.125 0 01-.26 1.431l-1.003.827c-.293.24-.438.613-.431.992a6.759 6.759 0 010 .255c-.007.378.138.75.43.99l1.005.828c.424.35.534.954.26 1.43l-1.298 2.247a1.125 1.125 0 01-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.57 6.57 0 01-.22.128c-.331.183-.581.495-.644.869l-.213 1.28c-.09.543-.56.941-1.11.941h-2.594c-.55 0-1.02-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 01-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 01-1.369-.49l-1.297-2.247a1.125 1.125 0 01.26-1.431l1.004-.827c.292-.24.437-.613.43-.992a6.932 6.932 0 010-.255c.007-.378-.138-.75-.43-.99l-1.004-.828a1.125 1.125 0 01-.26-1.43l1.297-2.247a1.125 1.125 0 011.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.087.22-.128.332-.183.582-.495.644-.869l.214-1.281z' }),
h('path', { 'stroke-linecap': 'round', 'stroke-linejoin': 'round', d: 'M15 12a3 3 0 11-6 0 3 3 0 016 0z' })
])
};
const SunIcon = {
render: () => h('svg', { fill: 'none', viewBox: '0 0 24 24', stroke: 'currentColor', 'stroke-width': '1.5' }, [
h('path', { 'stroke-linecap': 'round', 'stroke-linejoin': 'round', d: 'M12 3v2.25m6.364.386l-1.591 1.591M21 12h-2.25m-.386 6.364l-1.591-1.591M12 18.75V21m-4.773-4.227l-1.591 1.591M5.25 12H3m4.227-4.773L5.636 5.636M15.75 12a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0z' })
])
};
const MoonIcon = {
render: () => h('svg', { fill: 'none', viewBox: '0 0 24 24', stroke: 'currentColor', 'stroke-width': '1.5' }, [
h('path', { 'stroke-linecap': 'round', 'stroke-linejoin': 'round', d: 'M21.752 15.002A9.718 9.718 0 0118 15.75c-5.385 0-9.75-4.365-9.75-9.75 0-1.33.266-2.597.748-3.752A9.753 9.753 0 003 11.25C3 16.635 7.365 21 12.75 21a9.753 9.753 0 009.002-5.998z' })
])
};
const ChevronDoubleLeftIcon = {
render: () => h('svg', { fill: 'none', viewBox: '0 0 24 24', stroke: 'currentColor', 'stroke-width': '1.5' }, [
h('path', { 'stroke-linecap': 'round', 'stroke-linejoin': 'round', d: 'm18.75 4.5-7.5 7.5 7.5 7.5m-6-15L5.25 12l7.5 7.5' })
])
};
const ChevronDoubleRightIcon = {
render: () => h('svg', { fill: 'none', viewBox: '0 0 24 24', stroke: 'currentColor', 'stroke-width': '1.5' }, [
h('path', { 'stroke-linecap': 'round', 'stroke-linejoin': 'round', d: 'm5.25 4.5 7.5 7.5-7.5 7.5m6-15 7.5 7.5-7.5 7.5' })
])
};
// User navigation items (for regular users)
const userNavItems = computed(() => [
{ path: '/dashboard', label: t('nav.dashboard'), icon: DashboardIcon },
{ path: '/keys', label: t('nav.apiKeys'), icon: KeyIcon },
{ path: '/usage', label: t('nav.usage'), icon: ChartIcon },
{ path: '/subscriptions', label: t('nav.mySubscriptions'), icon: CreditCardIcon },
{ path: '/redeem', label: t('nav.redeem'), icon: GiftIcon },
{ path: '/profile', label: t('nav.profile'), icon: UserIcon },
]);
// Personal navigation items (for admin's "My Account" section, without Dashboard)
const personalNavItems = computed(() => [
{ path: '/keys', label: t('nav.apiKeys'), icon: KeyIcon },
{ path: '/usage', label: t('nav.usage'), icon: ChartIcon },
{ path: '/subscriptions', label: t('nav.mySubscriptions'), icon: CreditCardIcon },
{ path: '/redeem', label: t('nav.redeem'), icon: GiftIcon },
{ path: '/profile', label: t('nav.profile'), icon: UserIcon },
]);
// Admin navigation items
const adminNavItems = computed(() => [
{ path: '/admin/dashboard', label: t('nav.dashboard'), icon: DashboardIcon },
{ path: '/admin/users', label: t('nav.users'), icon: UsersIcon },
{ path: '/admin/groups', label: t('nav.groups'), icon: FolderIcon },
{ path: '/admin/subscriptions', label: t('nav.subscriptions'), icon: CreditCardIcon },
{ path: '/admin/accounts', label: t('nav.accounts'), icon: GlobeIcon },
{ path: '/admin/proxies', label: t('nav.proxies'), icon: ServerIcon },
{ path: '/admin/redeem', label: t('nav.redeemCodes'), icon: TicketIcon },
{ path: '/admin/usage', label: t('nav.usage'), icon: ChartIcon },
{ path: '/admin/settings', label: t('nav.settings'), icon: CogIcon },
]);
function toggleSidebar() {
appStore.toggleSidebar();
}
function toggleTheme() {
isDark.value = !isDark.value;
document.documentElement.classList.toggle('dark', isDark.value);
localStorage.setItem('theme', isDark.value ? 'dark' : 'light');
}
function closeMobile() {
mobileOpen.value = false;
}
function isActive(path: string): boolean {
return route.path === path || route.path.startsWith(path + '/');
}
// Initialize theme
const savedTheme = localStorage.getItem('theme');
if (savedTheme === 'dark' || (!savedTheme && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
isDark.value = true;
document.documentElement.classList.add('dark');
}
</script>
<style scoped>
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.2s ease;
}
.fade-enter-from,
.fade-leave-to {
opacity: 0;
}
</style>

View File

@@ -0,0 +1,77 @@
<template>
<div class="min-h-screen flex items-center justify-center p-4 relative overflow-hidden">
<!-- Background -->
<div class="absolute inset-0 bg-gradient-to-br from-gray-50 via-primary-50/30 to-gray-100 dark:from-dark-950 dark:via-dark-900 dark:to-dark-950"></div>
<!-- Decorative Elements -->
<div class="absolute inset-0 overflow-hidden pointer-events-none">
<!-- Gradient Orbs -->
<div class="absolute -top-40 -right-40 w-80 h-80 bg-primary-400/20 rounded-full blur-3xl"></div>
<div class="absolute -bottom-40 -left-40 w-80 h-80 bg-primary-500/15 rounded-full blur-3xl"></div>
<div class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-96 h-96 bg-primary-300/10 rounded-full blur-3xl"></div>
<!-- Grid Pattern -->
<div class="absolute inset-0 bg-[linear-gradient(rgba(20,184,166,0.03)_1px,transparent_1px),linear-gradient(90deg,rgba(20,184,166,0.03)_1px,transparent_1px)] bg-[size:64px_64px]"></div>
</div>
<!-- Content Container -->
<div class="relative w-full max-w-md z-10">
<!-- Logo/Brand -->
<div class="text-center mb-8">
<!-- Custom Logo or Default Logo -->
<div class="inline-flex items-center justify-center w-16 h-16 rounded-2xl overflow-hidden shadow-lg shadow-primary-500/30 mb-4">
<img :src="siteLogo || '/logo.png'" alt="Logo" class="w-full h-full object-contain" />
</div>
<h1 class="text-3xl font-bold text-gradient mb-2">
{{ siteName }}
</h1>
<p class="text-sm text-gray-500 dark:text-dark-400">
{{ siteSubtitle }}
</p>
</div>
<!-- Card Container -->
<div class="card-glass rounded-2xl p-8 shadow-glass">
<slot />
</div>
<!-- Footer Links -->
<div class="text-center mt-6 text-sm">
<slot name="footer" />
</div>
<!-- Copyright -->
<div class="text-center mt-8 text-xs text-gray-400 dark:text-dark-500">
&copy; {{ currentYear }} {{ siteName }}. All rights reserved.
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { getPublicSettings } from '@/api/auth';
const siteName = ref('Sub2API');
const siteLogo = ref('');
const siteSubtitle = ref('Subscription to API Conversion Platform');
const currentYear = computed(() => new Date().getFullYear());
onMounted(async () => {
try {
const settings = await getPublicSettings();
siteName.value = settings.site_name || 'Sub2API';
siteLogo.value = settings.site_logo || '';
siteSubtitle.value = settings.site_subtitle || 'Subscription to API Conversion Platform';
} catch (error) {
console.error('Failed to load public settings:', error);
}
});
</script>
<style scoped>
.text-gradient {
@apply bg-gradient-to-r from-primary-600 to-primary-500 bg-clip-text text-transparent;
}
</style>

View File

@@ -0,0 +1,424 @@
# Layout Component Examples
## Example 1: Dashboard Page
```vue
<template>
<AppLayout>
<div class="space-y-6">
<h1 class="text-3xl font-bold text-gray-900">Dashboard</h1>
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
<!-- Stats Cards -->
<div class="bg-white p-6 rounded-lg shadow">
<div class="text-sm text-gray-600">API Keys</div>
<div class="text-2xl font-bold text-gray-900">5</div>
</div>
<div class="bg-white p-6 rounded-lg shadow">
<div class="text-sm text-gray-600">Total Usage</div>
<div class="text-2xl font-bold text-gray-900">1,234</div>
</div>
<div class="bg-white p-6 rounded-lg shadow">
<div class="text-sm text-gray-600">Balance</div>
<div class="text-2xl font-bold text-indigo-600">${{ balance }}</div>
</div>
<div class="bg-white p-6 rounded-lg shadow">
<div class="text-sm text-gray-600">Status</div>
<div class="text-2xl font-bold text-green-600">Active</div>
</div>
</div>
<div class="bg-white p-6 rounded-lg shadow">
<h2 class="text-xl font-semibold mb-4">Recent Activity</h2>
<p class="text-gray-600">No recent activity</p>
</div>
</div>
</AppLayout>
</template>
<script setup lang="ts">
import { computed } from 'vue';
import { AppLayout } from '@/components/layout';
import { useAuthStore } from '@/stores';
const authStore = useAuthStore();
const balance = computed(() => authStore.user?.balance.toFixed(2) || '0.00');
</script>
```
---
## Example 2: Login Page
```vue
<template>
<AuthLayout>
<h2 class="text-2xl font-bold text-gray-900 mb-6">Welcome Back</h2>
<form @submit.prevent="handleSubmit" class="space-y-4">
<div>
<label for="username" class="block text-sm font-medium text-gray-700 mb-1">
Username
</label>
<input
id="username"
v-model="form.username"
type="text"
required
class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
placeholder="Enter your username"
/>
</div>
<div>
<label for="password" class="block text-sm font-medium text-gray-700 mb-1">
Password
</label>
<input
id="password"
v-model="form.password"
type="password"
required
class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
placeholder="Enter your password"
/>
</div>
<button
type="submit"
:disabled="loading"
class="w-full bg-indigo-600 text-white py-2 px-4 rounded-lg hover:bg-indigo-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
{{ loading ? 'Logging in...' : 'Login' }}
</button>
</form>
<template #footer>
<p class="text-gray-600">
Don't have an account?
<router-link to="/register" class="text-indigo-600 hover:underline font-medium">
Sign up
</router-link>
</p>
</template>
</AuthLayout>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { AuthLayout } from '@/components/layout';
import { useAuthStore, useAppStore } from '@/stores';
const router = useRouter();
const authStore = useAuthStore();
const appStore = useAppStore();
const form = ref({
username: '',
password: '',
});
const loading = ref(false);
async function handleSubmit() {
loading.value = true;
try {
await authStore.login(form.value);
appStore.showSuccess('Login successful!');
await router.push('/dashboard');
} catch (error) {
appStore.showError('Invalid username or password');
} finally {
loading.value = false;
}
}
</script>
```
---
## Example 3: API Keys Page with Custom Header Title
```vue
<template>
<AppLayout>
<div class="space-y-6">
<!-- Custom page header -->
<div class="flex items-center justify-between">
<h1 class="text-3xl font-bold text-gray-900">API Keys</h1>
<button
@click="showCreateModal = true"
class="bg-indigo-600 text-white px-4 py-2 rounded-lg hover:bg-indigo-700 transition-colors"
>
Create New Key
</button>
</div>
<!-- API Keys List -->
<div class="bg-white rounded-lg shadow overflow-hidden">
<table class="min-w-full divide-y divide-gray-200">
<thead class="bg-gray-50">
<tr>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
Name
</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
Key
</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
Status
</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
Created
</th>
<th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">
Actions
</th>
</tr>
</thead>
<tbody class="bg-white divide-y divide-gray-200">
<tr v-for="key in apiKeys" :key="key.id">
<td class="px-6 py-4 whitespace-nowrap">{{ key.name }}</td>
<td class="px-6 py-4 font-mono text-sm">{{ key.key }}</td>
<td class="px-6 py-4">
<span
class="px-2 py-1 text-xs rounded-full"
:class="key.status === 'active' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'"
>
{{ key.status }}
</span>
</td>
<td class="px-6 py-4 text-sm text-gray-500">
{{ new Date(key.created_at).toLocaleDateString() }}
</td>
<td class="px-6 py-4 text-right">
<button class="text-red-600 hover:text-red-800 text-sm">
Delete
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</AppLayout>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { AppLayout } from '@/components/layout';
import type { ApiKey } from '@/types';
const showCreateModal = ref(false);
const apiKeys = ref<ApiKey[]>([]);
// Fetch API keys on mount
// fetchApiKeys();
</script>
```
---
## Example 4: Admin Users Page
```vue
<template>
<AppLayout>
<div class="space-y-6">
<div class="flex items-center justify-between">
<h1 class="text-3xl font-bold text-gray-900">User Management</h1>
<button
@click="showCreateUser = true"
class="bg-indigo-600 text-white px-4 py-2 rounded-lg hover:bg-indigo-700 transition-colors"
>
Create User
</button>
</div>
<!-- Users Table -->
<div class="bg-white rounded-lg shadow">
<div class="p-6">
<div class="space-y-4">
<div v-for="user in users" :key="user.id" class="flex items-center justify-between border-b pb-4">
<div>
<div class="font-medium text-gray-900">{{ user.username }}</div>
<div class="text-sm text-gray-500">{{ user.email }}</div>
</div>
<div class="flex items-center space-x-4">
<span
class="px-2 py-1 text-xs rounded-full"
:class="user.role === 'admin' ? 'bg-purple-100 text-purple-800' : 'bg-blue-100 text-blue-800'"
>
{{ user.role }}
</span>
<span class="text-sm font-medium text-gray-700">
${{ user.balance.toFixed(2) }}
</span>
<button class="text-indigo-600 hover:text-indigo-800 text-sm">
Edit
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</AppLayout>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { AppLayout } from '@/components/layout';
import type { User } from '@/types';
const showCreateUser = ref(false);
const users = ref<User[]>([]);
// Fetch users on mount
// fetchUsers();
</script>
```
---
## Example 5: Profile Page
```vue
<template>
<AppLayout>
<div class="max-w-2xl space-y-6">
<h1 class="text-3xl font-bold text-gray-900">Profile Settings</h1>
<!-- User Info Card -->
<div class="bg-white rounded-lg shadow p-6 space-y-4">
<h2 class="text-xl font-semibold text-gray-900">Account Information</h2>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">
Username
</label>
<div class="px-3 py-2 bg-gray-50 rounded-lg text-gray-900">
{{ user?.username }}
</div>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">
Email
</label>
<div class="px-3 py-2 bg-gray-50 rounded-lg text-gray-900">
{{ user?.email }}
</div>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">
Role
</label>
<div class="px-3 py-2 bg-gray-50 rounded-lg">
<span
class="px-2 py-1 text-xs rounded-full"
:class="user?.role === 'admin' ? 'bg-purple-100 text-purple-800' : 'bg-blue-100 text-blue-800'"
>
{{ user?.role }}
</span>
</div>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">
Balance
</label>
<div class="px-3 py-2 bg-gray-50 rounded-lg text-indigo-600 font-semibold">
${{ user?.balance.toFixed(2) }}
</div>
</div>
</div>
</div>
<!-- Change Password Card -->
<div class="bg-white rounded-lg shadow p-6 space-y-4">
<h2 class="text-xl font-semibold text-gray-900">Change Password</h2>
<form @submit.prevent="handleChangePassword" class="space-y-4">
<div>
<label for="old-password" class="block text-sm font-medium text-gray-700 mb-1">
Current Password
</label>
<input
id="old-password"
v-model="passwordForm.old_password"
type="password"
required
class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500"
/>
</div>
<div>
<label for="new-password" class="block text-sm font-medium text-gray-700 mb-1">
New Password
</label>
<input
id="new-password"
v-model="passwordForm.new_password"
type="password"
required
class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500"
/>
</div>
<button
type="submit"
class="bg-indigo-600 text-white px-4 py-2 rounded-lg hover:bg-indigo-700 transition-colors"
>
Update Password
</button>
</form>
</div>
</div>
</AppLayout>
</template>
<script setup lang="ts">
import { ref, computed } from 'vue';
import { AppLayout } from '@/components/layout';
import { useAuthStore, useAppStore } from '@/stores';
const authStore = useAuthStore();
const appStore = useAppStore();
const user = computed(() => authStore.user);
const passwordForm = ref({
old_password: '',
new_password: '',
});
async function handleChangePassword() {
try {
// await changePasswordAPI(passwordForm.value);
appStore.showSuccess('Password updated successfully!');
passwordForm.value = { old_password: '', new_password: '' };
} catch (error) {
appStore.showError('Failed to update password');
}
}
</script>
```
---
## Tips for Using Layouts
1. **Page Titles**: Set route meta to automatically display page titles in the header
2. **Loading States**: Use `appStore.setLoading(true/false)` for global loading indicators
3. **Toast Notifications**: Use `appStore.showSuccess()`, `appStore.showError()`, etc.
4. **Authentication**: All authenticated pages should use `AppLayout`
5. **Auth Pages**: Login and Register pages should use `AuthLayout`
6. **Sidebar State**: The sidebar state persists across navigation
7. **Mobile First**: All examples are responsive by default using Tailwind's mobile-first approach

View File

@@ -0,0 +1,480 @@
# Layout Components Integration Guide
## Quick Start
### 1. Import Layout Components
```typescript
// In your view files
import { AppLayout, AuthLayout } from '@/components/layout';
```
### 2. Use in Routes
```typescript
// src/router/index.ts
import { createRouter, createWebHistory } from 'vue-router';
import type { RouteRecordRaw } from 'vue-router';
// Views
import DashboardView from '@/views/DashboardView.vue';
import LoginView from '@/views/auth/LoginView.vue';
import RegisterView from '@/views/auth/RegisterView.vue';
const routes: RouteRecordRaw[] = [
// Auth routes (no layout needed - views use AuthLayout internally)
{
path: '/login',
name: 'Login',
component: LoginView,
meta: { requiresAuth: false },
},
{
path: '/register',
name: 'Register',
component: RegisterView,
meta: { requiresAuth: false },
},
// User routes (use AppLayout)
{
path: '/dashboard',
name: 'Dashboard',
component: DashboardView,
meta: { requiresAuth: true, title: 'Dashboard' },
},
{
path: '/api-keys',
name: 'ApiKeys',
component: () => import('@/views/ApiKeysView.vue'),
meta: { requiresAuth: true, title: 'API Keys' },
},
{
path: '/usage',
name: 'Usage',
component: () => import('@/views/UsageView.vue'),
meta: { requiresAuth: true, title: 'Usage Statistics' },
},
{
path: '/redeem',
name: 'Redeem',
component: () => import('@/views/RedeemView.vue'),
meta: { requiresAuth: true, title: 'Redeem Code' },
},
{
path: '/profile',
name: 'Profile',
component: () => import('@/views/ProfileView.vue'),
meta: { requiresAuth: true, title: 'Profile Settings' },
},
// Admin routes (use AppLayout, admin only)
{
path: '/admin/dashboard',
name: 'AdminDashboard',
component: () => import('@/views/admin/DashboardView.vue'),
meta: { requiresAuth: true, requiresAdmin: true, title: 'Admin Dashboard' },
},
{
path: '/admin/users',
name: 'AdminUsers',
component: () => import('@/views/admin/UsersView.vue'),
meta: { requiresAuth: true, requiresAdmin: true, title: 'User Management' },
},
{
path: '/admin/groups',
name: 'AdminGroups',
component: () => import('@/views/admin/GroupsView.vue'),
meta: { requiresAuth: true, requiresAdmin: true, title: 'Groups' },
},
{
path: '/admin/accounts',
name: 'AdminAccounts',
component: () => import('@/views/admin/AccountsView.vue'),
meta: { requiresAuth: true, requiresAdmin: true, title: 'Accounts' },
},
{
path: '/admin/proxies',
name: 'AdminProxies',
component: () => import('@/views/admin/ProxiesView.vue'),
meta: { requiresAuth: true, requiresAdmin: true, title: 'Proxies' },
},
{
path: '/admin/redeem-codes',
name: 'AdminRedeemCodes',
component: () => import('@/views/admin/RedeemCodesView.vue'),
meta: { requiresAuth: true, requiresAdmin: true, title: 'Redeem Codes' },
},
// Default redirect
{
path: '/',
redirect: '/dashboard',
},
];
const router = createRouter({
history: createWebHistory(),
routes,
});
// Navigation guards
router.beforeEach((to, from, next) => {
const authStore = useAuthStore();
if (to.meta.requiresAuth && !authStore.isAuthenticated) {
// Redirect to login if not authenticated
next('/login');
} else if (to.meta.requiresAdmin && !authStore.isAdmin) {
// Redirect to dashboard if not admin
next('/dashboard');
} else {
next();
}
});
export default router;
```
### 3. Initialize Stores in main.ts
```typescript
// src/main.ts
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';
import router from './router';
import './style.css';
const app = createApp(App);
const pinia = createPinia();
app.use(pinia);
app.use(router);
// Initialize auth state on app startup
import { useAuthStore } from '@/stores';
const authStore = useAuthStore();
authStore.checkAuth();
app.mount('#app');
```
### 4. Update App.vue
```vue
<!-- src/App.vue -->
<template>
<router-view />
</template>
<script setup lang="ts">
// App.vue just renders the router view
// Layouts are handled by individual views
</script>
```
---
## View Component Templates
### Authenticated Page Template
```vue
<!-- src/views/DashboardView.vue -->
<template>
<AppLayout>
<div class="space-y-6">
<h1 class="text-3xl font-bold text-gray-900">Dashboard</h1>
<!-- Your content here -->
</div>
</AppLayout>
</template>
<script setup lang="ts">
import { AppLayout } from '@/components/layout';
// Your component logic here
</script>
```
### Auth Page Template
```vue
<!-- src/views/auth/LoginView.vue -->
<template>
<AuthLayout>
<h2 class="text-2xl font-bold text-gray-900 mb-6">Login</h2>
<!-- Your login form here -->
<template #footer>
<p class="text-gray-600">
Don't have an account?
<router-link to="/register" class="text-indigo-600 hover:underline">
Sign up
</router-link>
</p>
</template>
</AuthLayout>
</template>
<script setup lang="ts">
import { AuthLayout } from '@/components/layout';
// Your login logic here
</script>
```
---
## Customization
### Changing Colors
The components use Tailwind's indigo color scheme by default. To change:
```vue
<!-- Change all instances of indigo-* to your preferred color -->
<div class="bg-blue-600"> <!-- Instead of bg-indigo-600 -->
<div class="text-blue-600"> <!-- Instead of text-indigo-600 -->
```
### Adding Custom Icons
Replace HTML entity icons with your preferred icon library:
```vue
<!-- Before (HTML entities) -->
<span class="text-lg">&#128200;</span>
<!-- After (Heroicons example) -->
<ChartBarIcon class="w-5 h-5" />
```
### Sidebar Customization
Modify navigation items in `AppSidebar.vue`:
```typescript
// Add/remove/modify navigation items
const userNavItems = [
{ path: '/dashboard', label: 'Dashboard', icon: '&#128200;' },
{ path: '/new-page', label: 'New Page', icon: '&#128196;' }, // Add new item
// ...
];
```
### Header Customization
Modify user dropdown in `AppHeader.vue`:
```vue
<!-- Add new dropdown items -->
<router-link
to="/settings"
@click="closeDropdown"
class="flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
>
<span class="mr-2">&#9881;</span>
Settings
</router-link>
```
---
## Mobile Responsive Behavior
### Sidebar
- **Desktop (md+)**: Always visible, can be collapsed to icon-only view
- **Mobile**: Hidden by default, shown via menu toggle in header
### Header
- **Desktop**: Shows full user info and balance
- **Mobile**: Shows compact view with hamburger menu
To improve mobile experience, you can add overlay and transitions:
```vue
<!-- AppSidebar.vue enhancement for mobile -->
<aside
class="fixed left-0 top-0 h-screen transition-transform duration-300 z-40"
:class="[
sidebarCollapsed ? 'w-16' : 'w-64',
// Hide on mobile when collapsed
'md:translate-x-0',
sidebarCollapsed ? '-translate-x-full md:translate-x-0' : 'translate-x-0'
]"
>
<!-- ... -->
</aside>
<!-- Add overlay for mobile -->
<div
v-if="!sidebarCollapsed"
@click="toggleSidebar"
class="fixed inset-0 bg-black bg-opacity-50 z-30 md:hidden"
></div>
```
---
## State Management Integration
### Auth Store Usage
```typescript
import { useAuthStore } from '@/stores';
const authStore = useAuthStore();
// Check if user is authenticated
if (authStore.isAuthenticated) {
// User is logged in
}
// Check if user is admin
if (authStore.isAdmin) {
// User has admin role
}
// Get current user
const user = authStore.user;
```
### App Store Usage
```typescript
import { useAppStore } from '@/stores';
const appStore = useAppStore();
// Toggle sidebar
appStore.toggleSidebar();
// Show notifications
appStore.showSuccess('Operation completed!');
appStore.showError('Something went wrong');
appStore.showInfo('Did you know...');
appStore.showWarning('Be careful!');
// Loading state
appStore.setLoading(true);
// ... perform operation
appStore.setLoading(false);
// Or use helper
await appStore.withLoading(async () => {
// Your async operation
});
```
---
## Accessibility Features
All layout components include:
- **Semantic HTML**: Proper use of `<nav>`, `<header>`, `<main>`, `<aside>`
- **ARIA labels**: Buttons have descriptive labels
- **Keyboard navigation**: All interactive elements are keyboard accessible
- **Focus management**: Proper focus states with Tailwind's `focus:` utilities
- **Color contrast**: WCAG AA compliant color combinations
To enhance further:
```vue
<!-- Add skip to main content link -->
<a
href="#main-content"
class="sr-only focus:not-sr-only focus:absolute focus:top-4 focus:left-4 bg-white px-4 py-2 rounded"
>
Skip to main content
</a>
<main id="main-content">
<!-- Content -->
</main>
```
---
## Testing
### Unit Testing Layout Components
```typescript
// AppHeader.test.ts
import { describe, it, expect, beforeEach } from 'vitest';
import { mount } from '@vue/test-utils';
import { createPinia, setActivePinia } from 'pinia';
import AppHeader from '@/components/layout/AppHeader.vue';
describe('AppHeader', () => {
beforeEach(() => {
setActivePinia(createPinia());
});
it('renders user info when authenticated', () => {
const wrapper = mount(AppHeader);
// Add assertions
});
it('shows dropdown when clicked', async () => {
const wrapper = mount(AppHeader);
await wrapper.find('button').trigger('click');
expect(wrapper.find('.dropdown').exists()).toBe(true);
});
});
```
---
## Performance Optimization
### Lazy Loading
Views using layouts are already lazy loaded in the router example above.
### Code Splitting
Layout components are automatically code-split when imported:
```typescript
// This creates a separate chunk for layout components
import { AppLayout } from '@/components/layout';
```
### Reducing Re-renders
Layout components use `computed` refs to prevent unnecessary re-renders:
```typescript
const sidebarCollapsed = computed(() => appStore.sidebarCollapsed);
// This only re-renders when sidebarCollapsed changes
```
---
## Troubleshooting
### Sidebar not showing
- Check if `useAppStore` is properly initialized
- Verify Tailwind classes are being processed
- Check z-index conflicts with other components
### Routes not highlighting in sidebar
- Ensure route paths match exactly
- Check `isActive()` function logic
- Verify `useRoute()` is working correctly
### User info not displaying
- Ensure auth store is initialized with `checkAuth()`
- Verify user is logged in
- Check localStorage for auth data
### Mobile menu not working
- Verify `toggleSidebar()` is called correctly
- Check responsive breakpoints (md:)
- Test on actual mobile device or browser dev tools

View File

@@ -0,0 +1,212 @@
# Layout Components
Vue 3 layout components for the Sub2API frontend, built with Composition API, TypeScript, and TailwindCSS.
## Components
### 1. AppLayout.vue
Main application layout with sidebar and header.
**Usage:**
```vue
<template>
<AppLayout>
<!-- Your page content here -->
<h1>Dashboard</h1>
<p>Welcome to your dashboard!</p>
</AppLayout>
</template>
<script setup lang="ts">
import { AppLayout } from '@/components/layout';
</script>
```
**Features:**
- Responsive sidebar (collapsible)
- Fixed header at top
- Main content area with slot
- Automatically adjusts margin based on sidebar state
---
### 2. AppSidebar.vue
Navigation sidebar with user and admin sections.
**Features:**
- Logo/brand at top
- User navigation links:
- Dashboard
- API Keys
- Usage
- Redeem
- Profile
- Admin navigation links (shown only if user is admin):
- Admin Dashboard
- Users
- Groups
- Accounts
- Proxies
- Redeem Codes
- Collapsible sidebar with toggle button
- Active route highlighting
- Icons using HTML entities
- Responsive (mobile-friendly)
**Used automatically by AppLayout** - no need to import separately.
---
### 3. AppHeader.vue
Top header with user info and actions.
**Features:**
- Mobile menu toggle button
- Page title (from route meta or slot)
- User balance display (desktop only)
- User dropdown menu with:
- Profile link
- Logout button
- User avatar with initials
- Click-outside handling for dropdown
- Responsive design
**Usage with custom title:**
```vue
<template>
<AppLayout>
<template #title>
Custom Page Title
</template>
<!-- Your content -->
</AppLayout>
</template>
```
**Used automatically by AppLayout** - no need to import separately.
---
### 4. AuthLayout.vue
Simple centered layout for authentication pages (login/register).
**Usage:**
```vue
<template>
<AuthLayout>
<!-- Login/Register form content -->
<h2 class="text-2xl font-bold mb-6">Login</h2>
<form @submit.prevent="handleLogin">
<!-- Form fields -->
</form>
<!-- Optional footer slot -->
<template #footer>
<p>
Don't have an account?
<router-link to="/register" class="text-indigo-600 hover:underline">
Sign up
</router-link>
</p>
</template>
</AuthLayout>
</template>
<script setup lang="ts">
import { AuthLayout } from '@/components/layout';
function handleLogin() {
// Login logic
}
</script>
```
**Features:**
- Centered card container
- Gradient background
- Logo/brand at top
- Main content slot
- Optional footer slot for links
- Fully responsive
---
## Route Configuration
To set page titles in the header, add meta to your routes:
```typescript
// router/index.ts
const routes = [
{
path: '/dashboard',
component: DashboardView,
meta: { title: 'Dashboard' },
},
{
path: '/api-keys',
component: ApiKeysView,
meta: { title: 'API Keys' },
},
// ...
];
```
---
## Store Dependencies
These components use the following Pinia stores:
- **useAuthStore**: For user authentication state, role checking, and logout
- **useAppStore**: For sidebar state management and toast notifications
Make sure these stores are properly initialized in your app.
---
## Styling
All components use TailwindCSS utility classes. Make sure your `tailwind.config.js` includes the component paths:
```js
module.exports = {
content: [
'./index.html',
'./src/**/*.{vue,js,ts,jsx,tsx}',
],
// ...
}
```
---
## Icons
Components use HTML entity icons for simplicity:
- &#128200; Chart (Dashboard)
- &#128273; Key (API Keys)
- &#128202; Bar Chart (Usage)
- &#127873; Gift (Redeem)
- &#128100; User (Profile)
- &#128268; Admin
- &#128101; Users
- &#128193; Folder (Groups)
- &#127760; Globe (Accounts)
- &#128260; Network (Proxies)
- &#127991; Ticket (Redeem Codes)
You can replace these with your preferred icon library (e.g., Heroicons, Font Awesome) if needed.
---
## Mobile Responsiveness
All components are fully responsive:
- **AppSidebar**: Fixed positioning on desktop, hidden by default on mobile
- **AppHeader**: Shows mobile menu toggle on small screens, hides balance display
- **AuthLayout**: Adapts padding and card size for mobile devices
The sidebar uses Tailwind's responsive breakpoints (md:) to adjust behavior.

View File

@@ -0,0 +1,9 @@
/**
* Layout Components
* Export all layout components for easy importing
*/
export { default as AppLayout } from './AppLayout.vue';
export { default as AppSidebar } from './AppSidebar.vue';
export { default as AppHeader } from './AppHeader.vue';
export { default as AuthLayout } from './AuthLayout.vue';