Skip to main content

Services API Reference

This document provides API documentation for the core services in the Kuviq application.

Overview​

Services are static classes that encapsulate business logic and Firebase interactions. They follow a consistent pattern:

  • Static methods for all operations
  • Automatic organization scoping
  • Firestore document preparation with metadata
  • Consistent error handling

Core Services​

ItemService​

Manages items (equipment) in the system.

import { ItemService } from '@/services/ItemService'

Methods​

MethodDescriptionReturns
getAllItems()Get all items (admin only)Promise<Item[]>
getItemsByOrganization(orgId)Get items for an organizationPromise<Item[]>
getItem(itemId)Get a single item by IDPromise<Item | null>
createItem(item, userId)Create a new itemPromise<Item>
updateItem(itemId, updates, userId)Update an itemPromise<void>
deleteItem(itemId)Soft delete an itemPromise<void>
transferItemToOrganization(itemId, targetOrgId)Transfer item to another orgPromise<void>

Example​

// Get items for current organization
const items = await ItemService.getItemsByOrganization(organizationId)

// Create a new item
const newItem = await ItemService.createItem({
name: 'Fire Extinguisher',
itemTypeId: 'type123',
locationId: 'loc456',
status: ItemStatus.ACTIVE,
organizationId: organizationId,
}, userId)

SubscriptionService​

Manages organization subscriptions and feature limits.

import { SubscriptionService } from '@/services/SubscriptionService'

Methods​

MethodDescriptionReturns
getSubscription(orgId)Get subscription detailsPromise<Subscription | null>
getCurrentUsage(orgId)Get current usage metricsPromise<UsageMetrics | null>
checkUsageLimit(orgId, metric, value)Check if within limitsPromise<LimitCheck>
updateUsage(orgId, usage, userId)Update usage metricsPromise<void>
getFeatures(orgId)Get enabled featuresPromise<Features>
checkFeatureAccess(orgId, feature)Check feature availabilityPromise<boolean>

Example​

// Check if user can create more items
const { withinLimit, limit, current } = await SubscriptionService.checkUsageLimit(
organizationId,
'items',
currentItemCount + 1
)

if (!withinLimit) {
throw new Error(`Item limit reached (${current}/${limit})`)
}

UsageService​

Tracks and manages usage metrics for organizations.

import { UsageService } from '@/services/UsageService'

Methods​

MethodDescriptionReturns
incrementUsage(orgId, metric, amount, userId)Increment a metricPromise<void>
decrementUsage(orgId, metric, amount, userId)Decrement a metricPromise<void>
setUsage(orgId, metric, value, userId)Set a metric valuePromise<void>
getCurrentUsage(orgId)Get current usagePromise<UsageMetrics | null>
getUsageHistory(orgId, metric?, days?)Get usage historyPromise<UsageRecord[]>
checkUsageLimit(orgId, metric, increment?)Check limit with proposed changePromise<LimitCheckResult>
resetUsage(orgId, userId)Reset all usage (admin)Promise<void>

Metrics​

  • users - Active user count
  • items - Total items
  • inspections - Completed inspections
  • locations - Active locations
  • templates - Inspection templates
  • storage - Storage used (bytes)

SecurityService​

Handles security operations including rate limiting and audit logging.

import { SecurityService } from '@/services/SecurityService'

Methods​

MethodDescriptionReturns
checkRateLimit(userId, action)Check rate limit for actionPromise<boolean>
logSecurityEvent(event)Log a security eventPromise<void>
getSecurityEvents(orgId, filters?)Get security eventsPromise<SecurityEvent[]>
validateSession(sessionId)Validate a sessionPromise<boolean>

NotificationService​

Manages in-app notifications.

import { NotificationService } from '@/services/NotificationService'

Methods​

MethodDescriptionReturns
createNotification(notification)Create a notificationPromise<Notification>
getUserNotifications(userId, orgId)Get user notificationsPromise<Notification[]>
markAsRead(notificationId)Mark notification readPromise<void>
markAllAsRead(userId, orgId)Mark all as readPromise<void>
deleteNotification(notificationId)Delete a notificationPromise<void>

