-
Notifications
You must be signed in to change notification settings - Fork 0
/
clientsViewModel.swift
104 lines (85 loc) · 2.61 KB
/
clientsViewModel.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
//
// clientsViewModel.swift
// RestaurantApp
//
// Created by Maciej Bichajło on 11/01/2024.
//
import SwiftUI
import CoreData
enum SearchTokens:String, Hashable,CaseIterable,Identifiable{
public var id: Self{self}
case mainCourses = "Main course"
case drinks = "Drinks"
case appetizers = "Appetizers"
case soups = "Soups"
func name() -> String{
switch self {
case .mainCourses:
return "Main Course"
case .drinks:
return"Drinks"
case .appetizers:
return "Appetizers"
case .soups:
return "Soups"
}
}
}
@MainActor class ClientsViewModel:ObservableObject{
@Published var isListVisible=false
private let context=PersistenceController.shared.container.viewContext
var menuItems:[MenuItem]=[]
@Published var selectedTokens = [SearchTokens]()
@Published var suggestedTokens = SearchTokens.allCases
@Published var filteredMenuItems:[MenuItem]=[]
@Published var detailsSheetVisible = false
@Published var currentMenuItem:MenuItem?
@Published var searchQuery = ""
@Published var errorAlert = false
func showList(){
isListVisible=true
}
func hideList(){
isListVisible=false
}
func filter(){
if searchQuery.isEmpty{
filteredMenuItems = menuItems
}else{
filteredMenuItems = menuItems.filter({$0.name!.lowercased().contains(searchQuery.lowercased())})
}
for token in selectedTokens {
switch token {
case .mainCourses:
filteredMenuItems = filteredMenuItems.filter({$0.category == .mainCourse})
case .drinks:
filteredMenuItems = filteredMenuItems.filter({$0.category == .drinks})
case .appetizers:
filteredMenuItems = filteredMenuItems.filter({$0.category == .appetizers})
case .soups:
filteredMenuItems = filteredMenuItems.filter({$0.category == .soups})
}
}
}
func orderMenuItem(){
currentMenuItem?.orders += 1
save()
fetchMenuItems()
}
func fetchMenuItems(){
//let request = NSFetchRequest<MenuItem>(entityName: "MenuItem")
do{
try menuItems=context.fetch(MenuItem.fetchRequest())
filteredMenuItems = menuItems
}catch {
errorAlert = true
}
}
func save(){
do{
try context.save()
}catch{
errorAlert = true
}
}
}