Actualización sin cambiar de app: Share Extension "Quick Update" + clipboard auto-advance
El dolor: para actualizar cada source hay que saltar a la app del banco, copiar/ memorizar el valor y volver. iOS no permite ventanas flotantes editables (PiP es solo vídeo), así que se resuelve con las dos vías sancionadas: Share Extension (target nuevo PortfolioJournalQuickUpdate): - Al compartir texto desde CUALQUIER app aparece "Portfolio Journal": mini-form sobre la app anfitriona con el importe pre-parseado del texto compartido y la siguiente source pendiente del mes preseleccionada. Guardar → sigues en el banco. - Sin Core Data en la extensión: la app publica un espejo de sources activas en el App Group (SharedQuickUpdateSync.refreshMirror) y la extensión encola PendingQuickUpdate; la app los convierte en Snapshots reales al activarse (ingestPending). ExtSharedBridge duplica el contrato (keep-in-sync comentado). - Parser de importes tolerante a locales (12.345,67 € / $1,234.56 / 1234,5). - UI localizada en los 7 idiomas (lproj propios de la extensión). - pbxproj: target app-extension completo (sync group, embed, dependency, configs) replicando el patrón del widget. Entitlements solo con App Group. Clipboard auto-advance en Quick Update: - Al volver a la app con un importe copiado: banner de un tap "Pegar X en <source>" que rellena la siguiente source vacía y avanza el foco a la siguiente. - Badge NEXT en la fila activa; no repite sugerencias del mismo clipboard. Script de upload: -allowProvisioningUpdates + API key también en el archive para que el bundle id nuevo de la extensión se registre automáticamente. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015qUZrBusG82T37R7PeokqJ
This commit is contained in:
@@ -73,6 +73,12 @@ struct PortfolioJournalApp: App {
|
||||
NotificationService.shared.scheduleReEngagementNotification()
|
||||
NotificationService.shared.scheduleMonthlyCheckIn()
|
||||
NotificationService.shared.scheduleStreakProtectionReminder()
|
||||
// Share-extension bridge: apply values captured from other apps and
|
||||
// refresh the source mirror the extension reads.
|
||||
if coreDataStack.isLoaded {
|
||||
SharedQuickUpdateSync.ingestPending()
|
||||
SharedQuickUpdateSync.refreshMirror()
|
||||
}
|
||||
} else if newPhase == .background {
|
||||
guard iapService.isPremium else { return }
|
||||
guard UserDefaults.standard.bool(forKey: "backupsEnabled") else { return }
|
||||
|
||||
@@ -192,6 +192,11 @@ class CoreDataStack: ObservableObject {
|
||||
AllocationTargetStore.migrateIfNeeded(context: container.viewContext)
|
||||
// Seed demo data when running in screenshot capture mode.
|
||||
ScreenshotMode.seedIfNeeded()
|
||||
// Apply share-extension captures and publish the source mirror.
|
||||
Task { @MainActor in
|
||||
SharedQuickUpdateSync.ingestPending()
|
||||
SharedQuickUpdateSync.refreshMirror()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -446,3 +446,6 @@
|
||||
"chart_zoom_in" = "Vergrößern";
|
||||
"chart_zoom_out" = "Verkleinern";
|
||||
"chart_zoom_reset" = "Zoom zurücksetzen";
|
||||
|
||||
"quick_update_paste_suggestion" = "%@ in %@ einfügen";
|
||||
"quick_update_next_badge" = "NÄCHSTE";
|
||||
|
||||
@@ -454,3 +454,6 @@
|
||||
"chart_zoom_in" = "Zoom in";
|
||||
"chart_zoom_out" = "Zoom out";
|
||||
"chart_zoom_reset" = "Reset zoom";
|
||||
|
||||
"quick_update_paste_suggestion" = "Paste %@ into %@";
|
||||
"quick_update_next_badge" = "NEXT";
|
||||
|
||||
@@ -398,3 +398,6 @@
|
||||
"chart_zoom_in" = "Acercar";
|
||||
"chart_zoom_out" = "Alejar";
|
||||
"chart_zoom_reset" = "Restablecer zoom";
|
||||
|
||||
"quick_update_paste_suggestion" = "Pegar %@ en %@";
|
||||
"quick_update_next_badge" = "SIGUIENTE";
|
||||
|
||||
@@ -446,3 +446,6 @@
|
||||
"chart_zoom_in" = "Zoom avant";
|
||||
"chart_zoom_out" = "Zoom arrière";
|
||||
"chart_zoom_reset" = "Réinitialiser le zoom";
|
||||
|
||||
"quick_update_paste_suggestion" = "Coller %@ dans %@";
|
||||
"quick_update_next_badge" = "SUIVANTE";
|
||||
|
||||
@@ -446,3 +446,6 @@
|
||||
"chart_zoom_in" = "Ingrandisci";
|
||||
"chart_zoom_out" = "Riduci";
|
||||
"chart_zoom_reset" = "Reimposta zoom";
|
||||
|
||||
"quick_update_paste_suggestion" = "Incolla %@ in %@";
|
||||
"quick_update_next_badge" = "PROSSIMA";
|
||||
|
||||
@@ -446,3 +446,6 @@
|
||||
"chart_zoom_in" = "拡大";
|
||||
"chart_zoom_out" = "縮小";
|
||||
"chart_zoom_reset" = "ズームをリセット";
|
||||
|
||||
"quick_update_paste_suggestion" = "%@ を %@ に貼り付け";
|
||||
"quick_update_next_badge" = "次";
|
||||
|
||||
@@ -446,3 +446,6 @@
|
||||
"chart_zoom_in" = "Ampliar";
|
||||
"chart_zoom_out" = "Reduzir";
|
||||
"chart_zoom_reset" = "Redefinir zoom";
|
||||
|
||||
"quick_update_paste_suggestion" = "Colar %@ em %@";
|
||||
"quick_update_next_badge" = "PRÓXIMA";
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
import Foundation
|
||||
import CoreData
|
||||
|
||||
// MARK: - App Group bridge for the Quick Update share extension
|
||||
//
|
||||
// The share extension can't open the CloudKit-backed Core Data store, so the app
|
||||
// maintains a lightweight mirror of active sources in the App Group defaults and
|
||||
// the extension appends "pending updates" to a queue there. The app ingests the
|
||||
// queue on every activation, creating real snapshots.
|
||||
|
||||
/// Snapshot of an active source, enough for the extension's picker.
|
||||
struct SharedSourceInfo: Codable, Identifiable {
|
||||
let id: UUID
|
||||
let name: String
|
||||
let latestValue: Double
|
||||
let currencyCode: String
|
||||
/// True when a value was already recorded this month (by app or extension).
|
||||
var updatedThisMonth: Bool
|
||||
}
|
||||
|
||||
/// A value captured from the share extension, waiting to become a Snapshot.
|
||||
struct PendingQuickUpdate: Codable {
|
||||
let sourceId: UUID
|
||||
let amount: Double
|
||||
let capturedAt: Date
|
||||
}
|
||||
|
||||
enum SharedQuickUpdateStore {
|
||||
private static let mirrorKey = "sharedSourceMirror"
|
||||
private static let queueKey = "pendingQuickUpdates"
|
||||
|
||||
static var defaults: UserDefaults? {
|
||||
UserDefaults(suiteName: AppConstants.appGroupIdentifier)
|
||||
}
|
||||
|
||||
// MARK: Mirror (app writes, extension reads)
|
||||
|
||||
static func writeMirror(_ sources: [SharedSourceInfo]) {
|
||||
guard let data = try? JSONEncoder().encode(sources) else { return }
|
||||
defaults?.set(data, forKey: mirrorKey)
|
||||
}
|
||||
|
||||
static func readMirror() -> [SharedSourceInfo] {
|
||||
guard let data = defaults?.data(forKey: mirrorKey),
|
||||
let decoded = try? JSONDecoder().decode([SharedSourceInfo].self, from: data) else { return [] }
|
||||
return decoded
|
||||
}
|
||||
|
||||
// MARK: Pending queue (extension writes, app drains)
|
||||
|
||||
static func appendPending(_ update: PendingQuickUpdate) {
|
||||
var queue = readPending()
|
||||
queue.append(update)
|
||||
if let data = try? JSONEncoder().encode(queue) {
|
||||
defaults?.set(data, forKey: queueKey)
|
||||
}
|
||||
// Optimistically mark the source as updated in the mirror so the extension
|
||||
// suggests the next pending source on the following invocation.
|
||||
var mirror = readMirror()
|
||||
if let idx = mirror.firstIndex(where: { $0.id == update.sourceId }) {
|
||||
mirror[idx].updatedThisMonth = true
|
||||
writeMirror(mirror)
|
||||
}
|
||||
}
|
||||
|
||||
static func readPending() -> [PendingQuickUpdate] {
|
||||
guard let data = defaults?.data(forKey: queueKey),
|
||||
let decoded = try? JSONDecoder().decode([PendingQuickUpdate].self, from: data) else { return [] }
|
||||
return decoded
|
||||
}
|
||||
|
||||
static func clearPending() {
|
||||
defaults?.removeObject(forKey: queueKey)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - App-side sync & ingestion
|
||||
|
||||
enum SharedQuickUpdateSync {
|
||||
/// Refreshes the source mirror for the extension. Call on app activation and
|
||||
/// after snapshot saves.
|
||||
@MainActor
|
||||
static func refreshMirror() {
|
||||
let context = CoreDataStack.shared.viewContext
|
||||
let request = InvestmentSource.fetchRequest()
|
||||
request.predicate = NSPredicate(format: "isActive == YES")
|
||||
request.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
|
||||
guard let sources = try? context.fetch(request) else { return }
|
||||
|
||||
let settings = AppSettings.getOrCreate(in: context)
|
||||
let calendar = Calendar.current
|
||||
let monthStart = calendar.date(from: calendar.dateComponents([.year, .month], from: Date())) ?? Date()
|
||||
|
||||
let mirror = sources.map { source in
|
||||
SharedSourceInfo(
|
||||
id: source.id,
|
||||
name: source.name,
|
||||
latestValue: NSDecimalNumber(decimal: source.latestValue).doubleValue,
|
||||
currencyCode: source.account?.currency ?? settings.currency,
|
||||
updatedThisMonth: (source.latestSnapshot?.date ?? .distantPast) >= monthStart
|
||||
)
|
||||
}
|
||||
SharedQuickUpdateStore.writeMirror(mirror)
|
||||
}
|
||||
|
||||
/// Drains the extension's pending queue into real snapshots. Returns how many
|
||||
/// snapshots were created. Call on app activation.
|
||||
@MainActor
|
||||
@discardableResult
|
||||
static func ingestPending() -> Int {
|
||||
let pending = SharedQuickUpdateStore.readPending()
|
||||
guard !pending.isEmpty else { return 0 }
|
||||
|
||||
let context = CoreDataStack.shared.viewContext
|
||||
let request = InvestmentSource.fetchRequest()
|
||||
guard let sources = try? context.fetch(request) else { return 0 }
|
||||
let byId = Dictionary(uniqueKeysWithValues: sources.map { ($0.id, $0) })
|
||||
|
||||
var created = 0
|
||||
for update in pending {
|
||||
guard let source = byId[update.sourceId] else { continue }
|
||||
let snapshot = Snapshot(context: context)
|
||||
snapshot.id = UUID()
|
||||
snapshot.value = NSDecimalNumber(value: update.amount)
|
||||
snapshot.date = update.capturedAt
|
||||
snapshot.source = source
|
||||
created += 1
|
||||
}
|
||||
|
||||
if context.hasChanges {
|
||||
do {
|
||||
try context.save()
|
||||
} catch {
|
||||
print("Failed to ingest pending quick updates: \(error)")
|
||||
return 0
|
||||
}
|
||||
}
|
||||
SharedQuickUpdateStore.clearPending()
|
||||
refreshMirror()
|
||||
return created
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
import SwiftUI
|
||||
import CoreData
|
||||
import UIKit
|
||||
|
||||
struct QuickUpdateView: View {
|
||||
@Environment(\.dismiss) private var dismiss
|
||||
@Environment(\.managedObjectContext) private var context
|
||||
@Environment(\.scenePhase) private var scenePhase
|
||||
@FetchRequest(
|
||||
sortDescriptors: [NSSortDescriptor(keyPath: \InvestmentSource.name, ascending: true)],
|
||||
predicate: NSPredicate(format: "isActive == YES"),
|
||||
@@ -15,6 +17,19 @@ struct QuickUpdateView: View {
|
||||
@State private var isSaving = false
|
||||
@State private var saveError: String?
|
||||
|
||||
// Clipboard round-trip: copy a value in your bank app, come back, one tap fills
|
||||
// the next pending source and the focus advances — no retyping, no memorizing.
|
||||
@FocusState private var focusedSource: NSManagedObjectID?
|
||||
@State private var clipboardAmount: Decimal?
|
||||
@State private var lastSuggestedRaw: String?
|
||||
|
||||
/// First source (list order) still without a value — the "active" one.
|
||||
private var nextEmptySource: InvestmentSource? {
|
||||
sources.first { source in
|
||||
(values[source.objectID] ?? "").trimmingCharacters(in: .whitespaces).isEmpty
|
||||
}
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
NavigationStack {
|
||||
ZStack {
|
||||
@@ -28,6 +43,29 @@ struct QuickUpdateView: View {
|
||||
)
|
||||
} else {
|
||||
List {
|
||||
if let amount = clipboardAmount, let target = nextEmptySource {
|
||||
Section {
|
||||
Button {
|
||||
applyClipboard(amount, to: target)
|
||||
} label: {
|
||||
HStack(spacing: 8) {
|
||||
Image(systemName: "doc.on.clipboard.fill")
|
||||
Text(String(
|
||||
format: String(localized: "quick_update_paste_suggestion"),
|
||||
amount.currencyString, target.name
|
||||
))
|
||||
.multilineTextAlignment(.leading)
|
||||
Spacer()
|
||||
Image(systemName: "arrow.down.circle.fill")
|
||||
}
|
||||
.font(.subheadline.weight(.semibold))
|
||||
.foregroundColor(.white)
|
||||
.padding(.vertical, 2)
|
||||
}
|
||||
.listRowBackground(Color.appPrimary)
|
||||
}
|
||||
}
|
||||
|
||||
Section {
|
||||
ForEach(sources) { source in
|
||||
sourceRow(source)
|
||||
@@ -63,7 +101,13 @@ struct QuickUpdateView: View {
|
||||
} message: {
|
||||
Text(saveError ?? "")
|
||||
}
|
||||
.onAppear { prefillContributions() }
|
||||
.onAppear {
|
||||
prefillContributions()
|
||||
checkClipboard()
|
||||
}
|
||||
.onChange(of: scenePhase) { _, phase in
|
||||
if phase == .active { checkClipboard() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,8 +116,19 @@ struct QuickUpdateView: View {
|
||||
VStack(spacing: 6) {
|
||||
HStack {
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
Text(source.name)
|
||||
.font(.subheadline.weight(.medium))
|
||||
HStack(spacing: 6) {
|
||||
Text(source.name)
|
||||
.font(.subheadline.weight(.medium))
|
||||
if source.objectID == nextEmptySource?.objectID {
|
||||
Text(String(localized: "quick_update_next_badge"))
|
||||
.font(.caption2.weight(.bold))
|
||||
.padding(.horizontal, 6)
|
||||
.padding(.vertical, 1)
|
||||
.background(Color.appSecondary.opacity(0.15))
|
||||
.foregroundColor(.appSecondary)
|
||||
.clipShape(Capsule())
|
||||
}
|
||||
}
|
||||
if source.latestValue != .zero {
|
||||
Text(source.latestValue.currencyString)
|
||||
.font(.caption)
|
||||
@@ -89,6 +144,7 @@ struct QuickUpdateView: View {
|
||||
.multilineTextAlignment(.trailing)
|
||||
.frame(width: 120)
|
||||
.font(.subheadline)
|
||||
.focused($focusedSource, equals: source.objectID)
|
||||
}
|
||||
|
||||
if contributions[source.objectID] != nil {
|
||||
@@ -129,6 +185,29 @@ struct QuickUpdateView: View {
|
||||
)
|
||||
}
|
||||
|
||||
/// Reads the pasteboard and offers the parsed amount for the next pending source.
|
||||
/// Skips values already suggested (or already typed) so returning to the app
|
||||
/// with the same clipboard doesn't nag.
|
||||
private func checkClipboard() {
|
||||
guard let raw = UIPasteboard.general.string, raw != lastSuggestedRaw,
|
||||
let parsed = CurrencyFormatter.parseUserInput(raw), parsed > 0,
|
||||
nextEmptySource != nil else {
|
||||
return
|
||||
}
|
||||
lastSuggestedRaw = raw
|
||||
clipboardAmount = parsed
|
||||
}
|
||||
|
||||
private func applyClipboard(_ amount: Decimal, to source: InvestmentSource) {
|
||||
values[source.objectID] = String(format: "%.2f", NSDecimalNumber(decimal: amount).doubleValue)
|
||||
clipboardAmount = nil
|
||||
// Advance focus to the next source still pending, so the user can keep going
|
||||
// (type directly or hop to the next bank app and come back).
|
||||
if let next = nextEmptySource {
|
||||
focusedSource = next.objectID
|
||||
}
|
||||
}
|
||||
|
||||
private func prefillContributions() {
|
||||
for source in sources {
|
||||
if let amount = MonthlyContributionStore.contribution(for: source.id) {
|
||||
@@ -165,6 +244,8 @@ struct QuickUpdateView: View {
|
||||
for source in sources where values[source.objectID].map({ !$0.isEmpty }) == true {
|
||||
NotificationService.shared.scheduleReminder(for: source)
|
||||
}
|
||||
// Keep the share-extension mirror in sync with what was just saved
|
||||
SharedQuickUpdateSync.refreshMirror()
|
||||
dismiss()
|
||||
} catch {
|
||||
saveError = error.localizedDescription
|
||||
|
||||
Reference in New Issue
Block a user