Compare commits

23 Commits

Author SHA1 Message Date
ccba75097f debug godzin 1 2025-11-03 15:12:31 +01:00
0e1d13dc6e przekierowanie wyjscia na stout i stderr. dodanie ustawiania debugu z konfiguracji dodatku 2025-11-03 15:02:24 +01:00
0419a6b374 test daty co minute 2025-11-03 14:13:18 +01:00
6110c12624 sprawdzenie strefy czasowej w entrypoint 2025-11-03 13:49:48 +01:00
af7d3b92a3 dodany czas do logow 2025-11-03 13:46:17 +01:00
3005992ec7 dodalem konfiguracje godzin do ha 2025-11-03 11:13:40 +01:00
8818b4efc2 konfiguracja dla dodatku home assistant 2025-11-03 09:44:01 +01:00
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
5df9d62614 poprawki do kontenere docker
poprawiona sciezka do pythona
dodane TZ
uzycie nowszego obrazu python
2025-11-03 07:58:16 +01:00
09e5435e95 aktualizacja gitignore wykluczajaca klucz do google 2025-11-03 07:56:42 +01:00
3b28a7c400 dodalem kategerie do pustego arkusza google 2025-11-03 07:56:05 +01:00
57d6b1a607 Update crontab for multiple execution times and add docker-compose configuration for gsheet-bot service 2025-10-29 22:01:36 +01:00
8b5fa414d7 Add cron job setup and entrypoint script for scheduled task execution 2025-10-29 21:48:46 +01:00
0412ca1321 Add Dockerfile for containerized application setup 2025-10-29 21:47:19 +01:00
f5abf68bb6 Refactor select_sheet function to automatically generate sheet names based on the current month and year 2025-10-29 21:46:26 +01:00
3f1fd7e942 Add configuration, processing, and workflow modules for GoogleSheetBot 2025-10-29 21:37:53 +01:00
00739cec56 Refactor save_results function to improve data handling and streamline result summary 2025-10-29 21:33:12 +01:00
7cdd500cb6 Refactor process_all_rows function to streamline row processing and improve readability 2025-10-29 21:32:41 +01:00
2d920f0257 Refactor get_sheet_data function to improve data fetching and error handling 2025-10-29 21:32:04 +01:00
5f00e63f71 Refactor main function to improve sheet selection process and error handling 2025-10-29 21:31:09 +01:00
fd75bc88dc Refactor process_row function to streamline row processing and error handling 2025-10-29 21:30:04 +01:00
14 changed files with 328 additions and 150 deletions

4
.gitignore vendored
View File

@@ -54,4 +54,6 @@ htmlcov/
.coverage.*
.cache
coverage.xml
*.cover
*.cover
credentials.json

17
Dockerfile Normal file
View File

@@ -0,0 +1,17 @@
FROM python:3.9-slim-bookworm
# Install cron
RUN apt-get update && apt-get -y install cron
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
# Upewnij się, że skrypt entrypoint.sh jest wykonywalny
RUN chmod a+x /app/entrypoint.sh
# Uruchom skrypt entrypoint, który zajmie się resztą
CMD ["/app/entrypoint.sh"]

10
config.py Normal file
View File

@@ -0,0 +1,10 @@
import os
from dotenv import load_dotenv
load_dotenv()
DOC_NAME = os.getenv("DOC_NAME")
MAYO_URL = os.getenv("MAYO_URL")
LOGIN = os.getenv("MAYO_LOGIN")
PASSWORD = os.getenv("MAYO_PASSWORD")
RESULT_DOC = "gitary 2025"

21
config.yaml Normal file
View File

@@ -0,0 +1,21 @@
name: GoogleSheet Bot
version: "1.0.1"
slug: googlesheet_bot
description: Bot do automatyzacji zadań w Arkuszach Google.
arch:
- aarch64
- amd64
- armhf
- armv7
- i386
init: false
startup: application
boot: auto
options:
credentials_json: ""
run_hours: "9,13,16"
debug: false
schema:
credentials_json: str
run_hours: str
debug: bool

2
crontab Normal file
View File

@@ -0,0 +1,2 @@
0 9,13,16 * * * cd /app && /usr/local/bin/python main.py >> /proc/1/fd/1 2>/proc/1/fd/2
* * * * * date >> /proc/1/fd/1 2>/proc/1/fd/2

10
docker-compose.yml Normal file
View File

@@ -0,0 +1,10 @@
version: '3.8'
services:
gsheet-bot:
build: .
restart: unless-stopped
volumes:
- ./credentials.json:/app/credentials.json:ro
environment:
- TZ=Europe/Warsaw

39
entrypoint.sh Normal file
View File

