60 lines
1.7 KiB
Python
60 lines
1.7 KiB
Python
import gspread
|
||
from google.oauth2.service_account import Credentials
|
||
|
||
SCOPES = [
|
||
"https://www.googleapis.com/auth/spreadsheets",
|
||
"https://www.googleapis.com/auth/drive"
|
||
]
|
||
|
||
def connect():
|
||
creds = Credentials.from_service_account_file("credentials.json", scopes=SCOPES)
|
||
client = gspread.authorize(creds)
|
||
return client
|
||
|
||
|
||
def list_sheets(doc_name):
|
||
client = connect()
|
||
spreadsheet = client.open(doc_name)
|
||
return [ws.title for ws in spreadsheet.worksheets()]
|
||
|
||
|
||
def get_sheet_data(doc_name, sheet_name):
|
||
client = connect()
|
||
sheet = client.open(doc_name).worksheet(sheet_name)
|
||
return sheet.get_all_values()
|
||
|
||
|
||
def ensure_worksheet(doc_name, sheet_name):
|
||
"""
|
||
Zwraca worksheet o danej nazwie.
|
||
Tworzy nowy, jeśli nie istnieje.
|
||
"""
|
||
client = connect()
|
||
spreadsheet = 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"])
|
||
return ws
|
||
|
||
|
||
def append_unique_row(doc_name, sheet_name, row_data):
|
||
"""
|
||
Dodaje wiersz tylko, jeśli dany nr zamówienia (kolumna 3) jeszcze nie istnieje.
|
||
"""
|
||
client = connect()
|
||
ws = ensure_worksheet(doc_name, sheet_name)
|
||
|
||
existing = ws.col_values(3) # kolumna "Nr zamówienia"
|
||
order_number = str(row_data[2]).strip()
|
||
|
||
if order_number in existing:
|
||
print(f"⏭️ Pomijam – nr {order_number} już istnieje w arkuszu {sheet_name}")
|
||
return False
|
||
|
||
ws.append_row(row_data, value_input_option="USER_ENTERED")
|
||
print(f"📝 Dodano do {sheet_name}: {row_data}")
|
||
return True
|