158 lines
4.4 KiB
Python
158 lines
4.4 KiB
Python
import json
|
||
|
||
|
||
def load_orders(file_path):
|
||
with open(file_path, "r", encoding="utf-8") as f: # получаем список словарей orders
|
||
return json.load(f)
|
||
|
||
|
||
def validate_order(order):
|
||
if not isinstance(order, dict): # проверка что order это словарь (dict)
|
||
return False
|
||
|
||
for field in ["id", "customer", "items", "total_price"]:
|
||
if field not in order: # проверка что есть все элементы
|
||
return False
|
||
|
||
if not isinstance(order["items"], list):
|
||
return False
|
||
|
||
for item in order["items"]:
|
||
if not isinstance(item, dict):
|
||
return False
|
||
for field in ["name", "price", "quantity"]:
|
||
if field not in item:
|
||
return False
|
||
if not isinstance(item["price"], (int, float)):
|
||
return False
|
||
if not isinstance(item["quantity"], int):
|
||
return False
|
||
|
||
return True
|
||
|
||
|
||
def filter_orders_by_customer(orders, customer_name):
|
||
for order in orders:
|
||
if order["customer"] == customer_name:
|
||
return order
|
||
|
||
|
||
def calculate_order_total(order):
|
||
total = 0
|
||
for item in order["items"]:
|
||
total += item["price"] * item["quantity"]
|
||
return total
|
||
|
||
|
||
def update_order_totals(orders):
|
||
for order in orders:
|
||
order["total_price"] = calculate_order_total(order)
|
||
return orders
|
||
|
||
|
||
def get_top_expensive_orders(orders, n):
|
||
return sorted(orders, key=lambda x: x["total_price"], reverse=True)[:n]
|
||
|
||
|
||
def group_orders_by_customer(orders):
|
||
grouped = {}
|
||
for order in orders:
|
||
customer = order["customer"] # сравниваем по именам, или лучще по id
|
||
if customer not in grouped:
|
||
grouped[customer] = []
|
||
grouped[customer].append(order)
|
||
# id = order["id"]
|
||
# if id not in grouped:
|
||
# grouped[id] = []
|
||
# grouped[id].append(order)
|
||
return grouped
|
||
|
||
|
||
def calculate_customer_spending(orders):
|
||
spending = {}
|
||
for order in orders:
|
||
customer = order["customer"]
|
||
spending[customer] = spending.get(customer, 0) + order["total_price"]
|
||
return spending
|
||
|
||
|
||
def find_most_popular_product(orders):
|
||
product_counts = {}
|
||
|
||
for order in orders:
|
||
for item in order["items"]:
|
||
name = item["name"]
|
||
product_counts[name] = product_counts.get(name, 0) + item["quantity"]
|
||
|
||
if not product_counts:
|
||
return None
|
||
|
||
return max(product_counts, key=product_counts.get)
|
||
|
||
|
||
def generate_report(orders):
|
||
report = []
|
||
|
||
report.append(f"Общее количество действительных заказов: {len(orders)}")
|
||
|
||
spending = calculate_customer_spending(orders)
|
||
sorted_customers = sorted(spending.items(), key=lambda x: x[1], reverse=True)
|
||
|
||
report.append("\nТоп клиентов:")
|
||
for customer, amount in sorted_customers[:5]:
|
||
report.append(f"{customer}: {amount}")
|
||
|
||
popular_product = find_most_popular_product(orders)
|
||
report.append(f"\nСамый популярный продукт: {popular_product}")
|
||
|
||
return "\n".join(report)
|
||
|
||
|
||
def main():
|
||
file_path = "data/orders.txt"
|
||
|
||
try:
|
||
orders = load_orders(file_path)
|
||
except Exception as e:
|
||
print("Ошибка загрузки файла:", e)
|
||
return
|
||
|
||
# Валидация
|
||
valid_orders = []
|
||
invalid_count = 0
|
||
|
||
for order in orders:
|
||
if validate_order(order):
|
||
valid_orders.append(order)
|
||
else:
|
||
invalid_count += 1
|
||
|
||
print(f"Пропущенные недействительные заказы: {invalid_count}")
|
||
|
||
# Пересчет сумм
|
||
valid_orders = update_order_totals(valid_orders)
|
||
|
||
# Пример фильтрации
|
||
example_customer = "Alice"
|
||
customer_orders = filter_orders_by_customer(valid_orders, example_customer)
|
||
|
||
# Аналитика
|
||
grouped = group_orders_by_customer(valid_orders)
|
||
spending = calculate_customer_spending(valid_orders)
|
||
top_orders = get_top_expensive_orders(valid_orders, 3)
|
||
|
||
# Отчет
|
||
report = generate_report(valid_orders)
|
||
print("\n=== ОТЧЕТ ===")
|
||
print(report)
|
||
|
||
print("\n=== ТОП 3 ДОРОГИХ ЗАКАЗОВ ===")
|
||
for order in top_orders:
|
||
print(order)
|
||
|
||
print(f"\n{example_customer} приобрел(а) {len(customer_orders)} заказов")
|
||
print(f"Общее количество клиентов: {len(grouped)}")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main() |