AlternativeBolusCalcRootView.swift 22 KB

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