nimer1/project/nimez1.py
2026-05-07 21:14:33 +03:00

141 lines
4.8 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import datetime
# Превращаем "иванов ПЕТР" в "Иванов П. П."
def format_customer_name(full_name):
fio = full_name.split()
if not fio: return ""
surname = fio[0].capitalize()
# Собираем инициалы через цикл
initials = ""
for name in fio[1:]:
initials += f" {name[0].upper()}."
return f"{surname}{initials}"
# Считаем скидочку: электроника - 10%, остальное - 5%
def calculate_discount(total_sum, category):
if category.lower() == "electronics":
rate = 0.10
else:
rate = 0.05
return round(total_sum * rate, 2)
# Проверяем, не пустой ли склад
def validate_stock(product_id, quantity, warehouse_db):
v_nalichii = warehouse_db.get(product_id, 0)
return v_nalichii >= quantity
# Добавляем налог региона
def apply_tax(price, region_code):
taxes = {"77": 1.20, "78": 1.15} # Москва и Питер
tax_rate = taxes.get(region_code, 1.10) # Остальные - 10%
return round(price * tax_rate, 2)
# Бьем строку из файла на части
def parse_raw_order(csv_line):
d = csv_line.strip().split(';')
return {
"id": d[0], "product": d[1], "price": float(d[2]),
"qty": int(d[3]), "user_id": d[4], "customer_name": d[5],
"category": d[6], "region": d[7]
}
# Просто фильтр по цене
def filter_by_price(orders_list, min_price):
res = []
for o in orders_list:
if o['price'] >= min_price:
res.append(o)
return res
# Собираем все уникальные категории в кучу
def get_unique_categories(products_list):
cats = []
for p in products_list:
cats.append(p['category'])
return set(cats)
# Считаем сколько юзер накупил за все время
def summarize_user_activity(user_id, all_orders):
u_orders = [o for o in all_orders if o['user_id'] == user_id]
total = sum(o['total_spent'] for o in u_orders)
return {"total_orders": len(u_orders), "total_spent": round(total, 2)}
# Генерим красивый номер дока
def generate_invoice_id(index, region):
return f"2024-{region}-{index:04d}"
# Просто вывод лога с временем
def log_transaction(status, message):
t = datetime.datetime.now().strftime("%H:%M:%S")
return f"[{t}] {status.upper()}: {message}"
def main():
# Типа наша база данных
sklad = {"101": 50, "102": 2, "103": 100, "104": 15}
orders_list = []
# Читаем данные из файла
try:
with open('data.txt', 'r', encoding='utf-8') as f:
lines = f.readlines()
except FileNotFoundError:
print("Ошибка: Файл data.txt не найден!")
return
print(log_transaction("info", "Начинаем обработку..."))
for i, line in enumerate(lines, 1):
if not line.strip(): continue # Пропуск пустых строк
# Парсим строку в словарь
order = parse_raw_order(line)
# Проверяем склад
if validate_stock(order['id'], order['qty'], sklad):
# Считаем деньги
raw_sum = order['price'] * order['qty']
discount = calculate_discount(raw_sum, order['category'])
final_sum = apply_tax(raw_sum - discount, order['region'])
# Дописываем новые данные в словарь
order['invoice'] = generate_invoice_id(i, order['region'])
order['clean_name'] = format_customer_name(order['customer_name'])
order['total_spent'] = final_sum
orders_list.append(order)
print(log_transaction("ok", f"Заказ {order['invoice']} для {order['clean_name']} готов"))
else:
print(log_transaction("error", f"Товара {order['id']} маловато на складе"))
# Выводим финальную стату
print("\n" + "=" * 30)
print("ИТОГОВЫЙ ОТЧЕТ ПО ЮЗЕРАМ:")
print("=" * 30)
unique_users = set(o['user_id'] for o in orders_list)
for u in unique_users:
stats = summarize_user_activity(u, orders_list)
# Находим имя юзера для красоты
name = next(o['clean_name'] for o in orders_list if o['user_id'] == u)
print(f"Клиент: {name:20} | Заказов: {stats['total_orders']} | Итого: {stats['total_spent']} руб.")
# Список всех категорий
all_cats = get_unique_categories(orders_list)
print("\nРаботали с категориями:", ", ".join(all_cats))
if __name__ == "__main__":
main()