changeset 388:79c39987aaa4

Implementing Watchlists in ProfileView
author Dennis Concepción Martín <66180929+denniscm190@users.noreply.github.com>
date Sat, 24 Apr 2021 17:44:02 +0200
parents c206bd0bdb4e
children db8bc3ed526a
files LazyBear.xcodeproj/project.pbxproj LazyBear.xcodeproj/project.xcworkspace/xcuserdata/dennis.xcuserdatad/UserInterfaceState.xcuserstate LazyBear/Views/Global Helpers/ExtensiveList.swift LazyBear/Views/Global Helpers/StockRow.swift LazyBear/Views/Profile/Helpers/RenameSheet.swift LazyBear/Views/Profile/ProfileView.swift LazyBear/Views/WatchlistManagerTest.swift
diffstat 7 files changed, 161 insertions(+), 25 deletions(-) [+]
line wrap: on
line diff
--- a/LazyBear.xcodeproj/project.pbxproj	Sat Apr 24 12:21:23 2021 +0200
+++ b/LazyBear.xcodeproj/project.pbxproj	Sat Apr 24 17:44:02 2021 +0200
@@ -53,6 +53,7 @@
 		95C8C0DB262A36990082D1D9 /* Profile.swift in Sources */ = {isa = PBXBuildFile; fileRef = 95C8C0DA262A36990082D1D9 /* Profile.swift */; };
 		95C8C0E0262A369F0082D1D9 /* ProfileResponse.swift in Sources */ = {isa = PBXBuildFile; fileRef = 95C8C0DF262A369F0082D1D9 /* ProfileResponse.swift */; };
 		95D308F82624B3A400A39F77 /* CurrencyItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 95D308F72624B3A400A39F77 /* CurrencyItem.swift */; };
+		95E6C57626345CE700AC1518 /* WatchlistManagerTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 95E6C57526345CE700AC1518 /* WatchlistManagerTest.swift */; };
 		95ECCA5D2612169200A67EFA /* LineShape.swift in Sources */ = {isa = PBXBuildFile; fileRef = 95ECCA5C2612169200A67EFA /* LineShape.swift */; };
 		95ECCA60261216D500A67EFA /* LineView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 95ECCA5F261216D500A67EFA /* LineView.swift */; };
 		95FBE0DC2619CA7200440386 /* ProfileView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 95FBE0DB2619CA7200440386 /* ProfileView.swift */; };
@@ -129,6 +130,7 @@
 		95C8C0DA262A36990082D1D9 /* Profile.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Profile.swift; sourceTree = "<group>"; };
 		95C8C0DF262A369F0082D1D9 /* ProfileResponse.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProfileResponse.swift; sourceTree = "<group>"; };
 		95D308F72624B3A400A39F77 /* CurrencyItem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CurrencyItem.swift; sourceTree = "<group>"; };
+		95E6C57526345CE700AC1518 /* WatchlistManagerTest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WatchlistManagerTest.swift; sourceTree = "<group>"; };
 		95ECCA5C2612169200A67EFA /* LineShape.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LineShape.swift; sourceTree = "<group>"; };
 		95ECCA5F261216D500A67EFA /* LineView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LineView.swift; sourceTree = "<group>"; };
 		95FBE0DB2619CA7200440386 /* ProfileView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProfileView.swift; sourceTree = "<group>"; };
@@ -360,6 +362,7 @@
 				95A7C06126163943003E2EC1 /* Search */,
 				95FBE0DA2619CA6000440386 /* Profile */,
 				95893DD22613CAB5003698C5 /* Global Helpers */,
+				95E6C57526345CE700AC1518 /* WatchlistManagerTest.swift */,
 			);
 			path = Views;
 			sourceTree = "<group>";
@@ -559,6 +562,7 @@
 				955E73392623568F005652FF /* Home.swift in Sources */,
 				95721DA6262761E700EC527B /* CurrencyRow.swift in Sources */,
 				95672B8F25DDA54700DCBE4A /* LazyBearApp.swift in Sources */,
+				95E6C57626345CE700AC1518 /* WatchlistManagerTest.swift in Sources */,
 				95A7C066261639E0003E2EC1 /* SearchView.swift in Sources */,
 				95ECCA5D2612169200A67EFA /* LineShape.swift in Sources */,
 				9550444C26111FED000E0BCB /* StockItem.swift in Sources */,
Binary file LazyBear.xcodeproj/project.xcworkspace/xcuserdata/dennis.xcuserdatad/UserInterfaceState.xcuserstate has changed
--- a/LazyBear/Views/Global Helpers/ExtensiveList.swift	Sat Apr 24 12:21:23 2021 +0200
+++ b/LazyBear/Views/Global Helpers/ExtensiveList.swift	Sat Apr 24 17:44:02 2021 +0200
@@ -14,7 +14,11 @@
     var latestCurrencies: [String: CurrencyModel]?
     var addOnDelete: Bool
     
