Files
GoogleSheetBot/gsheet_api.py
2025-10-16 16:42:08 +02:00

80 lines
3.5 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 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)
print("✅ 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:
print(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"])
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:
print(" 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...")
# 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}")
# 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}...")
ws.append_rows(unique_rows_to_add, value_input_option="USER_ENTERED") # type: ignore
print("✅ Zakończono dodawanie.")
else:
print(" 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.")