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
| Method | Description | Returns |
|---|---|---|
getAllItems() | Get all items (admin only) | Promise<Item[]> |
getItemsByOrganization(orgId) | Get items for an organization | Promise<Item[]> |
getItem(itemId) | Get a single item by ID | Promise<Item | null> |
createItem(item, userId) | Create a new item | Promise<Item> |
updateItem(itemId, updates, userId) | Update an item | Promise<void> |
deleteItem(itemId) | Soft delete an item | Promise<void> |
transferItemToOrganization(itemId, targetOrgId) | Transfer item to another org | Promise<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
| Method | Description | Returns |
|---|---|---|
getSubscription(orgId) | Get subscription details | Promise<Subscription | null> |
getCurrentUsage(orgId) | Get current usage metrics | Promise<UsageMetrics | null> |
checkUsageLimit(orgId, metric, value) | Check if within limits | Promise<LimitCheck> |
updateUsage(orgId, usage, userId) | Update usage metrics | Promise<void> |
getFeatures(orgId) | Get enabled features | Promise<Features> |
checkFeatureAccess(orgId, feature) | Check feature availability | Promise<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
| Method | Description | Returns |
|---|---|---|
incrementUsage(orgId, metric, amount, userId) | Increment a metric | Promise<void> |
decrementUsage(orgId, metric, amount, userId) | Decrement a metric | Promise<void> |
setUsage(orgId, metric, value, userId) | Set a metric value | Promise<void> |
getCurrentUsage(orgId) | Get current usage | Promise<UsageMetrics | null> |
getUsageHistory(orgId, metric?, days?) | Get usage history | Promise<UsageRecord[]> |
checkUsageLimit(orgId, metric, increment?) | Check limit with proposed change | Promise<LimitCheckResult> |
resetUsage(orgId, userId) | Reset all usage (admin) | Promise<void> |
Metrics
users- Active user countitems- Total itemsinspections- Completed inspectionslocations- Active locationstemplates- Inspection templatesstorage- Storage used (bytes)
SecurityService
Handles security operations including rate limiting and audit logging.
import { SecurityService } from '@/services/SecurityService'
Methods
| Method | Description | Returns |
|---|---|---|
checkRateLimit(userId, action) | Check rate limit for action | Promise<boolean> |
logSecurityEvent(event) | Log a security event | Promise<void> |
getSecurityEvents(orgId, filters?) | Get security events | Promise<SecurityEvent[]> |
validateSession(sessionId) | Validate a session | Promise<boolean> |
NotificationService
Manages in-app notifications.
import { NotificationService } from '@/services/NotificationService'
Methods
| Method | Description | Returns |
|---|---|---|
createNotification(notification) | Create a notification | Promise<Notification> |
getUserNotifications(userId, orgId) | Get user notifications | Promise<Notification[]> |
markAsRead(notificationId) | Mark notification read | Promise<void> |
markAllAsRead(userId, orgId) | Mark all as read | Promise<void> |
deleteNotification(notificationId) | Delete a notification | Promise<void> |
AnalyticsService
Provides analytics and reporting data.
import { AnalyticsService } from '@/services/AnalyticsService'
Methods
| Method | Description | Returns |
|---|---|---|
getInspectionStats(orgId, dateRange) | Get inspection statistics | Promise<InspectionStats> |
getItemStats(orgId) | Get item statistics | Promise<ItemStats> |
getComplianceRate(orgId, dateRange) | Get compliance rate | Promise<number> |
getTrendData(orgId, metric, days) | Get trend data | Promise<TrendData[]> |
ReportService
Generates and manages reports.
import { ReportService } from '@/services/reportService'
Methods
| Method | Description | Returns |
|---|---|---|
generateReport(config) | Generate a report | Promise<Report> |
getReports(orgId) | Get saved reports | Promise<Report[]> |
getReport(reportId) | Get a single report | Promise<Report | null> |
deleteReport(reportId) | Delete a report | Promise<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
| Method | Description | Returns |
|---|---|---|
importData(entityType, data, options) | Import data from file | Promise<ImportResult> |
exportData(entityType, filters, format) | Export data to file | Promise<Blob> |
validateImportData(entityType, data) | Validate before import | Promise<ValidationResult> |
getImportTemplate(entityType, format) | Get import template | Promise<Blob> |
Supported Entity Types
items- Items/equipmentlocations- Locationsusers- UsersitemTypes- Item typesmanufacturers- Manufacturers
Supported Formats
xlsx- Excel (ExcelJS)csv- CSVjson- JSON
ExportService
Lower-level export functionality.
import { ExportService } from '@/services/ExportService'
Methods
| Method | Description | Returns |
|---|---|---|
exportToExcel(data, columns, filename) | Export to Excel | Promise<void> |
exportToCsv(data, columns, filename) | Export to CSV | Promise<void> |
exportToPdf(data, config) | Export to PDF | Promise<void> |
QR Code Services
QRCodeService
Generates and manages QR codes.
import { QRCodeService } from '@/services/QRCodeService'
Methods
| Method | Description | Returns |
|---|---|---|
generateQRCode(itemId, options?) | Generate QR code | Promise<string> |
generateBulkQRCodes(itemIds, options?) | Generate multiple QR codes | Promise<QRCodeData[]> |
parseQRCode(data) | Parse QR code data | QRCodeInfo |
QRCodePdfService
Generates printable QR code PDFs.
import { QRCodePdfService } from '@/services/QRCodePdfService'
Methods
| Method | Description | Returns |
|---|---|---|
generatePdf(items, options) | Generate QR code PDF | Promise<Blob> |
generateLabels(items, labelConfig) | Generate label sheet | Promise<Blob> |
Scheduling Services
AutoSchedulingService
Automatically schedules inspections based on rules.
import { AutoSchedulingService } from '@/services/AutoSchedulingService'
Methods
| Method | Description | Returns |
|---|---|---|
scheduleInspections(orgId, scheduleConfig) | Schedule inspections | Promise<Inspection[]> |
updateSchedule(scheduleId, updates) | Update schedule | Promise<void> |
cancelSchedule(scheduleId) | Cancel a schedule | Promise<void> |
getUpcomingInspections(orgId, days?) | Get upcoming inspections | Promise<Inspection[]> |
ScheduleUpdateService
Handles schedule updates and recalculations.
import { ScheduleUpdateService } from '@/services/ScheduleUpdateService'
Methods
| Method | Description | Returns |
|---|---|---|
recalculateSchedules(orgId) | Recalculate all schedules | Promise<void> |
updateNextInspectionDate(itemId) | Update item's next date | Promise<void> |
Trial & Onboarding Services
TrialService
Manages trial subscriptions.
import { TrialService } from '@/services/TrialService'
Methods
| Method | Description | Returns |
|---|---|---|
startTrial(orgId, plan) | Start a trial | Promise<Trial> |
getTrialStatus(orgId) | Get trial status | Promise<TrialStatus> |
extendTrial(orgId, days) | Extend trial | Promise<void> |
endTrial(orgId) | End trial early | Promise<void> |
OnboardingService
Manages user onboarding flow.
import { OnboardingService } from '@/services/OnboardingService'
Methods
| Method | Description | Returns |
|---|---|---|
getOnboardingStatus(userId) | Get onboarding status | Promise<OnboardingStatus> |
completeStep(userId, step) | Complete a step | Promise<void> |
skipOnboarding(userId) | Skip onboarding | Promise<void> |
generateDemoData(orgId) | Generate demo data | Promise<void> |
Monitoring Service
monitoringService
Application monitoring and error tracking.
import { monitoringService } from '@/services/monitoringService'
Methods
| Method | Description | Returns |
|---|---|---|
trackError(error, context?) | Track an error | void |
trackMetric(name, value, tags?) | Track a metric | void |
trackEvent(name, properties?) | Track an event | void |
startSpan(name) | Start a performance span | Span |
endSpan(span) | End a performance span | void |
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'