-    @Environment(\.presentationMode) private var extensiveListPresent
+    @Environment(\.presentationMode) private var presentationMode
+    @Environment(\.managedObjectContext) private var moc
+    @FetchRequest(entity: WatchlistCompany.entity(), sortDescriptors: [])
+    var watchlistCompany: FetchedResults<WatchlistCompany>
+    
     @State private var isEditMode: EditMode = .inactive
     @State private var showRenameAction = false
     @State private var showDeleteAlert = false
@@ -34,7 +38,7 @@
                                     )
                                 
                             }
-                            .onDelete(perform: addOnDelete ? removeCompany: nil)
+                            .onDelete(perform: addOnDelete ? deleteCompany: nil)
                         }
                     }
                     
@@ -54,7 +58,7 @@
                     .onTapGesture { showRenameAction = false }
                 
                 // Show rename Action Sheet
-                RenameSheet(showAction: $showRenameAction)
+                RenameSheet(listName: listName, showRenameAction: $showRenameAction, presentationMode: presentationMode)
                     .offset(y: showRenameAction ? 0: 700)
                     .animation(.easeInOut)
             }
@@ -63,9 +67,7 @@
                 Alert(
                     title: Text("Are you sure you want to delete this list?"),
                     message: Text("This action can't be undo"),
-                    primaryButton: .destructive(Text("Delete")) {
-                        print("Deleting...")
-                    },
+                    primaryButton: .destructive(Text("Delete")) { deleteList() },
                     secondaryButton: .cancel()
                 )
             }
@@ -76,7 +78,7 @@
                     if addOnDelete {
                         EditButton()
                     } else {
-                        Button(action: { extensiveListPresent.wrappedValue.dismiss() }) {
+                        Button(action: { presentationMode.wrappedValue.dismiss() }) {
                             Image(systemName: "multiply")
                                 .imageScale(.large)
                         }
@@ -111,8 +113,34 @@
             .environment(\.editMode, self.$isEditMode)  // Always after Toolbar
         }
     }
-    private func removeCompany(at offsets: IndexSet) {
-        print("Hello")
+    
+    // Delete company from watchlist
+    private func deleteCompany(at offsets: IndexSet) {
+        for index in offsets {
+            let company = watchlistCompany[index]
+            moc.delete(company)
+        }
+        do {
+            try moc.save()
+            print("Company deleted")
+        } catch {
+            // Error
+        }
+    }
+    
+    // Remove entire watchlist
+    private func deleteList() {
+        let selectedWatchlist = watchlistCompany.filter({ $0.watchlist == listName })
+        for company in selectedWatchlist {
+            moc.delete(company)
+        }
+        do {
+            try moc.save()
+            print("List deleted")
+            presentationMode.wrappedValue.dismiss()  // Dismiss view
+        } catch {
+            print(error.localizedDescription)
+        }
     }
 }
 
--- a/LazyBear/Views/Global Helpers/StockRow.swift	Sat Apr 24 12:21:23 2021 +0200
+++ b/LazyBear/Views/Global Helpers/StockRow.swift	Sat Apr 24 17:44:02 2021 +0200
@@ -15,6 +15,7 @@
     var addOnDelete: Bool
     
     @State private var showExtensiveList = false
+    @Environment(\.managedObjectContext) private var moc
     
     var body: some View {
         VStack(alignment: .leading) {
@@ -50,6 +51,8 @@
         .padding(.bottom)
         .sheet(isPresented: $showExtensiveList) {
             ExtensiveList(listName: listName, list: list, intradayPrices: intradayPrices, latestCurrencies: nil, addOnDelete: addOnDelete)
+                .environment(\.managedObjectContext, self.moc)
+            
         }
     }
 }
