Skip to content

Commit

Permalink
Refactor files in storage package
Browse files Browse the repository at this point in the history
  • Loading branch information
DextheChik3n committed Nov 13, 2023
1 parent bf4eedd commit 35f30a7
Show file tree
Hide file tree
Showing 4 changed files with 70 additions and 31 deletions.

This file was deleted.

78 changes: 55 additions & 23 deletions src/main/java/seedu/cafectrl/storage/Decoder.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,35 @@
* Pantry stock, and OrderList, allowing retrieval of data stored in a file.
*/
public class Decoder {

private static final Ui ui = new Ui();
private static final Logger logger = Logger.getLogger(CafeCtrl.class.getName());
private static final String DIVIDER = "\\| ";
private static final String INGREDIENT_DIVIDER = " - ";
private static final Ui ui = new Ui();
private static Logger logger = Logger.getLogger(CafeCtrl.class.getName());

/** For menu decoder */
public static final int MAX_INGREDIENTS_STRING_ARRAY_SIZE = 1;
public static final int DISH_NAME_INDEX_DISH_ARRAY = 0;
public static final int DISH_PRICE_INDEX_DISH_ARRAY = 1;
public static final int DISH_INGREDIENT_START_INDEX = 2;
public static final int NAME_INDEX_INGREDIENT_ARRAY = 0;
public static final int QTY_INDEX_INGREDIENT_ARRAY = 1;
public static final int UNIT_INDEX_INGREDIENT_ARRAY = 2;

/** for stock pantry decoder */
public static final int NAME_INDEX_PANTRY = 0;
public static final int QTY_INDEX_PANTRY = 1;
public static final int UNIT_INDEX_PANTRY = 2;
public static final int MAX_PANTRY_ARRAY_SIZE = 3;

/** for sales decoder */
public static final int DAY_INDEX_SALES = 0;
public static final int DISH_NAME_INDEX_SALES = 1;
public static final int QTY_INDEX_SALES = 2;
public static final int DISH_PRICE_INDEX_SALES = 3;
public static final int STATUS_INDEX_SALES = 4;
public static final String TRUE_STRING = "true";
public static final String FALSE_STRING = "false";
public static final int MIN_DISH_PRICE = 0;

//@@author ShaniceTang
/**
Expand Down Expand Up @@ -61,11 +85,15 @@ private static void decodeDishString(String dishString, ArrayList<Dish> menuDish
String dishName = "";
try {
String[] dishStringArray = dishString.split(DIVIDER);
dishName = dishStringArray[0].trim().toLowerCase();
dishName = dishStringArray[DISH_NAME_INDEX_DISH_ARRAY].trim().toLowerCase();

checkNameValidity(dishName);
float dishPrice = Parser.parsePriceToFloat(dishStringArray[1]);
String[] ingredientStringArray = Arrays.copyOfRange(dishStringArray, 2, dishStringArray.length);

float dishPrice = Parser.parsePriceToFloat(dishStringArray[DISH_PRICE_INDEX_DISH_ARRAY]);
String[] ingredientStringArray = Arrays.copyOfRange(
dishStringArray, DISH_INGREDIENT_START_INDEX, dishStringArray.length);
ArrayList<Ingredient> ingredientsList = decodeIngredientData(ingredientStringArray);

menuDishList.add(new Dish(dishName, ingredientsList, dishPrice));
} catch (ParserException e) {
logger.log(Level.WARNING, "Dish has invalid price: " + e.getMessage(), e);
Expand Down Expand Up @@ -94,19 +122,23 @@ private static void checkNameValidity(String name) throws Exception {
private static ArrayList<Ingredient> decodeIngredientData(String[] ingredientsStringArray) throws Exception {
ArrayList<Ingredient> ingredientList = new ArrayList<>();

if (ingredientsStringArray.length < 1) {
if (ingredientsStringArray.length < MAX_INGREDIENTS_STRING_ARRAY_SIZE) {
throw new RuntimeException(ErrorMessages.MISSING_INGREDIENT_MENU_DATA);
}

for(String ingredientString : ingredientsStringArray) {
logger.info("Ingredient to decode: " + ingredientString);

String[] array = ingredientString.split(INGREDIENT_DIVIDER);
String name = array[0].trim().toLowerCase();
String name = array[NAME_INDEX_INGREDIENT_ARRAY].trim().toLowerCase();
checkNameValidity(name);
int qty = Integer.parseInt(array[1].trim());

int qty = Integer.parseInt(array[QTY_INDEX_INGREDIENT_ARRAY].trim());
checkQtyValidity(qty);
String unit = array[2].trim();

String unit = array[UNIT_INDEX_INGREDIENT_ARRAY].trim();
checkUnitValidity(unit);

ingredientList.add(new Ingredient(name, qty, unit));
}
return ingredientList;
Expand Down Expand Up @@ -146,9 +178,9 @@ public static Pantry decodePantryStockData(ArrayList<String> encodedPantryStock)
ui.showToUser(ErrorMessages.ERROR_IN_PANTRY_STOCK_DATA + encodedData);
continue;
}
String ingredientName = decodedData[0].trim();
String qtyText = decodedData[1].trim();
String unit = decodedData[2].trim();
String ingredientName = decodedData[NAME_INDEX_PANTRY].trim();
String qtyText = decodedData[QTY_INDEX_PANTRY].trim();
String unit = decodedData[UNIT_INDEX_PANTRY].trim();

// Check whether qty is an integer
int qty;
Expand Down Expand Up @@ -200,11 +232,11 @@ private static boolean isValidUnit(String unit) {
* @return true if the format is correct, false otherwise
*/
private static boolean isValidPantryStockFormat(String[] decodedPantryStock) {
if (decodedPantryStock.length != 3) {
if (decodedPantryStock.length != MAX_PANTRY_ARRAY_SIZE) {
return false;
} else {
try {
Integer.parseInt(decodedPantryStock[1].trim());
Integer.parseInt(decodedPantryStock[QTY_INDEX_PANTRY].trim());
} catch (NumberFormatException e) {
return false;
}
Expand Down Expand Up @@ -254,8 +286,8 @@ public static Sales decodeSales(ArrayList<String> textLines, Menu menu) {
private static void decodeSalesData(String orderLine, ArrayList<OrderList> orderLists, Menu menu) {
try {
String[] orderData = orderLine.split(DIVIDER);
int day = Integer.parseInt(orderData[0].trim()) - Sales.DAY_DISPLAY_OFFSET;
String dishName = orderData[1].trim();
int day = Integer.parseInt(orderData[DAY_INDEX_SALES].trim()) - Sales.DAY_DISPLAY_OFFSET;
String dishName = orderData[DISH_NAME_INDEX_SALES].trim();

//@@author Cazh1
//keeps track of the number of days cafe has been operating for
Expand All @@ -265,9 +297,9 @@ private static void decodeSalesData(String orderLine, ArrayList<OrderList> order
}
//@@author

int quantity = Integer.parseInt(orderData[2].trim());
float decodedDishPrice = Float.parseFloat(orderData[3].trim());
String completeStatus = orderData[4].trim();
int quantity = Integer.parseInt(orderData[QTY_INDEX_SALES].trim());
float decodedDishPrice = Float.parseFloat(orderData[DISH_PRICE_INDEX_SALES].trim());
String completeStatus = orderData[STATUS_INDEX_SALES].trim();
float totalOrderCost = quantity * decodedDishPrice;

checkNameValidity(dishName);
Expand All @@ -291,16 +323,16 @@ && isValidQty(orderLine, quantity)
}

private static boolean isCompleteStatusAccurate(String orderLine, String completeStatus) {
if (completeStatus.equalsIgnoreCase("true")
|| completeStatus.equalsIgnoreCase("false")) {
if (completeStatus.equalsIgnoreCase(TRUE_STRING)
|| completeStatus.equalsIgnoreCase(FALSE_STRING)) {
return true;
}
ui.showToUser(ErrorMessages.INVALID_ORDER_STATUS + orderLine);
return false;
}

private static boolean isValidPrice(String orderLine, Float decodedDishPrice) {
if (decodedDishPrice >= 0) {
if (decodedDishPrice >= MIN_DISH_PRICE) {
return true;
}
ui.showToUser(ErrorMessages.INVALID_DISH_PRICE + orderLine);
Expand Down
14 changes: 12 additions & 2 deletions src/main/java/seedu/cafectrl/storage/Encoder.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ public class Encoder {
private static final String DIVIDER = " | ";
private static final String INGREDIENT_DIVIDER = " - ";
private static final Logger logger = Logger.getLogger(CafeCtrl.class.getName());
public static final String LINE_BREAK = "\n";
public static final String EMPTY_STRING = "";
public static final String CARRIAGE_RETURN = "\r";
public static final String TWO_DECIMAL_PLACE_FORMAT = "%.2f";

//@@author Cazh1
/**
Expand All @@ -35,7 +39,9 @@ private static ArrayList<String> hashEncoding(ArrayList<String> stringArrayList)
String stringArrayListAsString = String.join(", ", stringArrayList).trim();

//The generated String has line breaks, this removes line breaks
String stringArrayListAsStringInOneLine = stringArrayListAsString.replace("\n", "").replace("\r", "");
String stringArrayListAsStringInOneLine = stringArrayListAsString
.replace(LINE_BREAK, EMPTY_STRING)
.replace(CARRIAGE_RETURN, EMPTY_STRING);

//Generate Hash from content
int stringArrayListHash = stringArrayListAsStringInOneLine.hashCode();
Expand Down Expand Up @@ -138,15 +144,19 @@ public static ArrayList<String> encodeSales(Sales sales) {
StringBuilder orderString = new StringBuilder();

//day of each orderList is index + 1
float orderedDishPrice = order.getOrderedDish().getPrice();
String orderedDishPriceString = String.format(TWO_DECIMAL_PLACE_FORMAT, orderedDishPrice);

orderString.append((day + 1) + DIVIDER);
orderString.append(order.getDishName() + DIVIDER);
orderString.append(order.getQuantity() + DIVIDER);
orderString.append(String.format("%.2f", order.getOrderedDish().getPrice()) + DIVIDER);
orderString.append(orderedDishPriceString + DIVIDER);
orderString.append(order.getIsComplete());
orderString.append(System.lineSeparator());
encodedList.add(String.valueOf(orderString));
logger.info("Encoded order: " + orderString);
}

if (day == sales.getDaysAccounted()) {
encodedList = encodeLastSalesDay(encodedList, orderList, day);
}
Expand Down
5 changes: 3 additions & 2 deletions src/main/java/seedu/cafectrl/storage/FileManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
*/
public class FileManager {

public static final String USER_BASE_DIRECTORY = "user.dir";
private static Logger logger = Logger.getLogger(CafeCtrl.class.getName());
private final Ui ui;

Expand All @@ -35,7 +36,7 @@ public FileManager(Ui ui) {
*/
public ArrayList<String> readTextFile(String filePath) throws FileNotFoundException {
logger.info("Reading text file...");
String userWorkingDirectory = System.getProperty("user.dir");
String userWorkingDirectory = System.getProperty(USER_BASE_DIRECTORY);
Path dataFilePath = Paths.get(userWorkingDirectory, filePath);
File textFile = new File(String.valueOf(dataFilePath));
ArrayList<String> textLines = new ArrayList<>();
Expand All @@ -62,7 +63,7 @@ public void checkFileExists(String filePath) throws Exception {
throw new Exception(ErrorMessages.MISSING_FILEPATH);
}

String userWorkingDirectory = System.getProperty("user.dir");
String userWorkingDirectory = System.getProperty(USER_BASE_DIRECTORY);
Path dataFilePath = Paths.get(userWorkingDirectory, filePath);
Path dataFolderPath = dataFilePath.getParent();
File textFile = new File(String.valueOf(dataFilePath));
Expand Down

0 comments on commit 35f30a7

Please sign in to comment.