65 lines
2.2 KiB
Swift
65 lines
2.2 KiB
Swift
// Models/LocalTemplate.swift
|
|
// --------------------------
|
|
// SwiftData model for locally cached inspection templates.
|
|
// The form_schema is stored as a raw JSON string and decoded on demand.
|
|
|
|
import Foundation
|
|
import SwiftData
|
|
|
|
@Model
|
|
final class LocalTemplate {
|
|
@Attribute(.unique) var serverId: Int
|
|
var name: String
|
|
var templateDescription: String
|
|
var frequency: String
|
|
/// Raw JSON string of the form_schema array — decoded on demand
|
|
var formSchemaJSON: String
|
|
var lastSyncedAt: Date
|
|
|
|
init(from summary: APITemplateSummary) {
|
|
self.serverId = summary.id
|
|
self.name = summary.name
|
|
self.templateDescription = summary.description
|
|
self.frequency = summary.frequency
|
|
self.formSchemaJSON = "[]"
|
|
self.lastSyncedAt = Date()
|
|
}
|
|
|
|
func updateSummary(from summary: APITemplateSummary) {
|
|
self.name = summary.name
|
|
self.templateDescription = summary.description
|
|
self.frequency = summary.frequency
|
|
self.lastSyncedAt = Date()
|
|
}
|
|
|
|
func updateSchema(from template: APITemplate) {
|
|
// Re-serialize the form_schema to JSON for local storage
|
|
if let data = try? JSONSerialization.data(withJSONObject: template.formSchema.map({ dict in
|
|
dict.mapValues { $0.value }
|
|
})),
|
|
let str = String(data: data, encoding: .utf8) {
|
|
self.formSchemaJSON = str
|
|
}
|
|
self.lastSyncedAt = Date()
|
|
}
|
|
|
|
/// Decode the stored JSON string back into an array of field dictionaries.
|
|
/// Returns an empty array if the JSON is invalid.
|
|
var formSchema: [[String: Any]] {
|
|
guard let data = formSchemaJSON.data(using: .utf8),
|
|
let array = try? JSONSerialization.jsonObject(with: data) as? [[String: Any]]
|
|
else { return [] }
|
|
return array
|
|
}
|
|
|
|
var frequencyLabel: String {
|
|
switch frequency {
|
|
case "daily": return "Daily"
|
|
case "weekly": return "Weekly"
|
|
case "monthly": return "Monthly"
|
|
case "quarterly": return "Quarterly"
|
|
default: return frequency.capitalized
|
|
}
|
|
}
|
|
}
|