Skip to content

Add API usage log table #4288

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Jun 30, 2025
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions src/components/dialog/content/setting/CreditsPanel.vue
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@
</div>
</div>

<div class="flex justify-between items-center mt-8">
<div class="flex justify-between items-center">
<h3>{{ $t('credits.activity') }}</h3>
<Button
:label="$t('credits.invoiceHistory')"
text
Expand Down Expand Up @@ -81,6 +82,8 @@

<Divider />

<UsageLogsTable ref="usageLogsTableRef" />

<div class="flex flex-row gap-2">
<Button
:label="$t('credits.faqs')"
Expand Down Expand Up @@ -108,10 +111,11 @@ import DataTable from 'primevue/datatable'
import Divider from 'primevue/divider'
import Skeleton from 'primevue/skeleton'
import TabPanel from 'primevue/tabpanel'
import { computed, ref } from 'vue'
import { computed, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'

import UserCredit from '@/components/common/UserCredit.vue'
import UsageLogsTable from '@/components/dialog/content/setting/UsageLogsTable.vue'
import { useFirebaseAuthActions } from '@/composables/auth/useFirebaseAuthActions'
import { useDialogService } from '@/services/dialogService'
import { useFirebaseAuthStore } from '@/stores/firebaseAuthStore'
Expand All @@ -131,12 +135,23 @@ const authActions = useFirebaseAuthActions()
const loading = computed(() => authStore.loading)
const balanceLoading = computed(() => authStore.isFetchingBalance)

const usageLogsTableRef = ref<InstanceType<typeof UsageLogsTable> | null>(null)

const formattedLastUpdateTime = computed(() =>
authStore.lastBalanceUpdateTime
? authStore.lastBalanceUpdateTime.toLocaleString()
: ''
)

watch(
() => authStore.lastBalanceUpdateTime,
(newTime, oldTime) => {
if (newTime && newTime !== oldTime && usageLogsTableRef.value) {
usageLogsTableRef.value.refresh()
}
}
)

const handlePurchaseCreditsClick = () => {
dialogService.showTopUpCreditsDialog()
}
Expand Down
188 changes: 188 additions & 0 deletions src/components/dialog/content/setting/UsageLogsTable.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
<template>
<div>
<div v-if="loading" class="flex items-center justify-center p-8">
<ProgressSpinner />
</div>
<div v-else-if="error" class="p-4">
<Message severity="error" :closable="false">{{ error }}</Message>
</div>
<DataTable
v-else
:value="events"
:paginator="true"
:rows="pagination.limit"
:total-records="pagination.total"
:first="dataTableFirst"
:lazy="true"
class="p-datatable-sm custom-datatable"
@page="onPageChange"
>
<Column field="event_type" :header="$t('credits.eventType')">
<template #body="{ data }">
<Badge
:value="customerEventService.formatEventType(data.event_type)"
:severity="customerEventService.getEventSeverity(data.event_type)"
/>
</template>
</Column>
<Column field="details" :header="$t('credits.details')">
<template #body="{ data }">
<div class="event-details">
<!-- Credits Added -->
<template v-if="data.event_type === EventType.CREDIT_ADDED">
<div class="text-green-500 font-semibold">
{{ $t('credits.added') }} ${{
customerEventService.formatAmount(data.params?.amount)
}}
</div>
</template>

<!-- Account Created -->
<template v-else-if="data.event_type === EventType.ACCOUNT_CREATED">
<div>{{ $t('credits.accountInitialized') }}</div>
</template>

<!-- API Usage -->
<template
v-else-if="data.event_type === EventType.API_USAGE_COMPLETED"
>
<div class="flex flex-col gap-1">
<div class="font-semibold">
{{ data.params?.api_name || 'API' }}
</div>
<div class="text-sm text-gray-400">
{{ $t('credits.model') }}: {{ data.params?.model || '-' }}
</div>
</div>
</template>
</div>
</template>
</Column>
<Column field="createdAt" :header="$t('credits.time')">
<template #body="{ data }">
{{ customerEventService.formatDate(data.createdAt) }}
</template>
</Column>
<Column field="params" :header="$t('credits.additionalInfo')">
<template #body="{ data }">
<Button
v-if="customerEventService.hasAdditionalInfo(data)"
v-tooltip.top="{
escape: false,
value: tooltipContentMap.get(data.event_id) || '',
pt: {
text: {
style: {
width: 'max-content !important'
}
}
}
}"
icon="pi pi-info-circle"
class="p-button-text p-button-sm"
/>
</template>
</Column>
</DataTable>
</div>
</template>

