app.bettersight.io/backend/config/client.py

63 lines
2.1 KiB
Python

import os
import json
import gspread
from google.oauth2.service_account import Credentials
# Client-specific Sheet configuration — swapped per client within the
# adventure_travel vertical. Ported unchanged from the legacy app.py.
SHEET_ID = os.getenv('SHEET_ID')
STANDARD_TAB = os.getenv('STANDARD_TAB', 'Standard Competitive Tab')
NGS_TAB = os.getenv('NGS_TAB', 'NGS Competitive Tab')
SERVICE_ACCOUNT_JSON = os.getenv('GOOGLE_SERVICE_ACCOUNT_JSON')
def get_sheet_client():
"""Authorizes a gspread client against the Google service account credentials."""
scopes = [
'https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive',
]
info = json.loads(SERVICE_ACCOUNT_JSON)
creds = Credentials.from_service_account_info(info, scopes=scopes)
return gspread.authorize(creds)
def write_to_sheet(tab_name, col_index, data, fields):
"""
Writes one competitor's extracted fields into a single column of
the client Sheet, using the field→row map for this tab type
(STANDARD_FIELDS or NGS_FIELDS).
Data flow:
tab_name + col_index + extracted data dict + field row map →
batch_update() with one cell write per non-empty field →
Sheet updated in a single API call
"""
client = get_sheet_client()
sheet = client.open_by_key(SHEET_ID)
ws = sheet.worksheet(tab_name)
updates = []
for field, row in fields.items():
value = data.get(field)
if value is None or value == '':
continue
updates.append({
'range': gspread.utils.rowcol_to_a1(row, col_index),
'values': [[value]],
})
if updates:
ws.batch_update(updates)
def get_competitors_from_db():
"""Reads the client's 'Competitor DB' tab and returns only the active rows."""
client = get_sheet_client()
sheet = client.open_by_key(SHEET_ID)
ws = sheet.worksheet('Competitor DB')
rows = ws.get_all_records()
return [
{'style': r['Travel Style'], 'name': r['Competitor Name'], 'url': r['Website URL'], 'active': r['Active']}
for r in rows
if str(r.get('Active', '')).strip().lower() == 'yes'
]