Spaces:
Running

File size: 3,327 Bytes
fd5dd94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
"""Google Sheets through the Nango proxy (same pattern as ``core.channels.email``).



WorkPilot never holds the Google OAuth tokens; Nango does. A tool call reaches

``{nango}/proxy/v4/spreadsheets/<id>/values/<range>`` with the Nango secret key (resolved

by the gateway from the connector's secret ref) and the tenant's connection id.



The first row of the sheet holds the column names; rows are returned as entities

(``{column: value}``) and addressed by the connector's key column.

"""

from __future__ import annotations

from typing import Any
from urllib.parse import quote

import httpx

from core.channels.base import ChannelError
from core.channels.email import DEFAULT_NANGO_URL, NangoClient


def _a1(sheet: str, cell_range: str = "") -> str:
    name = "'" + sheet.replace("'", "''") + "'"
    return quote(f"{name}!{cell_range}" if cell_range else name, safe="")


def _col_letter(n: int) -> str:
    s = ""
    n += 1
    while n:
        n, r = divmod(n - 1, 26)
        s = chr(65 + r) + s
    return s


class SheetsClient:
    def __init__(

        self,

        config: dict[str, Any],

        secret: str,

        transport: httpx.AsyncBaseTransport | None = None,

    ) -> None:
        self.spreadsheet_id = quote(str(config["spreadsheet_id"]), safe="")
        self.sheet = str(config.get("sheet") or "Sheet1")
        self.nango = NangoClient(
            secret_key=secret,
            connection_id=str(config.get("connection_id") or ""),
            provider_config_key=str(config.get("provider_config_key") or "google-sheet"),
            base_url=str(config.get("nango_base_url") or DEFAULT_NANGO_URL),
            transport=transport,
        )

    def _values(self, cell_range: str = "") -> str:
        return f"/v4/spreadsheets/{self.spreadsheet_id}/values/{_a1(self.sheet, cell_range)}"

    async def read(self) -> tuple[list[str], list[dict[str, Any]]]:
        data = await self.nango.json("GET", self._values())
        values = data.get("values") or []
        if not values:
            return [], []
        headers = [str(h) for h in values[0]]
        rows = [
            {h: (r[i] if i < len(r) else "") for i, h in enumerate(headers)} for r in values[1:]
        ]
        return headers, rows

    async def append(self, headers: list[str], row: dict[str, Any]) -> dict[str, Any]:
        body = {"values": [[row.get(h, "") for h in headers]]}
        result: dict[str, Any] = await self.nango.json(
            "POST",
            self._values("A1") + ":append",
            params={"valueInputOption": "USER_ENTERED", "insertDataOption": "INSERT_ROWS"},
            json=body,
        )
        return result

    async def update_row(

        self, headers: list[str], index: int, row: dict[str, Any]

    ) -> dict[str, Any]:
        """``index`` is the 0-based data row (sheet row ``index + 2``)."""
        r = index + 2
        rng = f"A{r}:{_col_letter(len(headers) - 1)}{r}"
        result: dict[str, Any] = await self.nango.json(
            "PUT",
            self._values(rng),
            params={"valueInputOption": "USER_ENTERED"},
            json={"values": [[row.get(h, "") for h in headers]]},
        )
        return result


__all__ = ["ChannelError", "SheetsClient"]