Compare commits

...

3 Commits

Author SHA1 Message Date
5b40b4b76c refaktor logging
logging na std i debug do pliku
2025-11-03 09:16:47 +01:00
820db917ce zmieniono print na logging
zmieniono wyjscie cron z pliku na stdout i stderr
2025-11-03 09:05:45 +01:00
85377e9e1a dodalem config dla dodatku ha 2025-11-03 08:48:31 +01:00
8 changed files with 104 additions and 29 deletions

15
config.yaml Normal file
View File

@@ -0,0 +1,15 @@
name: GoogleSheet Bot
version: "1.0.0"
slug: googlesheet_bot
description: Bot do automatyzacji zadań w Arkuszach Google.
arch:
- aarch64
- amd64
- armhf
- armv7
- i386
init: false
startup: application
boot: auto
options: {}
schema: []

View File

@@ -1 +1 @@
0 9,13,16 * * * cd /app && /usr/local/bin/python main.py >> /var/log/cron.log 2>&1
0 9,13,16 * * * cd /app && /usr/local/bin/python main.py

View File

@@ -1,3 +1,4 @@
import logging
import gspread
from google.oauth2.service_account import Credentials
@@ -11,7 +12,7 @@ class GSheetAPI:
"""Inicjalizuje klienta API przy tworzeniu obiektu."""
creds = Credentials.from_service_account_file(credentials_file, scopes=SCOPES)
self.client = gspread.authorize(creds)
print("✅ Połączono z Google Sheets API.")
logging.info("✅ Połączono z Google Sheets API.")
def list_sheets(self, doc_name):
"""Zwraca listę arkuszy w danym dokumencie."""
@@ -32,7 +33,7 @@ class GSheetAPI:
try:
ws = spreadsheet.worksheet(sheet_name)
except gspread.exceptions.WorksheetNotFound:
print(f" Tworzę nowy arkusz: {sheet_name}")
logging.info(f" Tworzę nowy arkusz: {sheet_name}")
ws = spreadsheet.add_worksheet(title=sheet_name, rows=100, cols=10)
ws.append_row(["#", "Link", "Nr zamówienia", "Model", "Wykończenie", "Kolor Top", "Kolor Body", "Kolor Neck", "Kolor Head", "Finish K/C", "Finish S"])
return ws
@@ -43,38 +44,35 @@ class GSheetAPI:
których nr zamówienia (kolumna 3) już istnieje.
"""
if not rows_data:
print(" Brak danych do dodania.")
logging.info(" Brak danych do dodania.")
return
ws = self.ensure_worksheet(doc_name, sheet_name)
# 1. Pobierz wszystkie istniejące numery zamówień w JEDNYM zapytaniu
print("🔍 Sprawdzam istniejące numery zamówień w arkuszu docelowym...")
logging.info("🔍 Sprawdzam istniejące numery zamówień w arkuszu docelowym...")
# existing_orders = set(ws.col_values(3))
existing_orders = {str(x).strip() for x in ws.col_values(3)}
print(f"Znaleziono {len(existing_orders)} istniejących numerów.\n existing_orders: {existing_orders}")
logging.debug(f"Znaleziono {len(existing_orders)} istniejących numerów.\n existing_orders: {existing_orders}")
# 2. Filtruj nowe wiersze, aby znaleźć tylko te unikalne
unique_rows_to_add = []
for row in rows_data:
order_number = str(row[2]).strip()
# print(f"order_number: '{order_number}'", end="")
if order_number not in existing_orders:
# print(f" not in existing_order!", end="")
unique_rows_to_add.append(row)
# Dodaj nowo dodany numer do seta, aby uniknąć duplikatów w ramach jednej paczki
existing_orders.add(order_number)
# print(" ")
# 3. Dodaj wszystkie unikalne wiersze w JEDNYM zapytaniu
if unique_rows_to_add:
print(f"📝 Dodaję {len(unique_rows_to_add)} nowych unikalnych wierszy do arkusza {sheet_name}...")
logging.info(f"📝 Dodaję {len(unique_rows_to_add)} nowych unikalnych wierszy do arkusza {sheet_name}...")
ws.append_rows(unique_rows_to_add, value_input_option="USER_ENTERED") # type: ignore
print("✅ Zakończono dodawanie.")
logging.info("✅ Zakończono dodawanie.")
else:
print(" Nie znaleziono żadnych nowych wierszy do dodania.")
logging.info(" Nie znaleziono żadnych nowych wierszy do dodania.")
skipped_count = len(rows_data) - len(unique_rows_to_add)
if skipped_count > 0:
print(f"⏭️ Pominięto {skipped_count} wierszy, które już istniały w arkuszu.")
logging.info(f"⏭️ Pominięto {skipped_count} wierszy, które już istniały w arkuszu.")

58
logging_config.py Normal file
View File

@@ -0,0 +1,58 @@
import logging
import sys
import os
import datetime
def setup_logging():
"""Konfiguruje zaawansowane logowanie z dwoma handlerami i czyszczeniem starych logów."""
# 1. Pobierz główny logger, wyczyść istniejące handlery i ustaw najniższy poziom (DEBUG)
logger = logging.getLogger()
if logger.hasHandlers():
logger.handlers.clear()
logger.setLevel(logging.DEBUG)
# 2. Utwórz katalog 'logs', jeśli nie istnieje
LOGS_DIR = "logs"
if not os.path.exists(LOGS_DIR):
os.makedirs(LOGS_DIR)
# 3. Stwórz i skonfiguruj handler dla konsoli (poziom INFO)
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(logging.INFO)
console_formatter = logging.Formatter('%(levelname)s - %(message)s')
console_handler.setFormatter(console_formatter)
logger.addHandler(console_handler)
# 4. Stwórz i skonfiguruj handler dla pliku (poziom DEBUG)
log_filename = datetime.datetime.now().strftime("debug_%Y-%m-%d_%H-%M-%S.log")
file_handler = logging.FileHandler(os.path.join(LOGS_DIR, log_filename))
file_handler.setLevel(logging.DEBUG)
file_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
file_handler.setFormatter(file_formatter)
logger.addHandler(file_handler)
def cleanup_old_logs(log_dir="logs", retention_days=7):
"""Usuwa pliki logów starsze niż określona liczba dni."""
logging.info(f"Rozpoczynam czyszczenie starych logów (starszych niż {retention_days} dni)...")
try:
now = datetime.datetime.now()
cutoff = now - datetime.timedelta(days=retention_days)
files_deleted = 0
for filename in os.listdir(log_dir):
file_path = os.path.join(log_dir, filename)
# Upewnij się, że to plik i nie jest to aktualnie otwarty plik logu
if os.path.isfile(file_path) and filename != os.path.basename(file_handler.baseFilename):
file_mod_time = datetime.datetime.fromtimestamp(os.path.getmtime(file_path))
if file_mod_time < cutoff:
os.remove(file_path)
files_deleted += 1
logging.info(f"Usunięto stary plik logu: {filename}")
if files_deleted == 0:
logging.info("Nie znaleziono starych logów do usunięcia.")
except Exception as e:
logging.warning(f"Wystąpił błąd podczas czyszczenia starych logów: {e}")
# 5. Uruchom funkcję czyszczącą
cleanup_old_logs(LOGS_DIR)
logging.info("Logging został skonfigurowany.")

View File

@@ -1,10 +1,12 @@
from gsheet_api import GSheetAPI
from logging_config import setup_logging
from mayo import MayoSession
from config import MAYO_URL, LOGIN, PASSWORD
from workflow import select_sheet, get_sheet_data, save_results
from processing import process_all_rows
def main():
setup_logging()
gsheet_api = GSheetAPI()
sheet_name = select_sheet()

View File

@@ -1,6 +1,7 @@
import requests
from bs4 import BeautifulSoup
import re
import logging
class MayoSession:
def __init__(self, base_url, login, password, db="1"):
@@ -23,7 +24,7 @@ class MayoSession:
r = self.session.post(self.login_url, data=self.credentials)
if "Zaloguj się" in r.text or "login" in r.url:
raise Exception("Nie udało się zalogować do Mayo.")
print("✅ Zalogowano poprawnie do systemu Mayo.")
logging.info("✅ Zalogowano poprawnie do systemu Mayo.")
def get_order_info(self, url):
"""
@@ -62,7 +63,6 @@ class MayoSession:
value = None
# Wartość jest zazwyczaj pomiędzy myślnikiem a ukośnikiem
match = re.search(r'-\s*([^/]+)', text)
# print(f"label: {label}, match: {match}, text: {text}")
if match:
value = match.group(1).strip()
color_sections[label] = value

