AlternativeBolusCalcRootView.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. import Charts
  2. import CoreData
  3. import SwiftUI
  4. import Swinject
  5. extension Bolus {
  6. struct AlternativeBolusCalcRootView: BaseView {
  7. let resolver: Resolver
  8. let waitForSuggestion: Bool
  9. let fetch: Bool
  10. @StateObject var state: StateModel
  11. @State private var showInfo = false
  12. @State private var exceededMaxBolus = false
  13. private enum Config {
  14. static let dividerHeight: CGFloat = 2
  15. static let spacing: CGFloat = 3
  16. static let overlayColour: Color = .white // Currently not used
  17. }
  18. @Environment(\.colorScheme) var colorScheme
  19. @FetchRequest(
  20. entity: Meals.entity(),
  21. sortDescriptors: [NSSortDescriptor(key: "createdAt", ascending: false)]
  22. ) var meal: FetchedResults<Meals>
  23. private var formatter: NumberFormatter {
  24. let formatter = NumberFormatter()
  25. formatter.numberStyle = .decimal
  26. formatter.maximumFractionDigits = 2
  27. return formatter
  28. }
  29. private var mealFormatter: NumberFormatter {
  30. let formatter = NumberFormatter()
  31. formatter.numberStyle = .decimal
  32. formatter.maximumFractionDigits = 1
  33. return formatter
  34. }
  35. private var gluoseFormatter: NumberFormatter {
  36. let formatter = NumberFormatter()
  37. formatter.numberStyle = .decimal
  38. if state.units == .mmolL {
  39. formatter.maximumFractionDigits = 1
  40. } else { formatter.maximumFractionDigits = 0 }
  41. return formatter
  42. }
  43. private var fractionDigits: Int {
  44. if state.units == .mmolL {
  45. return 1
  46. } else { return 0 }
  47. }
  48. var body: some View {
  49. Form {
  50. if state.waitForSuggestion {
  51. HStack {
  52. Text("Wait please").foregroundColor(.secondary)
  53. Spacer()
  54. ActivityIndicator(isAnimating: .constant(true), style: .medium) // fix iOS 15 bug
  55. }
  56. }
  57. Section {
  58. if fetch {
  59. VStack {
  60. if let carbs = meal.first?.carbs, carbs > 0 {
  61. HStack {
  62. Text("Carbs")
  63. Spacer()
  64. Text(carbs.formatted())
  65. Text("g")
  66. }.foregroundColor(.secondary)
  67. }
  68. if let fat = meal.first?.fat, fat > 0 {
  69. HStack {
  70. Text("Fat")
  71. Spacer()
  72. Text(fat.formatted())
  73. Text("g")
  74. }.foregroundColor(.secondary)
  75. }
  76. if let protein = meal.first?.protein, protein > 0 {
  77. HStack {
  78. Text("Protein")
  79. Spacer()
  80. Text(protein.formatted())
  81. Text("g")
  82. }.foregroundColor(.secondary)
  83. }
  84. if let note = meal.first?.note, note != "" {
  85. HStack {
  86. Text("Note")
  87. Spacer()
  88. Text(note)
  89. }.foregroundColor(.secondary)
  90. }
  91. }
  92. } else {
  93. Text("No Meal")
  94. }
  95. } header: { Text("Meal Summary") }
  96. Section {
  97. Button {
  98. let id_ = meal.first?.id ?? ""
  99. state.backToCarbsView(complexEntry: fetch, id_)
  100. }
  101. label: { Text("Edit Meal / Add Meal") }.frame(maxWidth: .infinity, alignment: .center)
  102. }
  103. Section {
  104. HStack {
  105. Button(action: {
  106. showInfo.toggle()
  107. }, label: {
  108. Image(systemName: "info.circle")
  109. Text("Calculations")
  110. })
  111. .foregroundStyle(.blue)
  112. .font(.footnote)
  113. .buttonStyle(PlainButtonStyle())
  114. .frame(maxWidth: .infinity, alignment: .leading)
  115. if state.fattyMeals {
  116. Spacer()
  117. Toggle(isOn: $state.useFattyMealCorrectionFactor) {
  118. Text("Fatty Meal")
  119. }
  120. .toggleStyle(CheckboxToggleStyle())
  121. .font(.footnote)
  122. .onChange(of: state.useFattyMealCorrectionFactor) { _ in
  123. state.insulinCalculated = state.calculateInsulin()
  124. }
  125. }
  126. }
  127. if state.waitForSuggestion {
  128. HStack {
  129. Text("Wait please").foregroundColor(.secondary)
  130. Spacer()
  131. ActivityIndicator(isAnimating: .constant(true), style: .medium) // fix iOS 15 bug
  132. }
  133. } else {
  134. HStack {
  135. Text("Recommended Bolus")
  136. Spacer()
  137. Text(
  138. formatter
  139. .string(from: Double(state.insulinCalculated) as NSNumber) ?? ""
  140. )
  141. Text(
  142. NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)")
  143. ).foregroundColor(.secondary)
  144. }.contentShape(Rectangle())
  145. .onTapGesture { state.amount = state.insulinCalculated }
  146. }
  147. if !state.waitForSuggestion {
  148. HStack {
  149. Text("Bolus")
  150. Spacer()
  151. DecimalTextField(
  152. "0",
  153. value: $state.amount,
  154. formatter: formatter,
  155. autofocus: false,
  156. cleanInput: true
  157. )
  158. Text(exceededMaxBolus ? "😵" : " U").foregroundColor(.secondary)
  159. }
  160. .onChange(of: state.amount) { newValue in
  161. if newValue > state.maxBolus {
  162. exceededMaxBolus = true
  163. } else {
  164. exceededMaxBolus = false
  165. }
  166. }
  167. }
  168. } header: { Text("Bolus Summary") }
  169. Section {
  170. if state.amount == 0, waitForSuggestion {
  171. Button { state.showModal(for: nil) }
  172. label: { Text("Continue without bolus") }.frame(maxWidth: .infinity, alignment: .center)
  173. } else {
  174. Button { state.add() }
  175. label: { Text(exceededMaxBolus ? "Max Bolus exceeded!" : "Enact bolus") }
  176. .frame(maxWidth: .infinity, alignment: .center)
  177. .foregroundColor(exceededMaxBolus ? .loopRed : .accentColor)
  178. .disabled(
  179. state.amount <= 0 || state.amount > state.maxBolus
  180. )
  181. }
  182. }
  183. }
  184. .blur(radius: showInfo ? 3 : 0)
  185. .navigationTitle("Enact Bolus")
  186. .navigationBarTitleDisplayMode(.inline)
  187. .navigationBarItems(leading: Button("Close", action: state.hideModal))
  188. .onAppear {
  189. configureView {
  190. state.waitForSuggestionInitial = waitForSuggestion
  191. state.waitForSuggestion = waitForSuggestion
  192. state.insulinCalculated = state.calculateInsulin()
  193. }
  194. }
  195. .popup(isPresented: showInfo) {
  196. bolusInfoAlternativeCalculator
  197. }
  198. }
  199. var changed: Bool {
  200. ((meal.first?.carbs ?? 0) > 0) || ((meal.first?.fat ?? 0) > 0) || ((meal.first?.protein ?? 0) > 0)
  201. }
  202. var hasFatOrProtein: Bool {
  203. ((meal.first?.fat ?? 0) > 0) || ((meal.first?.protein ?? 0) > 0)
  204. }
  205. // Pop-up
  206. var bolusInfoAlternativeCalculator: some View {
  207. VStack {
  208. let unit = NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)")
  209. VStack {
  210. VStack(spacing: Config.spacing) {
  211. HStack {
  212. Text("Calculations")
  213. .font(.title3).frame(maxWidth: .infinity, alignment: .center)
  214. }.padding(10)
  215. if fetch {
  216. VStack {
  217. if let note = meal.first?.note, note != "" {
  218. HStack {
  219. Text("Note")
  220. .foregroundColor(.secondary)
  221. Spacer()
  222. Text(note)
  223. }
  224. }
  225. if let carbs = meal.first?.carbs, carbs > 0 {
  226. HStack {
  227. Text("Carbs")
  228. .foregroundColor(.secondary)
  229. Spacer()
  230. Text(mealFormatter.string(from: carbs as NSNumber) ?? "")
  231. Text("g").foregroundColor(.secondary)
  232. }
  233. }
  234. if let protein = meal.first?.protein, protein > 0 {
  235. HStack {
  236. Text("Protein")
  237. .foregroundColor(.secondary)
  238. Spacer()
  239. Text(mealFormatter.string(from: protein as NSNumber) ?? "")
  240. Text("g").foregroundColor(.secondary)
  241. }
  242. }
  243. if let fat = meal.first?.fat, fat > 0 {
  244. HStack {
  245. Text("Fat")
  246. .foregroundColor(.secondary)
  247. Spacer()
  248. Text(mealFormatter.string(from: fat as NSNumber) ?? "")
  249. Text("g").foregroundColor(.secondary)
  250. }
  251. }
  252. }.padding()
  253. }
  254. if fetch { Divider().frame(height: Config.dividerHeight) }
  255. VStack {
  256. HStack {
  257. Text("Carb Ratio")
  258. .foregroundColor(.secondary)
  259. Spacer()
  260. Text(state.carbRatio.formatted())
  261. Text(NSLocalizedString(" g/U", comment: " grams per Unit"))
  262. .foregroundColor(.secondary)
  263. }
  264. HStack {
  265. Text("ISF")
  266. .foregroundColor(.secondary)
  267. Spacer()
  268. let isf = state.isf
  269. Text(isf.formatted())
  270. Text(state.units.rawValue + NSLocalizedString("/U", comment: "/Insulin unit"))
  271. .foregroundColor(.secondary)
  272. }
  273. HStack {
  274. Text("Target Glucose")
  275. .foregroundColor(.secondary)
  276. Spacer()
  277. let target = state.units == .mmolL ? state.target.asMmolL : state.target
  278. Text(
  279. target
  280. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  281. )
  282. Text(state.units.rawValue)
  283. .foregroundColor(.secondary)
  284. }
  285. HStack {
  286. Text("Basal")
  287. .foregroundColor(.secondary)
  288. Spacer()
  289. let basal = state.basal
  290. Text(basal.formatted())
  291. Text(NSLocalizedString(" U/h", comment: " Units per hour"))
  292. .foregroundColor(.secondary)
  293. }
  294. HStack {
  295. Text("Fraction")
  296. .foregroundColor(.secondary)
  297. Spacer()
  298. let fraction = state.fraction
  299. Text(fraction.formatted())
  300. }
  301. if state.useFattyMealCorrectionFactor {
  302. HStack {
  303. Text("Fatty Meal Factor")
  304. .foregroundColor(.orange)
  305. Spacer()
  306. let fraction = state.fattyMealFactor
  307. Text(fraction.formatted())
  308. .foregroundColor(.orange)
  309. }
  310. }
  311. }.padding()
  312. }
  313. Divider().frame(height: Config.dividerHeight)
  314. VStack(spacing: Config.spacing) {
  315. HStack {
  316. Text("Glucose")
  317. .foregroundColor(.secondary)
  318. Spacer()
  319. let glucose = state.units == .mmolL ? state.currentBG.asMmolL : state.currentBG
  320. Text(glucose.formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))))
  321. Text(state.units.rawValue)
  322. .foregroundColor(.secondary)
  323. Spacer()
  324. Image(systemName: "arrow.right")
  325. Spacer()
  326. let targetDifferenceInsulin = state.targetDifferenceInsulin
  327. // rounding
  328. let targetDifferenceInsulinAsDouble = NSDecimalNumber(decimal: targetDifferenceInsulin).doubleValue
  329. let roundedTargetDifferenceInsulin = Decimal(round(100 * targetDifferenceInsulinAsDouble) / 100)
  330. Text(roundedTargetDifferenceInsulin.formatted())
  331. Text(unit)
  332. .foregroundColor(.secondary)
  333. }
  334. HStack {
  335. Text("IOB")
  336. .foregroundColor(.secondary)
  337. Spacer()
  338. let iob = state.iob
  339. // rounding
  340. let iobAsDouble = NSDecimalNumber(decimal: iob).doubleValue
  341. let roundedIob = Decimal(round(100 * iobAsDouble) / 100)
  342. Text(roundedIob.formatted())
  343. Text(unit)
  344. .foregroundColor(.secondary)
  345. Spacer()
  346. Image(systemName: "arrow.right")
  347. Spacer()
  348. let iobCalc = state.iobInsulinReduction
  349. // rounding
  350. let iobCalcAsDouble = NSDecimalNumber(decimal: iobCalc).doubleValue
  351. let roundedIobCalc = Decimal(round(100 * iobCalcAsDouble) / 100)
  352. Text(roundedIobCalc.formatted())
  353. Text(unit).foregroundColor(.secondary)
  354. }
  355. HStack {
  356. Text("Trend")
  357. .foregroundColor(.secondary)
  358. Spacer()
  359. let trend = state.units == .mmolL ? state.deltaBG.asMmolL : state.deltaBG
  360. Text(trend.formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))))
  361. Text(state.units.rawValue).foregroundColor(.secondary)
  362. Spacer()
  363. Image(systemName: "arrow.right")
  364. Spacer()
  365. let trendInsulin = state.fifteenMinInsulin
  366. // rounding
  367. let trendInsulinAsDouble = NSDecimalNumber(decimal: trendInsulin).doubleValue
  368. let roundedTrendInsulin = Decimal(round(100 * trendInsulinAsDouble) / 100)
  369. Text(roundedTrendInsulin.formatted())
  370. Text(unit)
  371. .foregroundColor(.secondary)
  372. }
  373. HStack {
  374. Text("COB")
  375. .foregroundColor(.secondary)
  376. Spacer()
  377. let cob = state.cob
  378. Text(cob.formatted())
  379. let unitGrams = NSLocalizedString(" g", comment: "grams")
  380. Text(unitGrams).foregroundColor(.secondary)
  381. Spacer()
  382. Image(systemName: "arrow.right")
  383. Spacer()
  384. let insulinCob = state.wholeCobInsulin
  385. // rounding
  386. let insulinCobAsDouble = NSDecimalNumber(decimal: insulinCob).doubleValue
  387. let roundedInsulinCob = Decimal(round(100 * insulinCobAsDouble) / 100)
  388. Text(roundedInsulinCob.formatted())
  389. Text(unit)
  390. .foregroundColor(.secondary)
  391. }
  392. }.padding()
  393. Divider().frame(height: Config.dividerHeight)
  394. VStack {
  395. HStack {
  396. Text("Full Bolus")
  397. .foregroundColor(.secondary)
  398. Spacer()
  399. let insulin = state.roundedWholeCalc
  400. Text(insulin.formatted()).foregroundStyle(state.roundedWholeCalc < 0 ? Color.loopRed : Color.primary)
  401. Text(unit)
  402. .foregroundColor(.secondary)
  403. }
  404. }.padding(.horizontal)
  405. Divider().frame(height: Config.dividerHeight)
  406. VStack {
  407. HStack {
  408. Text("Result")
  409. .fontWeight(.bold)
  410. Spacer()
  411. let fraction = state.fraction
  412. Text(fraction.formatted())
  413. Text(" x ")
  414. .foregroundColor(.secondary)
  415. // if fatty meal is chosen
  416. if state.useFattyMealCorrectionFactor {
  417. let fattyMealFactor = state.fattyMealFactor
  418. Text(fattyMealFactor.formatted())
  419. .foregroundColor(.orange)
  420. Text(" x ")
  421. .foregroundColor(.secondary)
  422. }
  423. let insulin = state.roundedWholeCalc
  424. Text(insulin.formatted()).foregroundStyle(state.roundedWholeCalc < 0 ? Color.loopRed : Color.primary)
  425. Text(unit)
  426. .foregroundColor(.secondary)
  427. Text(" = ")
  428. .foregroundColor(.secondary)
  429. let result = state.insulinCalculated
  430. // rounding
  431. let resultAsDouble = NSDecimalNumber(decimal: result).doubleValue
  432. let roundedResult = Decimal(round(100 * resultAsDouble) / 100)
  433. Text(roundedResult.formatted())
  434. .fontWeight(.bold)
  435. .font(.system(size: 16))
  436. .foregroundColor(.blue)
  437. Text(unit)
  438. .foregroundColor(.secondary)
  439. }
  440. }.padding()
  441. Divider().frame(height: Config.dividerHeight)
  442. if exceededMaxBolus {
  443. HStack {
  444. let maxBolus = state.maxBolus
  445. let maxBolusFormatted = maxBolus.formatted()
  446. Text("Your entered amount was limited by your max Bolus setting of \(maxBolusFormatted)\(unit)!")
  447. }
  448. .padding()
  449. .fontWeight(.semibold)
  450. .foregroundStyle(Color.loopRed)
  451. }
  452. }
  453. .padding(.top, 10)
  454. .padding(.bottom, 15)
  455. // Hide pop-up
  456. VStack {
  457. Button {
  458. showInfo = false
  459. }
  460. label: {
  461. Text("OK")
  462. }
  463. .frame(maxWidth: .infinity, alignment: .center)
  464. .font(.system(size: 16))
  465. .fontWeight(.semibold)
  466. .foregroundColor(.blue)
  467. }
  468. .padding(.bottom, 20)
  469. }
  470. .font(.footnote)
  471. .background(
  472. RoundedRectangle(cornerRadius: 10, style: .continuous)
  473. .fill(Color(colorScheme == .dark ? UIColor.systemGray4 : UIColor.systemGray4).opacity(0.9))
  474. )
  475. }
  476. }
  477. }