--- a/LazyBear/Views/Profile/Helpers/RenameSheet.swift	Sat Apr 24 12:21:23 2021 +0200
+++ b/LazyBear/Views/Profile/Helpers/RenameSheet.swift	Sat Apr 24 17:44:02 2021 +0200
@@ -8,8 +8,15 @@
 import SwiftUI
 
 struct RenameSheet: View {
-    @State private var name: String = String()
-    @Binding var showAction: Bool
+    var listName: String
+    
+    @State private var newListName: String = String()
+    @Binding var showRenameAction: Bool
+    @Binding var presentationMode: PresentationMode
+    
+    @Environment(\.managedObjectContext) private var moc
+    @FetchRequest(entity: WatchlistCompany.entity(), sortDescriptors: [])
+    var watchlistCompany: FetchedResults<WatchlistCompany>
     
     var body: some View {
         RoundedRectangle(cornerRadius: 20)
@@ -24,7 +31,7 @@
                         .font(.callout)
                     
                     Spacer()
-                    TextField("Technologies, banks, ...", text: $name)
+                    TextField("Technologies, banks...", text: $newListName)
                         .padding(8)
                         .background(
                             Color(.systemBackground)
@@ -37,7 +44,7 @@
                         Spacer()
                         Button(action: {
                             UIApplication.shared.endEditing()
-                            self.showAction = false
+                            self.showRenameAction = false
                         }) {
                             Text("Cancel")
                                 .fontWeight(.semibold)
@@ -49,7 +56,7 @@
                         Divider()
                             
                         Spacer()
-                        Button(action: {}) {
+                        Button(action: { renameList(newListName) }) {
                             Text("Done")
                         }
                         Spacer()
@@ -63,6 +70,22 @@
                .clipShape(RoundedRectangle(cornerRadius: 20))
         )
     }
+    
+    private func renameList(_ newListName: String) {
+        let selectedWatchlist = watchlistCompany.filter({ $0.watchlist == listName })
+        for company in selectedWatchlist {
+            company.watchlist = newListName
+        }
+        do {
+            try moc.save()
+            print("List updated")
+            UIApplication.shared.endEditing()  // Dismiss Keyboard
+            self.showRenameAction = false  // Dismiss action rename sheet
+            self.$presentationMode.wrappedValue.dismiss()  // Dismiss Modal View
+        } catch {
+            print(error.localizedDescription)
+        }
+    }
 }
 // Dismiss Keyboard
 extension UIApplication {
@@ -72,7 +95,9 @@
 }
 
 struct RenameSheet_Previews: PreviewProvider {
+    @Environment(\.presentationMode) static var presentationMode
+    
     static var previews: some View {
-        RenameSheet(showAction: .constant(true))
+        RenameSheet(listName: "MyWatchlist", showRenameAction: .constant(true), presentationMode: presentationMode)
     }
 }
--- a/LazyBear/Views/Profile/ProfileView.swift	Sat Apr 24 12:21:23 2021 +0200
+++ b/LazyBear/Views/Profile/ProfileView.swift	Sat Apr 24 17:44:02 2021 +0200
@@ -37,6 +37,13 @@
                 }
                 .navigationTitle("My profile")
                 .navigationBarTitleDisplayMode(.inline)
+                .toolbar {
+                    ToolbarItem(placement: .navigationBarTrailing) {
+                        Button(action: {}) {
+                            Image(systemName: "plus")
+                        }
+                    }
+                }
             }
         } else {
             ProgressView()
@@ -45,19 +52,23 @@
     }
     
     private func prepareUrl() {
-        let symbols = watchlistCompanies.map { $0.symbol }  // Get symbols in watchlists
-        var url = "https://api.lazybear.app/profile/type=init/symbols="
+        if watchlistCompanies.isEmpty {
+            profile.showView = true
+        } else {
+            let symbols = watchlistCompanies.map { $0.symbol }  // Get symbols in watchlists
+            var url = "https://api.lazybear.app/profile/type=init/symbols="
 
-        var counter = 0
-        for symbol in symbols {
-            counter += 1
-            if counter == 1 {
-                url += symbol
-            } else {
-                url += ",\(symbol)"
+            var counter = 0
+            for symbol in symbols {
+                counter += 1
+                if counter == 1 {
+                    url += symbol
+                } else {
+                    url += ",\(symbol)"
+                }
             }
+            profile.request(url)
         }
-        profile.request(url)
     }
 }
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/LazyBear/Views/WatchlistManagerTest.swift	Sat Apr 24 17:44:02 2021 +0200
@@ -0,0 +1,65 @@
+//
+//  WatchlistManagerTest.swift
+//  LazyBear
+//
+//  Created by Dennis Concepción Martín on 24/4/21.
+//
+
+import SwiftUI
+
+struct WatchlistManagerTest: View {
+    @Environment(\.managedObjectContext) private var moc
+    @FetchRequest(entity: WatchlistCompany.entity(), sortDescriptors: [])
+    var watchlistCompany: FetchedResults<WatchlistCompany>
+    
+    var body: some View {
+        VStack {
+            Button("Add company", action: addCompany)
+        }
+    }
+    
+//    private func removeCompany(at offsets: IndexSet) {
+//        for index in offsets {
+//            let company = companies[index]
+//            moc.delete(company)
+//        }
+//        do {
+//            try moc.save()
+//        } catch {
+//            // Error
+//        }
+//    }
+    
+    // Add to watchlist
+    private func addCompany() {
+        let watchlistCompany = WatchlistCompany(context: moc)
+        watchlistCompany.symbol = "TSLA"
+        watchlistCompany.name = "Tesla Inc"
+        watchlistCompany.watchlist = "Watchlist2"
+        do {
+            try moc.save()
+            print("Company saved")
+        } catch {
+            print(error.localizedDescription)
+        }
+    }
+    
+//    private func removeCompany() {
+//        let symbols = companies.map { $0.symbol }
+//        let index = symbols.firstIndex(of: symbol)
+//        let company = companies[index!]
+//        moc.delete(company)
+//        do {
+//            try moc.save()
+//            print("Company deleted")
+//        } catch {
+//            // Error
+//        }
+//    }
+}
+
+struct WatchlistManagerTest_Previews: PreviewProvider {
+    static var previews: some View {
+        WatchlistManagerTest()
+    }
+}