@@ -0,0 +1,39 @@
#!/bin/bash
set -e
echo "---------------------------------"
echo "Strefa czasowa kontenera:"
echo "Date: $(date)"
echo "Tryb debugowania: ${CONFIG_DEBUG:-'false'}"
echo "DEBUG: CONFIG_RUN_HOURS='${CONFIG_RUN_HOURS}'"
echo "---------------------------------"
# Odczytaj opcję 'credentials_json' z konfiguracji dodatku i utwórz plik
# Home Assistant udostępnia opcje jako zmienne środowiskowe z prefiksem CONFIG_
echo "${CONFIG_CREDENTIALS_JSON}" > /app/credentials.json
echo "✅ Plik credentials.json został utworzony."
# Odczytaj i oczyść godziny uruchomienia z konfiguracji
RUN_HOURS_CLEAN=$(echo "${CONFIG_RUN_HOURS}" | tr -d '"' | tr -d "'[:space:]")
if [ -z "$RUN_HOURS_CLEAN" ]; then
echo "⚠️ Brak konfiguracji godzin! Używam wartości domyślnej: 9,13,16"
RUN_HOURS_CLEAN="9,13,16"
fi
# Odczytaj godziny uruchomienia z konfiguracji i stwórz zadania crona
echo "Tworzę zadania crona dla godzin: ${RUN_HOURS_CLEAN}"
{
# Główne zadanie aplikacji
echo "0 ${RUN_HOURS_CLEAN} * * * cd /app && /usr/local/bin/python main.py >> /proc/1/fd/1 2>/proc/1/fd/2";
# Zadanie "heartbeat" - co godzinę wypisuje datę do logów
echo "* * * * * date >> /proc/1/fd/1 2>/proc/1/fd/2";
} | crontab -
echo "✅ Zadania crona zostały załadowane (główne zadanie + cogodzinny heartbeat)."
# Uruchom usługę cron na pierwszym planie, aby kontener się nie zamknął
echo "🚀 Uruchamiam usługę cron..."
cron -f

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,9 +33,9 @@ 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"])
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
def batch_append_unique_rows(self, doc_name, sheet_name, rows_data):
@@ -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.")

61
logging_config.py Normal file
View File

