mycode/myApp/HaruDanim/Shared/DataStore.swift
songyc macbook 40d917d4e2 feat(diary): add iPad-only premium diary tab with calendar, pencil notes, and export
- 달력(작성일 마커: 기분 이모지/연필 점) → 날짜별 일기, 이번 달 작성 수 표시
- 첫 페이지: 날짜·오늘 기분(이모지/사진, 끄기 옵션)·할 일 체크리스트(스크리블 입력)·
  타임테이블·통계(내보내기 스냅숏 재사용으로 화면·내보내기 일치)
- 노트 페이지: PencilKit 캔버스(도구 팔레트) + 줄 노트 배경 + 사진/도형(사각형·원·화살표·선)
  배치 모드(드래그·핀치), 페이지 무한 추가 — 논리 크기 768×1024 고정으로 WYSIWYG 내보내기
- 내보내기: 구간/복수 날짜(MultiDatePicker) → PDF 1개 또는 날짜별 세로 스티치 PNG
- SwiftData 모델 4종(CloudKit 호환 패턴) 스키마 추가, PremiumFeature.diary,
  iPhone 탭 컨텍스트(탭바·더보기·라디얼)에서 일기 제외, en/ja 번역 39건
- 검증 인자: -diarySeed/-diaryOpenToday/-diaryPage N/-diaryShowExport/-diaryExportRun pdf|image

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013yKDMhuF39GVYy3FMcGHh7
2026-07-13 02:51:30 +09:00

167 lines
7.4 KiB
Swift

//
// DataStore.swift
// Haru_Danim
//
// SwiftData (CLAUDE.md §2.2)
// - : App Group (·App Intents DB )
// - default.store 1 App Group
// - iCloud (): CloudKit ,
// - CloudKit . (.appex)
// CloudKit ·
// / . CloudKit .
//
import Foundation
import SwiftData
nonisolated enum DataStore {
/// .
/// App Intents .
static let shared: ModelContainer = makeContainer()
static let schema = Schema([
Tag.self,
Action.self,
TimeSession.self,
CountEntry.self,
Goal.self,
Quest.self,
DiaryEntry.self,
DiaryTodo.self,
DiaryPage.self,
DiaryPageItem.self,
])
/// iCloud on/off (, App Group defaults )
static let cloudSyncKey = "settings.cloudSync"
static let cloudContainerID = "iCloud.com.yechan.HaruDanim"
/// App Group
static var storeURL: URL {
guard let base = FileManager.default.containerURL(
forSecurityApplicationGroupIdentifier: AppGroup.identifier
) else {
// App Group ( )
return URL.applicationSupportDirectory.appending(path: "default.store")
}
return base.appending(path: "HaruDanim.store")
}
/// (.appex)
static var isExtensionProcess: Bool {
Bundle.main.bundleURL.pathExtension == "appex"
}
/// iCloud ( + on)
static var wantsCloudSync: Bool {
#if DEBUG
if UserDefaults.standard.object(forKey: "cloudSync") != nil {
return UserDefaults.standard.bool(forKey: "cloudSync")
}
#endif
return PremiumGate.isUnlocked(.cloudSync) && AppGroup.defaults.bool(forKey: cloudSyncKey)
}
/// ·· .
/// CloudKit .
/// (DataStore.shared) , .
static func makeContainer() -> ModelContainer {
do {
return try makeContainerThrowing()
} catch {
fatalError("[DataStore] 컨테이너 생성 실패: \(error)")
}
}
/// makeContainer throwing .
/// try? ,
/// (= ''
/// ) .
static func makeContainerThrowing() throws -> ModelContainer {
migrateLegacyStoreIfNeeded()
if wantsCloudSync && !isExtensionProcess {
do {
let config = ModelConfiguration(
schema: schema,
url: storeURL,
cloudKitDatabase: .private(cloudContainerID)
)
return try ModelContainer(for: schema, configurations: [config])
} catch {
// iCloud /
print("[DataStore] CloudKit 컨테이너 생성 실패, 로컬로 폴백: \(error)")
}
}
let config = ModelConfiguration(schema: schema, url: storeURL, cloudKitDatabase: .none)
return try ModelContainer(for: schema, configurations: [config])
}
/// uuid : UUID
/// ( · , 1 )
@MainActor
static func ensureUniqueEntityIDs(context: ModelContext) {
var changed = false
var tagIDs = Set<UUID>()
for tag in (try? context.fetch(FetchDescriptor<Tag>())) ?? [] where !tagIDs.insert(tag.uuid).inserted {
tag.uuid = UUID()
changed = true
}
var actionIDs = Set<UUID>()
for action in (try? context.fetch(FetchDescriptor<Action>())) ?? [] where !actionIDs.insert(action.uuid).inserted {
action.uuid = UUID()
changed = true
}
var goalIDs = Set<UUID>()
for goal in (try? context.fetch(FetchDescriptor<Goal>())) ?? [] where !goalIDs.insert(goal.uuid).inserted {
goal.uuid = UUID()
changed = true
}
var questIDs = Set<UUID>()
for quest in (try? context.fetch(FetchDescriptor<Quest>())) ?? [] where !questIDs.insert(quest.uuid).inserted {
quest.uuid = UUID()
changed = true
}
if changed { try? context.save() }
}
/// (Application Support/default.store) DB App Group 1
private static func migrateLegacyStoreIfNeeded() {
let fm = FileManager.default
let target = storeURL
guard target.path != URL.applicationSupportDirectory.appending(path: "default.store").path,
!fm.fileExists(atPath: target.path) else { return }
let legacy = URL.applicationSupportDirectory.appending(path: "default.store")
guard fm.fileExists(atPath: legacy.path) else { return }
// -wal/-shm
for suffix in ["", "-shm", "-wal"] {
let from = URL(fileURLWithPath: legacy.path + suffix)
let to = URL(fileURLWithPath: target.path + suffix)
if fm.fileExists(atPath: from.path) {
try? fm.copyItem(at: from, to: to)
}
}
}
}
// MARK: - App Group
/// · ( , , )
/// UserDefaults.standard App Group defaults 1
nonisolated enum SettingsMigration {
private static let doneKey = "migration.settingsToAppGroup"
static func runIfNeeded() {
let group = AppGroup.defaults
guard !group.bool(forKey: doneKey) else { return }
let standard = UserDefaults.standard
for key in [SettingsKeys.weekStartWeekday, SettingsKeys.dayStartMinutes,
SettingsKeys.liveActivityMode, SettingsKeys.minSessionSeconds,
SettingsKeys.theme] {
if group.object(forKey: key) == nil, let value = standard.object(forKey: key) {
group.set(value, forKey: key)
}
}
group.set(true, forKey: doneKey)
}
}