admin/services/notifications.ts
alisaza e1eaf5eff5 feat: initial ghabilee-admin backoffice app
Extract admin dashboard from ghabilee-frontend2 into a dedicated Next.js
app for backoffice.ghabilee.ir (no SEO indexing / Clarity).
2026-09-05 13:12:59 +03:30

85 lines
2.7 KiB
TypeScript

import type { NotificationResponseDto } from '@/api/generated/models'
import {
createServiceError,
errorResult,
handleServiceError,
type ServiceCallOptions,
type ServiceResult,
shouldBubbleErrorToParent,
successResult,
} from '@/services/errorHandler'
import { unwrapApiData } from '@/services/apiResponse'
import { getNotifications } from '@/api/generated/notifications/notifications'
import { parseRemittanceList } from '@/helpers/listResponse'
import { texts } from '@/texts'
export type InAppNotification = NotificationResponseDto
const notificationsApi = getNotifications()
export const LIST_NOTIFICATIONS = async (options?: ServiceCallOptions): Promise<ServiceResult<{ items: InAppNotification[] }>> => {
try {
const res = await notificationsApi.notificationsControllerListMine({ page: 1, pageSize: 30, sort: '-createdAt' })
const parsed = parseRemittanceList<InAppNotification>(res.data, 'items')
return successResult({ items: parsed.items })
} catch (error) {
const normalizedError = handleServiceError(error, options)
if (shouldBubbleErrorToParent(options)) {
throw normalizedError
}
return errorResult(normalizedError)
}
}
export const GET_UNREAD_NOTIFICATION_COUNT = async (options?: ServiceCallOptions): Promise<ServiceResult<{ totalUnread: number }>> => {
try {
const res = await notificationsApi.notificationsControllerUnreadCount()
if (!res.data.success) throw createServiceError(res.data.message)
const payload = unwrapApiData(res.data)
const totalUnread = Number(payload?.totalUnread ?? 0)
return successResult({ totalUnread: Number.isFinite(totalUnread) ? totalUnread : 0 })
} catch (error) {
const normalizedError = handleServiceError(error, options)
if (shouldBubbleErrorToParent(options)) {
throw normalizedError
}
return errorResult(normalizedError)
}
}
export const MARK_NOTIFICATION_READ = async (
notificationId: string,
options?: ServiceCallOptions
): Promise<ServiceResult<InAppNotification>> => {
try {
const res = await notificationsApi.notificationsControllerMarkAsRead(notificationId)
if (!res.data.success) throw createServiceError(res.data.message)
const payload = unwrapApiData(res.data)
if (!payload?.id) {
throw createServiceError(texts.common.invalidServerResponse)
}
return successResult(payload)
} catch (error) {
const normalizedError = handleServiceError(error, options)
if (shouldBubbleErrorToParent(options)) {
throw normalizedError
}
return errorResult(normalizedError)
}
}
export const countUnreadNotifications = (items: InAppNotification[]): number => items.filter((item) => !item.readAt).length