@@ -0,0 +1,61 @@
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 lub DEBUG)
debug_mode = os.getenv('CONFIG_DEBUG', 'false').lower() == 'true'
console_level = logging.DEBUG if debug_mode else logging.INFO
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(console_level)
console_formatter = logging.Formatter('%(asctime)s - %(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.")

146
main.py
View File

@@ -1,150 +1,28 @@
from gsheet_api import GSheetAPI
from logging_config import setup_logging
from mayo import MayoSession
from dotenv import load_dotenv
import os
import re
load_dotenv()
# --- konfiguracja ---
DOC_NAME = os.getenv("DOC_NAME")
MAYO_URL = os.getenv("MAYO_URL")
LOGIN = os.getenv("MAYO_LOGIN")
PASSWORD = os.getenv("MAYO_PASSWORD")
RESULT_DOC = "gitary 2025"
def normalize(text):
if not text:
return ""
return re.sub(r"\s+", "", text)
def get_finish_suffix(color):
"""Extracts the finish suffix (e.g., 'G', 'S', 'M') from a color string."""
if not color:
return None
return color.strip().split('-')[-1].upper()
def get_finish_type(row_data):
"""Determines the finish type (GLOSS, SATIN, MAT, MIX) based on color suffixes."""
try:
top_suffix = get_finish_suffix(row_data.get("color_top"))
body_suffix = get_finish_suffix(row_data.get("color_body"))
if not top_suffix and not body_suffix:
return None
# If one suffix is missing, assume it's the same as the other.
top_suffix = top_suffix or body_suffix
body_suffix = body_suffix or top_suffix
suffix_to_category = {
'G': 'gloss',
'S': 'satin',
'M': 'mat',
'R': 'mat',
'MAT': 'mat',
'RAW': 'mat',
}
top_category = suffix_to_category.get(top_suffix)
body_category = suffix_to_category.get(body_suffix)
if not top_category or not body_category:
return None # Suffix not in our map
if top_category == body_category:
return top_category.upper()
if 'mat' in {top_category, body_category}:
return 'MIX'
except (KeyError, AttributeError):
# This will catch if row_data is not a dict or keys are missing
return None
return None
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():
# Inicjalizuj API raz na początku
setup_logging()
gsheet_api = GSheetAPI()
print("📄 Pobieram listę arkuszy...")
try:
sheets = gsheet_api.list_sheets(DOC_NAME)
for i, name in enumerate(sheets):
print(f"{i+1}. {name}")
except Exception as e:
print(f"❌ Błąd podczas pobierania listy arkuszy: {e}")
sheet_name = select_sheet()
if not sheet_name:
return
sheet_name = input("\nWybierz arkusz do przetworzenia: ")
print(f"📋 Pobieram dane z arkusza: {sheet_name}")
try:
rows = gsheet_api.get_sheet_data(DOC_NAME, sheet_name)
except Exception as e:
print(f"❌ Błąd podczas pobierania danych z arkusza: {e}")
rows = get_sheet_data(gsheet_api, sheet_name)
if rows is None:
return
mayo = MayoSession(MAYO_URL, LOGIN, PASSWORD)
mayo.login()
rows_to_process = []
counter = 1
# Zakładamy: kolumna B = link, kolumna C = nr zam.
for row in rows[1:]:
if len(row) < 3:
continue # Pomiń wiersze, które nie mają wystarczającej liczby kolumn
processed_rows = process_all_rows(rows, mayo)
link = row[1]
nr_zam = row[2]
if not link:
continue
print(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}")
if normalize(order_number) == normalize(nr_zam):
print("✅ Numer się zgadza")
else:
print("⚠️ Numer NIE pasuje!")
row_data = [
counter,
link,
nr_zam,
model,
get_finish_type(info),
info.get("color_top"),
info.get("color_body"),
info.get("color_neck"),
info.get("color_head"),
info.get("finish_kc"),
info.get("finish_s"),
]
print(f"raw_data: {row_data}")
rows_to_process.append(row_data)
counter += 1
except Exception as e:
print(f"❌ Błąd podczas przetwarzania linku {link}: {e}")
# Po zakończeniu pętli, dodaj wszystkie zebrane wiersze za jednym razem
if rows_to_process:
print(f"\n\n--- Podsumowanie ---")
print(f"Zebrano {len(rows_to_process)} wierszy do przetworzenia.")
gsheet_api.batch_append_unique_rows(RESULT_DOC, sheet_name, rows_to_process)
else:
print("\nNie zebrano żadnych danych do przetworzenia.")
save_results(gsheet_api, sheet_name, processed_rows)
if __name__ == "__main__":
main()
main()

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

112
processing.py Normal file
View File

@@ -0,0 +1,112 @@
import re
import logging
def normalize(text):
if not text:
return ""
return re.sub(r"\s+", "", text)
def get_finish_suffix(color):
"""Extracts the finish suffix (e.g., 'G', 'S', 'M') from a color string."""
if not color:
return None
return color.strip().split('-')[-1].upper()
def get_finish_type(row_data):
"""Determines the finish type (GLOSS, SATIN, MAT, MIX) based on color suffixes."""
try:
top_suffix = get_finish_suffix(row_data.get("color_top"))
body_suffix = get_finish_suffix(row_data.get("color_body"))
if not top_suffix and not body_suffix:
return None
# If one suffix is missing, assume it's the same as the other.
top_suffix = top_suffix or body_suffix
body_suffix = body_suffix or top_suffix
suffix_to_category = {
'G': 'gloss',
'S': 'satin',
'M': 'mat',
'R': 'mat',
'MAT': 'mat',
'RAW': 'mat',
}
top_category = suffix_to_category.get(top_suffix)
body_category = suffix_to_category.get(body_suffix)
if not top_category or not body_category:
return None # Suffix not in our map
if top_category == body_category:
return top_category.upper()
if 'mat' in {top_category, body_category}:
return 'MIX'
except (KeyError, AttributeError):
# This will catch if row_data is not a dict or keys are missing
return None
return None
def process_row(row, mayo, counter):
"""Processes a single row from the sheet."""
if len(row) < 3:
return None # Skip rows with insufficient columns
link = row[1]
nr_zam = row[2]
if not link:
return None
logging.info(f"\n🔗 Sprawdzam: {link}")
try:
info = mayo.get_order_info(link)
order_number = info["order_number"]
model = info["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):
logging.info("✅ Numer się zgadza")
else:
logging.warning("⚠️ Numer NIE pasuje!")
row_data = [
counter,
link,
nr_zam,
model,
get_finish_type(info),
info.get("color_top"),
info.get("color_body"),
info.get("color_neck"),
info.get("color_head"),
info.get("finish_kc"),
info.get("finish_s"),
]
logging.debug(f"raw_data: {row_data}")
return row_data
except Exception as e:
logging.error(f"❌ Błąd podczas przetwarzania linku {link}: {e}")
return None
def process_all_rows(rows, mayo):
"""Processes all rows from the sheet."""
rows_to_process = []
counter = 1
# Skip header row by starting from index 1
for row in rows[1:]:
processed_row = process_row(row, mayo, counter)
if processed_row:
rows_to_process.append(processed_row)
counter += 1
return rows_to_process

28
workflow.py Normal file
View File

@@ -0,0 +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")
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."""
logging.info(f"📋 Pobieram dane z arkusza: {sheet_name}")
try:
return gsheet_api.get_sheet_data(DOC_NAME, sheet_name)
except Exception as 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:
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:
logging.info("\nNie zebrano żadnych danych do przetworzenia.")