Spaces:
Running
Running
axeronis commited on
Commit ·
5787b31
1
Parent(s): 0a36827
fix: remove google_sheets files causing ImportError
Browse files- backend/app/api/google_sheets.py +0 -321
- backend/app/main.py +1 -1
- backend/app/services/google_sheets_service.py +0 -228
backend/app/api/google_sheets.py
DELETED
|
@@ -1,321 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Google Sheets Integration API endpoints.
|
| 3 |
-
Allows tenants to connect their Google Sheets for real-time inventory sync.
|
| 4 |
-
"""
|
| 5 |
-
|
| 6 |
-
from fastapi import APIRouter, Depends, HTTPException
|
| 7 |
-
from sqlalchemy.ext.asyncio import AsyncSession
|
| 8 |
-
from pydantic import BaseModel
|
| 9 |
-
from typing import Optional, Dict, List, Any
|
| 10 |
-
from datetime import datetime
|
| 11 |
-
from uuid import UUID
|
| 12 |
-
|
| 13 |
-
from app.core.database import get_session
|
| 14 |
-
from app.core.security import get_current_user
|
| 15 |
-
from app.models.user import User
|
| 16 |
-
from app.models.tenant import Tenant
|
| 17 |
-
from app.models.product import Product
|
| 18 |
-
from app.services.google_sheets_service import get_google_sheets_service
|
| 19 |
-
from app.core.logging import get_logger
|
| 20 |
-
from sqlmodel import select
|
| 21 |
-
|
| 22 |
-
logger = get_logger(__name__)
|
| 23 |
-
router = APIRouter(prefix="/integrations/google-sheets", tags=["Google Sheets"])
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
class GoogleSheetsConnectRequest(BaseModel):
|
| 27 |
-
"""Request to connect a Google Sheet."""
|
| 28 |
-
sheet_url: str
|
| 29 |
-
sheet_name: str = "Sheet1"
|
| 30 |
-
mapping: Dict[str, str] # {"name": "A", "price": "B", "quantity": "C"}
|
| 31 |
-
sync_enabled: bool = True
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
class GoogleSheetsPreviewRequest(BaseModel):
|
| 35 |
-
"""Request to preview sheet data."""
|
| 36 |
-
sheet_url: str
|
| 37 |
-
sheet_name: str = "Sheet1"
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
class GoogleSheetsPreviewResponse(BaseModel):
|
| 41 |
-
"""Preview of sheet data."""
|
| 42 |
-
headers: List[str]
|
| 43 |
-
rows: List[List[str]]
|
| 44 |
-
total_rows: int
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
@router.post("/preview")
|
| 48 |
-
async def preview_sheet(
|
| 49 |
-
request: GoogleSheetsPreviewRequest,
|
| 50 |
-
current_user: User = Depends(get_current_user),
|
| 51 |
-
session: AsyncSession = Depends(get_session)
|
| 52 |
-
):
|
| 53 |
-
"""
|
| 54 |
-
Preview Google Sheet data to help with column mapping.
|
| 55 |
-
Returns first 10 rows.
|
| 56 |
-
"""
|
| 57 |
-
service = get_google_sheets_service()
|
| 58 |
-
|
| 59 |
-
# Validate sheet ID
|
| 60 |
-
sheet_id = service.extract_sheet_id(request.sheet_url)
|
| 61 |
-
if not sheet_id:
|
| 62 |
-
raise HTTPException(status_code=400, detail="Invalid Google Sheet URL")
|
| 63 |
-
|
| 64 |
-
# Fetch data
|
| 65 |
-
rows = await service.fetch_sheet_data(request.sheet_url, request.sheet_name)
|
| 66 |
-
|
| 67 |
-
if rows is None:
|
| 68 |
-
raise HTTPException(
|
| 69 |
-
status_code=400,
|
| 70 |
-
detail="Could not fetch sheet. Make sure it's public (Anyone with link can view)"
|
| 71 |
-
)
|
| 72 |
-
|
| 73 |
-
if len(rows) < 2:
|
| 74 |
-
raise HTTPException(status_code=400, detail="Sheet is empty or has no data rows")
|
| 75 |
-
|
| 76 |
-
return {
|
| 77 |
-
"ok": True,
|
| 78 |
-
"headers": rows[0],
|
| 79 |
-
"rows": rows[1:11], # First 10 data rows
|
| 80 |
-
"total_rows": len(rows) - 1
|
| 81 |
-
}
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
@router.post("/connect")
|
| 85 |
-
async def connect_sheet(
|
| 86 |
-
request: GoogleSheetsConnectRequest,
|
| 87 |
-
current_user: User = Depends(get_current_user),
|
| 88 |
-
session: AsyncSession = Depends(get_session)
|
| 89 |
-
):
|
| 90 |
-
"""
|
| 91 |
-
Connect a Google Sheet for inventory sync.
|
| 92 |
-
"""
|
| 93 |
-
tenant_id = current_user.tenant_id
|
| 94 |
-
if not tenant_id:
|
| 95 |
-
raise HTTPException(status_code=400, detail="User has no tenant")
|
| 96 |
-
|
| 97 |
-
# Validate sheet
|
| 98 |
-
service = get_google_sheets_service()
|
| 99 |
-
sheet_id = service.extract_sheet_id(request.sheet_url)
|
| 100 |
-
if not sheet_id:
|
| 101 |
-
raise HTTPException(status_code=400, detail="Invalid Google Sheet URL")
|
| 102 |
-
|
| 103 |
-
# Test fetch
|
| 104 |
-
rows = await service.fetch_sheet_data(request.sheet_url, request.sheet_name)
|
| 105 |
-
if rows is None:
|
| 106 |
-
raise HTTPException(
|
| 107 |
-
status_code=400,
|
| 108 |
-
detail="Could not fetch sheet. Make sure it's public"
|
| 109 |
-
)
|
| 110 |
-
|
| 111 |
-
# Validate mapping
|
| 112 |
-
required_fields = ['name']
|
| 113 |
-
for field in required_fields:
|
| 114 |
-
if field not in request.mapping:
|
| 115 |
-
raise HTTPException(status_code=400, detail=f"Missing required mapping: {field}")
|
| 116 |
-
|
| 117 |
-
# Save config
|
| 118 |
-
tenant = await session.get(Tenant, tenant_id)
|
| 119 |
-
if not tenant:
|
| 120 |
-
raise HTTPException(status_code=404, detail="Tenant not found")
|
| 121 |
-
|
| 122 |
-
tenant.google_sheets_config = {
|
| 123 |
-
"url": request.sheet_url,
|
| 124 |
-
"sheet_name": request.sheet_name,
|
| 125 |
-
"mapping": request.mapping,
|
| 126 |
-
"sync_enabled": request.sync_enabled,
|
| 127 |
-
"last_sync": None
|
| 128 |
-
}
|
| 129 |
-
|
| 130 |
-
session.add(tenant)
|
| 131 |
-
await session.commit()
|
| 132 |
-
|
| 133 |
-
logger.info(f"✅ Google Sheets connected for tenant {tenant_id}")
|
| 134 |
-
|
| 135 |
-
# Do initial sync
|
| 136 |
-
sync_result = await sync_inventory(tenant, session, service)
|
| 137 |
-
|
| 138 |
-
return {
|
| 139 |
-
"ok": True,
|
| 140 |
-
"message": "Google Sheet connected successfully",
|
| 141 |
-
"synced_products": sync_result.get("synced", 0)
|
| 142 |
-
}
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
@router.post("/sync")
|
| 146 |
-
async def trigger_sync(
|
| 147 |
-
current_user: User = Depends(get_current_user),
|
| 148 |
-
session: AsyncSession = Depends(get_session)
|
| 149 |
-
):
|
| 150 |
-
"""
|
| 151 |
-
Manually trigger inventory sync from Google Sheet.
|
| 152 |
-
"""
|
| 153 |
-
tenant_id = current_user.tenant_id
|
| 154 |
-
if not tenant_id:
|
| 155 |
-
raise HTTPException(status_code=400, detail="User has no tenant")
|
| 156 |
-
|
| 157 |
-
tenant = await session.get(Tenant, tenant_id)
|
| 158 |
-
if not tenant:
|
| 159 |
-
raise HTTPException(status_code=404, detail="Tenant not found")
|
| 160 |
-
|
| 161 |
-
if not tenant.google_sheets_config:
|
| 162 |
-
raise HTTPException(status_code=400, detail="No Google Sheet connected")
|
| 163 |
-
|
| 164 |
-
service = get_google_sheets_service()
|
| 165 |
-
result = await sync_inventory(tenant, session, service)
|
| 166 |
-
|
| 167 |
-
return {
|
| 168 |
-
"ok": True,
|
| 169 |
-
"message": "Sync completed",
|
| 170 |
-
**result
|
| 171 |
-
}
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
@router.get("/status")
|
| 175 |
-
async def get_status(
|
| 176 |
-
current_user: User = Depends(get_current_user),
|
| 177 |
-
session: AsyncSession = Depends(get_session)
|
| 178 |
-
):
|
| 179 |
-
"""
|
| 180 |
-
Get Google Sheets integration status.
|
| 181 |
-
"""
|
| 182 |
-
tenant_id = current_user.tenant_id
|
| 183 |
-
if not tenant_id:
|
| 184 |
-
raise HTTPException(status_code=400, detail="User has no tenant")
|
| 185 |
-
|
| 186 |
-
tenant = await session.get(Tenant, tenant_id)
|
| 187 |
-
if not tenant:
|
| 188 |
-
raise HTTPException(status_code=404, detail="Tenant not found")
|
| 189 |
-
|
| 190 |
-
config = tenant.google_sheets_config
|
| 191 |
-
|
| 192 |
-
if not config:
|
| 193 |
-
return {
|
| 194 |
-
"connected": False,
|
| 195 |
-
"sheet_url": None,
|
| 196 |
-
"sync_enabled": False,
|
| 197 |
-
"last_sync": None
|
| 198 |
-
}
|
| 199 |
-
|
| 200 |
-
return {
|
| 201 |
-
"connected": True,
|
| 202 |
-
"sheet_url": config.get("url"),
|
| 203 |
-
"sheet_name": config.get("sheet_name", "Sheet1"),
|
| 204 |
-
"mapping": config.get("mapping", {}),
|
| 205 |
-
"sync_enabled": config.get("sync_enabled", False),
|
| 206 |
-
"last_sync": config.get("last_sync")
|
| 207 |
-
}
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
@router.delete("/disconnect")
|
| 211 |
-
async def disconnect_sheet(
|
| 212 |
-
current_user: User = Depends(get_current_user),
|
| 213 |
-
session: AsyncSession = Depends(get_session)
|
| 214 |
-
):
|
| 215 |
-
"""
|
| 216 |
-
Disconnect Google Sheet integration.
|
| 217 |
-
"""
|
| 218 |
-
tenant_id = current_user.tenant_id
|
| 219 |
-
if not tenant_id:
|
| 220 |
-
raise HTTPException(status_code=400, detail="User has no tenant")
|
| 221 |
-
|
| 222 |
-
tenant = await session.get(Tenant, tenant_id)
|
| 223 |
-
if not tenant:
|
| 224 |
-
raise HTTPException(status_code=404, detail="Tenant not found")
|
| 225 |
-
|
| 226 |
-
tenant.google_sheets_config = None
|
| 227 |
-
session.add(tenant)
|
| 228 |
-
await session.commit()
|
| 229 |
-
|
| 230 |
-
logger.info(f"🔌 Google Sheets disconnected for tenant {tenant_id}")
|
| 231 |
-
|
| 232 |
-
return {"ok": True, "message": "Google Sheet disconnected"}
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
async def sync_inventory(
|
| 236 |
-
tenant: Tenant,
|
| 237 |
-
session: AsyncSession,
|
| 238 |
-
service = None
|
| 239 |
-
) -> Dict[str, Any]:
|
| 240 |
-
"""
|
| 241 |
-
Sync inventory data from Google Sheet to products.
|
| 242 |
-
|
| 243 |
-
Updates stock_quantity and in_stock for matching products.
|
| 244 |
-
"""
|
| 245 |
-
if service is None:
|
| 246 |
-
service = get_google_sheets_service()
|
| 247 |
-
|
| 248 |
-
config = tenant.google_sheets_config
|
| 249 |
-
if not config:
|
| 250 |
-
return {"error": "No config", "synced": 0}
|
| 251 |
-
|
| 252 |
-
sheet_url = config.get("url")
|
| 253 |
-
sheet_name = config.get("sheet_name", "Sheet1")
|
| 254 |
-
mapping = config.get("mapping", {})
|
| 255 |
-
|
| 256 |
-
# Fetch and parse sheet data
|
| 257 |
-
products_data = await service.sync_products_from_sheet(sheet_url, mapping, sheet_name)
|
| 258 |
-
|
| 259 |
-
if products_data is None:
|
| 260 |
-
return {"error": "Could not fetch sheet", "synced": 0}
|
| 261 |
-
|
| 262 |
-
# Get existing products for this tenant
|
| 263 |
-
result = await session.execute(
|
| 264 |
-
select(Product).where(Product.tenant_id == tenant.id, Product.is_active == True)
|
| 265 |
-
)
|
| 266 |
-
existing_products = {p.name.lower(): p for p in result.scalars().all()}
|
| 267 |
-
|
| 268 |
-
synced = 0
|
| 269 |
-
created = 0
|
| 270 |
-
|
| 271 |
-
for item in products_data:
|
| 272 |
-
name = item.get("name", "").strip()
|
| 273 |
-
if not name:
|
| 274 |
-
continue
|
| 275 |
-
|
| 276 |
-
name_lower = name.lower()
|
| 277 |
-
quantity = item.get("quantity", item.get("stock", None))
|
| 278 |
-
price = item.get("price", 0)
|
| 279 |
-
|
| 280 |
-
if name_lower in existing_products:
|
| 281 |
-
# Update existing product
|
| 282 |
-
product = existing_products[name_lower]
|
| 283 |
-
|
| 284 |
-
# Update stock quantity
|
| 285 |
-
if quantity is not None:
|
| 286 |
-
product.stock_quantity = int(quantity) if quantity else 0
|
| 287 |
-
product.in_stock = product.stock_quantity > 0
|
| 288 |
-
|
| 289 |
-
# Update price if provided and different
|
| 290 |
-
if price and price != product.price:
|
| 291 |
-
product.price = float(price)
|
| 292 |
-
|
| 293 |
-
session.add(product)
|
| 294 |
-
synced += 1
|
| 295 |
-
else:
|
| 296 |
-
# Create new product from sheet
|
| 297 |
-
new_product = Product(
|
| 298 |
-
tenant_id=tenant.id,
|
| 299 |
-
name=name,
|
| 300 |
-
price=float(price) if price else 0,
|
| 301 |
-
stock_quantity=int(quantity) if quantity is not None else None,
|
| 302 |
-
in_stock=int(quantity) > 0 if quantity is not None else True,
|
| 303 |
-
category=item.get("category", "From Google Sheets")
|
| 304 |
-
)
|
| 305 |
-
session.add(new_product)
|
| 306 |
-
created += 1
|
| 307 |
-
|
| 308 |
-
# Update last sync time
|
| 309 |
-
config["last_sync"] = datetime.utcnow().isoformat()
|
| 310 |
-
tenant.google_sheets_config = config
|
| 311 |
-
session.add(tenant)
|
| 312 |
-
|
| 313 |
-
await session.commit()
|
| 314 |
-
|
| 315 |
-
logger.info(f"📦 Synced {synced} products, created {created} new for tenant {tenant.id}")
|
| 316 |
-
|
| 317 |
-
return {
|
| 318 |
-
"synced": synced,
|
| 319 |
-
"created": created,
|
| 320 |
-
"total_in_sheet": len(products_data)
|
| 321 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/app/main.py
CHANGED
|
@@ -7,7 +7,7 @@ from app.core.config import settings
|
|
| 7 |
from app.core.database import init_pgvector
|
| 8 |
from app.core.logging import configure_logging, get_logger
|
| 9 |
from app.middleware.request_id import RequestIDMiddleware
|
| 10 |
-
from app.api import webhook, leads, knowledge, channels, auth, tenants, analytics, chats, playbook, billing, ai_training, crm, admin, team, telegram_webhook, partners, notifications, products, bookings, jobs, system, meta_webhooks, voice, google_calendar, websocket_voice, websocket_chat, oauth, landing, site_settings
|
| 11 |
|
| 12 |
# ... (omitted lines)
|
| 13 |
|
|
|
|
| 7 |
from app.core.database import init_pgvector
|
| 8 |
from app.core.logging import configure_logging, get_logger
|
| 9 |
from app.middleware.request_id import RequestIDMiddleware
|
| 10 |
+
from app.api import webhook, leads, knowledge, channels, auth, tenants, analytics, chats, playbook, billing, ai_training, crm, admin, team, telegram_webhook, partners, notifications, products, bookings, jobs, system, meta_webhooks, voice, google_calendar, websocket_voice, websocket_chat, oauth, landing, site_settings
|
| 11 |
|
| 12 |
# ... (omitted lines)
|
| 13 |
|
backend/app/services/google_sheets_service.py
DELETED
|
@@ -1,228 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Google Sheets Service for reading public spreadsheets.
|
| 3 |
-
No OAuth required - works with publicly shared sheets.
|
| 4 |
-
"""
|
| 5 |
-
|
| 6 |
-
import httpx
|
| 7 |
-
import re
|
| 8 |
-
from typing import Optional, Dict, List, Any
|
| 9 |
-
from app.core.logging import get_logger
|
| 10 |
-
|
| 11 |
-
logger = get_logger(__name__)
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
class GoogleSheetsService:
|
| 15 |
-
"""
|
| 16 |
-
Service to read data from public Google Sheets.
|
| 17 |
-
Uses the Sheets JSON export API (no auth required for public sheets).
|
| 18 |
-
"""
|
| 19 |
-
|
| 20 |
-
def __init__(self):
|
| 21 |
-
self.base_url = "https://docs.google.com/spreadsheets/d"
|
| 22 |
-
|
| 23 |
-
def extract_sheet_id(self, url_or_id: str) -> Optional[str]:
|
| 24 |
-
"""
|
| 25 |
-
Extract spreadsheet ID from URL or return as-is if already an ID.
|
| 26 |
-
|
| 27 |
-
Supports formats:
|
| 28 |
-
- https://docs.google.com/spreadsheets/d/SHEET_ID/edit#gid=0
|
| 29 |
-
- https://docs.google.com/spreadsheets/d/SHEET_ID/
|
| 30 |
-
- SHEET_ID (raw ID)
|
| 31 |
-
"""
|
| 32 |
-
if not url_or_id:
|
| 33 |
-
return None
|
| 34 |
-
|
| 35 |
-
# If it's already just an ID (no slashes)
|
| 36 |
-
if "/" not in url_or_id and len(url_or_id) > 20:
|
| 37 |
-
return url_or_id
|
| 38 |
-
|
| 39 |
-
# Extract from URL
|
| 40 |
-
match = re.search(r'/spreadsheets/d/([a-zA-Z0-9-_]+)', url_or_id)
|
| 41 |
-
if match:
|
| 42 |
-
return match.group(1)
|
| 43 |
-
|
| 44 |
-
return None
|
| 45 |
-
|
| 46 |
-
async def fetch_sheet_data(
|
| 47 |
-
self,
|
| 48 |
-
sheet_url: str,
|
| 49 |
-
sheet_name: str = "Sheet1"
|
| 50 |
-
) -> Optional[List[List[str]]]:
|
| 51 |
-
"""
|
| 52 |
-
Fetch data from a public Google Sheet.
|
| 53 |
-
|
| 54 |
-
Args:
|
| 55 |
-
sheet_url: Google Sheet URL or ID
|
| 56 |
-
sheet_name: Name of the sheet tab (default: Sheet1)
|
| 57 |
-
|
| 58 |
-
Returns:
|
| 59 |
-
List of rows, where each row is a list of cell values
|
| 60 |
-
"""
|
| 61 |
-
sheet_id = self.extract_sheet_id(sheet_url)
|
| 62 |
-
if not sheet_id:
|
| 63 |
-
logger.error(f"❌ Invalid Google Sheet URL: {sheet_url}")
|
| 64 |
-
return None
|
| 65 |
-
|
| 66 |
-
# Use the JSON export endpoint
|
| 67 |
-
# Format: /spreadsheets/d/{id}/gviz/tq?tqx=out:json&sheet={sheetName}
|
| 68 |
-
export_url = f"{self.base_url}/{sheet_id}/gviz/tq?tqx=out:json&sheet={sheet_name}"
|
| 69 |
-
|
| 70 |
-
try:
|
| 71 |
-
async with httpx.AsyncClient(timeout=30.0) as client:
|
| 72 |
-
response = await client.get(export_url)
|
| 73 |
-
|
| 74 |
-
if response.status_code == 404:
|
| 75 |
-
logger.error(f"❌ Sheet not found or not public: {sheet_id}")
|
| 76 |
-
return None
|
| 77 |
-
|
| 78 |
-
response.raise_for_status()
|
| 79 |
-
|
| 80 |
-
# Response is JSONP, extract the JSON part
|
| 81 |
-
# Format: /*O_o*/\ngoogle.visualization.Query.setResponse({...});
|
| 82 |
-
text = response.text
|
| 83 |
-
|
| 84 |
-
# Extract JSON from JSONP wrapper
|
| 85 |
-
json_start = text.find('(')
|
| 86 |
-
json_end = text.rfind(')')
|
| 87 |
-
|
| 88 |
-
if json_start == -1 or json_end == -1:
|
| 89 |
-
logger.error(f"❌ Invalid response format from Google Sheets")
|
| 90 |
-
return None
|
| 91 |
-
|
| 92 |
-
import json
|
| 93 |
-
data = json.loads(text[json_start + 1:json_end])
|
| 94 |
-
|
| 95 |
-
if data.get('status') == 'error':
|
| 96 |
-
errors = data.get('errors', [])
|
| 97 |
-
logger.error(f"❌ Google Sheets error: {errors}")
|
| 98 |
-
return None
|
| 99 |
-
|
| 100 |
-
# Parse the table data
|
| 101 |
-
table = data.get('table', {})
|
| 102 |
-
rows = table.get('rows', [])
|
| 103 |
-
cols = table.get('cols', [])
|
| 104 |
-
|
| 105 |
-
# Extract column headers
|
| 106 |
-
headers = [col.get('label', f'Col{i}') for i, col in enumerate(cols)]
|
| 107 |
-
|
| 108 |
-
# Extract row data
|
| 109 |
-
result = [headers] # First row is headers
|
| 110 |
-
for row in rows:
|
| 111 |
-
cells = row.get('c', [])
|
| 112 |
-
row_data = []
|
| 113 |
-
for cell in cells:
|
| 114 |
-
if cell is None:
|
| 115 |
-
row_data.append('')
|
| 116 |
-
else:
|
| 117 |
-
# Get the value, prefer formatted value for display
|
| 118 |
-
val = cell.get('f') or cell.get('v') or ''
|
| 119 |
-
row_data.append(str(val) if val else '')
|
| 120 |
-
result.append(row_data)
|
| 121 |
-
|
| 122 |
-
logger.info(f"✅ Fetched {len(result)} rows from Google Sheet")
|
| 123 |
-
return result
|
| 124 |
-
|
| 125 |
-
except httpx.TimeoutException:
|
| 126 |
-
logger.error(f"❌ Timeout fetching Google Sheet: {sheet_id}")
|
| 127 |
-
return None
|
| 128 |
-
except Exception as e:
|
| 129 |
-
logger.error(f"❌ Error fetching Google Sheet: {e}")
|
| 130 |
-
return None
|
| 131 |
-
|
| 132 |
-
def parse_with_mapping(
|
| 133 |
-
self,
|
| 134 |
-
rows: List[List[str]],
|
| 135 |
-
mapping: Dict[str, str]
|
| 136 |
-
) -> List[Dict[str, Any]]:
|
| 137 |
-
"""
|
| 138 |
-
Parse sheet data using column mapping.
|
| 139 |
-
|
| 140 |
-
Args:
|
| 141 |
-
rows: Raw rows from sheet (first row = headers)
|
| 142 |
-
mapping: Dict like {"name": "A", "price": "B", "quantity": "C"}
|
| 143 |
-
|
| 144 |
-
Returns:
|
| 145 |
-
List of dicts with mapped values
|
| 146 |
-
"""
|
| 147 |
-
if not rows or len(rows) < 2:
|
| 148 |
-
return []
|
| 149 |
-
|
| 150 |
-
headers = rows[0]
|
| 151 |
-
data_rows = rows[1:]
|
| 152 |
-
|
| 153 |
-
# Convert column letters to indices (A=0, B=1, etc.)
|
| 154 |
-
def col_to_idx(col: str) -> int:
|
| 155 |
-
col = col.upper().strip()
|
| 156 |
-
if col.isdigit():
|
| 157 |
-
return int(col) - 1 # 1-indexed
|
| 158 |
-
# Handle A-Z
|
| 159 |
-
result = 0
|
| 160 |
-
for char in col:
|
| 161 |
-
result = result * 26 + (ord(char) - ord('A') + 1)
|
| 162 |
-
return result - 1
|
| 163 |
-
|
| 164 |
-
result = []
|
| 165 |
-
for row in data_rows:
|
| 166 |
-
item = {}
|
| 167 |
-
for field, col in mapping.items():
|
| 168 |
-
idx = col_to_idx(col)
|
| 169 |
-
if 0 <= idx < len(row):
|
| 170 |
-
value = row[idx]
|
| 171 |
-
# Parse numeric values
|
| 172 |
-
if field in ('price', 'quantity', 'stock'):
|
| 173 |
-
try:
|
| 174 |
-
# Remove currency symbols and spaces
|
| 175 |
-
clean_val = re.sub(r'[^\d.,]', '', str(value))
|
| 176 |
-
clean_val = clean_val.replace(',', '.')
|
| 177 |
-
if '.' in clean_val:
|
| 178 |
-
item[field] = float(clean_val)
|
| 179 |
-
else:
|
| 180 |
-
item[field] = int(clean_val) if clean_val else 0
|
| 181 |
-
except (ValueError, TypeError):
|
| 182 |
-
item[field] = 0
|
| 183 |
-
else:
|
| 184 |
-
item[field] = value
|
| 185 |
-
else:
|
| 186 |
-
item[field] = None
|
| 187 |
-
|
| 188 |
-
# Only include rows with a name
|
| 189 |
-
if item.get('name'):
|
| 190 |
-
result.append(item)
|
| 191 |
-
|
| 192 |
-
return result
|
| 193 |
-
|
| 194 |
-
async def sync_products_from_sheet(
|
| 195 |
-
self,
|
| 196 |
-
sheet_url: str,
|
| 197 |
-
mapping: Dict[str, str],
|
| 198 |
-
sheet_name: str = "Sheet1"
|
| 199 |
-
) -> Optional[List[Dict[str, Any]]]:
|
| 200 |
-
"""
|
| 201 |
-
Fetch and parse product data from Google Sheet.
|
| 202 |
-
|
| 203 |
-
Args:
|
| 204 |
-
sheet_url: Google Sheet URL
|
| 205 |
-
mapping: Column mapping {"name": "A", "price": "B", "quantity": "C"}
|
| 206 |
-
sheet_name: Sheet tab name
|
| 207 |
-
|
| 208 |
-
Returns:
|
| 209 |
-
List of product dicts with name, price, quantity
|
| 210 |
-
"""
|
| 211 |
-
rows = await self.fetch_sheet_data(sheet_url, sheet_name)
|
| 212 |
-
if not rows:
|
| 213 |
-
return None
|
| 214 |
-
|
| 215 |
-
products = self.parse_with_mapping(rows, mapping)
|
| 216 |
-
logger.info(f"📦 Parsed {len(products)} products from Google Sheet")
|
| 217 |
-
|
| 218 |
-
return products
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
# Singleton instance
|
| 222 |
-
_google_sheets_service: Optional[GoogleSheetsService] = None
|
| 223 |
-
|
| 224 |
-
def get_google_sheets_service() -> GoogleSheetsService:
|
| 225 |
-
global _google_sheets_service
|
| 226 |
-
if _google_sheets_service is None:
|
| 227 |
-
_google_sheets_service = GoogleSheetsService()
|
| 228 |
-
return _google_sheets_service
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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