AlternativeBolusCalcRootView.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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. Spacer()
  197. }
  198. .padding(.vertical, 10)
  199. if fetch {
  200. VStack {
  201. if let note = meal.first?.note, note != "" {
  202. HStack {
  203. Text("Note")
  204. .foregroundColor(.secondary)
  205. Spacer()
  206. Text(note)
  207. }
  208. }
  209. if let carbs = meal.first?.carbs, carbs > 0 {
  210. HStack {
  211. Text("Carbs")
  212. .foregroundColor(.secondary)
  213. Spacer()
  214. Text(carbs.formatted())
  215. Text("g").foregroundColor(.secondary)
  216. }
  217. }
  218. if let protein = meal.first?.protein, protein > 0 {
  219. HStack {
  220. Text("Protein")
  221. .foregroundColor(.secondary)
  222. Spacer()
  223. Text(protein.formatted())
  224. Text("g").foregroundColor(.secondary)
  225. }
  226. }
  227. if let fat = meal.first?.fat, fat > 0 {
  228. HStack {
  229. Text("Fat")
  230. .foregroundColor(.secondary)
  231. Spacer()
  232. Text(fat.formatted()).foregroundColor(.orange)
  233. Text("g").foregroundColor(.secondary)
  234. }
  235. }
  236. }.padding()
  237. }
  238. Divider().fontWeight(.bold)
  239. VStack {
  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(
  263. target
  264. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  265. )
  266. Text(state.units.rawValue)
  267. .foregroundColor(.secondary)
  268. }
  269. HStack {
  270. Text("Basal")
  271. .foregroundColor(.secondary)
  272. Spacer()
  273. let basal = state.basal
  274. Text(basal.formatted())
  275. Text(NSLocalizedString(" U/h", comment: " Units per hour"))
  276. .foregroundColor(.secondary)
  277. }
  278. HStack {
  279. Text("Fraction")
  280. .foregroundColor(.secondary)
  281. Spacer()
  282. let fraction = state.fraction
  283. Text(fraction.formatted())
  284. }
  285. if state.useFattyMealCorrectionFactor {
  286. HStack {
  287. Text("Fatty Meal Factor")
  288. .foregroundColor(.orange)
  289. Spacer()
  290. let fraction = state.fattyMealFactor
  291. Text(fraction.formatted())
  292. .foregroundColor(.orange)
  293. }
  294. }
  295. }
  296. }.padding()
  297. Divider().fontWeight(.bold)
  298. VStack(spacing: 2) {
  299. HStack {
  300. Text("Glucose")
  301. .foregroundColor(.secondary)
  302. Spacer()
  303. let glucose = state.units == .mmolL ? state.currentBG.asMmolL : state.currentBG
  304. Text(glucose.formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))))
  305. Text(state.units.rawValue)
  306. .foregroundColor(.secondary)
  307. Spacer()
  308. Image(systemName: "arrow.right")
  309. Spacer()
  310. let targetDifferenceInsulin = state.targetDifferenceInsulin
  311. // rounding
  312. let targetDifferenceInsulinAsDouble = NSDecimalNumber(decimal: targetDifferenceInsulin).doubleValue
  313. let roundedTargetDifferenceInsulin = Decimal(round(100 * targetDifferenceInsulinAsDouble) / 100)
  314. Text(roundedTargetDifferenceInsulin.formatted())
  315. Text(unit)
  316. .foregroundColor(.secondary)
  317. }
  318. HStack {
  319. Text("IOB")
  320. .foregroundColor(.secondary)
  321. Spacer()
  322. let iob = state.iob
  323. // rounding
  324. let iobAsDouble = NSDecimalNumber(decimal: iob).doubleValue
  325. let roundedIob = Decimal(round(100 * iobAsDouble) / 100)
  326. Text(roundedIob.formatted())
  327. Text(unit)
  328. .foregroundColor(.secondary)
  329. Spacer()
  330. Image(systemName: "arrow.right")
  331. Spacer()
  332. let iobCalc = state.iobInsulinReduction
  333. // rounding
  334. let iobCalcAsDouble = NSDecimalNumber(decimal: iobCalc).doubleValue
  335. let roundedIobCalc = Decimal(round(100 * iobCalcAsDouble) / 100)
  336. Text(roundedIobCalc.formatted())
  337. Text(unit).foregroundColor(.secondary)
  338. }
  339. HStack {
  340. Text("Trend")
  341. .foregroundColor(.secondary)
  342. Spacer()
  343. let trend = state.units == .mmolL ? state.deltaBG.asMmolL : state.deltaBG
  344. Text(trend.formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))))
  345. Text(state.units.rawValue).foregroundColor(.secondary)
  346. Spacer()
  347. Image(systemName: "arrow.right")
  348. Spacer()
  349. let trendInsulin = state.fifteenMinInsulin
  350. // rounding
  351. let trendInsulinAsDouble = NSDecimalNumber(decimal: trendInsulin).doubleValue
  352. let roundedTrendInsulin = Decimal(round(100 * trendInsulinAsDouble) / 100)
  353. Text(roundedTrendInsulin.formatted())
  354. Text(unit)
  355. .foregroundColor(.secondary)
  356. }
  357. HStack {
  358. Text("COB")
  359. .foregroundColor(.secondary)
  360. Spacer()
  361. let cob = state.cob
  362. Text(cob.formatted())
  363. let unitGrams = NSLocalizedString(" g", comment: "grams")
  364. Text(unitGrams).foregroundColor(.secondary)
  365. Spacer()
  366. Image(systemName: "arrow.right")
  367. Spacer()
  368. let insulinCob = state.wholeCobInsulin
  369. // rounding
  370. let insulinCobAsDouble = NSDecimalNumber(decimal: insulinCob).doubleValue
  371. let roundedInsulinCob = Decimal(round(100 * insulinCobAsDouble) / 100)
  372. Text(roundedInsulinCob.formatted())
  373. Text(unit)
  374. .foregroundColor(.secondary)
  375. }
  376. }
  377. .padding()
  378. Divider()
  379. .fontWeight(.bold)
  380. HStack {
  381. Text("Full Bolus")
  382. .foregroundColor(.secondary)
  383. Spacer()
  384. let insulin = state.roundedWholeCalc
  385. Text(insulin.formatted()).foregroundStyle(state.roundedWholeCalc < 0 ? Color.loopRed : Color.primary)
  386. Text(unit)
  387. .foregroundColor(.secondary)
  388. }.padding()
  389. Divider().fontWeight(.bold)
  390. HStack {
  391. Text("Result")
  392. .fontWeight(.bold)
  393. Spacer()
  394. let fraction = state.fraction
  395. Text(fraction.formatted())
  396. Text(" x ")
  397. .foregroundColor(.secondary)
  398. // if fatty meal is chosen
  399. if state.useFattyMealCorrectionFactor {
  400. let fattyMealFactor = state.fattyMealFactor
  401. Text(fattyMealFactor.formatted())
  402. .foregroundColor(.orange)
  403. Text(" x ")
  404. .foregroundColor(.secondary)
  405. }
  406. let insulin = state.roundedWholeCalc
  407. Text(insulin.formatted()).foregroundStyle(state.roundedWholeCalc < 0 ? Color.loopRed : Color.primary)
  408. Text(unit)
  409. .foregroundColor(.secondary)
  410. Text(" = ")
  411. .foregroundColor(.secondary)
  412. let result = state.insulinCalculated
  413. // rounding
  414. let resultAsDouble = NSDecimalNumber(decimal: result).doubleValue
  415. let roundedResult = Decimal(round(100 * resultAsDouble) / 100)
  416. Text(roundedResult.formatted())
  417. .fontWeight(.bold)
  418. .font(.system(size: 16))
  419. .foregroundColor(.blue)
  420. Text(unit)
  421. .foregroundColor(.secondary)
  422. }
  423. .padding()
  424. Divider()
  425. if exceededMaxBolus {
  426. HStack {
  427. let maxBolus = state.maxBolus
  428. let maxBolusFormatted = maxBolus.formatted()
  429. Text("Your entered amount was limited by your max Bolus setting of \(maxBolusFormatted)\(unit)!")
  430. }
  431. .padding()
  432. .fontWeight(.semibold)
  433. .foregroundStyle(Color.loopRed)
  434. }
  435. }
  436. .padding(.top, 10)
  437. .padding(.bottom, 15)
  438. // Hide pop-up
  439. VStack {
  440. Button {
  441. showInfo = false
  442. }
  443. label: {
  444. Text("OK")
  445. }
  446. .frame(maxWidth: .infinity, alignment: .center)
  447. .font(.system(size: 16))
  448. .fontWeight(.semibold)
  449. .foregroundColor(.blue)
  450. }
  451. .padding(.bottom, 20)
  452. }
  453. .font(.footnote)
  454. .background(
  455. RoundedRectangle(cornerRadius: 10, style: .continuous)
  456. .fill(Color(colorScheme == .dark ? UIColor.systemGray4 : UIColor.systemGray4).opacity(0.9))
  457. )
  458. }
  459. }
  460. }