Files
GoogleSheetBot/gsheet_api.py
bartool 820db917ce zmieniono print na logging
zmieniono wyjscie cron z pliku na stdout i stderr
2025-11-03 09:05:45 +01:00

78 lines
3.4 KiB
Python
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 logging
import gspread
from google.oauth2.service_account import Credentials
SCOPES = [
"https://www.googleapis.com/auth/spreadsheets",
"https://www.googleapis.com/auth/drive"
]
class GSheetAPI:
def __init__(self, credentials_file="credentials.json"):
"""Inicjalizuje klienta API przy tworzeniu obiektu."""
creds = Credentials.from_service_account_file(credentials_file, scopes=SCOPES)
self.client = gspread.authorize(creds)
logging.info("✅ Połączono z Google Sheets API.")
def list_sheets(self, doc_name):
"""Zwraca listę arkuszy w danym dokumencie."""
spreadsheet = self.client.open(doc_name)
return [ws.title for ws in spreadsheet.worksheets()]
def get_sheet_data(self, doc_name, sheet_name):
"""Pobiera wszystkie dane z danego arkusza."""
sheet = self.client.open(doc_name).worksheet(sheet_name)
return sheet.get_all_values()
def ensure_worksheet(self, doc_name, sheet_name):
"""
Zwraca worksheet o danej nazwie.
Tworzy nowy, jeśli nie istnieje.
"""
spreadsheet = self.client.open(doc_name)
try:
ws = spreadsheet.worksheet(sheet_name)
except gspread.exceptions.WorksheetNotFound:
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
def batch_append_unique_rows(self, doc_name, sheet_name, rows_data):
"""
Dodaje wiele wierszy za jednym razem, pomijając te,
których nr zamówienia (kolumna 3) już istnieje.
"""
if not rows_data:
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
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)}
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()
if order_number not in existing_orders:
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)
# 3. Dodaj wszystkie unikalne wiersze w JEDNYM zapytaniu
if unique_rows_to_add:
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
logging.info("✅ Zakończono dodawanie.")
else:
logging.info(" Nie znaleziono żadnych nowych wierszy do dodania.")
skipped_count = len(rows_data) - len(unique_rows_to_add)
if skipped_count > 0:
logging.info(f"⏭️ Pominięto {skipped_count} wierszy, które już istniały w arkuszu.")