Merge origin/main into worktree/brave-valley-9578

Resolve conflict in api_key_repo.go: keep both ListAllByUserID (this PR)
and attachLastUsedIPs/latestUsageLogIPs (main), and have ListAllByUserID
attach last-used IPs so the current_concurrency sort path keeps the
last_used_ip column populated.
This commit is contained in:
shaw committed 2026-07-09 17:17:16 +08:00
commit 49fb18e073
144 files changed
+6978 -300

No files matched your search

+2 -1
View File
@@ -410,6 +410,7 @@ import { useI18n } from 'vue-i18n'
import { useAuthStore, useAppStore } from '@/stores'
import LocaleSwitcher from '@/components/common/LocaleSwitcher.vue'
import Icon from '@/components/icons/Icon.vue'
import { sanitizeUrl } from '@/utils/url'
const { t } = useI18n()
@@ -420,7 +421,7 @@ const appStore = useAppStore()
const siteName = computed(() => appStore.cachedPublicSettings?.site_name || appStore.siteName || 'Sub2API')
const siteLogo = computed(() => appStore.cachedPublicSettings?.site_logo || appStore.siteLogo || '')
const siteSubtitle = computed(() => appStore.cachedPublicSettings?.site_subtitle || 'AI API Gateway Platform')
const docUrl = computed(() => appStore.cachedPublicSettings?.doc_url || appStore.docUrl || '')
const docUrl = computed(() => sanitizeUrl(appStore.cachedPublicSettings?.doc_url || appStore.docUrl || ''))
const homeContent = computed(() => appStore.cachedPublicSettings?.home_content || '')
// Check if homeContent is a URL (for iframe display)
+2 -1
View File
@@ -423,6 +423,7 @@ import { useAppStore } from '@/stores'
import LocaleSwitcher from '@/components/common/LocaleSwitcher.vue'
import Icon from '@/components/icons/Icon.vue'
import { buildGatewayUrl } from '@/api/client'
import { sanitizeUrl } from '@/utils/url'
const { t, locale } = useI18n()
const appStore = useAppStore()
@@ -431,7 +432,7 @@ const appStore = useAppStore()
const siteName = computed(() => appStore.cachedPublicSettings?.site_name || appStore.siteName || 'Sub2API')
const siteLogo = computed(() => appStore.cachedPublicSettings?.site_logo || appStore.siteLogo || '')
const docUrl = computed(() => appStore.cachedPublicSettings?.doc_url || appStore.docUrl || '')
const docUrl = computed(() => sanitizeUrl(appStore.cachedPublicSettings?.doc_url || appStore.docUrl || ''))
const githubUrl = 'https://github.com/Wei-Shaw/sub2api'
// ==================== Theme (same as HomeView) ====================
+402 -43
View File
@@ -168,20 +168,40 @@
<!-- Subscription Limits - compact single line -->
<div
v-if="row.subscription_type === 'subscription'"
class="text-xs text-gray-500 dark:text-gray-400"
class="space-y-0.5 text-xs text-gray-500 dark:text-gray-400"
>
<template
<div
v-if="
row.daily_limit_usd ||
row.weekly_limit_usd ||
row.monthly_limit_usd
"
class="flex flex-wrap items-center gap-x-1 gap-y-0.5"
>
<span v-if="row.daily_limit_usd"
>${{ row.daily_limit_usd }}/{{
t("admin.groups.limitDay")
}}</span
>
<span v-if="row.daily_limit_usd" class="whitespace-nowrap">
<span
v-if="usageLoading"
class="font-medium text-gray-400 dark:text-gray-500"
>—</span
>
<span
v-else
:class="
getQuotaUsageClass(
usageMap.get(row.id)?.today_cost ?? 0,
row.daily_limit_usd
)
"
>{{
formatUsd(usageMap.get(row.id)?.today_cost ?? 0)
}}</span
>
<span class="text-gray-400 dark:text-gray-500">
/ {{ formatUsd(row.daily_limit_usd) }}/{{
t("admin.groups.limitDay")
}}</span
>
</span>
<span
v-if="
row.daily_limit_usd &&
@@ -190,8 +210,8 @@
class="mx-1 text-gray-300 dark:text-gray-600"
>·</span
>
<span v-if="row.weekly_limit_usd"
>${{ row.weekly_limit_usd }}/{{
<span v-if="row.weekly_limit_usd" class="whitespace-nowrap"
>{{ formatUsd(row.weekly_limit_usd) }}/{{
t("admin.groups.limitWeek")
}}</span
>
@@ -200,15 +220,25 @@
class="mx-1 text-gray-300 dark:text-gray-600"
>·</span
>
<span v-if="row.monthly_limit_usd"
>${{ row.monthly_limit_usd }}/{{
<span v-if="row.monthly_limit_usd" class="whitespace-nowrap"
>{{ formatUsd(row.monthly_limit_usd) }}/{{
t("admin.groups.limitMonth")
}}</span
>
</template>
</div>
<span v-else class="text-gray-400 dark:text-gray-500">{{
t("admin.groups.subscription.noLimit")
}}</span>
<div class="text-gray-400 dark:text-gray-500">
{{ t("admin.groups.usageTotal") }}
<span class="ml-1 font-medium text-gray-600 dark:text-gray-300"
>{{
usageLoading
? "—"
: formatUsd(usageMap.get(row.id)?.total_cost ?? 0)
}}</span
>
</div>
</div>
</div>
</template>
@@ -795,10 +825,10 @@
<label
class="block mb-2 font-medium text-gray-700 dark:text-gray-300"
>
{{ t("admin.groups.imagePricing.title") }}
{{ t(imagePricingI18nKey(createForm.platform, "title")) }}
</label>
<p class="text-xs text-gray-500 dark:text-gray-400 mb-3">
{{ t("admin.groups.imagePricing.description") }}
{{ t(imagePricingI18nKey(createForm.platform, "description")) }}
</p>
<div class="mb-4 grid grid-cols-1 gap-3 md:grid-cols-2">
<label class="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
@@ -807,7 +837,7 @@
type="checkbox"
class="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
/>
{{ t("admin.groups.imagePricing.allowImageGeneration") }}
{{ t(imagePricingI18nKey(createForm.platform, "allowImageGeneration")) }}
</label>
<label class="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
<input
@@ -815,7 +845,7 @@
type="checkbox"
class="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
/>
{{ t("admin.groups.imagePricing.independentMultiplier") }}
{{ t(imagePricingI18nKey(createForm.platform, "independentMultiplier")) }}
</label>
</div>
<div
@@ -823,7 +853,7 @@
class="mb-4"
>
<label class="input-label">{{
t("admin.groups.imagePricing.imageMultiplier")
t(imagePricingI18nKey(createForm.platform, "imageMultiplier"))
}}</label>
<input
v-model.number="createForm.image_rate_multiplier"
@@ -843,7 +873,7 @@
step="0.001"
min="0"
class="input"
placeholder="0.134"
:placeholder="getImagePricePlaceholder(createForm.platform, 'image_price_1k')"
/>
</div>
<div>
@@ -854,7 +884,7 @@
step="0.001"
min="0"
class="input"
placeholder="0.201"
:placeholder="getImagePricePlaceholder(createForm.platform, 'image_price_2k')"
/>
</div>
<div>
@@ -865,16 +895,16 @@
step="0.001"
min="0"
class="input"
placeholder="0.268"
:placeholder="getImagePricePlaceholder(createForm.platform, 'image_price_4k')"
/>
</div>
</div>
<p class="mt-3 text-xs text-gray-500 dark:text-gray-400">
{{ t("admin.groups.imagePricing.modeHint") }}
{{ t(imagePricingI18nKey(createForm.platform, "modeHint")) }}
</p>
<div class="mt-2 rounded-lg bg-gray-50 p-3 text-xs text-gray-700 dark:bg-gray-800 dark:text-gray-300">
<div class="mb-1 font-medium">
{{ t("admin.groups.imagePricing.finalPricePreview") }}
{{ t(imagePricingI18nKey(createForm.platform, "finalPricePreview")) }}
</div>
<div class="grid grid-cols-3 gap-2">
<div
@@ -939,6 +969,98 @@
</p>
</div>
<!-- 视频生成计费配置(仅 Grok 平台) -->
<div
v-if="supportsVideoPricingPlatform(createForm.platform)"
class="border-t pt-4"
>
<label
class="block mb-2 font-medium text-gray-700 dark:text-gray-300"
>
{{ t(videoPricingI18nKey("title")) }}
</label>
<p class="text-xs text-gray-500 dark:text-gray-400 mb-3">
{{ t(videoPricingI18nKey("description")) }}
</p>
<div class="mb-4">
<label class="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
<input
v-model="createForm.video_rate_independent"
type="checkbox"
class="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
/>
{{ t(videoPricingI18nKey("independentMultiplier")) }}
</label>
</div>
<div
v-if="createForm.video_rate_independent"
class="mb-4"
>
<label class="input-label">{{
t(videoPricingI18nKey("videoMultiplier"))
}}</label>
<input
v-model.number="createForm.video_rate_multiplier"
type="number"
step="0.0001"
min="0"
class="input"
placeholder="1"
/>
</div>
<div class="grid grid-cols-3 gap-3">
<div>
<label class="input-label">480p ($/s)</label>
<input
v-model.number="createForm.video_price_480p"
type="number"
step="0.001"
min="0"
class="input"
:placeholder="getVideoPricePlaceholder(createForm.platform, 'video_price_480p')"
/>
</div>
<div>
<label class="input-label">720p ($/s)</label>
<input
v-model.number="createForm.video_price_720p"
type="number"
step="0.001"
min="0"
class="input"
:placeholder="getVideoPricePlaceholder(createForm.platform, 'video_price_720p')"
/>
</div>
<div>
<label class="input-label">1080p ($/s)</label>
<input
v-model.number="createForm.video_price_1080p"
type="number"
step="0.001"
min="0"
class="input"
:placeholder="getVideoPricePlaceholder(createForm.platform, 'video_price_1080p')"
/>
</div>
</div>
<p class="mt-3 text-xs text-gray-500 dark:text-gray-400">
{{ t(videoPricingI18nKey("modeHint")) }}
</p>
<div class="mt-2 rounded-lg bg-gray-50 p-3 text-xs text-gray-700 dark:bg-gray-800 dark:text-gray-300">
<div class="mb-1 font-medium">
{{ t(videoPricingI18nKey("finalPricePreview")) }}
</div>
<div class="grid grid-cols-3 gap-2">
<div
v-for="item in createVideoFinalPricePreview"
:key="item.label"
>
{{ item.label }}: {{ item.value }}
</div>
</div>
</div>
</div>
<!-- 高峰时段倍率配置(仅订阅类型分组) -->
<div v-if="createForm.subscription_type === 'subscription'" class="border-t pt-4">
<div class="mb-4 grid grid-cols-1 gap-3 md:grid-cols-2">
@@ -2182,10 +2304,10 @@
<label
class="block mb-2 font-medium text-gray-700 dark:text-gray-300"
>
{{ t("admin.groups.imagePricing.title") }}
{{ t(imagePricingI18nKey(editForm.platform, "title")) }}
</label>
<p class="text-xs text-gray-500 dark:text-gray-400 mb-3">
{{ t("admin.groups.imagePricing.description") }}
{{ t(imagePricingI18nKey(editForm.platform, "description")) }}
</p>
<div class="mb-4 grid grid-cols-1 gap-3 md:grid-cols-2">
<label class="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
@@ -2194,7 +2316,7 @@
type="checkbox"
class="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
/>
{{ t("admin.groups.imagePricing.allowImageGeneration") }}
{{ t(imagePricingI18nKey(editForm.platform, "allowImageGeneration")) }}
</label>
<label class="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
<input
@@ -2202,7 +2324,7 @@
type="checkbox"
class="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
/>
{{ t("admin.groups.imagePricing.independentMultiplier") }}
{{ t(imagePricingI18nKey(editForm.platform, "independentMultiplier")) }}
</label>
</div>
<div
@@ -2210,7 +2332,7 @@
class="mb-4"
>
<label class="input-label">{{
t("admin.groups.imagePricing.imageMultiplier")
t(imagePricingI18nKey(editForm.platform, "imageMultiplier"))
}}</label>
<input
v-model.number="editForm.image_rate_multiplier"
@@ -2230,7 +2352,7 @@
step="0.001"
min="0"
class="input"
placeholder="0.134"
:placeholder="getImagePricePlaceholder(editForm.platform, 'image_price_1k')"
/>
</div>
<div>
@@ -2241,7 +2363,7 @@
step="0.001"
min="0"
class="input"
placeholder="0.201"
:placeholder="getImagePricePlaceholder(editForm.platform, 'image_price_2k')"
/>
</div>
<div>
@@ -2252,16 +2374,16 @@
step="0.001"
min="0"
class="input"
placeholder="0.268"
:placeholder="getImagePricePlaceholder(editForm.platform, 'image_price_4k')"
/>
</div>
</div>
<p class="mt-3 text-xs text-gray-500 dark:text-gray-400">
{{ t("admin.groups.imagePricing.modeHint") }}
{{ t(imagePricingI18nKey(editForm.platform, "modeHint")) }}
</p>
<div class="mt-2 rounded-lg bg-gray-50 p-3 text-xs text-gray-700 dark:bg-gray-800 dark:text-gray-300">
<div class="mb-1 font-medium">
{{ t("admin.groups.imagePricing.finalPricePreview") }}
{{ t(imagePricingI18nKey(editForm.platform, "finalPricePreview")) }}
</div>
<div class="grid grid-cols-3 gap-2">
<div
@@ -2326,6 +2448,98 @@
</p>
</div>
<!-- 视频生成计费配置(仅 Grok 平台) -->
<div
v-if="supportsVideoPricingPlatform(editForm.platform)"
class="border-t pt-4"
>
<label
class="block mb-2 font-medium text-gray-700 dark:text-gray-300"
>
{{ t(videoPricingI18nKey("title")) }}
</label>
<p class="text-xs text-gray-500 dark:text-gray-400 mb-3">
{{ t(videoPricingI18nKey("description")) }}
</p>
<div class="mb-4">
<label class="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
<input
v-model="editForm.video_rate_independent"
type="checkbox"
class="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
/>
{{ t(videoPricingI18nKey("independentMultiplier")) }}
</label>
</div>
<div
v-if="editForm.video_rate_independent"
class="mb-4"
>
<label class="input-label">{{
t(videoPricingI18nKey("videoMultiplier"))
}}</label>
<input
v-model.number="editForm.video_rate_multiplier"
type="number"
step="0.0001"
min="0"
class="input"
placeholder="1"
/>
</div>
<div class="grid grid-cols-3 gap-3">
<div>
<label class="input-label">480p ($/s)</label>
<input
v-model.number="editForm.video_price_480p"
type="number"
step="0.001"
min="0"
class="input"
:placeholder="getVideoPricePlaceholder(editForm.platform, 'video_price_480p')"
/>
</div>
<div>
<label class="input-label">720p ($/s)</label>
<input
v-model.number="editForm.video_price_720p"
type="number"
step="0.001"
min="0"
class="input"
:placeholder="getVideoPricePlaceholder(editForm.platform, 'video_price_720p')"
/>
</div>
<div>
<label class="input-label">1080p ($/s)</label>
<input
v-model.number="editForm.video_price_1080p"
type="number"
step="0.001"
min="0"
class="input"
:placeholder="getVideoPricePlaceholder(editForm.platform, 'video_price_1080p')"
/>
</div>
</div>
<p class="mt-3 text-xs text-gray-500 dark:text-gray-400">
{{ t(videoPricingI18nKey("modeHint")) }}
</p>
<div class="mt-2 rounded-lg bg-gray-50 p-3 text-xs text-gray-700 dark:bg-gray-800 dark:text-gray-300">
<div class="mb-1 font-medium">
{{ t(videoPricingI18nKey("finalPricePreview")) }}
</div>
<div class="grid grid-cols-3 gap-2">
<div
v-for="item in editVideoFinalPricePreview"
:key="item.label"
>
{{ item.label }}: {{ item.value }}
</div>
</div>
</div>
</div>
<!-- 高峰时段倍率配置(仅订阅类型分组) -->
<div v-if="editForm.subscription_type === 'subscription'" class="border-t pt-4">
<div class="mb-4 grid grid-cols-1 gap-3 md:grid-cols-2">
@@ -3312,7 +3526,16 @@ import {
} from "./groupsModelsList";
import { createModelsListCandidatesTracker } from "./groupsModelsListCandidates";
import { normalizeSupportedModelScopesForPlatform } from "./groupsSupportedModelScopes";
import { supportsImagePricingPlatform } from "./groupsImagePricing";
import {
getDefaultImagePreviewPrice,
getDefaultVideoPreviewPrice,
getImagePricePlaceholder,
getVideoPricePlaceholder,
imagePricingI18nKey,
supportsImagePricingPlatform,
supportsVideoPricingPlatform,
videoPricingI18nKey,
} from "./groupsImagePricing";
const { t } = useI18n();
const appStore = useAppStore();
@@ -3396,7 +3619,9 @@ const saveColumnsToStorage = () => {
};
const isColumnVisible = (key: string) => !hiddenColumns.has(key);
const hasVisibleUsageColumn = computed(() => isColumnVisible("usage"));
const hasVisibleUsageSummaryConsumer = computed(
() => isColumnVisible("usage") || isColumnVisible("billing_type"),
);
const hasVisibleCapacityColumn = computed(() => isColumnVisible("capacity"));
const toggleColumn = (key: string) => {
@@ -3411,7 +3636,7 @@ const toggleColumn = (key: string) => {
}
saveColumnsToStorage();
if (wasHidden && key === "usage") {
if (wasHidden && (key === "usage" || key === "billing_type")) {
loadUsageSummary();
}
if (wasHidden && key === "capacity") {
@@ -3571,9 +3796,12 @@ const copyAccountsGroupOptionsForEdit = computed(() => {
const groups = ref<AdminGroup[]>([]);
const loading = ref(false);
const usageMap = ref<Map<number, { today_cost: number; total_cost: number }>>(
new Map(),
);
type GroupUsageSummary = {
today_cost: number;
total_cost: number;
};
const usageMap = ref<Map<number, GroupUsageSummary>>(new Map());
const usageLoading = ref(false);
const capacityMap = ref<
Map<
@@ -3654,6 +3882,12 @@ const createForm = reactive({
image_price_1k: null as number | null,
image_price_2k: null as number | null,
image_price_4k: null as number | null,
// 视频生成计费配置(仅 Grok 平台)
video_rate_independent: false,
video_rate_multiplier: 1,
video_price_480p: null as number | null,
video_price_720p: null as number | null,
video_price_1080p: null as number | null,
// 高峰时段倍率配置
peak_rate_enabled: false,
peak_start: "",
@@ -3993,6 +4227,12 @@ const editForm = reactive({
image_price_1k: null as number | null,
image_price_2k: null as number | null,
image_price_4k: null as number | null,
// 视频生成计费配置(仅 Grok 平台)
video_rate_independent: false,
video_rate_multiplier: 1,
video_price_480p: null as number | null,
video_price_720p: null as number | null,
video_price_1080p: null as number | null,
// 高峰时段倍率配置
peak_rate_enabled: false,
peak_start: "",
@@ -4042,12 +4282,28 @@ type ImagePricingFormState = {
peak_rate_multiplier: number;
};
type VideoPricingFormState = {
platform: GroupPlatform;
rate_multiplier: number;
video_rate_independent: boolean;
video_rate_multiplier: number;
video_price_480p: number | string | null;
video_price_720p: number | string | null;
video_price_1080p: number | string | null;
};
const imagePricingTiers = [
{ key: "image_price_1k", label: "1K" },
{ key: "image_price_2k", label: "2K" },
{ key: "image_price_4k", label: "4K" },
] as const;
const videoPricingTiers = [
{ key: "video_price_480p", label: "480p" },
{ key: "video_price_720p", label: "720p" },
{ key: "video_price_1080p", label: "1080p" },
] as const;
const normalizePreviewNumber = (value: number | string | null | undefined, fallback = 0) => {
if (value === null || value === undefined || value === "") {
return fallback;
@@ -4056,6 +4312,14 @@ const normalizePreviewNumber = (value: number | string | null | undefined, fallb
return Number.isFinite(parsed) ? parsed : fallback;
};
const parsePreviewPrice = (value: number | string | null | undefined) => {
if (value === null || value === undefined || value === "") {
return null;
}
const parsed = Number(value);
return Number.isFinite(parsed) && parsed >= 0 ? parsed : null;
};
const formatImagePricePreview = (value: number | string | null | undefined) => {
if (value === null || value === undefined || value === "") {
return t("admin.groups.imagePricing.notConfigured");
@@ -4067,28 +4331,64 @@ const formatImagePricePreview = (value: number | string | null | undefined) => {
return `$${price.toFixed(6).replace(/0+$/, "").replace(/\.$/, "")}`;
};
const formatVideoPricePreview = (value: number | string | null | undefined) => {
if (value === null || value === undefined || value === "") {
return t("admin.groups.videoPricing.notConfigured");
}
const price = Number(value);
if (!Number.isFinite(price) || price < 0) {
return t("admin.groups.videoPricing.notConfigured");
}
return `$${price.toFixed(6).replace(/0+$/, "").replace(/\.$/, "")}`;
};
const buildImageFinalPricePreview = (form: ImagePricingFormState) => {
const imageMultiplier = form.image_rate_independent
? normalizePreviewNumber(form.image_rate_multiplier, 1)
: normalizePreviewNumber(form.rate_multiplier, 1);
const multiplier = imageMultiplier;
return imagePricingTiers.map((tier) => {
const basePrice = normalizePreviewNumber(form[tier.key]);
const basePrice =
parsePreviewPrice(form[tier.key]) ??
getDefaultImagePreviewPrice(form.platform, tier.key);
return {
label: tier.label,
value: basePrice > 0
value: basePrice !== null
? formatImagePricePreview(basePrice * multiplier)
: t("admin.groups.imagePricing.notConfigured"),
};
});
};
const buildVideoFinalPricePreview = (form: VideoPricingFormState) => {
const multiplier = form.video_rate_independent
? normalizePreviewNumber(form.video_rate_multiplier, 1)
: normalizePreviewNumber(form.rate_multiplier, 1);
return videoPricingTiers.map((tier) => {
const basePrice =
parsePreviewPrice(form[tier.key]) ??
getDefaultVideoPreviewPrice(form.platform, tier.key);
return {
label: tier.label,
value: basePrice !== null
? formatVideoPricePreview(basePrice * multiplier)
: t("admin.groups.videoPricing.notConfigured"),
};
});
};
const createImageFinalPricePreview = computed(() =>
buildImageFinalPricePreview(createForm),
);
const editImageFinalPricePreview = computed(() =>
buildImageFinalPricePreview(editForm),
);
const createVideoFinalPricePreview = computed(() =>
buildVideoFinalPricePreview(createForm),
);
const editVideoFinalPricePreview = computed(() =>
buildVideoFinalPricePreview(editForm),
);
const resetDisabledBatchImagePricing = (
form: Pick<
@@ -4146,7 +4446,7 @@ const loadGroups = async () => {
groups.value = response.items;
pagination.total = response.total;
pagination.pages = response.pages;
if (hasVisibleUsageColumn.value) {
if (hasVisibleUsageSummaryConsumer.value) {
loadUsageSummary();
} else {
usageLoading.value = false;
@@ -4177,8 +4477,28 @@ const formatCost = (cost: number): string => {
return cost.toFixed(2);
};
const formatUsd = (cost: number | null | undefined): string =>
`$${formatCost(cost ?? 0)}`;
const getQuotaUsageClass = (
used: number,
limit: number | null | undefined,
): string => {
if (!limit || limit <= 0) {
return "font-medium text-gray-700 dark:text-gray-300";
}
const ratio = used / limit;
if (ratio >= 1) {
return "font-semibold text-red-600 dark:text-red-400";
}
if (ratio >= 0.8) {
return "font-semibold text-amber-600 dark:text-amber-400";
}
return "font-medium text-gray-700 dark:text-gray-300";
};
const loadUsageSummary = async () => {
if (!hasVisibleUsageColumn.value) {
if (!hasVisibleUsageSummaryConsumer.value) {
usageLoading.value = false;
return;
}
@@ -4186,7 +4506,7 @@ const loadUsageSummary = async () => {
try {
const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
const data = await adminAPI.groups.getUsageSummary(tz);
const map = new Map<number, { today_cost: number; total_cost: number }>();
const map = new Map<number, GroupUsageSummary>();
for (const item of data) {
map.set(item.group_id, {
today_cost: item.today_cost,
@@ -4290,6 +4610,11 @@ const closeCreateModal = () => {
createForm.image_price_1k = null;
createForm.image_price_2k = null;
createForm.image_price_4k = null;
createForm.video_rate_independent = false;
createForm.video_rate_multiplier = 1;
createForm.video_price_480p = null;
createForm.video_price_720p = null;
createForm.video_price_1080p = null;
createForm.peak_rate_enabled = false;
createForm.peak_start = "";
createForm.peak_end = "";
@@ -4390,6 +4715,17 @@ const handleCreateGroup = async () => {
requestData.batch_image_hold_multiplier = normalizeRateMultiplier(
requestData.batch_image_hold_multiplier,
);
requestData.video_rate_multiplier = normalizeRateMultiplier(
requestData.video_rate_multiplier,
);
// 媒体价格输入清空时 v-model.number 产生 "",直接提交会被后端 *float64 反序列化拒绝(400),
// 创建时按"未配置"(null)处理。
requestData.image_price_1k = emptyToNull(requestData.image_price_1k);
requestData.image_price_2k = emptyToNull(requestData.image_price_2k);
requestData.image_price_4k = emptyToNull(requestData.image_price_4k);
requestData.video_price_480p = emptyToNull(requestData.video_price_480p);
requestData.video_price_720p = emptyToNull(requestData.video_price_720p);
requestData.video_price_1080p = emptyToNull(requestData.video_price_1080p);
requestData.peak_rate_enabled = createForm.peak_rate_enabled;
requestData.peak_start = createForm.peak_start;
requestData.peak_end = createForm.peak_end;
@@ -4438,6 +4774,11 @@ const handleEdit = async (group: AdminGroup) => {
editForm.image_price_1k = group.image_price_1k;
editForm.image_price_2k = group.image_price_2k;
editForm.image_price_4k = group.image_price_4k;
editForm.video_rate_independent = group.video_rate_independent ?? false;
editForm.video_rate_multiplier = group.video_rate_multiplier ?? 1;
editForm.video_price_480p = group.video_price_480p;
editForm.video_price_720p = group.video_price_720p;
editForm.video_price_1080p = group.video_price_1080p;
editForm.peak_rate_enabled = group.peak_rate_enabled ?? false;
editForm.peak_start = group.peak_start ?? "";
editForm.peak_end = group.peak_end ?? "";
@@ -4490,6 +4831,11 @@ const closeEditModal = () => {
editForm.peak_start = "";
editForm.peak_end = "";
editForm.peak_rate_multiplier = 1.0;
editForm.video_rate_independent = false;
editForm.video_rate_multiplier = 1;
editForm.video_price_480p = null;
editForm.video_price_720p = null;
editForm.video_price_1080p = null;
resetMessagesDispatchFormState(editForm);
resetModelsListState(editModelsListState);
};
@@ -4555,6 +4901,19 @@ const handleUpdateGroup = async () => {
payload.batch_image_hold_multiplier = normalizeRateMultiplier(
payload.batch_image_hold_multiplier,
);
payload.video_rate_multiplier = normalizeRateMultiplier(
payload.video_rate_multiplier,
);
// 媒体价格输入清空时 v-model.number 产生 "",直接提交会被后端 *float64 反序列化拒绝(400)。
// 更新语义中 null 表示"不修改",因此清空后的字段发送 -1:后端 normalizePrice 将负价归一为
// NULL,从而真正清除已配置的价格。
const emptyPriceToClear = (v: any) => (v === "" || v === null ? -1 : v);
payload.image_price_1k = emptyPriceToClear(payload.image_price_1k);
payload.image_price_2k = emptyPriceToClear(payload.image_price_2k);
payload.image_price_4k = emptyPriceToClear(payload.image_price_4k);
payload.video_price_480p = emptyPriceToClear(payload.video_price_480p);
payload.video_price_720p = emptyPriceToClear(payload.video_price_720p);
payload.video_price_1080p = emptyPriceToClear(payload.video_price_1080p);
payload.peak_rate_enabled = editForm.peak_rate_enabled;
payload.peak_start = editForm.peak_start;
payload.peak_end = editForm.peak_end;
@@ -1,5 +1,6 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
import type { DashboardStats } from '@/types'
import DashboardView from '../DashboardView.vue'
@@ -87,6 +88,8 @@ const createDashboardStats = (): DashboardStats => ({
describe('admin DashboardView', () => {
beforeEach(() => {
setActivePinia(createPinia())
getSnapshotV2.mockReset()
getUserUsageTrend.mockReset()
getUserSpendingRanking.mockReset()
@@ -308,8 +308,11 @@ describe('admin GroupsView column settings', () => {
expect(localStorage.getItem('group-hidden-columns')).toBe(JSON.stringify(['usage']))
})
it('skips hidden usage and capacity fetches until those columns are shown', async () => {
localStorage.setItem('group-hidden-columns', JSON.stringify(['usage', 'capacity']))
it('skips usage and capacity fetches until consuming columns are shown', async () => {
localStorage.setItem(
'group-hidden-columns',
JSON.stringify(['billing_type', 'usage', 'capacity']),
)
const wrapper = await mountView()
@@ -1,17 +1,52 @@
import { describe, expect, it } from "vitest";
import {
getDefaultImagePreviewPrice,
getDefaultVideoPreviewPrice,
getImagePricePlaceholder,
getVideoPricePlaceholder,
imagePricingPlatforms,
imagePricingI18nKey,
supportsImagePricingPlatform,
supportsVideoPricingPlatform,
videoPricingI18nKey,
} from "../groupsImagePricing";
describe("groups image pricing platform support", () => {
it("includes Grok media groups", () => {
it("includes Grok image groups", () => {
expect(supportsImagePricingPlatform("grok")).toBe(true);
expect(imagePricingPlatforms.has("grok")).toBe(true);
});
it("enables video pricing controls for Grok only", () => {
expect(supportsVideoPricingPlatform("grok")).toBe(true);
expect(supportsVideoPricingPlatform("openai")).toBe(false);
});
it("keeps non-media group platforms out of the image pricing controls", () => {
expect(supportsImagePricingPlatform("anthropic")).toBe(false);
});
it("keeps image and video pricing copy separate", () => {
expect(imagePricingI18nKey("grok", "title")).toBe(
"admin.groups.imagePricing.title",
);
expect(videoPricingI18nKey("title")).toBe("admin.groups.videoPricing.title");
});
it("uses Grok media defaults instead of generic image fallback placeholders", () => {
expect(getImagePricePlaceholder("grok", "image_price_1k")).toBe("0.02");
expect(getImagePricePlaceholder("grok", "image_price_2k")).toBe("0.02");
// 视频 placeholder 为每秒单价:480p/720p 取 grok-imagine-video 官方每秒价,
// 1080p 仅 video-1.5 支持、取 1.5 每秒价。
expect(getVideoPricePlaceholder("grok", "video_price_480p")).toBe("0.05");
expect(getVideoPricePlaceholder("grok", "video_price_720p")).toBe("0.07");
expect(getVideoPricePlaceholder("grok", "video_price_1080p")).toBe("0.25");
});
it("keeps non-Grok image placeholders on the generic image card", () => {
expect(getImagePricePlaceholder("openai", "image_price_1k")).toBe("0.134");
expect(getDefaultImagePreviewPrice("openai", "image_price_2k")).toBe(0.201);
expect(getDefaultVideoPreviewPrice("openai", "video_price_480p")).toBeNull();
});
});
@@ -7,3 +7,87 @@ export const imagePricingPlatforms = new Set([
export const supportsImagePricingPlatform = (platform: string): boolean =>
imagePricingPlatforms.has(platform);
export const supportsVideoPricingPlatform = (platform: string): boolean =>
platform === "grok";
export const imagePricingI18nKey = (_platform: string, key: string): string =>
`admin.groups.imagePricing.${key}`;
export const videoPricingI18nKey = (key: string): string =>
`admin.groups.videoPricing.${key}`;
type ImagePricingTierKey = "image_price_1k" | "image_price_2k" | "image_price_4k";
type VideoPricingTierKey =
| "video_price_480p"
| "video_price_720p"
| "video_price_1080p";
const defaultImagePricePlaceholders: Record<
string,
Record<ImagePricingTierKey, string>
> = {
default: {
image_price_1k: "0.134",
image_price_2k: "0.201",
image_price_4k: "0.268",
},
grok: {
image_price_1k: "0.02",
image_price_2k: "0.02",
image_price_4k: "0.02",
},
};
// 视频价为每秒单价(USD/s)。480p/720p 取 grok-imagine-video(文生视频实际走该模型)的
// 官方每秒价;1080p 仅 grok-imagine-video-1.5 图生视频支持,取 1.5 的每秒价。
const defaultVideoPricePlaceholders: Record<
string,
Record<VideoPricingTierKey, string>
> = {
grok: {
video_price_480p: "0.05",
video_price_720p: "0.07",
video_price_1080p: "0.25",
},
};
export const getImagePricePlaceholder = (
platform: string,
tier: ImagePricingTierKey,
): string => {
const card = defaultImagePricePlaceholders[platform] ?? defaultImagePricePlaceholders.default;
return card[tier];
};
export const getVideoPricePlaceholder = (
platform: string,
tier: VideoPricingTierKey,
): string => {
const card = defaultVideoPricePlaceholders[platform];
return card?.[tier] ?? "";
};
export const getDefaultImagePreviewPrice = (
platform: string,
tier: ImagePricingTierKey,
): number | null => {
const placeholder = getImagePricePlaceholder(platform, tier);
if (placeholder === "") {
return null;
}
const value = Number(placeholder);
return Number.isFinite(value) ? value : null;
};
export const getDefaultVideoPreviewPrice = (
platform: string,
tier: VideoPricingTierKey,
): number | null => {
const placeholder = getVideoPricePlaceholder(platform, tier);
if (placeholder === "") {
return null;
}
const value = Number(placeholder);
return Number.isFinite(value) ? value : null;
};
+27 -3
View File
@@ -354,6 +354,13 @@
<span v-else class="text-sm text-gray-400 dark:text-dark-500">-</span>
</template>
<template #cell-last_used_ip="{ value }">
<span v-if="value" class="text-sm text-gray-500 dark:text-dark-400">
{{ value }}
</span>
<span v-else class="text-sm text-gray-400 dark:text-dark-500">-</span>
</template>
<template #cell-created_at="{ value }">
<span class="text-sm text-gray-500 dark:text-dark-400">{{ formatDateTime(value) }}</span>
</template>
@@ -1174,15 +1181,19 @@ const allColumns = computed<Column[]>(() => [
{ key: 'expires_at', label: t('keys.expiresAt'), sortable: true },
{ key: 'status', label: t('common.status'), sortable: true },
{ key: 'last_used_at', label: t('keys.lastUsedAt'), sortable: true },
{ key: 'last_used_ip', label: t('keys.lastUsedIP'), sortable: false },
{ key: 'created_at', label: t('keys.created'), sortable: true },
{ key: 'actions', label: t('common.actions'), sortable: false }
])
const ALWAYS_VISIBLE_COLUMNS = new Set(['name', 'actions'])
const DEFAULT_HIDDEN_COLUMNS = ['rate_limit', 'last_used_at']
const DEFAULT_HIDDEN_COLUMNS = ['rate_limit', 'last_used_at', 'last_used_ip']
const HIDDEN_COLUMNS_KEY = 'api-key-hidden-columns'
const COLUMN_SETTINGS_VERSION_KEY = 'api-key-column-settings-version'
const COLUMN_SETTINGS_VERSION = 1
const COLUMN_SETTINGS_VERSION = 2
const VERSION_NEW_HIDDEN_COLUMNS: Record<number, string[]> = {
2: ['last_used_ip']
}
const toggleableColumns = computed(() =>
allColumns.value.filter((col) => !ALWAYS_VISIBLE_COLUMNS.has(col.key))
@@ -1213,10 +1224,23 @@ const loadSavedColumns = () => {
!ALWAYS_VISIBLE_COLUMNS.has(key)
)
.forEach((key) => hiddenColumns.add(key))
const storedVersion = Number(localStorage.getItem(COLUMN_SETTINGS_VERSION_KEY) ?? '1')
if (storedVersion < COLUMN_SETTINGS_VERSION) {
for (let v = storedVersion + 1; v <= COLUMN_SETTINGS_VERSION; v++) {
for (const key of VERSION_NEW_HIDDEN_COLUMNS[v] ?? []) {
if (validColumnKeys.has(key) && !ALWAYS_VISIBLE_COLUMNS.has(key)) {
hiddenColumns.add(key)
}
}
}
saveColumnsToStorage()
} else {
localStorage.setItem(COLUMN_SETTINGS_VERSION_KEY, String(COLUMN_SETTINGS_VERSION))
}
} else {
DEFAULT_HIDDEN_COLUMNS.forEach((key) => hiddenColumns.add(key))
localStorage.setItem(COLUMN_SETTINGS_VERSION_KEY, String(COLUMN_SETTINGS_VERSION))
}
localStorage.setItem(COLUMN_SETTINGS_VERSION_KEY, String(COLUMN_SETTINGS_VERSION))
} catch (error) {
console.error('Failed to load API key table columns:', error)
DEFAULT_HIDDEN_COLUMNS.forEach((key) => hiddenColumns.add(key))
+18 -8
View File
@@ -132,16 +132,26 @@ async function renderQR() {
}
}
let pollInFlight = false
async function pollStatus() {
if (!orderId.value) return
const order = await paymentStore.pollOrderStatus(orderId.value)
if (!order) return
if (order.status === 'COMPLETED' || order.status === 'PAID') {
cleanup()
router.push({ path: '/payment/result', query: { order_id: String(orderId.value), status: 'success' } })
} else if (order.status === 'EXPIRED' || order.status === 'CANCELLED' || order.status === 'FAILED') {
cleanup()
expired.value = true
// 防重入:接口响应慢于 3 秒轮询间隔时避免并发重叠请求与重复跳转。
if (pollInFlight) return
pollInFlight = true
try {
const order = await paymentStore.pollOrderStatus(orderId.value)
if (!order) return
// 定时器已被 cleanup 清除时不再执行终态跳转(响应可能在 cleanup 后才回来)。
if (!pollTimer) return
if (order.status === 'COMPLETED' || order.status === 'PAID') {
cleanup()
router.push({ path: '/payment/result', query: { order_id: String(orderId.value), status: 'success' } })
} else if (order.status === 'EXPIRED' || order.status === 'CANCELLED' || order.status === 'FAILED') {
cleanup()
expired.value = true
}
} finally {
pollInFlight = false
}
}
+35 -8
View File
@@ -84,23 +84,38 @@ const success = ref(false)
const hint = ref(t('payment.stripePopup.redirecting'))
let pollTimer: ReturnType<typeof setInterval> | null = null
let initTimeoutTimer: ReturnType<typeof setTimeout> | null = null
let messageHandler: ((event: MessageEvent) => void) | null = null
function closeWindow() { window.close() }
function clearInitTimeout() {
if (initTimeoutTimer) {
clearTimeout(initTimeoutTimer)
initTimeoutTimer = null
}
}
onMounted(() => {
const handler = (event: MessageEvent) => {
messageHandler = (event: MessageEvent) => {
if (event.origin !== window.location.origin) return
if (event.data?.type !== 'STRIPE_POPUP_INIT') return
window.removeEventListener('message', handler)
// INIT 已到达,取消兜底超时,避免长时间的扫码支付被误判为超时。
clearInitTimeout()
if (messageHandler) {
window.removeEventListener('message', messageHandler)
messageHandler = null
}
initStripe(event.data.clientSecret, event.data.publishableKey)
}
window.addEventListener('message', handler)
window.addEventListener('message', messageHandler)
if (window.opener) {
window.opener.postMessage({ type: 'STRIPE_POPUP_READY' }, window.location.origin)
}
setTimeout(() => {
// 仅兜底“父窗口始终未发 STRIPE_POPUP_INIT”的场景。
initTimeoutTimer = setTimeout(() => {
if (!error.value && !success.value) {
error.value = t('payment.stripePopup.timeout')
}
@@ -108,7 +123,12 @@ onMounted(() => {
})
onUnmounted(() => {
if (pollTimer) clearInterval(pollTimer)
if (pollTimer) { clearInterval(pollTimer); pollTimer = null }
clearInitTimeout()
if (messageHandler) {
window.removeEventListener('message', messageHandler)
messageHandler = null
}
})
async function initStripe(clientSecret: string, publishableKey: string) {
@@ -149,10 +169,15 @@ async function initStripe(clientSecret: string, publishableKey: string) {
}
function startPolling() {
let inFlight = false
pollTimer = setInterval(async () => {
// 防重入:接口响应慢于轮询间隔时避免并发重叠请求。
if (inFlight) return
inFlight = true
try {
const token = document.cookie.split('; ').find(c => c.startsWith('token='))?.split('=')[1]
|| localStorage.getItem('token') || ''
// access token 存储在 localStorage 的 'auth_token' 键下(见 api/client.ts),
// 之前误读 'token' 导致轮询请求不带认证、永远 401,支付成功无法被检测到。
const token = localStorage.getItem('auth_token') || ''
const res = await fetch(buildApiUrl(`/payment/orders/${orderId}`), {
headers: token ? { Authorization: 'Bearer ' + token } : {},
credentials: 'include',
@@ -165,7 +190,9 @@ function startPolling() {
success.value = true
setTimeout(closeWindow, 2000)
}
} catch { /* ignore */ }
} catch { /* ignore */ } finally {
inFlight = false
}
}, 3000)
}
</script>
+1
View File
@@ -389,6 +389,7 @@ const billingModeOptions = computed<SelectOption[]>(() => [
{ value: 'token', label: t('admin.usage.billingModeToken') },
{ value: 'per_request', label: t('admin.usage.billingModePerRequest') },
{ value: 'image', label: t('admin.usage.billingModeImage') },
{ value: 'video', label: t('admin.usage.billingModeVideo') },
])
const apiKeys = ref<ApiKey[]>([])
@@ -44,6 +44,7 @@ const messages: Record<string, string> = {
'keys.group': 'Group',
'keys.currentConcurrency': 'Current Concurrency',
'keys.lastUsedAt': 'Last Used',
'keys.lastUsedIP': 'Last Used IP',
'keys.rateLimitColumn': 'Rate Limit',
'keys.searchPlaceholder': 'Search name or key...',
'keys.status.active': 'Active',
@@ -113,6 +114,7 @@ const createApiKey = (): ApiKey => ({
ip_whitelist: [],
ip_blacklist: [],
last_used_at: null,
last_used_ip: null,
quota: 0,
quota_used: 0,
expires_at: null,
@@ -164,6 +166,12 @@ const DataTableStub = {
<div data-test="current-concurrency">
<slot name="cell-current_concurrency" :value="row.current_concurrency" :row="row" />
</div>
<div
v-if="columns.some((col) => col.key === 'last_used_ip')"
data-test="last-used-ip"
>
<slot name="cell-last_used_ip" :value="row.last_used_ip" :row="row" />
</div>
</div>
<slot name="empty" />
</div>
@@ -286,6 +294,7 @@ describe('user KeysView column settings', () => {
])
expect(visibleColumnKeys(wrapper)).not.toContain('rate_limit')
expect(visibleColumnKeys(wrapper)).not.toContain('last_used_at')
expect(visibleColumnKeys(wrapper)).not.toContain('last_used_ip')
})
it('shows a hidden column when toggled and persists the preference', async () => {
@@ -296,8 +305,28 @@ describe('user KeysView column settings', () => {
await nextTick()
expect(visibleColumnKeys(wrapper)).toContain('rate_limit')
expect(localStorage.getItem('api-key-hidden-columns')).toBe(JSON.stringify(['last_used_at']))
expect(localStorage.getItem('api-key-column-settings-version')).toBe('1')
expect(localStorage.getItem('api-key-hidden-columns')).toBe(
JSON.stringify(['last_used_at', 'last_used_ip'])
)
expect(localStorage.getItem('api-key-column-settings-version')).toBe('2')
})
it('shows the last used IP column when toggled', async () => {
listKeys.mockResolvedValueOnce({
items: [{ ...createApiKey(), last_used_ip: '203.0.113.10' }],
total: 1,
page: 1,
page_size: 20,
pages: 1,
})
const wrapper = await mountView()
await wrapper.get('button[title="Column Settings"]').trigger('click')
await getButtonByText(wrapper, 'Last Used IP').trigger('click')
await nextTick()
expect(visibleColumnKeys(wrapper)).toContain('last_used_ip')
expect(wrapper.get('[data-test="last-used-ip"]').text()).toBe('203.0.113.10')
})
it('restores column preferences from localStorage on mount', async () => {
@@ -317,6 +346,10 @@ describe('user KeysView column settings', () => {
'last_used_at',
'actions',
])
expect(localStorage.getItem('api-key-hidden-columns')).toBe(
JSON.stringify(['group', 'created_at', 'last_used_ip'])
)
expect(localStorage.getItem('api-key-column-settings-version')).toBe('2')
})
it('does not include always-visible columns in the toggleable menu', async () => {
@@ -329,6 +362,7 @@ describe('user KeysView column settings', () => {
expect(columnMenuText).toContain('API Key')
expect(columnMenuText).toContain('Current Concurrency')
expect(columnMenuText).toContain('Rate Limit')
expect(columnMenuText).toContain('Last Used IP')
expect(columnMenuText).not.toContain('Name')
expect(columnMenuText).not.toContain('Actions')
})