AnalyticsService​

Provides analytics and reporting data.

import { AnalyticsService } from '@/services/AnalyticsService'

Methods​

MethodDescriptionReturns
getInspectionStats(orgId, dateRange)Get inspection statisticsPromise<InspectionStats>
getItemStats(orgId)Get item statisticsPromise<ItemStats>
getComplianceRate(orgId, dateRange)Get compliance ratePromise<number>
getTrendData(orgId, metric, days)Get trend dataPromise<TrendData[]>

ReportService​

Generates and manages reports.

import { ReportService } from '@/services/reportService'

Methods​

MethodDescriptionReturns
generateReport(config)Generate a reportPromise<Report>
getReports(orgId)Get saved reportsPromise<Report[]>
getReport(reportId)Get a single reportPromise<Report | null>
deleteReport(reportId)Delete a reportPromise<void>
exportReport(reportId, format)Export report (PDF/Excel)Promise<Blob>

Import/Export Services​

UnifiedImportExportService​

Unified service for bulk import/export operations.

import { UnifiedImportExportService } from '@/services/UnifiedImportExportService'

Methods​

MethodDescriptionReturns
importData(entityType, data, options)Import data from filePromise<ImportResult>
exportData(entityType, filters, format)Export data to filePromise<Blob>
validateImportData(entityType, data)Validate before importPromise<ValidationResult>
getImportTemplate(entityType, format)Get import templatePromise<Blob>

Supported Entity Types​

  • items - Items/equipment
  • locations - Locations
  • users - Users
  • itemTypes - Item types
  • manufacturers - Manufacturers

Supported Formats​

  • xlsx - Excel (ExcelJS)
  • csv - CSV
  • json - JSON

ExportService​

Lower-level export functionality.

import { ExportService } from '@/services/ExportService'

Methods​

MethodDescriptionReturns
exportToExcel(data, columns, filename)Export to ExcelPromise<void>
exportToCsv(data, columns, filename)Export to CSVPromise<void>
exportToPdf(data, config)Export to PDFPromise<void>

QR Code Services​

QRCodeService​

Generates and manages QR codes.

import { QRCodeService } from '@/services/QRCodeService'

Methods​

MethodDescriptionReturns
generateQRCode(itemId, options?)Generate QR codePromise<string>
generateBulkQRCodes(itemIds, options?)Generate multiple QR codesPromise<QRCodeData[]>
parseQRCode(data)Parse QR code dataQRCodeInfo

QRCodePdfService​

Generates printable QR code PDFs.

import { QRCodePdfService } from '@/services/QRCodePdfService'

Methods​

MethodDescriptionReturns
generatePdf(items, options)Generate QR code PDFPromise<Blob>
generateLabels(items, labelConfig)Generate label sheetPromise<Blob>

Scheduling Services​

AutoSchedulingService​

Automatically schedules inspections based on rules.

import { AutoSchedulingService } from '@/services/AutoSchedulingService'

Methods​

MethodDescriptionReturns
scheduleInspections(orgId, scheduleConfig)Schedule inspectionsPromise<Inspection[]>
updateSchedule(scheduleId, updates)Update schedulePromise<void>
cancelSchedule(scheduleId)Cancel a schedulePromise<void>
getUpcomingInspections(orgId, days?)Get upcoming inspectionsPromise<Inspection[]>

ScheduleUpdateService​

Handles schedule updates and recalculations.

import { ScheduleUpdateService } from '@/services/ScheduleUpdateService'

Methods​

MethodDescriptionReturns
recalculateSchedules(orgId)Recalculate all schedulesPromise<void>
updateNextInspectionDate(itemId)Update item's next datePromise<void>

Trial & Onboarding Services​

TrialService​

Manages trial subscriptions, extensions, and auto-extension logic.

import { TrialService } from '@/services/TrialService'

Methods​

