Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/target/
/.idea/
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,14 @@
4. Найденный в соответствии с условием задачи месяц должен выводиться на английском языке в нижнем регистре. Если месяцев несколько, то на вывод они все подаются на английском языке в нижнем регистре в порядке их следования в течение года.

## Автор решения
Соловьева Кристина Вадимовна

## Описание реализации
AnalyticsSystem - класс для создания отчёта, основной метод public String getMostProfitMonths(String filename)

JsonReader - класс для считывания json, основной метод static List<Order> readJsonAndSaveData(String filePath)

## Инструкция по сборке и запуску решения
Сборка: запустить mvn clean install из директории school2024-test-task1

Запуск: java -jar target/school2024-test-task1-1.0.jar path_to_json, где path_to_json - путь до файла с данными, например, /Users/User/IdeaProjects/school2024-test-task1/src/main/resources/format.json
62 changes: 62 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.soloveva</groupId>
<artifactId>school2024-test-task1</artifactId>
<version>1.0</version>

<dependencies>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
</dependencies>

<properties>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>prepare-package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
<overWriteReleases>false</overWriteReleases>
<overWriteSnapshots>false</overWriteSnapshots>
<overWriteIfNewer>true</overWriteIfNewer>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<mainClass>com.soloveva.Main</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>

</project>
Binary file added school2024-test-task1-1.0.jar
Binary file not shown.
28 changes: 28 additions & 0 deletions src/main/java/com/soloveva/Main.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.soloveva;

import com.soloveva.services.AnalyticsSystem;
import org.json.simple.parser.ParseException;

import java.io.IOException;

public class Main {
public static void main(String[] args) {
if (args.length != 1){
System.out.println("Неверное количество аргументов!");
return;
}

AnalyticsSystem analyticsSystem = new AnalyticsSystem();

try {
String result = analyticsSystem.getMostProfitMonths(args[0]);

System.out.println("Отчёт сформирован успешно!");
System.out.println(result);
} catch (IOException | ParseException e) {
System.out.println("Ошибка при формировании отчёта!");
System.out.println(e.getMessage());
}
}
}

29 changes: 29 additions & 0 deletions src/main/java/com/soloveva/models/Order.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.soloveva.models;

import java.time.LocalDateTime;

public class Order {
private String userID;
private LocalDateTime orderTime;
private OrderStatus status;
private double totalPrice;

public Order(String userID, LocalDateTime orderTime, OrderStatus status, double totalPrice){
this.userID = userID;
this.orderTime = orderTime;
this.status = status;
this.totalPrice = totalPrice;
}
public String getUserID() {
return userID;
}
public LocalDateTime getOrderTime() {
return orderTime;
}
public OrderStatus getStatus(){
return status;
}
public double getTotalPrice() {
return totalPrice;
}
}
8 changes: 8 additions & 0 deletions src/main/java/com/soloveva/models/OrderStatus.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package com.soloveva.models;

public enum OrderStatus {
COMPLETED,
CANCELED,
CREATED,
DELIVERY
}
45 changes: 45 additions & 0 deletions src/main/java/com/soloveva/readers/JsonReader.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package com.soloveva.readers;
import com.soloveva.models.Order;
import com.soloveva.models.OrderStatus;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.FileReader;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
public class JsonReader {
public static List<Order> readJsonAndSaveData(String filePath)
throws IOException, ParseException, NumberFormatException {
JSONParser parser = new JSONParser();
List<Order> orders = new ArrayList<>();

try (FileReader reader = new FileReader(filePath)) {
Object array = parser.parse(reader);
JSONArray jsonArray = (JSONArray) array;

for(Object element : jsonArray){
JSONObject jsonData = (JSONObject) element;

String userID = (String) jsonData.get("user_id");

String orderedAt = (String) jsonData.get("ordered_at");
LocalDateTime orderTime = LocalDateTime.parse(orderedAt);

String status = (String) jsonData.get("status");
OrderStatus orderStatus = OrderStatus.valueOf(status);

String total = (String) jsonData.get("total");
Double totalPrice = Double.parseDouble(total);

Order order = new Order(userID, orderTime, orderStatus, totalPrice);

orders.add(order);
}
}

return orders;
}
}
54 changes: 54 additions & 0 deletions src/main/java/com/soloveva/services/AnalyticsSystem.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package com.soloveva.services;

import com.soloveva.models.Order;
import com.soloveva.models.OrderStatus;
import com.soloveva.readers.JsonReader;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.ParseException;

import java.io.IOException;
import java.time.Month;
import java.util.*;

public class AnalyticsSystem {
public String getMostProfitMonths(String filename) throws IOException, ParseException {
List<Order> orders = JsonReader.readJsonAndSaveData(filename);
List<String> months = calculateMostProfitMonths(orders);

return generateJson(months);
}

private List<String> calculateMostProfitMonths(List<Order> orders){
List<Order> completedOrders = orders.stream()
.filter(order -> order.getStatus().equals(OrderStatus.COMPLETED)).toList();

Map<Month, Double> profitsByMonths = new HashMap<>();

for(Order order : completedOrders){
Month month = order.getOrderTime().getMonth();
double totalPrice = order.getTotalPrice();

profitsByMonths.compute(month, (k, v) -> (v != null ? v : 0.0) + totalPrice);
}

Double maxProfit = profitsByMonths.values().stream().max(Double::compare).orElse(null);

if(maxProfit == null){
return null;
} else {
return profitsByMonths.entrySet().stream()
.filter(entry -> Objects.equals(entry.getValue(), maxProfit))
.map(Map.Entry::getKey).sorted(Comparator.comparingInt(Month::getValue))
.map(month -> month.name().toLowerCase()).toList();
}
}

private String generateJson(List<String> months){
JSONObject jsonObject = new JSONObject();
JSONArray monthArray = new JSONArray();
monthArray.addAll(months);
jsonObject.put("months", monthArray);
return jsonObject.toJSONString();
}
}
File renamed without changes.