View File

@@ -1,4 +1,5 @@
import re
import logging
def normalize(text):
if not text:
@@ -63,20 +64,20 @@ def process_row(row, mayo, counter):
if not link:
return None
print(f"\n🔗 Sprawdzam: {link}")
logging.info(f"\n🔗 Sprawdzam: {link}")
try:
info = mayo.get_order_info(link)
order_number = info["order_number"]
model = info["model"]
print(f"Nr z arkusza: {nr_zam}")
print(f"Nr ze strony: {order_number}")
print(f"Model: {model}")
logging.info(f"Nr z arkusza: {nr_zam}")
logging.info(f"Nr ze strony: {order_number}")
logging.info(f"Model: {model}")
if normalize(order_number) == normalize(nr_zam):
print("✅ Numer się zgadza")
logging.info("✅ Numer się zgadza")
else:
print("⚠️ Numer NIE pasuje!")
logging.warning("⚠️ Numer NIE pasuje!")
row_data = [
counter,
@@ -91,11 +92,11 @@ def process_row(row, mayo, counter):
info.get("finish_kc"),
info.get("finish_s"),
]
print(f"raw_data: {row_data}")
logging.debug(f"raw_data: {row_data}")
return row_data
except Exception as e:
print(f"❌ Błąd podczas przetwarzania linku {link}: {e}")
logging.error(f"❌ Błąd podczas przetwarzania linku {link}: {e}")
return None
def process_all_rows(rows, mayo):

