Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

feat: Customer invoice history

Blue Mouse8013b488e855
diff --git a/backend/apps/cloud/src/user/user.controller.ts b/backend/apps/cloud/src/user/user.controller.ts
index f85233267..2a6133541 100644
--- a/backend/apps/cloud/src/user/user.controller.ts
+++ b/backend/apps/cloud/src/user/user.controller.ts
@@ -43,7 +43,7 @@ import { Markup } from 'telegraf'
import { Public, CurrentUserId, Auth } from '../auth/decorators'
import { TelegramService } from '../integrations/telegram/telegram.service'
-import { UserService } from './user.service'
+import { UserService, UserPayment } from './user.service'
import { ProjectService, deleteProjectRedis } from '../project/project.service'
import {
User,
@@ -863,6 +863,12 @@ export class UserController {
}
}
+ @ApiBearerAuth()
+ @Get('payments')
+ async getPayments(@CurrentUserId() uid: string): Promise<UserPayment[]> {
+ return this.userService.getPayments(uid)
+ }
+
@ApiBearerAuth()
@Post('change-plan')
async changePlan(
diff --git a/backend/apps/cloud/src/user/user.service.ts b/backend/apps/cloud/src/user/user.service.ts
index c0196860f..0e76d434a 100644
--- a/backend/apps/cloud/src/user/user.service.ts
+++ b/backend/apps/cloud/src/user/user.service.ts
@@ -63,7 +63,7 @@ import {
} from './entities/subscription-dunning.entity'
import { UserGoogleDTO } from './dto/user-google.dto'
import { UserGithubDTO } from './dto/user-github.dto'
-import { EMAIL_ACTION_ENCRYPTION_KEY } from '../common/constants'
+import { EMAIL_ACTION_ENCRYPTION_KEY, redis } from '../common/constants'
import { ReportFrequency } from '../project/enums'
import { OrganisationService } from '../organisation/organisation.service'
@@ -124,6 +124,18 @@ const CURRENCY_BY_COUNTRY = {
}
const { PADDLE_VENDOR_ID, PADDLE_API_KEY } = process.env
+// Paddle's vendor API is slow and rate limited; receipts do not change once
+// issued, so an hour-long cache is safe
+const PAYMENTS_CACHE_TTL_SECONDS = 3600
+
+export interface UserPayment {
+ id: number
+ date: string
+ amount: number
+ currency: string
+ isOneOff: boolean
+ receiptUrl: string | null
+}
const DEFAULT_CDN_URL = 'https://cdn.swetrix.com'
const FEEDBACK_ATTACHMENT_UPLOAD_TIMEOUT_MS = 10_000
const WEBSITE_ADDON_BUNDLE_SIZE = 50
@@ -1051,6 +1063,72 @@ export class UserService {
return data.response || {}
}
+ // Payments (receipts) for the currently authenticated user only: the
+ // subscription id is always read from the user's own DB record and is never
+ // accepted from the client
+ async getPayments(userId: string): Promise<UserPayment[]> {
+ const user = await this.findOne({
+ where: { id: userId },
+ select: ['id', 'subID'],
+ })
+
+ if (!user?.subID || !PADDLE_VENDOR_ID || !PADDLE_API_KEY) {
+ return []
+ }
+
+ const cacheKey = `user-payments:${user.id}`
+ const cached = await redis.get(cacheKey).catch(() => null)
+
+ if (cached) {
+ try {
+ return JSON.parse(cached)
+ } catch {
+ // fall through to a fresh fetch
+ }
+ }
+
+ const body = new URLSearchParams()
+ body.set('vendor_id', String(Number(PADDLE_VENDOR_ID)))
+ body.set('vendor_auth_code', PADDLE_API_KEY)
+ body.set('subscription_id', String(Number(user.subID)))
+ body.set('is_paid', '1')
+
+ const res = await fetch(
+ 'https://vendors.paddle.com/api/2.0/subscription/payments',
+ {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
+ body,
+ },
+ )
+ const data = await res.json()
+
+ if (!res.ok || !data?.success) {
+ console.error(
+ '[ERROR] (getPayments) Paddle payments request failed:',
+ JSON.stringify(data?.error || data),
+ )
+ throw new ServiceUnavailableException('Failed to load payment history')
+ }
+
+ const payments: UserPayment[] = (data.response || [])
+ .map((payment: Record<string, any>) => ({
+ id: Number(payment.id),
+ date: String(payment.payout_date || ''),
+ amount: Number(payment.amount) || 0,
+ currency: String(payment.currency || 'USD'),
+ isOneOff: Boolean(payment.is_one_off_charge),
+ receiptUrl: payment.receipt_url ? String(payment.receipt_url) : null,
+ }))
+ .sort((a: UserPayment, b: UserPayment) => b.date.localeCompare(a.date))
+
+ await redis
+ .set(cacheKey, JSON.stringify(payments), 'EX', PAYMENTS_CACHE_TTL_SECONDS)
+ .catch(() => null)
+
+ return payments
+ }
+
private buildWebsiteAddonChargeKey(
addon: UserAddon,
user: User,
diff --git a/web/app/pages/UserSettings/UserSettings.tsx b/web/app/pages/UserSettings/UserSettings.tsx
index 05c75709d..be8d8cd76 100644
--- a/web/app/pages/UserSettings/UserSettings.tsx
+++ b/web/app/pages/UserSettings/UserSettings.tsx
@@ -19,6 +19,8 @@ import {
CaretDownIcon,
CreditCardIcon,
ArrowRightIcon,
+ ArrowSquareOutIcon,
+ ReceiptIcon,
} from '@phosphor-icons/react'
import _round from 'lodash/round'
import React, {
@@ -68,6 +70,7 @@ import { useAuth } from '~/providers/AuthProvider'
import { useTheme } from '~/providers/ThemeProvider'
import type {
SessionReplayAddonPreview,
+ UserPayment,
UserSettingsActionData,
UserSettingsLoaderData,
WebsiteAddonPreview,
@@ -281,6 +284,7 @@ const UserSettings = () => {
const websiteAddonPreviewFetcher = useFetcher<UserSettingsActionData>()
const sessionReplayAddonFetcher = useFetcher<UserSettingsActionData>()
const sessionReplayAddonPreviewFetcher = useFetcher<UserSettingsActionData>()
+ const paymentsFetcher = useFetcher<UserSettingsActionData>()
// Stable submit handle for the preview fetcher. Effects must depend on this,
// not on the fetcher object (whose identity changes on every state transition
@@ -301,6 +305,13 @@ const UserSettings = () => {
sessionReplayAddonPreviewFetcherRef.current.submit(...args),
[],
)
+ const paymentsFetcherRef = useRef(paymentsFetcher)
+ paymentsFetcherRef.current = paymentsFetcher
+ const paymentsSubmit = useCallback(
+ (...args: Parameters<typeof paymentsFetcher.submit>) =>
+ paymentsFetcherRef.current.submit(...args),
+ [],
+ )
const [searchParams, setSearchParams] = useSearchParams()
@@ -931,6 +942,41 @@ const UserSettings = () => {
sessionReplayAddonPreviewSubmit,
])
+ // Lazily load the payment history the first time the billing tab is opened.
+ // Kept out of the route loader so a cold Paddle fetch never delays the page.
+ const hasRequestedPaymentsRef = useRef(false)
+ useEffect(() => {
+ if (
+ activeTab !== TAB_MAPPING.BILLING ||
+ isSelfhosted ||
+ !user?.id ||
+ hasRequestedPaymentsRef.current
+ ) {
+ return
+ }
+
+ hasRequestedPaymentsRef.current = true
+ const formData = new FormData()
+ formData.set('intent', 'get-payments')
+ paymentsSubmit(formData, { method: 'POST', action: '/user-settings' })
+ }, [activeTab, user?.id, paymentsSubmit])
+
+ const payments = useMemo(() => {
+ if (paymentsFetcher.data?.success && paymentsFetcher.data.data) {
+ return paymentsFetcher.data.data as UserPayment[]
+ }
+ return null
+ }, [paymentsFetcher.data])
+ const paymentsError =
+ paymentsFetcher.state === 'idle' ? paymentsFetcher.data?.error : undefined
+ const isPaymentsLoading = !payments && !paymentsError
+
+ const onRetryPayments = useCallback(() => {
+ const formData = new FormData()
+ formData.set('intent', 'get-payments')
+ paymentsSubmit(formData, { method: 'POST', action: '/user-settings' })
+ }, [paymentsSubmit])
+
useEffect(() => {
if (fetcher.state !== 'idle' || !fetcher.data) return
if (!shouldHandleFetcherData(fetcher.data)) return
@@ -2674,6 +2720,171 @@ const UserSettings = () => {
</Button>
</div>
</SettingsSection>
+
+ <SettingsSection
+ title={t('billing.invoicesTitle')}
+ description={t('billing.invoicesDesc')}
+ >
+ <div className='border-t border-gray-200 pt-4 dark:border-slate-800'>
+ {isPaymentsLoading ? (
+ <div className='space-y-2' aria-hidden='true'>
+ {[0, 1, 2].map((index) => (
+ <div
+ key={index}
+ className='h-12 animate-pulse rounded-lg bg-gray-100 dark:bg-slate-800/60'
+ />
+ ))}
+ </div>
+ ) : paymentsError ? (
+ <Alert
+ variant='error'
+ title={t('billing.invoicesLoadError')}
+ >
+ <button
+ type='button'
+ onClick={onRetryPayments}
+ className='font-medium underline underline-offset-4 hover:no-underline'
+ >
+ {t('billing.invoicesRetry')}
+ </button>
+ </Alert>
+ ) : _isEmpty(payments) ? (
+ <div className='flex flex-col items-center rounded-lg border border-dashed border-gray-300 px-6 py-10 text-center dark:border-slate-700'>
+ <ReceiptIcon
+ className='size-8 text-gray-400 dark:text-slate-500'
+ aria-hidden='true'
+ />
+ <Text
+ as='p'
+ size='base'
+ weight='semibold'
+ className='mt-3'
+ >
+ {t('billing.invoicesEmpty')}
+ </Text>
+ <Text
+ as='p'
+ size='sm'
+ colour='secondary'
+ className='mt-1 max-w-sm'
+ >
+ {t('billing.invoicesEmptyDesc')}
+ </Text>
+ </div>
+ ) : (
+ <>
+ <div className='overflow-hidden rounded-lg border border-gray-200 dark:border-slate-800'>
+ <div className='overflow-x-auto'>
+ <table className='min-w-full divide-y divide-gray-200 dark:divide-slate-800'>
+ <thead className='bg-gray-50 dark:bg-slate-900'>
+ <tr>
+ <th
+ scope='col'
+ className='px-4 py-3 text-left text-xs font-bold tracking-wider text-gray-900 uppercase dark:text-white'
+ >
+ {t('billing.invoicesTableDate')}
+ </th>
+ <th
+ scope='col'
+ className='px-4 py-3 text-left text-xs font-bold tracking-wider text-gray-900 uppercase dark:text-white'
+ >
+ {t('billing.invoicesTableDescription')}
+ </th>
+ <th
+ scope='col'
+ className='px-4 py-3 text-right text-xs font-bold tracking-wider text-gray-900 uppercase dark:text-white'
+ >
+ {t('billing.invoicesTableAmount')}
+ </th>
+ <th
+ scope='col'
+ aria-label={t('ariaLabels.actions')}
+ className='px-4 py-3'
+ />
+ </tr>
+ </thead>
+ <tbody className='divide-y divide-gray-200 bg-white dark:divide-slate-800 dark:bg-slate-950'>
+ {_map(payments, (payment) => (
+ <tr
+ key={payment.id}
+ onClick={
+ payment.receiptUrl
+ ? (event) => {
+ if (
+ (
+ event.target as HTMLElement
+ ).closest('a')
+ ) {
+ return
+ }
+ window.open(
+ payment.receiptUrl as string,
+ '_blank',
+ 'noopener,noreferrer',
+ )
+ }
+ : undefined
+ }
+ className={cx({
+ 'cursor-pointer transition-colors hover:bg-gray-50 dark:hover:bg-slate-900/50':
+ !!payment.receiptUrl,
+ })}
+ >
+ <td className='px-4 py-3 text-sm font-medium whitespace-nowrap text-gray-900 dark:text-gray-50'>
+ {formatBillingDate(payment.date)}
+ </td>
+ <td className='px-4 py-3 text-sm whitespace-nowrap text-gray-700 dark:text-gray-300'>
+ {payment.isOneOff
+ ? t('billing.invoicesOneOffCharge')
+ : t(
+ 'billing.invoicesSubscriptionPayment',
+ )}
+ </td>
+ <td className='px-4 py-3 text-right text-sm font-medium whitespace-nowrap text-gray-900 tabular-nums dark:text-gray-50'>
+ {formatCurrencyAmount(
+ payment.amount,
+ payment.currency,
+ language,
+ {
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2,
+ },
+ )}
+ </td>
+ <td className='px-4 py-3 text-right text-sm whitespace-nowrap'>
+ {payment.receiptUrl ? (
+ <a
+ href={payment.receiptUrl}
+ target='_blank'
+ rel='noopener noreferrer'
+ className='inline-flex items-center gap-1 font-medium text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-300'
+ >
+ {t('billing.invoicesViewReceipt')}
+ <ArrowSquareOutIcon
+ className='size-4'
+ aria-hidden='true'
+ />
+ </a>
+ ) : null}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ </div>
+ <Text
+ as='p'
+ size='xs'
+ colour='secondary'
+ className='mt-3'
+ >
+ {t('billing.invoicesPaddleNote')}
+ </Text>
+ </>
+ )}
+ </div>
+ </SettingsSection>
</>
)}
</>
diff --git a/web/app/routes/user-settings.tsx b/web/app/routes/user-settings.tsx
index 604a15569..51e59e6a8 100644
--- a/web/app/routes/user-settings.tsx
+++ b/web/app/routes/user-settings.tsx
@@ -103,6 +103,15 @@ export interface UserSettingsActionData {
data?: unknown
}
+export interface UserPayment {
+ id: number
+ date: string
+ amount: number
+ currency: string
+ isOneOff: boolean
+ receiptUrl: string | null
+}
+
export interface WebsiteAddonPreview {
code: 'websites'
quantity: number
@@ -832,6 +841,22 @@ export async function action({ request }: ActionFunctionArgs) {
)
}
+ case 'get-payments': {
+ const result = await serverFetch<UserPayment[]>(request, 'user/payments')
+
+ if (result.error) {
+ return data<UserSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
+ }
+
+ return data<UserSettingsActionData>(
+ { intent, success: true, data: result.data },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+ }
+
case 'accept-organisation-invitation': {
const membershipId = formData.get('membershipId')?.toString()
diff --git a/web/public/locales/en.json b/web/public/locales/en.json
index 2822feef5..65ad20bbc 100644
--- a/web/public/locales/en.json
+++ b/web/public/locales/en.json
@@ -3086,7 +3086,20 @@
"sessionReplayAddonNextRenewal": "the next renewal",
"sessionReplayAddonPendingChange": "A scheduled session replay add-on change will take effect on {{date}}. Select a new quantity or update the current settings to replace it.",
"sessionReplayAddonSave": "Update add-on",
- "sessionReplayAddonComingSoon": "Self-serve session replay add-ons are coming soon."
+ "sessionReplayAddonComingSoon": "Self-serve session replay add-ons are coming soon.",
+ "invoicesTitle": "Invoices",
+ "invoicesDesc": "Receipts for every payment made on your account.",
+ "invoicesTableDate": "Date",
+ "invoicesTableDescription": "Description",
+ "invoicesTableAmount": "Amount",
+ "invoicesSubscriptionPayment": "Subscription payment",
+ "invoicesOneOffCharge": "One-off charge",
+ "invoicesViewReceipt": "View receipt",
+ "invoicesEmpty": "No invoices yet",
+ "invoicesEmptyDesc": "Once you are charged for your subscription, receipts will show up here.",
+ "invoicesLoadError": "We could not load your invoices. Please try again later.",
+ "invoicesRetry": "Try again",
+ "invoicesPaddleNote": "Payments are processed by Paddle, our merchant of record. Receipts open on paddle.com."
},
"modals": {
"paidFeature": {