Skip to content

Commit

Permalink
Add non-pump insulin dialog (#271)
Browse files Browse the repository at this point in the history
Move add external insulin to pump history.
Add buttons for hiding future entries and external insulin
  • Loading branch information
dnzxy authored Oct 29, 2023
1 parent 7c7693c commit 73a341d
Show file tree
Hide file tree
Showing 4 changed files with 174 additions and 50 deletions.
50 changes: 4 additions & 46 deletions FreeAPS/Sources/Modules/Bolus/View/BolusRootView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,6 @@ extension Bolus {
}
}
header: { Text("Recommendation") }

if !state.waitForSuggestion {
Section {
HStack {
Expand All @@ -85,54 +84,13 @@ extension Bolus {
state.amount <= 0 || state.amount > state.maxBolus
)
}
Section {
if waitForSuggestion {

if waitForSuggestion {
Section {
Button { state.showModal(for: nil) }
label: { Text("Continue without bolus") }
} else {
Button { isAddInsulinAlertPresented = true }
label: { Text("Add insulin without actually bolusing") }
.disabled(state.amount <= 0 || state.amount > state.maxBolus * 3)
label: { Text("Continue without bolus") }.frame(maxWidth: .infinity, alignment: .center)
}
}
.alert(isPresented: $isAddInsulinAlertPresented) {
let isOverMax = state.amount > state.maxBolus ? true : false
let secondParagrap1 = "Add"
let secondParagraph2 = " U"
let secondParagraph3 = " without bolusing"
let insulinAmount = formatter.string(from: state.amount as NSNumber)!

// Actual alert
return Alert(
title: Text(
isOverMax ? "Warning" : "Are you sure?"
),
message:
Text(
isOverMax ? (
NSLocalizedString(
"\nAmount is more than your Max Bolus setting! \nAre you sure you want to add ",
comment: "Alert"
) + insulinAmount +
NSLocalizedString(secondParagraph2, comment: "Insulin unit") +
NSLocalizedString(secondParagraph3, comment: "Add insulin without bolusing alert") + "?"
) :
NSLocalizedString(secondParagrap1, comment: "Add insulin without bolusing alert") +
" " +
insulinAmount +
NSLocalizedString(secondParagraph2, comment: "Insulin unit") +
NSLocalizedString(secondParagraph3, comment: "Add insulin without bolusing alert")
),
primaryButton: .destructive(
Text("Add"),
action: {
state.addWithoutBolus()
isAddInsulinAlertPresented = false
}
),
secondaryButton: .cancel()
)
}
}
}
.alert(isPresented: $displayError) {
Expand Down
6 changes: 6 additions & 0 deletions FreeAPS/Sources/Modules/DataTable/DataTableProvider.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@ extension DataTable {
pumpHistoryStorage.recent()
}

func pumpSettings() -> PumpSettings {
storage.retrieve(OpenAPS.Settings.settings, as: PumpSettings.self)
?? PumpSettings(from: OpenAPS.defaults(for: OpenAPS.Settings.settings))
?? PumpSettings(insulinActionCurve: 6, maxBolus: 10, maxBasal: 2)
}

func tempTargets() -> [TempTarget] {
tempTargetsStorage.recent()
}
Expand Down
39 changes: 39 additions & 0 deletions FreeAPS/Sources/Modules/DataTable/DataTableStateModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ extension DataTable {
@Injected() var broadcaster: Broadcaster!
@Injected() var unlockmanager: UnlockManager!
@Injected() private var storage: FileStorage!
@Injected() var pumpHistoryStorage: PumpHistoryStorage!
@Injected() var healthKitManager: HealthKitManager!

let coredataContext = CoreDataStack.shared.persistentContainer.viewContext
Expand All @@ -14,11 +15,15 @@ extension DataTable {
@Published var treatments: [Treatment] = []
@Published var glucose: [Glucose] = []
@Published var manualGlucose: Decimal = 0
@Published var maxBolus: Decimal = 0
@Published var nonPumpInsulinAmount: Decimal = 0
@Published var nonPumpInsulinDate = Date()

var units: GlucoseUnits = .mmolL

override func subscribe() {
units = settingsManager.settings.units
maxBolus = provider.pumpSettings().maxBolus
setupTreatments()
setupGlucose()
broadcaster.register(SettingsObserver.self, observer: self)
Expand Down Expand Up @@ -193,6 +198,40 @@ extension DataTable {
var saveToHealth = [BloodGlucose]()
saveToHealth.append(saveToJSON)
}

func addNonPumpInsulin() {
guard nonPumpInsulinAmount > 0 else {
showModal(for: nil)
return
}

nonPumpInsulinAmount = min(nonPumpInsulinAmount, maxBolus * 3) // Allow for 3 * Max Bolus for non-pump insulin
unlockmanager.unlock()
.sink { _ in } receiveValue: { [weak self] _ in
guard let self = self else { return }
pumpHistoryStorage.storeEvents(
[
PumpHistoryEvent(
id: UUID().uuidString,
type: .bolus,
timestamp: nonPumpInsulinDate,
amount: nonPumpInsulinAmount,
duration: nil,
durationMin: nil,
rate: nil,
temp: nil,
carbInput: nil,
isNonPumpInsulin: true
)
]
)
debug(.default, "Non-pump insulin saved to pumphistory.json")

// Reset amount to 0 for next entry.
nonPumpInsulinAmount = 0
}
.store(in: &lifetime)
}
}
}

Expand Down
129 changes: 125 additions & 4 deletions FreeAPS/Sources/Modules/DataTable/View/DataTableRootView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,20 @@ extension DataTable {
@State private var removeCarbsAlert: Alert?
@State private var isRemoveInsulinAlertPresented = false
@State private var removeInsulinAlert: Alert?
@State private var showNonPumpInsulin: Bool = false
@State private var showFutureEntries: Bool = false // default to hide future entries
@State private var showManualGlucose: Bool = false
@State private var isAmountUnconfirmed: Bool = true

@Environment(\.colorScheme) var colorScheme

private var insulinFormatter: NumberFormatter {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 2
return formatter
}

private var glucoseFormatter: NumberFormatter {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
Expand Down Expand Up @@ -57,12 +66,59 @@ extension DataTable {
.sheet(isPresented: $showManualGlucose) {
addGlucoseView
}
.sheet(isPresented: $showNonPumpInsulin, onDismiss: { if isAmountUnconfirmed { state.nonPumpInsulinAmount = 0
state.nonPumpInsulinDate = Date() } }) {
addNonPumpInsulinView
}
}

private var treatmentsList: some View {
List {
ForEach(state.treatments) { item in
treatmentView(item)
HStack {
Button(action: { showFutureEntries.toggle() }, label: {
HStack {
Image(systemName: showFutureEntries ? "calendar.badge.minus" : "calendar.badge.plus")
.foregroundColor(Color.accentColor)
Text(showFutureEntries ? "Hide Future" : "Show Future")
.foregroundColor(Color.secondary)
.font(.caption)

}.frame(maxWidth: .infinity, alignment: .leading)

}).buttonStyle(.borderless)

Spacer()

Button(action: { showNonPumpInsulin = true
state.nonPumpInsulinDate = Date() }, label: {
HStack {
Text("Add")
.foregroundColor(Color.secondary)
.font(.caption)

Image(systemName: "syringe")
.foregroundColor(Color.accentColor)
}.frame(maxWidth: .infinity, alignment: .trailing)

}).buttonStyle(.borderless)
}

if !state.treatments.isEmpty {
if !showFutureEntries {
ForEach(state.treatments.filter { item in
item.date <= Date()
}) { item in
treatmentView(item)
}
} else {
ForEach(state.treatments) { item in
treatmentView(item)
}
}
} else {
HStack {
Text("No data.")
}
}
}
}
Expand All @@ -87,7 +143,7 @@ extension DataTable {
.onDelete(perform: deleteGlucose)
} else {
HStack {
Text(NSLocalizedString("No data.", comment: "No data text when no entries in history list"))
Text("No data.")
}
}
}
Expand Down Expand Up @@ -162,7 +218,8 @@ extension DataTable {
message: Text(item.amountText),
primaryButton: .destructive(
Text("Delete"),
action: { state.deleteCarbs(item) }
action: {
state.deleteCarbs(item) }
),
secondaryButton: .cancel()
)
Expand Down Expand Up @@ -219,6 +276,70 @@ extension DataTable {
}
}

var addNonPumpInsulinView: some View {
NavigationView {
VStack {
Form {
Section {
HStack {
Text("Amount")
Spacer()
DecimalTextField(
"0",
value: $state.nonPumpInsulinAmount,
formatter: insulinFormatter,
autofocus: true,
cleanInput: true
)
Text("U").foregroundColor(.secondary)
}
}

Section {
DatePicker("Date", selection: $state.nonPumpInsulinDate, in: ...Date())
}

let amountWarningCondition = (state.nonPumpInsulinAmount > state.maxBolus) &&
(state.nonPumpInsulinAmount <= state.maxBolus * 3)

Section {
HStack {
Button {
state.addNonPumpInsulin()
isAmountUnconfirmed = false
showNonPumpInsulin = false
}
label: {
Text("Log non-pump insulin")
}
.foregroundColor(amountWarningCondition ? Color.white : Color.accentColor)
.frame(maxWidth: .infinity, alignment: .center)
.disabled(
state.nonPumpInsulinAmount <= 0 || state.nonPumpInsulinAmount > state
.maxBolus * 3
)
}
}
header: {
if amountWarningCondition
{
Text("⚠️ Warning! The entered insulin amount is greater than your Max Bolus setting!")
}
}
.listRowBackground(
amountWarningCondition ? Color
.red : colorScheme == .dark ? Color(UIColor.secondarySystemBackground) : Color.white
)
}
}
.onAppear(perform: configureView)
.navigationTitle("Non-Pump Insulin")
.navigationBarTitleDisplayMode(.inline)
.navigationBarItems(leading: Button("Close", action: { showNonPumpInsulin = false
state.nonPumpInsulinAmount = 0 }))
}
}

@ViewBuilder private func glucoseView(_ item: Glucose, isManual: BloodGlucose) -> some View {
VStack(alignment: .leading, spacing: 4) {
HStack {
Expand Down

0 comments on commit 73a341d

Please sign in to comment.