<script setup lang="ts">
import Badge from 'primevue/badge'
import Button from 'primevue/button'
import Column from 'primevue/column'
import DataTable from 'primevue/datatable'
import Message from 'primevue/message'
import ProgressSpinner from 'primevue/progressspinner'
import { computed, ref } from 'vue'

import {
AuditLog,
EventType,
useCustomerEventsService
} from '@/services/customerEventsService'

const events = ref<AuditLog[]>([])
const loading = ref(true)
const error = ref<string | null>(null)

const customerEventService = useCustomerEventsService()

const pagination = ref({
page: 1,
limit: 7,
total: 0,
totalPages: 0
})

const dataTableFirst = computed(
() => (pagination.value.page - 1) * pagination.value.limit
)

const tooltipContentMap = computed(() => {
const map = new Map<string, string>()
events.value.forEach((event) => {
if (customerEventService.hasAdditionalInfo(event) && event.event_id) {
map.set(event.event_id, customerEventService.getTooltipContent(event))
}
})
return map
})

const loadEvents = async () => {
loading.value = true
error.value = null

try {
const response = await customerEventService.getMyEvents({
page: pagination.value.page,
limit: pagination.value.limit
})

if (response) {
if (response.events) {
events.value = response.events
}

if (response.page) {
pagination.value.page = response.page
}

if (response.limit) {
pagination.value.limit = response.limit
}

if (response.total) {
pagination.value.total = response.total
}

if (response.totalPages) {
pagination.value.totalPages = response.totalPages
}
} else {
error.value = customerEventService.error.value || 'Failed to load events'
}
} catch (err) {
error.value = err instanceof Error ? err.message : 'Unknown error'
console.error('Error loading events:', err)
} finally {
loading.value = false
}
}

const onPageChange = (event: { page: number }) => {
pagination.value.page = event.page + 1
void loadEvents()
}

const refresh = async () => {
pagination.value.page = 1
await loadEvents()
}

defineExpose({
refresh
})
</script>