View File

@@ -1,27 +1,28 @@
import datetime
import logging
from config import DOC_NAME, RESULT_DOC
def select_sheet():
"""Generates the sheet name based on the current month and year (MM.YYYY)."""
now = datetime.datetime.now()
sheet_name = now.strftime("%m.%Y")
print(f"📄 Automatycznie wybrano arkusz: {sheet_name}")
logging.info(f"📄 Automatycznie wybrano arkusz: {sheet_name}")
return sheet_name
def get_sheet_data(gsheet_api, sheet_name):
"""Fetches all data from a given sheet."""
print(f"📋 Pobieram dane z arkusza: {sheet_name}")
logging.info(f"📋 Pobieram dane z arkusza: {sheet_name}")
try:
return gsheet_api.get_sheet_data(DOC_NAME, sheet_name)
except Exception as e:
print(f"❌ Błąd podczas pobierania danych z arkusza: {e}")
logging.error(f"❌ Błąd podczas pobierania danych z arkusza: {e}")
return None
def save_results(gsheet_api, sheet_name, processed_rows):
"""Saves the processed rows to the spreadsheet."""
if processed_rows:
print(f"\n\n--- Podsumowanie ---")
print(f"Zebrano {len(processed_rows)} wierszy do przetworzenia.")
logging.info(f"\n\n--- Podsumowanie ---")
logging.info(f"Zebrano {len(processed_rows)} wierszy do przetworzenia.")
gsheet_api.batch_append_unique_rows(RESULT_DOC, sheet_name, processed_rows)
else:
print("\nNie zebrano żadnych danych do przetworzenia.")
logging.info("\nNie zebrano żadnych danych do przetworzenia.")