103 lines
3.2 KiB
Java
103 lines
3.2 KiB
Java
import java.io.File;
|
|
import java.io.FileNotFoundException;
|
|
import java.io.FileWriter;
|
|
import java.io.IOException;
|
|
import java.util.List;
|
|
import java.util.Scanner;
|
|
|
|
public class ReportGenerator {
|
|
|
|
private final String ordersFilePath;
|
|
private final List<Product> productList;
|
|
|
|
private double totalFinalCost = 0;
|
|
private int totalQuantity = 0;
|
|
private double totalDiscountValue = 0;
|
|
private int totalInvalidLines = 0;
|
|
|
|
public ReportGenerator(String ordersFilePath, List<Product> productList) {
|
|
this.ordersFilePath = ordersFilePath;
|
|
this.productList = productList;
|
|
}
|
|
|
|
public void processFile()
|
|
{
|
|
|
|
File file = new File(ordersFilePath);
|
|
|
|
try (Scanner scanner = new Scanner(file)){
|
|
|
|
while (scanner.hasNextLine()) {
|
|
|
|
String line = scanner.nextLine();
|
|
|
|
try {
|
|
String[] parts = line.split(",");
|
|
|
|
int productId = Integer.parseInt(parts[0].trim());
|
|
int quantity = Integer.parseInt(parts[1].trim());
|
|
int discountPercent = Integer.parseInt(parts[2].trim());
|
|
|
|
if (productId <= 0 || quantity <= 0 || discountPercent < 0 || discountPercent > 99) {
|
|
totalInvalidLines++;
|
|
continue;
|
|
}
|
|
|
|
Product foundProduct = null;
|
|
|
|
for (Product currentProduct : productList) {
|
|
if (currentProduct.getProductID() == productId) {
|
|
foundProduct = currentProduct;
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (foundProduct == null) {
|
|
totalInvalidLines++;
|
|
continue;
|
|
}
|
|
|
|
double subtotal = quantity * foundProduct.getPrice();
|
|
double discountValue = subtotal * discountPercent / 100.0;
|
|
double finalCost = subtotal - discountValue;
|
|
|
|
totalQuantity += quantity;
|
|
totalFinalCost += finalCost;
|
|
totalDiscountValue += discountValue;
|
|
|
|
} catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
|
|
totalInvalidLines++;
|
|
}
|
|
}
|
|
|
|
} catch (FileNotFoundException e) {
|
|
System.out.println("File not found: " + ordersFilePath);
|
|
}
|
|
|
|
}
|
|
|
|
public void saveReport()
|
|
{
|
|
String report =
|
|
"========= SALES REPORT =========\n" +
|
|
"Total Quantity Sold: " + totalQuantity + "\n" +
|
|
"Total Final Cost: $" + String.format("%.2f", totalFinalCost) + "\n" +
|
|
"Total Discount Value: $" + String.format("%.2f", totalDiscountValue) + "\n" +
|
|
"Invalid Rows: " + totalInvalidLines + "\n" +
|
|
"================================";
|
|
|
|
try
|
|
{
|
|
FileWriter fileWriter = new FileWriter("report.txt");
|
|
|
|
fileWriter.write(report);
|
|
|
|
fileWriter.close();
|
|
}
|
|
catch (IOException e)
|
|
{
|
|
System.out.println("Error writing report: " + e.getMessage());
|
|
}
|
|
}
|
|
|
|
} |