<style scoped></style>
10 changes: 9 additions & 1 deletion src/locales/en/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -1419,6 +1419,7 @@
"personalDataConsentRequired": "You must agree to the processing of your personal data."
},
"credits": {
"activity": "Activity",
"credits": "Credits",
"yourCreditBalance": "Your credit balance",
"purchaseCredits": "Purchase Credits",
Expand All @@ -1435,7 +1436,14 @@
"buyNow": "Buy now",
"seeDetails": "See details",
"topUp": "Top Up"
}
},
"eventType": "Event Type",
"details": "Details",
"time": "Time",
"additionalInfo": "Additional Info",
"model": "Model",
"added": "Added",
"accountInitialized": "Account initialized"
},
"userSettings": {
"title": "User Settings",
Expand Down
8 changes: 8 additions & 0 deletions src/locales/es/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -138,13 +138,21 @@
"Unpin": "Desanclar"
},
"credits": {
"accountInitialized": "Cuenta inicializada",
"activity": "Actividad",
"added": "Añadido",
"additionalInfo": "Información adicional",
"apiPricing": "Precios de la API",
"credits": "Créditos",
"details": "Detalles",
"eventType": "Tipo de evento",
"faqs": "Preguntas frecuentes",
"invoiceHistory": "Historial de facturas",
"lastUpdated": "Última actualización",
"messageSupport": "Contactar soporte",
"model": "Modelo",
"purchaseCredits": "Comprar créditos",
"time": "Hora",
"topUp": {
"buyNow": "Comprar ahora",
"insufficientMessage": "No tienes suficientes créditos para ejecutar este flujo de trabajo.",
Expand Down
8 changes: 8 additions & 0 deletions src/locales/fr/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -138,13 +138,21 @@
"Unpin": "Désépingler"
},
"credits": {
"accountInitialized": "Compte initialisé",
"activity": "Activité",
"added": "Ajouté",
"additionalInfo": "Informations supplémentaires",
"apiPricing": "Tarification de l’API",
"credits": "Crédits",
"details": "Détails",
"eventType": "Type d'événement",
"faqs": "FAQ",
"invoiceHistory": "Historique des factures",
"lastUpdated": "Dernière mise à jour",
"messageSupport": "Contacter le support",
"model": "Modèle",
"purchaseCredits": "Acheter des crédits",
"time": "Heure",
"topUp": {
"buyNow": "Acheter maintenant",
"insufficientMessage": "Vous n'avez pas assez de crédits pour exécuter ce workflow.",
Expand Down
8 changes: 8 additions & 0 deletions src/locales/ja/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -138,13 +138,21 @@
"Unpin": "ピンを解除"
},
"credits": {
"accountInitialized": "アカウントが初期化されました",
"activity": "アクティビティ",
"added": "追加済み",
"additionalInfo": "追加情報",
"apiPricing": "API料金",
"credits": "クレジット",
"details": "詳細",
"eventType": "イベントタイプ",
"faqs": "よくある質問",
"invoiceHistory": "請求履歴",
"lastUpdated": "最終更新",
"messageSupport": "サポートにメッセージ",
"model": "モデル",
"purchaseCredits": "クレジットを購入",
"time": "時間",
"topUp": {
"buyNow": "今すぐ購入",
"insufficientMessage": "このワークフローを実行するのに十分なクレジットがありません。",
Expand Down
8 changes: 8 additions & 0 deletions src/locales/ko/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -138,13 +138,21 @@
"Unpin": "고정 해제"
},
"credits": {
"accountInitialized": "계정이 초기화됨",
"activity": "활동",
"added": "추가됨",
"additionalInfo": "추가 정보",
"apiPricing": "API 가격",
"credits": "크레딧",
"details": "세부 정보",
"eventType": "이벤트 유형",
"faqs": "자주 묻는 질문",
"invoiceHistory": "청구서 내역",
"lastUpdated": "마지막 업데이트",
"messageSupport": "지원 문의",
"model": "모델",
"purchaseCredits": "크레딧 구매",
"time": "시간",
"topUp": {
"buyNow": "지금 구매",
"insufficientMessage": "이 워크플로우를 실행하기에 크레딧이 부족합니다.",
Expand Down
8 changes: 8 additions & 0 deletions src/locales/ru/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -138,13 +138,21 @@
"Unpin": "Открепить"
},
"credits": {
"accountInitialized": "Аккаунт инициализирован",
"activity": "Активность",
"added": "Добавлено",
"additionalInfo": "Дополнительная информация",
"apiPricing": "Цены на API",
"credits": "Кредиты",
"details": "Детали",
"eventType": "Тип события",
"faqs": "Часто задаваемые вопросы",
"invoiceHistory": "История счетов",
"lastUpdated": "Последнее обновление",
"messageSupport": "Связаться с поддержкой",
"model": "Модель",
"purchaseCredits": "Купить кредиты",
"time": "Время",
"topUp": {
"buyNow": "Купить сейчас",
"insufficientMessage": "У вас недостаточно кредитов для запуска этого рабочего процесса.",
Expand Down
Loading