-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCustomer.java
More file actions
657 lines (619 loc) · 29.6 KB
/
Copy pathCustomer.java
File metadata and controls
657 lines (619 loc) · 29.6 KB
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
/**
* Project 5 - Customer.java
*
* Class to represent the permissions and details associated with a customer
*
* @author Shafer Anthony Hofmann, Qihang Gan, Shreyas Viswanathan, Nathan Pasic
* Miller, Oliver Long
*
* @version December 9, 2023
*/
public class Customer extends User {
private ArrayList<String> shoppingCart;
private ArrayList<String> purchasehistory;
private Database db = new Database();
public Customer(String email, String password, UserRole role) throws Exception {
super(email, password, role);
shoppingCart = db.getMatchedEntries("shoppingCarts.csv", 0, getUserID());
purchasehistory = db.getMatchedEntries("purchaseHistories.csv", 0, getUserID());
}
public Customer(String userID, String email, String password, UserRole role) throws Exception {
super(userID, email, password, UserRole.CUSTOMER);
shoppingCart = db.getMatchedEntries("shoppingCarts.csv", 0, getUserID());
purchasehistory = db.getMatchedEntries("purchaseHistories.csv", 0, getUserID());
}
/**
* Fetches all the stores that exist in the application and returns them in the form of an arraylist.
* Utilized to determine customer dashboard behavior.
*
* @return An arraylist containing all the stores
*/
public ArrayList<String> fetchAllStores() throws CustomerException {
ArrayList<String> allStores = db.getDatabaseContents("stores.csv");
if (allStores.isEmpty()) {
throw new CustomerException("No stores have been created yet!");
}
return allStores;
}
/**
* Converts arrays to list of strings
*
* @return String of array's contents
*/
public String arrToString(ArrayList<String> array) {
StringBuilder output = new StringBuilder();
output.append("Product Name - Store Name - Quantity - Price\n");
for (int i = 0; i < array.size(); i++) {
output.append(i + 1).append(") ").append(array.get(i)).append("\n");
}
return output.toString();
}
/**
* Returns the user's shopping history
*
* @return The shopping history as a string
* @throws CustomerException
*/
public String getShoppingHistory() throws CustomerException {
String[] info;
StringBuilder sb = new StringBuilder();
ArrayList<String> output = new ArrayList<>();
purchasehistory = db.getMatchedEntries("purchaseHistories.csv", 0, getUserID());
if (purchasehistory.isEmpty()) {
throw new CustomerException("Shopping History is Empty");
} else {
for (String product : db.getMatchedEntries("purchaseHistories.csv", 0, getUserID())) {
sb = new StringBuilder();
info = product.split(",");
sb.append(info[5]).append(" ");
sb.append(info[4]).append(" ");
sb.append(info[6]).append(" ");
sb.append(info[7]).append(" ");
output.add(sb.toString());
}
}
return arrToString(output);
}
/**
* Returns a specific products's info
*
* @return The product's info
* @throws CustomerException
*/
public String getProductInfo(int index) throws CustomerException {
try {
StringBuilder sb = new StringBuilder();
String[] prodInfo = db.getDatabaseContents("products.csv").get(index).split(",");
sb.append(prodInfo[3]).append(",");
sb.append(prodInfo[4]).append(",");
sb.append(prodInfo[5]).append(",");
sb.append(prodInfo[6]).append(",");
sb.append(prodInfo[7]).append(",");
sb.append(prodInfo[8]).append(",");
if (prodInfo[9].equals("[]")) {
sb.append("No Reviews").append(",");
} else {
sb.append(prodInfo[9]).append(",");
}
sb.append(prodInfo[11]).append(","); // sale price
return sb.toString();
} catch (IndexOutOfBoundsException e) {
throw new CustomerException("Unable to retrieve information about this product. Please try again!");
}
}
/**
* Returns the all the products in the csv
*
* @return The products listed as a string
* @throws CustomerException
*/
public String getAllProducts() throws CustomerException {
ArrayList<String> productList = db.getDatabaseContents("products.csv");
StringBuilder sb = new StringBuilder();
String[] info;
ArrayList<String> output = new ArrayList<>();
if (productList.isEmpty()) {
throw new CustomerException("No sellers have added products to any of their stores yet");
} else {
for (String product : productList) {
sb = new StringBuilder();
info = product.split(",");
sb.append(info[4]).append(" ");
sb.append(info[3]).append(" ");
sb.append(info[5]).append(" ");
sb.append(info[6]).append(" ");
output.add(sb.toString());
}
}
return arrToString(output);
}
/**
* Internal Supplementary formatting method
*
* @return The products formatted as a string
* @throws CustomerException
*/
public String formatProducts(ArrayList<String> productList) throws CustomerException {
StringBuilder sb = new StringBuilder();
String[] info;
ArrayList<String> output = new ArrayList<>();
if (productList.isEmpty()) {
throw new CustomerException("No Products Available");
} else {
for (String product : productList) {
sb = new StringBuilder();
info = product.split(",");
sb.append(info[4]).append(" ");
sb.append(info[3]).append(" ");
sb.append(info[5]).append(" ");
sb.append(info[6]).append(" ");
output.add(sb.toString());
}
}
return arrToString(output);
}
/**
* Returns the user's shopping cart
*
* @return The shopping cart as a string
* @throws CustomerException
*/
public String getCart() throws CustomerException {
String[] info;
StringBuilder sb = new StringBuilder();
ArrayList<String> output = new ArrayList<>();
shoppingCart = db.getMatchedEntries("shoppingCarts.csv", 0, getUserID());
if (shoppingCart.isEmpty()) {
throw new CustomerException("No Items in Shopping Cart");
} else {
for (String product : shoppingCart) {
sb = new StringBuilder();
info = product.split(",");
sb.append(info[5]).append(" ");
sb.append(info[4]).append(" ");
sb.append(info[6]).append(" ");
sb.append(info[7]).append(" ");
output.add(sb.toString());
}
}
return arrToString(output);
}
/**
* Removes an item in its entirety from the cart
*
* @param index the index of the cart the remove
* @throws CustomerException
*/
public void removeFromCart(int index) throws CustomerException {
try {
db.removeFromDatabase("shoppingCarts.csv", shoppingCart.get(index));
shoppingCart.remove(index);
} catch (IndexOutOfBoundsException e) {
throw new CustomerException("Unable to remove this item from cart. Please try again!");
}
}
// Removes a certain quantity of an item in the cart
public void removeFromCart(int index, String desiredQuantity) throws CustomerException {
if (desiredQuantity.isBlank() || desiredQuantity.isEmpty()) {
throw new CustomerException("The modified quantity cannot be blank or empty");
}
int newQuantity;
// Case 1: They enter a string literal for how much they'd like to remove
try {
newQuantity = Integer.parseInt(desiredQuantity);
} catch (NumberFormatException e) {
throw new CustomerException("The quantity has to be an integer and cannot be a string");
}
if (newQuantity <= 0) {
throw new CustomerException("The quantity selected must be greater than 0");
}
shoppingCart = db.getMatchedEntries("shoppingCarts.csv", 0, getUserID());
String prevEntry = shoppingCart.get(index);
int originalQuantity = Integer.parseInt(prevEntry.split(",")[6]);
double price = Double.parseDouble(prevEntry.split(",")[7]);
// Case 2: They enter a quantity that exceeds what's already in cart
if (newQuantity >= originalQuantity) {
removeFromCart(index);
} else {
int modifiedQuantity = originalQuantity - newQuantity;
String[] newEntry = prevEntry.split(",");
newEntry[6] = String.valueOf(modifiedQuantity);
newEntry[7] = String.valueOf(String.format("%.2f", modifiedQuantity * price));
db.modifyDatabase("shoppingCarts.csv", prevEntry, String.join(",", newEntry));
}
}
/**
* Adds a given item from the cart
*
* @param productID the index of the product the add
* @throws CustomerException
*/
public void addToCart(int index, String desiredQuantity) throws CustomerException {
try {
ArrayList<String> products = db.getDatabaseContents("products.csv");
// get the product with that index in the products.csv file
String[] target = products.get(index).split(",");
int quantity;
try {
quantity = Integer.parseInt(desiredQuantity);
} catch (NumberFormatException e) {
throw new CustomerException("The quantity has to be an integer and cannot be a string");
}
if (quantity <= 0) {
throw new CustomerException("The quantity selected must be greater than 0");
} else if (Integer.parseInt(target[5]) < quantity) {
throw new CustomerException("There are only " + Integer.parseInt(target[5]) + " of this item for sale!");
}
int orderLimit = Integer.parseInt(target[8]);
if (orderLimit == 0) {
// This is a possibility
} else if (orderLimit > 0) {
if (quantity > orderLimit) {
throw new CustomerException("At a time, you can only add " + Integer.parseInt(target[8]) + " of this item to your cart");
}
}
shoppingCart = db.getMatchedEntries("shoppingCarts.csv", 0, getUserID());
StringBuilder output = new StringBuilder();
int updatedQuant = quantity;
output.append(getUserID()).append(",");
// if they're adding more of the same item to their cart(quantity is just updated)
Iterator<String> iterator = shoppingCart.iterator();
while (iterator.hasNext()) {
String item = iterator.next();
if (item.contains(target[2])) {
updatedQuant = Integer.parseInt(item.split(",")[6]) + quantity;
db.removeFromDatabase("shoppingCarts.csv", item);
iterator.remove();
break;
}
}
for (int i = 0; i < 5; i++) {
output.append(target[i]).append(",");
}
output.append(updatedQuant).append(",");
double actualPrice = Double.parseDouble(target[6]);
// check if the current quantity equals the sale quantity
int saleQty = Integer.parseInt(target[10]);
if (saleQty > 0 && Integer.parseInt(target[5]) <= saleQty) {
actualPrice = Double.parseDouble(target[11]);
System.out.println("Sale Price Applied: " + actualPrice);
}
output.append(String.format("%.2f", actualPrice * (double) updatedQuant));
shoppingCart.add(output.toString());
db.addToDatabase("shoppingCarts.csv", shoppingCart.get(shoppingCart.size() - 1));
} catch (Exception e) {
throw new CustomerException(e.getMessage());
}
}
/**
* Purchases the items in the cart
*
* @throws CustomerException
*/
public void purchaseItems() throws CustomerException {
StringBuilder output = new StringBuilder();
String[] updatedEntry;
String[] target;
int quantity;
shoppingCart = db.getMatchedEntries("shoppingCarts.csv", 0, getUserID());
purchasehistory = db.getMatchedEntries("purchaseHistories.csv", 0, getUserID());
if (shoppingCart.isEmpty()) {
throw new CustomerException("You don\'t have any items added to your cart yet!");
}
output.append(getUserID()).append(",");
String item;
boolean duplicate = false;
for (int i = shoppingCart.size() - 1; i >= 0; i--) {
item = shoppingCart.get(i);
// gets the product with the associated ID
target = db.getMatchedEntries("products.csv", 2, item.split(",")[3]).get(0).split(",");
quantity = Integer.parseInt(item.split(",")[6]);
// the quantity being checked out is greater than what is actually available
// if its just for one product but everything else being checked out is within limits, no need to throw an exception
if (Integer.parseInt(target[5]) < quantity) {
db.removeFromDatabase("shoppingCarts.csv", item);
shoppingCart.remove(item);
// throw new CustomerException("Not Enough Product Stocked");
} else {
duplicate = false;
for (int j = 0; j < purchasehistory.size(); j++) {
if (item.split(",")[3].equals(purchasehistory.get(i).split(",")[3])) {
updatedEntry = purchasehistory.get(i).split(",");
updatedEntry[6] = String
.valueOf(Integer.parseInt(updatedEntry[6]) + Integer.parseInt(item.split(",")
[6]));
updatedEntry[7] = String
.valueOf(Double.parseDouble(updatedEntry[7]) + Double.parseDouble(item.split(",")[7]));
db.modifyDatabase("purchaseHistories.csv", purchasehistory.get(i),
String.join(",", updatedEntry));
duplicate = true;
}
}
// Correctly updates it if more of the same item from the same store is purchased
if (!duplicate) {
db.addToDatabase("purchaseHistories.csv", item);
}
// updates the remaining quantity of the product in the products.csv file
target = db.getMatchedEntries("products.csv", 2, item.split(",")[3]).get(0).split(",");
target[5] = String.valueOf(Integer.parseInt(target[5]) - Integer.parseInt(item.split(",")[6]));
db.modifyDatabase("products.csv",
db.getMatchedEntries("products.csv", 2, target[2]).get(0),
String.join(",", target));
}
db.removeFromDatabase("shoppingCarts.csv", item);
shoppingCart.remove(item);
}
}
/**
* Sorts based on user's choice of price or quantity
*
* @return Returns the sorted string
* @throws CustomerException
*/
public String sortProducts(String choice, boolean ascending) throws CustomerException {
ArrayList<String> sorted = db.getDatabaseContents("products.csv");
int n = sorted.size();
String temp = "";
int searchIndex = -1;
if (choice.equals("price")) {
searchIndex = 6;
} else if (choice.equals("quantity")) {
searchIndex = 5;
}
if (searchIndex != -1) {
if (sorted.size() > 1) {
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (Double.parseDouble(sorted.get(j - 1).split(",")[searchIndex]) > Double
.parseDouble(sorted.get(j).split(",")[searchIndex])) {
temp = sorted.get(j - 1);
sorted.set(j - 1, sorted.get(j));
sorted.set(j, temp);
}
}
}
}
if (ascending) {
return formatProducts(sorted);
} else {
Collections.reverse(sorted);
return formatProducts(sorted);
}
} else {
throw new CustomerException("You can only choose to sort the price or quantity");
}
}
public void returnItems(int index) throws CustomerException {
// TO DO: can select only one item to return at a time
// PH: Customer ID,Seller ID,Store ID,Product ID,Store Name,Product Name,Purchase Quantity,Price
// Products.csv: Seller ID,Store ID,Product ID,Store Name,Product Name,Available Quantity,Price,Description,Order Limit,Reviews
// Notes:
// They can only return purchased items
// They cannot choose how many of the item they want to return. The whole item and how many ever were purchases is taken into consideration
purchasehistory = db.getMatchedEntries("purchaseHistories.csv", 0, getUserID());
if (purchasehistory.isEmpty()) {
throw new CustomerException("You haven\'t purchased any items yet!");
}
int purchasedQuantity = Integer.parseInt(purchasehistory.get(index).split(",")[6]);
String productName = purchasehistory.get(index).split(",")[5];
String matchedProductEntry = db.getMatchedEntries("products.csv", 4, productName).get(0);
String[] matchedProductContents = matchedProductEntry.split(",");
int newQuantity = Integer.parseInt(matchedProductContents[5]) + purchasedQuantity;
matchedProductContents[5] = String.valueOf(newQuantity);
db.modifyDatabase("products.csv", matchedProductEntry, String.join(",", matchedProductContents));
db.removeFromDatabase("purchaseHistories.csv", purchasehistory.get(index));
}
public void addReview(int index, String review) throws CustomerException {
// TO DO: can select only one product to leave a review for at a time
// Customer ID,Seller ID,Store ID,Product ID,Store Name,Product Name,Purchase Quantity,Price
// Notes:
// They can only leave reviews on products they have purchased
// Duplicate reviews will not be allowed
// At the present time, customers cannot edit reviews or delete reviews. They can just provide one
if (review.isBlank() || review.isEmpty()) {
throw new CustomerException("The review cannot be blank or empty!");
} else if (review.contains(",")) {
throw new CustomerException("The review cannot contain any commas!");
}
purchasehistory = db.getMatchedEntries("purchaseHistories.csv", 0, getUserID());
String productName = purchasehistory.get(index).split(",")[5];
String matchedProductEntry = db.getMatchedEntries("products.csv", 4, productName).get(0);
String[] matchedProductContents = matchedProductEntry.split(",");
// Seller ID,Store ID,Product ID,Store Name,Product Name,Available Quantity,Price,Description,Order Limit,Reviews
// email-review;email-review...
if (matchedProductContents[9].equals("[]")) {
// The given product doesn't have any reviews yet
String newReview = getEmail() + "-" + review + ";";
matchedProductContents[9] = newReview;
db.modifyDatabase("products.csv", matchedProductEntry, String.join(",", matchedProductContents));
} else {
matchedProductContents[9] += (getEmail() + "-" + review + ";");
db.modifyDatabase("products.csv", matchedProductEntry, String.join(",", matchedProductContents));
}
}
// fetches all the reviews provided by this customer
public ArrayList<String> fetchReviews() throws CustomerException {
ArrayList<String> reviewsProvided = new ArrayList<>();
reviewsProvided.add("Store Name-Product Name-Review");
purchasehistory = db.getMatchedEntries("purchaseHistories.csv", 0, getUserID());
for (int i = 0; i < purchasehistory.size(); i++) {
String productName = purchasehistory.get(i).split(",")[5];
String matchedProductEntry = db.getMatchedEntries("products.csv", 4, productName).get(0);
String reviews = matchedProductEntry.split(",")[9];
if (reviews.equals("[]")) {
continue;
} else {
String[] reviewContents = reviews.split(";");
for (int j = 0; j < reviewContents.length; j++) {
String review = reviewContents[j];
if (review.substring(0, review.indexOf("-")).equals(getEmail())) {
// storeName-productName-review
reviewsProvided.add(matchedProductEntry.split(",")[3] + "-" + matchedProductEntry.split(",")[4] + "-" + review.substring(review.indexOf("-") + 1));
}
}
}
}
if (reviewsProvided.size() == 1) {
throw new CustomerException("You haven\'t provided reviews for any purchased products yet!");
}
return reviewsProvided;
}
// format: email-review;email-review ...
public void modifyReview(int index, String modifiedReview) throws CustomerException {
if (modifiedReview.isBlank() || modifiedReview.isEmpty()) {
throw new CustomerException("The modified review cannot be blank or empty");
} else if (modifiedReview.contains(",")) {
throw new CustomerException("The modified review cannot contain any commas");
}
ArrayList<String> allReviews = fetchReviews();
String[] reviewToEdit = allReviews.get(index).split("-"); // storeName-productName-review
String productEntry = db.getMatchedEntries("products.csv", 4, reviewToEdit[1]).get(0);
String[] productEntryContents = productEntry.split(",");
String[] reviews = productEntryContents[9].split(";");
for (int i = 0; i < reviews.length; i++) { // email-review;email-review;email-review
String[] currReview = reviews[i].split("-");
if (currReview[1].equals(reviewToEdit[2])) {
currReview[1] = modifiedReview;
reviews[i] = String.join("-", currReview);
if (reviews.length == 1) {
productEntryContents[9] = reviews[0] + ";";
} else if (reviews.length > 1) {
productEntryContents[9] = (String.join(";", reviews) + ";");
}
db.modifyDatabase("products.csv", productEntry, String.join(",", productEntryContents));
break;
}
}
}
public void deleteReview(int index) throws CustomerException {
ArrayList<String> allReviews = fetchReviews();
String[] reviewToDelete = allReviews.get(index).split("-"); // storeName-productName-review
String productEntry = db.getMatchedEntries("products.csv", 4, reviewToDelete[1]).get(0);
String[] productEntryContents = productEntry.split(",");
String[] reviews = productEntryContents[9].split(";");
if (reviews.length == 1) {
productEntryContents[9] = "[]";
db.modifyDatabase("products.csv", productEntry, String.join(",", productEntryContents));
return;
} else {
for (int i = 0; i < reviews.length; i++) {
String[] currReview = reviews[i].split("-");
if (currReview[1].equals(reviewToDelete[2])) {
if (i == 0) {
String[] modifiedArr = Arrays.copyOfRange(reviews, 1, reviews.length);
if (modifiedArr.length == 1) {
productEntryContents[9] = modifiedArr[0] + ";";
} else if (modifiedArr.length > 1) {
productEntryContents[9] = (String.join(";", modifiedArr) + ";");
}
db.modifyDatabase("products.csv", productEntry, String.join(",", productEntryContents));
break;
} else if (i == reviews.length - 1) {
String[] modifiedArr = Arrays.copyOfRange(reviews, 0, reviews.length - 1);
if (modifiedArr.length == 1) {
productEntryContents[9] = modifiedArr[0] + ";";
} else if (modifiedArr.length > 1) {
productEntryContents[9] = (String.join(";", modifiedArr) + ";");
}
db.modifyDatabase("products.csv", productEntry, String.join(",", productEntryContents));
break;
} else {
// i is the index of the review to delete
String[] prevContents = Arrays.copyOfRange(reviews, 0, i);
String[] remainingContents = Arrays.copyOfRange(reviews, i + 1, reviews.length);
String[] res = new String[prevContents.length + remainingContents.length];
System.arraycopy(prevContents, 0, res, 0, prevContents.length);
System.arraycopy(remainingContents, 0, res, prevContents.length, remainingContents.length);
productEntryContents[9] = String.join(";", res);
db.modifyDatabase("products.csv", productEntry, String.join(",", productEntryContents));
break;
}
}
}
}
}
/**
* Exports the user's purchase history
*
* @return Returns true if the process is successful
* @throws CustomerException
*/
public void exportPurchaseHistory() throws CustomerException {
purchasehistory = db.getMatchedEntries("purchaseHistories.csv", 0, getUserID());
try {
if (!(purchasehistory.isEmpty())) {
File targetDir = new File("exportedHistory");
if (!targetDir.exists()) {
targetDir.mkdir();
}
File output = new File(targetDir, getEmail() + ".csv");
if (!output.exists()) {
output.createNewFile();
writeToExportedHistory(output, purchasehistory);
} else {
File existing = new File(targetDir, getEmail() + ".csv");
writeToExportedHistory(existing, purchasehistory);
}
} else {
throw new CustomerException("Purchase History is Empty");
}
} catch (IOException e) {
throw new CustomerException("An error occurred when exporting purchase history. Please try again");
}
}
/**
* Updates the contents of the customer's purchase history file with the new values
*
* @param output The customer's exported purchase history file to write to
* @param matchedPurchaseHistoryEntries The purchase history entries associated with the customer
* @throws CustomerException
*/
public void writeToExportedHistory(File output, ArrayList<String> matchedPurchaseHistoryEntries)
throws CustomerException {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(output, false))) {
String headers = db.getFileHeaders("purchaseHistories.csv");
bw.write(headers + "\n");
for (int i = 0; i < matchedPurchaseHistoryEntries.size(); i++) {
bw.write(matchedPurchaseHistoryEntries.get(i) + "\n");
}
} catch (IOException e) {
throw new CustomerException("An error occurred when exporting purchase history. Please try again");
}
}
/**
* Searches for all products containing a given query
*
* @return Returns the products found
* @throws CustomerException
*/
public String searchProducts(String query) throws CustomerException {
if (query == null || query.isBlank() || query.isEmpty()) {
throw new CustomerException("The query cannot be null, blank, or empty!");
} else if (query.contains(",")) {
throw new CustomerException("The query cannot contain any commas!");
}
ArrayList<String> productsFound = new ArrayList<>();
for (String product : db.getDatabaseContents("products.csv")) {
String[] productEntry = product.split(",");
// They can search by store name, product name, quantity, price, and description ONLY
productEntry = Arrays.copyOfRange(productEntry, 3, 8);
String queryLine = String.join(",", productEntry);
if (queryLine.toLowerCase().contains(query.toLowerCase())) {
productsFound.add(product);
}
}
if (productsFound.isEmpty()) {
throw new CustomerException("There are no products that match your query. Please try again!");
} else {
return formatProducts(productsFound);
}
}
}