MethodDescriptionReturns
startTrial(orgId, options?)Start a trial (accepts optional intendedPlan)Promise<Trial>
getTrialStatus(orgId)Get trial status with daysRemaining, canExtend, etc.Promise<TrialStatus>
requestExtension(orgId, reason)Submit an extension requestPromise<void>
getExtensionStatus(orgId)Check pending extension requestsPromise<ExtensionStatus>
approveExtension(extensionId, notes?)Approve an extension (admin)Promise<void>
rejectExtension(extensionId, notes?)Reject an extension (admin)Promise<void>
endTrial(orgId)End trial earlyPromise<void>

Trial Duration Resolution​

Duration is resolved in priority order:

  1. Per-org trialDurationDays override (set by admin)
  2. Plan-based planDurations[intendedPlan] from TrialConfig
  3. Global durationDays default (14 days)

TrialConfig Structure​

Configuration stored at systemConfig/trial in Firestore:

interface TrialConfig {
durationDays: number // Global default (14)
maxUsage: { locations: number, items: number, templates: number, inspections: number }
featureOverrides?: Partial<SubscriptionFeatures> // Enable Pro features in trial
planDurations?: Partial<Record<SubscriptionPlan, number>> // Per-plan trial durations
emailReminders?: { threeDayWarning: boolean, oneDayWarning: boolean, expiredNotice: boolean }
autoExtension?: {
enabled: boolean // Default: false
minItemsCreated: number // Default: 3
minInspectionsCompleted: number // Default: 1
maxAutoExtensions: number // Default: 1
extensionDays: number // Default: 7
}
}

Config is loaded from Firestore with in-memory caching.

Example​

// Start a trial with enterprise plan duration
await TrialService.startTrial(orgId, { intendedPlan: 'enterprise' })

// Check trial status
const status = await TrialService.getTrialStatus(orgId)
// → { daysRemaining: 12, isExpired: false, canExtend: true, extensionCount: 0 }

// Request an extension
await TrialService.requestExtension(orgId, 'Need more time to evaluate')

TrialActivityService​

Tracks aggregate usage during the trial period. Counters are used for auto-extension qualification, email personalization, and the activity summary on the TrialExpiredWall.

import { TrialActivityService } from '@/services/TrialActivityService'

Tracked Fields​

FieldIncremented When
itemsCreatedUser creates a new item
inspectionsCompletedUser completes an inspection
templatesCreatedUser creates a template
locationsAddedUser adds a location
schedulesCreatedUser creates a schedule

Activity is only tracked when subscriptionStatus === 'trial'. Counters are stored on organization.trialActivity.


OnboardingService​

Manages organization setup and auto-provisioning.

import { OnboardingService } from '@/services/OnboardingService'

Methods​

MethodDescriptionReturns
provisionOrganization(orgId, industry)Auto-provision industry-default dataPromise<void>
generateDemoData(orgId)Generate demo dataPromise<void>

Monitoring Service​

monitoringService​

Application monitoring and error tracking.

import { monitoringService } from '@/services/monitoringService'

Methods​

MethodDescriptionReturns
trackError(error, context?)Track an errorvoid
trackMetric(name, value, tags?)Track a metricvoid
trackEvent(name, properties?)Track an eventvoid
startSpan(name)Start a performance spanSpan
endSpan(span)End a performance spanvoid

Example​

// Track an error
monitoringService.trackError(error, {
component: 'InspectionForm',
action: 'submit',
userId: currentUser.id,
})

// Track a metric
monitoringService.trackMetric('inspection_duration', durationMs, {
templateId: template.id,
})

Error Handling​

All services use consistent error handling:

try {
await SomeService.someMethod()
} catch (error) {
// Errors are logged to console with context
// Original error is wrapped in a descriptive Error
throw new Error('Failed to perform operation')
}

Type Imports​

Service types are available from the types directory:

import type { Item, Inspection, Location } from '@/types/models'
import type { Subscription, UsageMetrics } from '@/types/subscription'
import type { Report, ReportConfig } from '@/types/report'