diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1561a5f --- /dev/null +++ b/.gitignore @@ -0,0 +1,26 @@ +# Виртуальное окружение +.venv/ +venv/ +env/ + +# Кэш Python +__pycache__/ +*.pyc +*.pyo + +# Отчёты (генерируются программой) +reports/ +*.txt + +# IDE +.idea/ +.vscode/ +*.swp + +# Системные файлы +.DS_Store +Thumbs.db +desktop.ini + +# Бэкапы +*.backup diff --git a/.idea/InventoryManager.iml b/.idea/InventoryManager.iml deleted file mode 100644 index 3d53442..0000000 --- a/.idea/InventoryManager.iml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/.idea/inspectionProfiles/profiles_settings.xml b/.idea/inspectionProfiles/profiles_settings.xml deleted file mode 100644 index 105ce2d..0000000 --- a/.idea/inspectionProfiles/profiles_settings.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml deleted file mode 100644 index 7a68218..0000000 --- a/.idea/misc.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml deleted file mode 100644 index 5ca585a..0000000 --- a/.idea/modules.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml deleted file mode 100644 index 94a25f7..0000000 --- a/.idea/vcs.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/.idea/workspace.xml b/.idea/workspace.xml deleted file mode 100644 index 94d17da..0000000 --- a/.idea/workspace.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - - - - - - - - - - - - - 1775248363717 - - - - \ No newline at end of file diff --git a/reports/inventory_report.txt b/reports/inventory_report.txt deleted file mode 100644 index e048a8f..0000000 --- a/reports/inventory_report.txt +++ /dev/null @@ -1,15 +0,0 @@ -ИНВЕНТАРИЗАЦИОННЫЙ ОТЧЁТ -================================================== - -Общее количество товаров: 8 -Общая стоимость склада: 2,750,000.00 руб. - -Топ-3 категории по количеству товаров: - 1. Электроника: 4 товаров - 2. Мебель: 2 товаров - 3. Канцелярия: 2 товаров - -Товары с остатком менее 10 единиц: - - Стул офисный Ergohuman: 8 шт. - - Клавиатура Mechanical: 0 шт. - - Стол письменный: 5 шт. diff --git a/inventory_manager.py b/src/main.py similarity index 73% rename from inventory_manager.py rename to src/main.py index b9e51db..9a3f376 100644 --- a/inventory_manager.py +++ b/src/main.py @@ -1,8 +1,3 @@ -""" -Модуль управления складскими запасами интернет-магазина -Содержит функции для работы с товарами, фильтрации, анализа и отчётности -""" - import csv import os from typing import List, Dict, Optional @@ -10,15 +5,6 @@ from collections import Counter def load_products(filepath: str) -> List[Dict]: - """ - Загружает данные о товарах из CSV-файла. - - Args: - filepath: Путь к CSV-файлу - - Returns: - Список словарей с данными о товарах. При отсутствии файла возвращает пустой список - """ products = [] try: @@ -45,15 +31,6 @@ def load_products(filepath: str) -> List[Dict]: def validate_product(product: Dict) -> bool: - """ - Проверяет корректность данных товара. - - Args: - product: Словарь с данными товара - - Returns: - True, если все поля присутствуют и корректны, иначе False - """ required_fields = ['product_id', 'name', 'category', 'quantity', 'price', 'supplier'] for field in required_fields: @@ -85,73 +62,25 @@ def validate_product(product: Dict) -> bool: def filter_by_category(products: List[Dict], category: str) -> List[Dict]: - """ - Фильтрует товары по категории (регистронезависимо). - - Args: - products: Список товаров - category: Название категории для фильтрации - - Returns: - Новый список товаров указанной категории - """ return [product for product in products if product['category'].lower() == category.lower()] def filter_by_quantity(products: List[Dict], min_quantity: int) -> List[Dict]: - """ - Фильтрует товары с остатком не ниже заданного. - - Args: - products: Список товаров - min_quantity: Минимальное количество - - Returns: - Отфильтрованный список товаров - """ return [product for product in products if product['quantity'] >= min_quantity] def calculate_total_value(products: List[Dict]) -> float: - """ - Вычисляет общую стоимость всех товаров на складе. - - Args: - products: Список товаров - - Returns: - Сумма произведений quantity * price для каждого товара - """ return sum(product['quantity'] * product['price'] for product in products) def find_low_stock(products: List[Dict], threshold: int) -> List[Dict]: - """ - Находит товары с критически низким остатком. - - Args: - products: Список товаров - threshold: Пороговое значение - - Returns: - Список товаров с quantity <= threshold, отсортированный по возрастанию остатка - """ low_stock = [product for product in products if product['quantity'] <= threshold] return sorted(low_stock, key=lambda x: x['quantity']) def group_by_supplier(products: List[Dict]) -> Dict[str, Dict]: - """ - Группирует товары по поставщикам. - - Args: - products: Список товаров - - Returns: - Словарь, где ключ — поставщик, значение — словарь со статистикой - """ suppliers = {} for product in products: @@ -169,15 +98,6 @@ def group_by_supplier(products: List[Dict]) -> Dict[str, Dict]: def get_most_expensive_product(products: List[Dict]) -> Optional[Dict]: - """ - Находит самый дорогой товар. - - Args: - products: Список товаров - - Returns: - Словарь товара с максимальной ценой, при пустом списке возвращает None - """ if not products: return None @@ -185,32 +105,12 @@ def get_most_expensive_product(products: List[Dict]) -> Optional[Dict]: def search_by_name(products: List[Dict], keyword: str) -> List[Dict]: - """ - Ищет товары по ключевому слову в названии (регистронезависимо). - - Args: - products: Список товаров - keyword: Ключевое слово для поиска - - Returns: - Список товаров, содержащих ключевое слово в названии - """ keyword_lower = keyword.lower() return [product for product in products if keyword_lower in product['name'].lower()] def save_inventory_report(products: List[Dict], filepath: str) -> bool: - """ - Сохраняет инвентаризационный отчёт в текстовый файл. - - Args: - products: Список товаров - filepath: Путь для сохранения отчёта - - Returns: - True при успешной записи, False при ошибке - """ try: os.makedirs(os.path.dirname(filepath), exist_ok=True) @@ -245,9 +145,6 @@ def save_inventory_report(products: List[Dict], filepath: str) -> bool: def create_products_csv(): - """ - Создаёт файл data/products.csv с тестовыми данными - """ os.makedirs('data', exist_ok=True) data = [ @@ -270,9 +167,6 @@ def create_products_csv(): def main(): - """ - Главная функция программы, выполняющая все шаги по анализу складских запасов. - """ print("=" * 60) print("УПРАВЛЕНИЕ СКЛАДСКИМИ ЗАПАСАМИ ИНТЕРНЕТ-МАГАЗИНА") print("=" * 60)