-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathutils.ts
265 lines (240 loc) · 6.49 KB
/
utils.ts
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
import { signInWithEmailAndPassword, signOut } from "firebase/auth";
import { auth } from "./firebase";
import { toast } from "react-toastify";
import { AppRouterInstance } from "next/dist/shared/lib/app-router-context";
import { doc, deleteDoc, onSnapshot, collection, addDoc, query, where, serverTimestamp, orderBy, Timestamp } from "firebase/firestore";
import db from "./firebase";
export interface Items {
[key: string]: any,
name: string,
quantity: string,
price: string,
amount: string
}
export interface Item {
name: string,
id: string,
number_of_products: number
}
export interface User {
email: string | null,
uid: string | null
}
export interface Product {
id: string,
category: string,
price: number,
quantity: string,
name: string
}
export interface ProductItem {
price: number,
amount: string,
quantity: string,
name: string,
}
export interface Sales{
customerEmail: string,
customerName: string,
id: string,
totalAmount: number,
timestamp: {
seconds: number;
nanoseconds: number;
},
products: ProductItem[]
}
export function calculateTotalAmount(objectsArray: Items[]) {
let totalAmount = 0;
for (let i = 0; i < objectsArray.length; i++) {
const stringAmount = objectsArray[i].amount
const amount = Number(stringAmount.replace(/,/g, ""))
totalAmount += amount
}
return totalAmount;
}
export const successMessage = (message:string) => {
toast.success(message, {
position: "top-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
});
};
export const errorMessage = (message:string) => {
toast.error(message, {
position: "top-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
});
};
export const LoginUser = (email: string, password: string, router: AppRouterInstance) => {
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
const user = userCredential.user;
successMessage("Authentication successful 🎉");
router.push("/dashboard");
})
.catch((error) => {
console.error(error);
errorMessage("Incorrect Email/Password ❌");
});
};
export const LogOut = (router: AppRouterInstance) => {
signOut(auth)
.then(() => {
successMessage("Logout successful! 🎉");
router.push("/");
})
.catch((error) => {
errorMessage("Couldn't sign out ❌");
});
};
export const getCategories = async (setCategories: any) => {
try {
const unsub = onSnapshot(collection(db, "categories"), doc => {
const docs: any = []
doc.forEach((d: any) => {
docs.push( { ...d.data(), id: d.id })
});
setCategories(docs)
})
} catch (err) {
console.error(err)
setCategories([])
}
}
export const deleteCategory = async (id: string, name:string) => {
try {
await deleteDoc(doc(db, "categories", id));
const q = query(collection(db, "products"), where("category", "==", name));
const unsubscribe = onSnapshot(q, (querySnapshot) => {
querySnapshot.forEach((document) => {
deleteDoc(doc(db, "products", document.id));
});
});
successMessage(`${name} category deleted 🎉`)
} catch (err) {
errorMessage("Encountered an error ❌")
console.log(err)
}
}
export const addCategory = async (name: string) => {
try {
await addDoc(collection(db, "categories"), {
name
})
successMessage(`${name} category added! 🎉`)
} catch (err) {
errorMessage("Error! ❌")
console.error(err)
}
}
export const addProduct = async (name: string, price: number, category: string) => {
try {
await addDoc(collection(db, "products"), {
name, price, category
})
successMessage(`${name} product added! 🎉`)
}
catch (err) {
errorMessage("Error! ❌")
console.error(err)
}
}
export const getProducts = async (setProducts: any) => {
try {
const unsub = onSnapshot(collection(db, "products"), doc => {
const docs: any = []
doc.forEach((d: any) => {
docs.unshift( { ...d.data(), id: d.id })
});
setProducts(docs)
})
} catch (err) {
console.error(err)
setProducts([])
}
}
export const deleteProduct = async (id: string, name:string) => {
try {
await deleteDoc(doc(db, "products", id));
successMessage(`${name} deleted 🎉`)
} catch (err) {
errorMessage("Encountered an error ❌")
console.log(err)
}
}
export const addSales = async (customerName: string, customerEmail: string, products: Items[], totalAmount: number, setAddNew: any) => {
try {
await addDoc(collection(db, "sales"), {
customerName, customerEmail, products, totalAmount, timestamp: serverTimestamp()
})
successMessage("Sales recorded! 🎉")
setAddNew(false)
} catch (err) {
console.error(err)
errorMessage("Error! Try again ❌")
}
}
export const getSales = async (setSales: any) => {
try {
const docRef = collection(db, "sales")
const q = query(docRef, orderBy("timestamp"))
onSnapshot(q, (snapshot) => {
const docs: any = []
snapshot.forEach((d: any) => {
docs.unshift( { ...d.data(), id: d.id })
});
setSales(docs)
})
} catch (err) {
console.error(err)
setSales([])
}
}
export const getTotalSales = async (setTotalSales: any) => {
try {
const unsub = onSnapshot(collection(db, "sales"), doc => {
let totalSales:number = 0
doc.forEach((d: any) => {
totalSales += d.data().totalAmount
});
setTotalSales(totalSales)
})
} catch (err) {
console.error(err)
}
}
export const getSalesForDay = async (date: Date | null, setSales: any) => {
try {
const day = date?.getDate()
const month = date?.getMonth()
const year: number | undefined = date?.getFullYear()
if (day !== undefined && month !== undefined && year !== undefined) {
const startDate = new Date(year, month, day, 0, 0, 0);
const endDate = new Date(year, month, day, 23, 59, 59);
const docRef = collection(db, "sales")
const q = query(docRef, orderBy("timestamp"), where("timestamp", ">=", Timestamp.fromDate(startDate)), where("timestamp", "<=", Timestamp.fromDate(endDate)))
onSnapshot(q, (snapshot) => {
const docs: any = []
snapshot.forEach((d: any) => {
docs.unshift( { ...d.data(), id: d.id })
});
setSales(docs)
})
}
}
catch (err) {
console.error(err)
}
}