:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement zoho_crm source (#73789)
Tom Owers867d3cceb5b9
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 0334ad10a05d..e3ff7055865a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -648,6 +648,7 @@ the row lists both.| zenduty | HTTP | requests | ✅ || zenloop | HTTP | requests | ✅ || zep | HTTP | requests | ✅ |+| zoho_crm | HTTP | requests | ✅ || zonka_feedback | HTTP | requests | ✅ || zoom | HTTP | requests | ✅ || zuora | HTTP | requests | ✅ |@@ -1413,7 +1414,6 @@ doesn't conflict with concurrent PRs.- zoho_billing- zoho_books- zoho_campaign-- zoho_crm- zoho_desk- zoho_expense- zoho_inventorydiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/zohocrm.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/zohocrm.pyindex 969c3568c328..95b4194f11c5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/zohocrm.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/zohocrm.py@@ -1,9 +1,14 @@# This file is automatically generated from `SourceRegistry.get_all_sources()`# Do not edit manually - run `pnpm generate:source-configs` to regenerate.+from typing import Literal+from products.warehouse_sources.backend.temporal.data_imports.sources.common import config@config.configclass ZohoCRMSourceConfig(config.Config):- pass+ client_id: str+ client_secret: str+ refresh_token: str+ region: Literal["us", "eu", "in", "au", "jp", "ca", "cn"] = config.value(default="us")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/canonical_descriptions.pynew file mode 100644index 000000000000..d497c07c6032--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/canonical_descriptions.py@@ -0,0 +1,390 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_MODULES_DOCS_URL = "https://www.zoho.com/crm/developer/docs/api/v8/get-records.html"++# System fields every Zoho CRM record module returns.+_COMMON_COLUMNS: dict[str, str] = {+ "id": "Unique record identifier, generated by Zoho CRM.",+ "Owner": "User the record is assigned to, as a lookup object with id, name, and email.",+ "Created_By": "User who created the record, as a lookup object with id, name, and email.",+ "Modified_By": "User who last updated the record, as a lookup object with id, name, and email.",+ "Created_Time": "Timestamp the record was created, in the org's time zone.",+ "Modified_Time": "Timestamp the record was last updated, in the org's time zone.",+ "Last_Activity_Time": "Timestamp of the most recent activity logged against the record.",+ "Tag": "Tags applied to the record.",+ "$approval_state": "Approval state of the record (approved, pending, or rejected).",+}+++def _columns(**extra: str) -> dict[str, str]:+ return {**_COMMON_COLUMNS, **extra}+++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "Leads": {+ "description": "Unqualified prospects captured in Zoho CRM before they are converted into a contact, account, and deal.",+ "docs_url": _MODULES_DOCS_URL,+ "columns": _columns(+ Company="Company the lead works for.",+ First_Name="Lead's first name.",+ Last_Name="Lead's last name. Mandatory on every lead.",+ Full_Name="Lead's salutation, first name, and last name combined.",+ Email="Primary email address of the lead.",+ Phone="Primary phone number of the lead.",+ Mobile="Mobile number of the lead.",+ Website="Website of the lead's company.",+ Lead_Source="Channel the lead came from, such as an advertisement or a web download.",+ Lead_Status="Stage the lead is at, such as contacted or not qualified.",+ Industry="Industry the lead's company operates in.",+ Annual_Revenue="Annual revenue of the lead's company.",+ No_of_Employees="Number of employees at the lead's company.",+ Rating="How likely the lead is to convert, such as hot or cold.",+ Converted__s="Whether the lead has been converted into a contact, account, and deal.",+ Designation="Job title of the lead.",+ Email_Opt_Out="Whether the lead has opted out of emails.",+ Description="Free-text notes about the lead.",+ ),+ },+ "Contacts": {+ "description": "People associated with an account that your organization does business with.",+ "docs_url": _MODULES_DOCS_URL,+ "columns": _columns(+ First_Name="Contact's first name.",+ Last_Name="Contact's last name. Mandatory on every contact.",+ Full_Name="Contact's salutation, first name, and last name combined.",+ Email="Primary email address of the contact.",+ Phone="Primary phone number of the contact.",+ Mobile="Mobile number of the contact.",+ Account_Name="Account the contact belongs to, as a lookup object.",+ Vendor_Name="Vendor the contact is associated with, as a lookup object.",+ Reporting_To="Contact this person reports to, as a lookup object.",+ Title="Job title of the contact.",+ Department="Department the contact works in.",+ Lead_Source="Channel the contact originally came from.",+ Mailing_City="City of the contact's mailing address.",+ Mailing_Country="Country of the contact's mailing address.",+ Date_of_Birth="Contact's date of birth.",+ Email_Opt_Out="Whether the contact has opted out of emails.",+ Description="Free-text notes about the contact.",+ ),+ },+ "Accounts": {+ "description": "Companies or departments your organization does business with.",+ "docs_url": _MODULES_DOCS_URL,+ "columns": _columns(+ Account_Name="Name of the account. Mandatory on every account.",+ Account_Number="Account number assigned by your organization.",+ Account_Type="Relationship type, such as customer, reseller, or partner.",+ Account_Site="Location or branch of the account.",+ Parent_Account="Parent company of this account, as a lookup object.",+ Industry="Industry the account operates in.",+ Annual_Revenue="Annual revenue of the account.",+ Employees="Number of employees at the account.",+ Phone="Primary phone number of the account.",+ Website="Website of the account.",+ Billing_City="City of the account's billing address.",+ Billing_Country="Country of the account's billing address.",+ Shipping_City="City of the account's shipping address.",+ Shipping_Country="Country of the account's shipping address.",+ Rating="How likely the account is to buy, such as active or market failed.",+ Description="Free-text notes about the account.",+ ),+ },+ "Deals": {+ "description": "Sales opportunities in the pipeline, each tied to an account and a stage.",+ "docs_url": _MODULES_DOCS_URL,+ "columns": _columns(+ Deal_Name="Name of the deal. Mandatory on every deal.",+ Account_Name="Account the deal belongs to, as a lookup object.",+ Contact_Name="Primary contact on the deal, as a lookup object.",+ Amount="Total value of the deal.",+ Stage="Pipeline stage the deal is at, such as qualification or closed won.",+ Closing_Date="Date the deal is expected to close.",+ Probability="Chance of winning the deal, as a percentage.",+ Expected_Revenue="Deal amount weighted by the win probability.",+ Type="Type of deal, such as new business or existing business.",+ Lead_Source="Channel the deal came from.",+ Next_Step="Next action planned on the deal.",+ Campaign_Source="Campaign the deal is attributed to, as a lookup object.",+ Description="Free-text notes about the deal.",+ ),+ },+ "Campaigns": {+ "description": "Marketing campaigns tracked in Zoho CRM, with their budget, dates, and generated revenue.",+ "docs_url": _MODULES_DOCS_URL,+ "columns": _columns(+ Campaign_Name="Name of the campaign. Mandatory on every campaign.",+ Type="Type of campaign, such as webinar, conference, or email.",+ Status="Status of the campaign, such as planning, active, or complete.",+ Start_Date="Date the campaign starts.",+ End_Date="Date the campaign ends.",+ Budgeted_Cost="Budget allocated to the campaign.",+ Actual_Cost="Amount actually spent on the campaign.",+ Expected_Revenue="Revenue the campaign is expected to generate.",+ Expected_Response="Expected response rate for the campaign, as a percentage.",+ Num_sent="Number of contacts or leads the campaign was sent to.",+ Parent_Campaign="Parent campaign, as a lookup object.",+ Description="Free-text notes about the campaign.",+ ),+ },+ "Tasks": {+ "description": "To-do items assigned to a user and optionally linked to a lead, contact, account, or deal.",+ "docs_url": _MODULES_DOCS_URL,+ "columns": _columns(+ Subject="Short description of the task. Mandatory on every task.",+ Status="Status of the task, such as not started, in progress, or completed.",+ Priority="Priority of the task, such as high, highest, or low.",+ Due_Date="Date the task is due.",+ Closed_Time="Timestamp the task was marked completed.",+ What_Id="Account, deal, or other record the task relates to, as a lookup object.",+ Who_Id="Lead or contact the task relates to, as a lookup object.",+ se_module="API name of the module `What_Id` points at.",+ Remind_At="Reminder time set on the task.",+ Recurring_Activity="Recurrence rule when the task repeats.",+ Description="Free-text notes about the task.",+ ),+ },+ "Events": {+ "description": "Calendar meetings and appointments, with their participants and scheduled window.",+ "docs_url": _MODULES_DOCS_URL,+ "columns": _columns(+ Event_Title="Title of the event. Mandatory on every event.",+ Start_DateTime="Timestamp the event starts.",+ End_DateTime="Timestamp the event ends.",+ All_day="Whether the event spans the whole day.",+ Venue="Location of the event.",+ Participants="People invited to the event, with their type and RSVP status.",+ What_Id="Account, deal, or other record the event relates to, as a lookup object.",+ Who_Id="Lead or contact the event relates to, as a lookup object.",+ se_module="API name of the module `What_Id` points at.",+ Remind_At="Reminder time set on the event.",+ Recurring_Activity="Recurrence rule when the event repeats.",+ Description="Free-text notes about the event.",+ ),+ },+ "Calls": {+ "description": "Logged and scheduled phone calls, including their outcome and duration.",+ "docs_url": _MODULES_DOCS_URL,+ "columns": _columns(+ Subject="Short description of the call. Mandatory on every call.",+ Call_Type="Direction of the call: inbound, outbound, or missed.",+ Call_Purpose="Reason for the call, such as demo or negotiation.",+ Call_Start_Time="Timestamp the call started.",+ Call_Duration="Duration of the call, as mm:ss.",+ Call_Duration_in_seconds="Duration of the call in seconds.",+ Call_Result="Outcome of the call, such as not interested or scheduled next call.",+ Call_Agenda="Agenda planned for the call.",+ Dialled_Number="Number that was dialled.",+ What_Id="Account, deal, or other record the call relates to, as a lookup object.",+ Who_Id="Lead or contact the call relates to, as a lookup object.",+ se_module="API name of the module `What_Id` points at.",+ Description="Free-text notes about the call.",+ ),+ },+ "Notes": {+ "description": "Free-text notes attached to any Zoho CRM record.",+ "docs_url": _MODULES_DOCS_URL,+ "columns": _columns(+ Note_Title="Title of the note.",+ Note_Content="Body of the note.",+ Parent_Id="Record the note is attached to, as a lookup object.",+ se_module="API name of the module the note is attached to.",+ Attachments="Files attached to the note.",+ ),+ },+ "Products": {+ "description": "Goods and services your organization sells or buys, used on quotes, orders, and invoices.",+ "docs_url": _MODULES_DOCS_URL,+ "columns": _columns(+ Product_Name="Name of the product. Mandatory on every product.",+ Product_Code="Internal code for the product.",+ Product_Category="Category the product belongs to.",+ Product_Active="Whether the product is available for selection on transactions.",+ Unit_Price="List price of one unit.",+ Qty_in_Stock="Quantity currently in stock.",+ Qty_Ordered="Quantity ordered from the vendor.",+ Reorder_Level="Stock level at which the product should be reordered.",+ Manufacturer="Manufacturer of the product.",+ Vendor_Name="Vendor that supplies the product, as a lookup object.",+ Taxable="Whether tax applies to the product.",+ Sales_Start_Date="Date the product becomes available for sale.",+ Sales_End_Date="Date the product stops being available for sale.",+ Description="Free-text notes about the product.",+ ),+ },+ "Vendors": {+ "description": "Suppliers your organization buys goods or services from.",+ "docs_url": _MODULES_DOCS_URL,+ "columns": _columns(+ Vendor_Name="Name of the vendor. Mandatory on every vendor.",+ Email="Primary email address of the vendor.",+ Phone="Primary phone number of the vendor.",+ Website="Website of the vendor.",+ Category="Category of goods or services the vendor supplies.",+ GL_Account="General ledger account the vendor's spend is booked to.",+ City="City of the vendor's address.",+ Country="Country of the vendor's address.",+ Description="Free-text notes about the vendor.",+ ),+ },+ "Price_Books": {+ "description": "Named price lists that apply per-product discounts to quotes, orders, and invoices.",+ "docs_url": _MODULES_DOCS_URL,+ "columns": _columns(+ Price_Book_Name="Name of the price book. Mandatory on every price book.",+ Pricing_Model="How the discount is applied: flat or differential.",+ Active="Whether the price book can be selected on transactions.",+ Pricing_Details="Per-quantity discount tiers defined on the price book.",+ Description="Free-text notes about the price book.",+ ),+ },+ "Quotes": {+ "description": "Formal price proposals sent to a customer, with their line items and totals.",+ "docs_url": _MODULES_DOCS_URL,+ "columns": _columns(+ Subject="Title of the quote. Mandatory on every quote.",+ Quote_Number="Quote number generated by Zoho CRM.",+ Quote_Stage="Stage of the quote, such as draft, delivered, or closed won.",+ Account_Name="Account the quote is addressed to, as a lookup object.",+ Contact_Name="Contact the quote is addressed to, as a lookup object.",+ Deal_Name="Deal the quote belongs to, as a lookup object.",+ Valid_Till="Date the quote expires.",+ Product_Details="Line items on the quote, with product, quantity, and price.",+ Sub_Total="Total of the line items before discount, tax, and shipping.",+ Discount="Discount applied to the quote.",+ Tax="Tax charged on the quote.",+ Adjustment="Manual adjustment applied to the grand total.",+ Grand_Total="Final payable amount on the quote.",+ Currency="Currency the quote is denominated in.",+ Description="Free-text notes about the quote.",+ ),+ },+ "Sales_Orders": {+ "description": "Confirmed customer orders raised from an accepted quote.",+ "docs_url": _MODULES_DOCS_URL,+ "columns": _columns(+ Subject="Title of the sales order. Mandatory on every sales order.",+ SO_Number="Sales order number generated by Zoho CRM.",+ Status="Status of the order, such as created, approved, or delivered.",+ Account_Name="Account the order is for, as a lookup object.",+ Contact_Name="Contact the order is for, as a lookup object.",+ Deal_Name="Deal the order belongs to, as a lookup object.",+ Quote_Name="Quote the order was raised from, as a lookup object.",+ Customer_No="Customer's own reference number for the order.",+ Purchase_Order="Customer's purchase order number.",+ Due_Date="Date the order is due.",+ Product_Details="Line items on the order, with product, quantity, and price.",+ Sub_Total="Total of the line items before discount, tax, and shipping.",+ Discount="Discount applied to the order.",+ Tax="Tax charged on the order.",+ Grand_Total="Final payable amount on the order.",+ Currency="Currency the order is denominated in.",+ Description="Free-text notes about the sales order.",+ ),+ },+ "Purchase_Orders": {+ "description": "Orders your organization places with a vendor.",+ "docs_url": _MODULES_DOCS_URL,+ "columns": _columns(+ Subject="Title of the purchase order. Mandatory on every purchase order.",+ PO_Number="Purchase order number generated by Zoho CRM.",+ Status="Status of the purchase order, such as created, approved, or delivered.",+ Vendor_Name="Vendor the order is placed with, as a lookup object.",+ Contact_Name="Contact at the vendor, as a lookup object.",+ PO_Date="Date the purchase order was raised.",+ Due_Date="Date the purchase order is due.",+ Tracking_Number="Shipment tracking number for the order.",+ Product_Details="Line items on the order, with product, quantity, and price.",+ Sub_Total="Total of the line items before discount, tax, and shipping.",+ Discount="Discount applied to the order.",+ Tax="Tax charged on the order.",+ Grand_Total="Final payable amount on the order.",+ Currency="Currency the order is denominated in.",+ Description="Free-text notes about the purchase order.",+ ),+ },+ "Invoices": {+ "description": "Bills issued to a customer, with their line items, totals, and due date.",+ "docs_url": _MODULES_DOCS_URL,+ "columns": _columns(+ Subject="Title of the invoice. Mandatory on every invoice.",+ Invoice_Number="Invoice number generated by Zoho CRM.",+ Status="Status of the invoice, such as created, sent, or paid.",+ Account_Name="Account the invoice is billed to, as a lookup object.",+ Contact_Name="Contact the invoice is billed to, as a lookup object.",+ Sales_Order="Sales order the invoice was raised from, as a lookup object.",+ Invoice_Date="Date the invoice was issued.",+ Due_Date="Date payment is due.",+ Purchase_Order="Customer's purchase order number.",+ Product_Details="Line items on the invoice, with product, quantity, and price.",+ Sub_Total="Total of the line items before discount, tax, and shipping.",+ Discount="Discount applied to the invoice.",+ Tax="Tax charged on the invoice.",+ Grand_Total="Final payable amount on the invoice.",+ Currency="Currency the invoice is denominated in.",+ Description="Free-text notes about the invoice.",+ ),+ },+ "Cases": {+ "description": "Customer support requests logged against an account or contact. Requires the Cases module to be enabled.",+ "docs_url": _MODULES_DOCS_URL,+ "columns": _columns(+ Subject="Short description of the case. Mandatory on every case.",+ Case_Number="Case number generated by Zoho CRM.",+ Status="Status of the case, such as new, escalated, or closed.",+ Priority="Priority of the case, such as high or low.",+ Type="Type of case, such as question, problem, or feature request.",+ Case_Origin="Channel the case came in through, such as email, phone, or web.",+ Case_Reason="Reason the case was raised.",+ Account_Name="Account the case belongs to, as a lookup object.",+ Deal_Name="Deal the case relates to, as a lookup object.",+ Product_Name="Product the case is about, as a lookup object.",+ Reported_By="Person who reported the case.",+ Internal_Comments="Internal-only notes on the case.",+ Solution="Resolution recorded on the case.",+ Description="Free-text description of the case.",+ ),+ },+ "Solutions": {+ "description": "Knowledge base articles that resolve recurring cases. Requires the Solutions module to be enabled.",+ "docs_url": _MODULES_DOCS_URL,+ "columns": _columns(+ Solution_Title="Title of the solution. Mandatory on every solution.",+ Solution_Number="Solution number generated by Zoho CRM.",+ Status="Status of the solution, such as draft or approved.",+ Question="Question the solution answers.",+ Answer="Answer recorded in the solution.",+ Product_Name="Product the solution applies to, as a lookup object.",+ Published="Whether the solution is published to the customer portal.",+ No_of_comments="Number of comments left on the solution.",+ ),+ },+ "Users": {+ "description": "Users in the Zoho CRM organization, with their role, profile, and status.",+ "docs_url": "https://www.zoho.com/crm/developer/docs/api/v8/get-users.html",+ "columns": {+ "id": "Unique user identifier, generated by Zoho CRM.",+ "full_name": "User's first and last name combined.",+ "first_name": "User's first name.",+ "last_name": "User's last name.",+ "email": "User's email address, which is also their Zoho sign-in.",+ "phone": "User's phone number.",+ "role": "Role assigned to the user, as an object with id and name.",+ "profile": "Permission profile assigned to the user, as an object with id and name.",+ "status": "Whether the user is active or inactive.",+ "confirm": "Whether the user has confirmed their Zoho account invitation.",+ "Isonline": "Whether the user is currently signed in.",+ "time_zone": "Time zone set on the user's profile.",+ "locale": "Locale set on the user's profile.",+ "country": "Country set on the user's profile.",+ "created_time": "Timestamp the user was added to the organization.",+ "Modified_Time": "Timestamp the user record was last updated.",+ "created_by": "User who added this user, as an object with id and name.",+ "Modified_By": "User who last updated this user, as an object with id and name.",+ "territories": "Territories the user belongs to.",+ "reporting_to": "User this user reports to, as an object with id and name.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/settings.pynew file mode 100644index 000000000000..2ce3fc6e0e64--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/settings.py@@ -0,0 +1,85 @@+from dataclasses import dataclass+from typing import Optional++from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# Every Zoho CRM record carries these system fields. `Modified_Time` is what the+# `If-Modified-Since` header filters on server-side; `Created_Time` never changes, so it is+# the partition key.+MODIFIED_TIME_FIELD = "Modified_Time"+CREATED_TIME_FIELD = "Created_Time"+++@dataclass(frozen=True)+class ZohoCRMEndpointConfig:+ name: str+ # Module API name for record modules (`/crm/{version}/{path}`), or the fixed path segment+ # for Zoho's own non-module endpoints.+ path: str+ # Record modules go through Get Records: their readable fields come from the fields+ # metadata API and they honour `If-Modified-Since`. Non-module endpoints (users) have a+ # different envelope, no field metadata, and no documented modified-since filter.+ is_module: bool = True+ # Key the records live under in the response body.+ data_key: str = "data"+ incremental: bool = True+ partition_key: Optional[str] = CREATED_TIME_FIELD+ # Modules that only exist on some Zoho CRM editions start unticked so a first sync doesn't+ # fail with INVALID_MODULE on an org that never enabled them.+ should_sync_default: bool = True+ # Extra query params Zoho requires on this endpoint.+ extra_params: Optional[dict[str, str]] = None++ @property+ def incremental_fields(self) -> list[IncrementalField]:+ if not self.incremental:+ return []+ return [incremental_field(MODIFIED_TIME_FIELD, IncrementalFieldType.DateTime)]+++def _module(name: str, should_sync_default: bool = True) -> ZohoCRMEndpointConfig:+ return ZohoCRMEndpointConfig(name=name, path=name, should_sync_default=should_sync_default)+++ZOHO_CRM_ENDPOINTS: dict[str, ZohoCRMEndpointConfig] = {+ # Core CRM modules — present on every edition.+ "Leads": _module("Leads"),+ "Contacts": _module("Contacts"),+ "Accounts": _module("Accounts"),+ "Deals": _module("Deals"),+ "Campaigns": _module("Campaigns"),+ "Tasks": _module("Tasks"),+ "Events": _module("Events"),+ "Calls": _module("Calls"),+ "Notes": _module("Notes"),+ "Products": _module("Products"),+ "Vendors": _module("Vendors"),+ # Inventory and support modules — edition/setup dependent.+ "Price_Books": _module("Price_Books", should_sync_default=False),+ "Quotes": _module("Quotes", should_sync_default=False),+ "Sales_Orders": _module("Sales_Orders", should_sync_default=False),+ "Purchase_Orders": _module("Purchase_Orders", should_sync_default=False),+ "Invoices": _module("Invoices", should_sync_default=False),+ "Cases": _module("Cases", should_sync_default=False),+ "Solutions": _module("Solutions", should_sync_default=False),+ # Org users are served by a dedicated endpoint, not the Get Records API.+ "Users": ZohoCRMEndpointConfig(+ name="Users",+ path="users",+ is_module=False,+ data_key="users",+ incremental=False,+ # The users endpoint names its system fields in lower case, unlike record modules.+ partition_key="created_time",+ extra_params={"type": "AllUsers"},+ ),+}++ENDPOINTS = tuple(ZOHO_CRM_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in ZOHO_CRM_ENDPOINTS.items()+}++SHOULD_SYNC_DEFAULT: dict[str, bool] = {name: config.should_sync_default for name, config in ZOHO_CRM_ENDPOINTS.items()}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/source.pyindex cb7e41073a4c..ed88baad4e7f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/source.py@@ -1,25 +1,65 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.zohocrm import (ZohoCRMSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.zoho_crm.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ SHOULD_SYNC_DEFAULT,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.zoho_crm.zoho_crm import (+ ZohoCRMResumeConfig,+ validate_credentials as validate_zoho_crm_credentials,+ zoho_crm_source,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class ZohoCRMSource(SimpleSource[ZohoCRMSourceConfig]):+class ZohoCRMSource(ResumableSource[ZohoCRMSourceConfig, ZohoCRMResumeConfig]):+ lists_tables_without_credentials = True # static module catalog — safe for public docs+ supported_versions = ("v8",)+ default_version = "v8"+ api_docs_url = "https://www.zoho.com/crm/developer/docs/api/v8/"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.ZOHOCRM+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "Zoho CRM token refresh failed": "Zoho CRM rejected your refresh token. Generate a new one for your self client and reconnect.",+ "400 Client Error: Bad Request for url: https://accounts.zoho": "Zoho CRM rejected your OAuth credentials. Check that the client ID, client secret, and refresh token all belong to the same self client.",+ "401 Client Error: Unauthorized for url": "Your Zoho CRM access token is invalid or expired. Reconnect the source to issue a new one.",+ "403 Client Error: Forbidden for url": "Your Zoho CRM token is missing a scope for this module. Re-authorize with the ZohoCRM.modules.ALL and ZohoCRM.settings.fields.READ scopes.",+ }+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(@@ -27,7 +67,124 @@ class ZohoCRMSource(SimpleSource[ZohoCRMSourceConfig]):category=DataWarehouseSourceCategory.CRM,keywords=["zoho"],label="Zoho CRM",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Connect your Zoho CRM account to pull leads, contacts, deals, and your other modules into the PostHog Data warehouse.++In the [Zoho API console](https://api-console.zoho.com), create a **Self Client** and generate a refresh token for the scopes `ZohoCRM.modules.ALL` and `ZohoCRM.settings.fields.READ`. Paste the client ID, client secret, and refresh token below, then pick the data center your Zoho account lives in.""",iconPath="/static/services/zoho_crm.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/zoho-crm",+ fields=cast(+ list[FieldType],+ [+ SourceFieldSelectConfig(+ name="region",+ label="Data center",+ required=True,+ defaultValue="us",+ options=[+ SourceFieldSelectConfigOption(label="United States (.com)", value="us"),+ SourceFieldSelectConfigOption(label="Europe (.eu)", value="eu"),+ SourceFieldSelectConfigOption(label="India (.in)", value="in"),+ SourceFieldSelectConfigOption(label="Australia (.com.au)", value="au"),+ SourceFieldSelectConfigOption(label="Japan (.jp)", value="jp"),+ SourceFieldSelectConfigOption(label="Canada (.ca)", value="ca"),+ SourceFieldSelectConfigOption(label="China (.com.cn)", value="cn"),+ ],+ ),+ SourceFieldInputConfig(+ name="client_id",+ label="Client ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="1000.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="client_secret",+ label="Client secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="refresh_token",+ label="Refresh token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="1000.XXXXXXXX.XXXXXXXX",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.zoho_crm.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: ZohoCRMSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ names,+ should_sync_default=SHOULD_SYNC_DEFAULT,+ )++ def validate_credentials(+ self,+ config: ZohoCRMSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ is_valid, error = validate_zoho_crm_credentials(+ region=config.region,+ client_id=config.client_id,+ client_secret=config.client_secret,+ refresh_token=config.refresh_token,+ api_version=self.resolve_api_version(api_version),+ )+ if is_valid:+ return True, None++ return False, error or "Invalid Zoho CRM credentials"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ZohoCRMResumeConfig]:+ # Each module keeps its own cursor: page tokens are bound to the query that issued them.+ return ResumableSourceManager[ZohoCRMResumeConfig](inputs, ZohoCRMResumeConfig).with_namespace(+ inputs.schema_name+ )++ def source_for_pipeline(+ self,+ config: ZohoCRMSourceConfig,+ resumable_source_manager: ResumableSourceManager[ZohoCRMResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return zoho_crm_source(+ region=config.region,+ client_id=config.client_id,+ client_secret=config.client_secret,+ refresh_token=config.refresh_token,+ endpoint=inputs.schema_name,+ api_version=self.resolve_api_version(inputs.api_version),+ resumable_source_manager=resumable_source_manager,+ logger=inputs.logger,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ incremental_field=inputs.incremental_field,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/tests/test_zoho_crm.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/tests/test_zoho_crm.pynew file mode 100644index 000000000000..8c040e27047e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/tests/test_zoho_crm.py@@ -0,0 +1,492 @@+from collections.abc import Iterable+from datetime import UTC, date, datetime+from typing import Any, Optional, cast++import pytest+from unittest import mock++import requests++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.zoho_crm.settings import ZOHO_CRM_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.zoho_crm.zoho_crm import (+ MAX_FIELDS_PER_REQUEST,+ MAX_PAGE,+ PAGE_SIZE,+ ZohoCRMAuthError,+ ZohoCRMClient,+ ZohoCRMResumeConfig,+ chunk_fields,+ format_modified_since,+ get_rows,+ readable_field_names,+ resolve_hosts,+ validate_credentials,+ zoho_crm_source,+)++_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.zoho_crm.zoho_crm"+++class FakeResumeManager(ResumableSourceManager[ZohoCRMResumeConfig]):+ """In-memory stand-in for the Redis-backed manager."""++ def __init__(self, state: Optional[ZohoCRMResumeConfig] = None) -> None:+ self.state = state+ self.saved: list[ZohoCRMResumeConfig] = []+ self.cleared = False++ def can_resume(self) -> bool:+ return self.state is not None++ def load_state(self) -> Optional[ZohoCRMResumeConfig]:+ return self.state++ def save_state(self, data: ZohoCRMResumeConfig) -> None:+ self.saved.append(data)++ def clear_state(self) -> None:+ self.cleared = True+++def _response(status_code: int = 200, body: Optional[dict[str, Any]] = None) -> mock.MagicMock:+ response = mock.MagicMock()+ response.status_code = status_code+ response.ok = 200 <= status_code < 400+ response.json.return_value = body if body is not None else {}+ return response+++def _token_response(api_domain: str = "https://www.zohoapis.com") -> mock.MagicMock:+ return _response(200, {"access_token": "access-token", "api_domain": api_domain, "expires_in": 3600})+++def _fields_response(count: int) -> mock.MagicMock:+ return _response(200, {"fields": [{"api_name": f"Field_{index}"} for index in range(count)]})+++def _records_response(+ records: list[dict[str, Any]],+ more_records: bool = False,+ next_page_token: Optional[str] = None,+ data_key: str = "data",+) -> mock.MagicMock:+ info: dict[str, Any] = {"more_records": more_records, "per_page": PAGE_SIZE}+ if next_page_token is not None:+ info["next_page_token"] = next_page_token+ return _response(200, {data_key: records, "info": info})+++def _session(+ get_responses: list[mock.MagicMock], post_responses: Optional[list[mock.MagicMock]] = None+) -> mock.MagicMock:+ session = mock.MagicMock()+ session.get.side_effect = list(get_responses)+ session.post.side_effect = list(post_responses) if post_responses is not None else [_token_response()]+ return session+++def _client() -> ZohoCRMClient:+ return ZohoCRMClient("us", "cid", "secret", "refresh")+++def _get_params(session: mock.MagicMock, index: int) -> dict[str, str]:+ return cast(dict[str, str], session.get.call_args_list[index].kwargs["params"])+++def _get_headers(session: mock.MagicMock, index: int) -> dict[str, str]:+ return cast(dict[str, str], session.get.call_args_list[index].kwargs["headers"])+++class TestResolveHosts:+ @pytest.mark.parametrize(+ "region, accounts_host, api_host",+ [+ ("us", "https://accounts.zoho.com", "https://www.zohoapis.com"),+ ("eu", "https://accounts.zoho.eu", "https://www.zohoapis.eu"),+ ("in", "https://accounts.zoho.in", "https://www.zohoapis.in"),+ ("au", "https://accounts.zoho.com.au", "https://www.zohoapis.com.au"),+ ("jp", "https://accounts.zoho.jp", "https://www.zohoapis.jp"),+ ("ca", "https://accounts.zohocloud.ca", "https://www.zohoapis.ca"),+ ("cn", "https://accounts.zoho.com.cn", "https://www.zohoapis.com.cn"),+ ],+ )+ def test_regional_hosts(self, region: str, accounts_host: str, api_host: str) -> None:+ assert resolve_hosts(region) == (accounts_host, api_host)++ def test_unknown_region_raises(self) -> None:+ with pytest.raises(ValueError):+ resolve_hosts("mars")+++class TestFormatModifiedSince:+ @pytest.mark.parametrize(+ "value, expected",+ [+ (datetime(2024, 3, 1, 12, 30, 15, tzinfo=UTC), "2024-03-01T12:30:15+00:00"),+ (datetime(2024, 3, 1, 12, 30, 15), "2024-03-01T12:30:15+00:00"),+ (date(2024, 3, 1), "2024-03-01T00:00:00+00:00"),+ ("2024-03-01T00:00:00+00:00", "2024-03-01T00:00:00+00:00"),+ ],+ )+ def test_formats_cursor_values(self, value: Any, expected: str) -> None:+ assert format_modified_since(value) == expected+++class TestChunkFields:+ @pytest.mark.parametrize(+ "count, expected_sizes",+ [+ (0, [0]),+ (1, [1]),+ (MAX_FIELDS_PER_REQUEST, [MAX_FIELDS_PER_REQUEST]),+ (MAX_FIELDS_PER_REQUEST + 1, [MAX_FIELDS_PER_REQUEST, 1]),+ (MAX_FIELDS_PER_REQUEST * 2 + 3, [MAX_FIELDS_PER_REQUEST, MAX_FIELDS_PER_REQUEST, 3]),+ ],+ )+ def test_slices_never_exceed_the_request_cap(self, count: int, expected_sizes: list[int]) -> None:+ slices = chunk_fields([f"Field_{index}" for index in range(count)])+ assert [len(chunk) for chunk in slices] == expected_sizes+++class TestZohoCRMClient:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_token_response_api_domain_overrides_regional_default(self, make_session: mock.MagicMock) -> None:+ make_session.return_value = _session([], post_responses=[_token_response("https://www.zohoapis.eu/")])+ client = ZohoCRMClient("us", "cid", "secret", "refresh")++ client.mint_access_token()++ assert client.api_domain == "https://www.zohoapis.eu"++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_error_body_on_a_200_raises_auth_error(self, make_session: mock.MagicMock) -> None:+ make_session.return_value = _session([], post_responses=[_response(200, {"error": "invalid_code"})])+ client = _client()++ with pytest.raises(ZohoCRMAuthError, match="invalid_code"):+ client.mint_access_token()++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_authorization_header_uses_the_zoho_scheme(self, make_session: mock.MagicMock) -> None:+ session = _session([_response(200, {"modules": []})])+ make_session.return_value = session++ _client().get("/crm/v8/settings/modules")++ assert _get_headers(session, 0)["Authorization"] == "Zoho-oauthtoken access-token"++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_remints_once_on_401_and_replays_the_request(self, make_session: mock.MagicMock) -> None:+ session = _session(+ [_response(401), _response(200, {"data": []})],+ post_responses=[_token_response(), _token_response()],+ )+ make_session.return_value = session++ response = _client().get("/crm/v8/Leads")++ assert response.status_code == 200+ assert session.post.call_count == 2++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_204_is_returned_without_raising(self, make_session: mock.MagicMock) -> None:+ no_content = _response(204)+ no_content.raise_for_status.side_effect = AssertionError("204 must not be treated as an error")+ make_session.return_value = _session([no_content])++ assert _client().get("/crm/v8/Leads").status_code == 204++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_session_disables_sample_capture_and_redacts_credentials(self, make_session: mock.MagicMock) -> None:+ # Reverting capture=False would upload raw CRM records (contacts, notes, emails) and the+ # minted access token to the shared HTTP sample-capture prefix.+ make_session.return_value = _session([])++ ZohoCRMClient("us", "cid", "secret-value", "refresh-value")++ assert make_session.call_args.kwargs == {"redact_values": ("secret-value", "refresh-value"), "capture": False}+++class TestReadableFieldNames:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_skips_fields_the_api_never_returns(self, make_session: mock.MagicMock) -> None:+ make_session.return_value = _session(+ [+ _response(+ 200,+ {+ "fields": [+ {"api_name": "Last_Name", "view_type": {"view": True}},+ {"api_name": "Hidden", "view_type": {"view": False}},+ {"api_name": "No_View_Type"},+ {"data_type": "text"},+ ]+ },+ )+ ]+ )++ assert readable_field_names(_client(), "v8", "Leads") == ["Last_Name", "No_View_Type"]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_204_metadata_yields_no_projection(self, make_session: mock.MagicMock) -> None:+ make_session.return_value = _session([_response(204)])++ assert readable_field_names(_client(), "v8", "Leads") == []+++class TestGetRows:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_single_page_module_requests_its_fields_and_clears_state(self, make_session: mock.MagicMock) -> None:+ session = _session([_fields_response(3), _records_response([{"id": "1"}, {"id": "2"}])])+ make_session.return_value = session+ manager = FakeResumeManager()++ batches = list(get_rows(_client(), "v8", "Leads", manager, mock.MagicMock()))++ assert batches == [[{"id": "1"}, {"id": "2"}]]+ records_params = _get_params(session, 1)+ assert records_params["fields"] == "Field_0,Field_1,Field_2"+ assert records_params["per_page"] == str(PAGE_SIZE)+ assert records_params["page"] == "1"+ assert manager.saved == []+ assert manager.cleared is True++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_full_refresh_sorts_by_the_immutable_id(self, make_session: mock.MagicMock) -> None:+ session = _session([_fields_response(1), _records_response([{"id": "1"}])])+ make_session.return_value = session++ list(get_rows(_client(), "v8", "Leads", FakeResumeManager(), mock.MagicMock()))++ assert _get_params(session, 1)["sort_by"] == "id"+ assert _get_params(session, 1)["sort_order"] == "asc"+ assert "If-Modified-Since" not in _get_headers(session, 1)++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_incremental_sync_filters_and_sorts_on_the_cursor_field(self, make_session: mock.MagicMock) -> None:+ session = _session([_fields_response(1), _records_response([{"id": "1"}])])+ make_session.return_value = session++ list(+ get_rows(+ _client(),+ "v8",+ "Contacts",+ FakeResumeManager(),+ mock.MagicMock(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 6, 1, tzinfo=UTC),+ incremental_field="Modified_Time",+ )+ )++ assert _get_headers(session, 1)["If-Modified-Since"] == "2024-06-01T00:00:00+00:00"+ assert _get_params(session, 1)["sort_by"] == "Modified_Time"++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_paginates_by_page_then_by_token_and_checkpoints_each_page(self, make_session: mock.MagicMock) -> None:+ session = _session(+ [+ _fields_response(1),+ _records_response([{"id": "1"}], more_records=True),+ _records_response([{"id": "2"}], more_records=True, next_page_token="tok-2"),+ _records_response([{"id": "3"}], more_records=False),+ ]+ )+ make_session.return_value = session+ manager = FakeResumeManager()++ batches = list(get_rows(_client(), "v8", "Leads", manager, mock.MagicMock()))++ assert batches == [[{"id": "1"}], [{"id": "2"}], [{"id": "3"}]]+ assert _get_params(session, 2)["page"] == "2"+ assert "page_token" not in _get_params(session, 2)+ assert _get_params(session, 3)["page_token"] == "tok-2"+ assert "page" not in _get_params(session, 3)+ assert [(state.page, state.page_tokens) for state in manager.saved] == [(2, []), (3, ["tok-2"])]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_stops_when_the_api_reports_no_more_records(self, make_session: mock.MagicMock) -> None:+ session = _session([_fields_response(1), _records_response([{"id": "1"}], more_records=False)])+ make_session.return_value = session++ list(get_rows(_client(), "v8", "Leads", FakeResumeManager(), mock.MagicMock()))++ assert session.get.call_count == 2++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_empty_page_stops_pagination_even_when_more_records_is_set(self, make_session: mock.MagicMock) -> None:+ session = _session([_fields_response(1), _records_response([], more_records=True)])+ make_session.return_value = session++ assert list(get_rows(_client(), "v8", "Leads", FakeResumeManager(), mock.MagicMock())) == []+ assert session.get.call_count == 2++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_204_module_response_yields_nothing(self, make_session: mock.MagicMock) -> None:+ session = _session([_fields_response(1), _response(204)])+ make_session.return_value = session++ assert list(get_rows(_client(), "v8", "Leads", FakeResumeManager(), mock.MagicMock())) == []++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_stops_at_the_page_window_when_no_token_is_offered(self, make_session: mock.MagicMock) -> None:+ pages = [_records_response([{"id": str(page)}], more_records=True) for page in range(MAX_PAGE + 2)]+ session = _session([_fields_response(1), *pages])+ make_session.return_value = session+ logger = mock.MagicMock()++ batches = list(get_rows(_client(), "v8", "Leads", FakeResumeManager(), logger))++ assert len(batches) == MAX_PAGE+ logger.warning.assert_called_once()++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_wide_module_merges_its_field_slices_per_page(self, make_session: mock.MagicMock) -> None:+ session = _session(+ [+ _fields_response(MAX_FIELDS_PER_REQUEST + 2),+ _records_response([{"id": "1", "Field_0": "a"}, {"id": "2", "Field_0": "b"}]),+ _records_response([{"id": "1", "Field_50": "x"}, {"id": "2", "Field_50": "y"}]),+ ]+ )+ make_session.return_value = session++ batches = list(get_rows(_client(), "v8", "Leads", FakeResumeManager(), mock.MagicMock()))++ assert batches == [+ [+ {"id": "1", "Field_0": "a", "Field_50": "x"},+ {"id": "2", "Field_0": "b", "Field_50": "y"},+ ]+ ]+ assert len(_get_params(session, 1)["fields"].split(",")) == MAX_FIELDS_PER_REQUEST+ assert _get_params(session, 2)["fields"] == "Field_50,Field_51"++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_resumes_from_the_saved_page_token(self, make_session: mock.MagicMock) -> None:+ session = _session([_fields_response(1), _records_response([{"id": "9"}])])+ make_session.return_value = session+ manager = FakeResumeManager(ZohoCRMResumeConfig(page=12, page_tokens=["tok-11"]))++ batches = list(get_rows(_client(), "v8", "Leads", manager, mock.MagicMock()))++ assert batches == [[{"id": "9"}]]+ assert _get_params(session, 1)["page_token"] == "tok-11"++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_resumes_from_the_saved_page_number_within_the_window(self, make_session: mock.MagicMock) -> None:+ session = _session([_fields_response(1), _records_response([{"id": "9"}])])+ make_session.return_value = session+ manager = FakeResumeManager(ZohoCRMResumeConfig(page=3, page_tokens=[]))++ list(get_rows(_client(), "v8", "Leads", manager, mock.MagicMock()))++ assert _get_params(session, 1)["page"] == "3"++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_restarts_when_saved_tokens_no_longer_match_the_field_slices(self, make_session: mock.MagicMock) -> None:+ # Two slices now, but the checkpoint only carries one token — the tokens are unusable.+ session = _session(+ [+ _fields_response(MAX_FIELDS_PER_REQUEST + 1),+ _records_response([{"id": "1"}]),+ _records_response([{"id": "1"}]),+ ]+ )+ make_session.return_value = session+ manager = FakeResumeManager(ZohoCRMResumeConfig(page=25, page_tokens=["stale"]))++ list(get_rows(_client(), "v8", "Leads", manager, mock.MagicMock()))++ assert _get_params(session, 1)["page"] == "1"+ assert "page_token" not in _get_params(session, 1)++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_users_endpoint_skips_field_metadata_and_reads_its_own_envelope(self, make_session: mock.MagicMock) -> None:+ session = _session([_records_response([{"id": "u1"}], data_key="users")])+ make_session.return_value = session++ batches = list(get_rows(_client(), "v8", "Users", FakeResumeManager(), mock.MagicMock()))++ assert batches == [[{"id": "u1"}]]+ assert session.get.call_count == 1+ assert session.get.call_args_list[0].args[0] == "https://www.zohoapis.com/crm/v8/users"+ assert _get_params(session, 0)["type"] == "AllUsers"+ assert "sort_by" not in _get_params(session, 0)+ assert "fields" not in _get_params(session, 0)+++class TestValidateCredentials:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_valid_when_the_modules_probe_succeeds(self, make_session: mock.MagicMock) -> None:+ make_session.return_value = _session([_response(200, {"modules": []})])++ assert validate_credentials("us", "cid", "secret", "refresh") == (True, None)++ def test_unknown_region_is_rejected_without_a_request(self) -> None:+ is_valid, error = validate_credentials("mars", "cid", "secret", "refresh")++ assert is_valid is False+ assert error is not None and "mars" in error++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_refresh_token_rejection_surfaces_the_reason(self, make_session: mock.MagicMock) -> None:+ make_session.return_value = _session([], post_responses=[_response(200, {"error": "invalid_client"})])++ is_valid, error = validate_credentials("us", "cid", "secret", "refresh")++ assert is_valid is False+ assert error is not None and "invalid_client" in error++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_http_failure_is_not_valid(self, make_session: mock.MagicMock) -> None:+ forbidden = _response(403)+ forbidden.raise_for_status.side_effect = requests.HTTPError(+ "403 Client Error: Forbidden for url", response=mock.MagicMock()+ )+ make_session.return_value = _session([forbidden])++ assert validate_credentials("us", "cid", "secret", "refresh") == (False, None)+++class TestZohoCRMSourceResponse:+ @pytest.mark.parametrize("endpoint", sorted(ZOHO_CRM_ENDPOINTS))+ def test_response_shape_per_endpoint(self, endpoint: str) -> None:+ response = zoho_crm_source(+ region="us",+ client_id="cid",+ client_secret="secret",+ refresh_token="refresh",+ endpoint=endpoint,+ api_version="v8",+ resumable_source_manager=FakeResumeManager(),+ logger=mock.MagicMock(),+ )++ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ assert response.sort_mode == "asc"+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [ZOHO_CRM_ENDPOINTS[endpoint].partition_key]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_items_are_lazy_until_iterated(self, make_session: mock.MagicMock) -> None:+ session = _session([_fields_response(1), _records_response([{"id": "1"}])])+ make_session.return_value = session++ response = zoho_crm_source(+ region="us",+ client_id="cid",+ client_secret="secret",+ refresh_token="refresh",+ endpoint="Leads",+ api_version="v8",+ resumable_source_manager=FakeResumeManager(),+ logger=mock.MagicMock(),+ )++ assert session.get.call_count == 0+ assert list(cast("Iterable[Any]", response.items())) == [[{"id": "1"}]]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/tests/test_zoho_crm_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/tests/test_zoho_crm_source.pynew file mode 100644index 000000000000..f352d66fcba8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/tests/test_zoho_crm_source.py@@ -0,0 +1,225 @@+from typing import Any++import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.zohocrm import (+ ZohoCRMSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.zoho_crm.settings import (+ ENDPOINTS,+ ZOHO_CRM_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.zoho_crm.source import ZohoCRMSource+from products.warehouse_sources.backend.temporal.data_imports.sources.zoho_crm.zoho_crm import (+ ZOHO_REGIONS,+ ZohoCRMResumeConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType++_SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.zoho_crm.source"++INCREMENTAL_ENDPOINTS = sorted(name for name, config in ZOHO_CRM_ENDPOINTS.items() if config.incremental)+FULL_REFRESH_ENDPOINTS = sorted(name for name, config in ZOHO_CRM_ENDPOINTS.items() if not config.incremental)+++def _inputs(schema_name: str = "Leads", **overrides: Any) -> mock.MagicMock:+ defaults: dict[str, Any] = {+ "schema_name": schema_name,+ "schema_id": "schema-1",+ "source_id": "source-1",+ "team_id": 1,+ "should_use_incremental_field": False,+ "db_incremental_field_last_value": None,+ "db_incremental_field_earliest_value": None,+ "incremental_field": None,+ "incremental_field_type": None,+ "job_id": "job-1",+ "logger": mock.MagicMock(),+ "reset_pipeline": False,+ "api_version": None,+ }+ defaults.update(overrides)+ return mock.MagicMock(**defaults)+++class TestZohoCRMSource:+ def setup_method(self) -> None:+ self.source = ZohoCRMSource()+ self.team_id = 123+ self.config = ZohoCRMSourceConfig(region="eu", client_id="cid", client_secret="secret", refresh_token="refresh")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.ZOHOCRM++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config++ assert config.name.value == "ZohoCRM"+ assert config.label == "Zoho CRM"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert not config.unreleasedSource+ assert config.iconPath == "/static/services/zoho_crm.png"+ assert [field.name for field in config.fields] == ["region", "client_id", "client_secret", "refresh_token"]++ def test_region_options_cover_every_supported_data_center(self) -> None:+ region_field = next(field for field in self.source.get_source_config.fields if field.name == "region")++ assert isinstance(region_field, SourceFieldSelectConfig)+ assert region_field.defaultValue == "us"+ assert {option.value for option in region_field.options} == set(ZOHO_REGIONS)++ @pytest.mark.parametrize("field_name", ["client_secret", "refresh_token"])+ def test_credentials_are_required_secret_passwords(self, field_name: str) -> None:+ field = next(+ f+ for f in self.source.get_source_config.fields+ if isinstance(f, SourceFieldInputConfig) and f.name == field_name+ )++ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_api_version_is_pinned_to_what_the_transport_calls(self) -> None:+ assert self.source.supported_versions == ("v8",)+ assert self.source.default_version == "v8"+ assert self.source.api_docs_url.startswith("https://")++ @pytest.mark.parametrize(+ "observed_error",+ [+ "Zoho CRM token refresh failed: invalid_client",+ "400 Client Error: Bad Request for url: https://accounts.zoho.eu/oauth/v2/token",+ "401 Client Error: Unauthorized for url: https://www.zohoapis.com/crm/v8/Leads",+ "403 Client Error: Forbidden for url: https://www.zohoapis.com/crm/v8/Deals",+ ],+ )+ def test_auth_failures_are_non_retryable(self, observed_error: str) -> None:+ assert any(key in observed_error for key in self.source.get_non_retryable_errors())++ @pytest.mark.parametrize(+ "observed_error",+ [+ "500 Server Error for url: https://www.zohoapis.com/crm/v8/Leads",+ "429 Client Error: Too Many Requests for url: https://www.zohoapis.com/crm/v8/Leads",+ ],+ )+ def test_transient_failures_stay_retryable(self, observed_error: str) -> None:+ assert not any(key in observed_error for key in self.source.get_non_retryable_errors())++ def test_get_schemas_lists_every_module(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {schema.name for schema in schemas} == set(ENDPOINTS)++ @pytest.mark.parametrize("endpoint", INCREMENTAL_ENDPOINTS)+ def test_record_modules_advertise_the_modified_time_cursor(self, endpoint: str) -> None:+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)++ assert schema.supports_incremental is True+ assert [field["field"] for field in schema.incremental_fields] == ["Modified_Time"]++ @pytest.mark.parametrize("endpoint", FULL_REFRESH_ENDPOINTS)+ def test_endpoints_without_a_server_side_filter_are_full_refresh(self, endpoint: str) -> None:+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)++ assert schema.supports_incremental is False+ assert schema.incremental_fields == []++ def test_edition_dependent_modules_are_not_ticked_by_default(self) -> None:+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert schemas["Leads"].should_sync_default is True+ assert schemas["Cases"].should_sync_default is False+ assert schemas["Invoices"].should_sync_default is False++ def test_get_schemas_filters_by_name(self) -> None:+ assert [s.name for s in self.source.get_schemas(self.config, self.team_id, names=["Deals"])] == ["Deals"]++ def test_get_schemas_with_an_unknown_name_returns_nothing(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["Nope"]) == []++ def test_table_catalog_is_publishable_without_credentials(self) -> None:+ assert self.source.lists_tables_without_credentials is True++ def test_canonical_descriptions_cover_the_published_tables(self) -> None:+ descriptions = self.source.get_canonical_descriptions()++ assert set(descriptions) == set(ENDPOINTS)+ assert all("id" in (entry.get("columns") or {}) for entry in descriptions.values())++ @mock.patch(f"{_SOURCE_MODULE}.validate_zoho_crm_credentials")+ def test_validate_credentials_passes_the_resolved_version(self, mock_validate: mock.MagicMock) -> None:+ mock_validate.return_value = (True, None)++ assert self.source.validate_credentials(self.config, self.team_id) == (True, None)+ assert mock_validate.call_args.kwargs == {+ "region": "eu",+ "client_id": "cid",+ "client_secret": "secret",+ "refresh_token": "refresh",+ "api_version": "v8",+ }++ @pytest.mark.parametrize(+ "probe_result, expected",+ [+ ((False, "Zoho CRM token refresh failed: invalid_client"), "Zoho CRM token refresh failed: invalid_client"),+ ((False, None), "Invalid Zoho CRM credentials"),+ ],+ )+ @mock.patch(f"{_SOURCE_MODULE}.validate_zoho_crm_credentials")+ def test_validate_credentials_surfaces_a_reason(+ self, mock_validate: mock.MagicMock, probe_result: tuple[bool, str | None], expected: str+ ) -> None:+ mock_validate.return_value = probe_result++ assert self.source.validate_credentials(self.config, self.team_id) == (False, expected)++ def test_resumable_manager_is_namespaced_per_schema(self) -> None:+ manager = self.source.get_resumable_source_manager(_inputs("Contacts"))++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is ZohoCRMResumeConfig+ assert manager._namespace == "Contacts"++ @mock.patch(f"{_SOURCE_MODULE}.zoho_crm_source")+ def test_source_for_pipeline_plumbs_the_incremental_cursor(self, mock_source: mock.MagicMock) -> None:+ manager = mock.MagicMock()+ inputs = _inputs(+ "Deals",+ should_use_incremental_field=True,+ db_incremental_field_last_value="2024-06-01T00:00:00+00:00",+ incremental_field="Modified_Time",+ )++ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_source.call_args.kwargs+ assert kwargs["region"] == "eu"+ assert kwargs["endpoint"] == "Deals"+ assert kwargs["api_version"] == "v8"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2024-06-01T00:00:00+00:00"+ assert kwargs["incremental_field"] == "Modified_Time"++ @mock.patch(f"{_SOURCE_MODULE}.zoho_crm_source")+ def test_full_refresh_never_forwards_a_stale_watermark(self, mock_source: mock.MagicMock) -> None:+ inputs = _inputs(+ "Leads", should_use_incremental_field=False, db_incremental_field_last_value="2024-06-01T00:00:00+00:00"+ )++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None++ @mock.patch(f"{_SOURCE_MODULE}.zoho_crm_source")+ def test_source_for_pipeline_honors_a_stored_version_pin(self, mock_source: mock.MagicMock) -> None:+ self.source.source_for_pipeline(self.config, mock.MagicMock(), _inputs("Leads", api_version="v7"))++ assert mock_source.call_args.kwargs["api_version"] == "v7"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/zoho_crm.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/zoho_crm.pynew file mode 100644index 000000000000..21c601b1bd0d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zoho_crm/zoho_crm.py@@ -0,0 +1,366 @@+import dataclasses+from collections.abc import Iterator+from typing import Any, Optional++import requests+from structlog.types import FilteringBoundLogger++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import (+ coerce_datetime_to_utc,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.zoho_crm.settings import (+ MODIFIED_TIME_FIELD,+ ZOHO_CRM_ENDPOINTS,+ ZohoCRMEndpointConfig,+)++DEFAULT_API_VERSION = "v8"++# Zoho accounts are pinned to one data center; the accounts host mints the token and the+# API host serves the records. The token response also names the account's real API domain,+# which wins over this mapping when present.+ZOHO_REGIONS: dict[str, tuple[str, str]] = {+ "us": ("https://accounts.zoho.com", "https://www.zohoapis.com"),+ "eu": ("https://accounts.zoho.eu", "https://www.zohoapis.eu"),+ "in": ("https://accounts.zoho.in", "https://www.zohoapis.in"),+ "au": ("https://accounts.zoho.com.au", "https://www.zohoapis.com.au"),+ "jp": ("https://accounts.zoho.jp", "https://www.zohoapis.jp"),+ "ca": ("https://accounts.zohocloud.ca", "https://www.zohoapis.ca"),+ "cn": ("https://accounts.zoho.com.cn", "https://www.zohoapis.com.cn"),+}++# Zoho caps `per_page` at 200.+PAGE_SIZE = 200+# `page`-based pagination stops at 2000 records (page * per_page); past that Zoho only+# serves further records through the response's `next_page_token`.+MAX_PAGE = 2000 // PAGE_SIZE+# Get Records accepts a bounded list of field API names, so wide modules are fetched as+# several field slices walked in lockstep and merged per page.+MAX_FIELDS_PER_REQUEST = 50+REQUEST_TIMEOUT_SECONDS = 60+++class ZohoCRMAuthError(Exception):+ pass+++class ZohoCRMResumeConfig:+ # 1-based page number for the `page` pagination window.+ page: int = 1+ # One `next_page_token` per field slice, in slice order. Empty until Zoho starts+ # returning tokens (i.e. once the page window is exhausted).+ page_tokens: list[str] = dataclasses.field(default_factory=list)+++def resolve_hosts(region: str) -> tuple[str, str]:+ hosts = ZOHO_REGIONS.get(region)+ if hosts is None:+ raise ValueError(f"Invalid Zoho CRM region: {region}")+ return hosts+++def format_modified_since(value: Any) -> str:+ """Format an incremental cursor as the ISO 8601 timestamp `If-Modified-Since` expects."""+ parsed = coerce_datetime_to_utc(value)+ if parsed is None:+ return str(value)+ return parsed.strftime("%Y-%m-%dT%H:%M:%S+00:00")+++def chunk_fields(names: list[str], size: int = MAX_FIELDS_PER_REQUEST) -> list[list[str]]:+ """Split field API names into request-sized slices. An empty list means "no projection"."""+ if not names:+ return [[]]+ return [names[index : index + size] for index in range(0, len(names), size)]+++class ZohoCRMClient:+ """Minimal Zoho CRM client: refresh-token auth, regional hosts, JSON GETs.++ Status-code retries (429/5xx) come from the tracked session, so nothing retries here.+ """++ def __init__(+ self,+ region: str,+ client_id: str,+ client_secret: str,+ refresh_token: str,+ ) -> None:+ self._accounts_host, self._api_domain = resolve_hosts(region)+ self._client_id = client_id+ self._client_secret = client_secret+ self._refresh_token = refresh_token+ # capture=False keeps requests metered and logged but excludes them from HTTP sample+ # capture: Zoho responses carry raw CRM records (contacts, notes, emails, phone numbers,+ # free-text) and the token exchange returns the access token in a bare `access_token`+ # field — content the name-based scrubbers can't reliably redact.+ self._session = make_tracked_session(redact_values=(client_secret, refresh_token), capture=False)+ self._access_token: Optional[str] = None++ @property+ def api_domain(self) -> str:+ return self._api_domain++ def mint_access_token(self) -> str:+ response = self._session.post(+ f"{self._accounts_host}/oauth/v2/token",+ data={+ "grant_type": "refresh_token",+ "refresh_token": self._refresh_token,+ "client_id": self._client_id,+ "client_secret": self._client_secret,+ },+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ response.raise_for_status()+ body = response.json()++ access_token = body.get("access_token")+ if not access_token:+ # Zoho answers a revoked or malformed refresh token with HTTP 200 and an `error` key.+ raise ZohoCRMAuthError(f"Zoho CRM token refresh failed: {body.get('error') or 'no access token returned'}")++ api_domain = body.get("api_domain")+ if api_domain:+ # The token response names the data center that actually owns this account.+ self._api_domain = str(api_domain).rstrip("/")++ self._access_token = str(access_token)+ return self._access_token++ def get(+ self,+ path: str,+ params: Optional[dict[str, str]] = None,+ headers: Optional[dict[str, str]] = None,+ ) -> requests.Response:+ if self._access_token is None:+ self.mint_access_token()++ def _send() -> requests.Response:+ request_headers = {"Authorization": f"Zoho-oauthtoken {self._access_token}"}+ if headers:+ request_headers.update(headers)+ return self._session.get(+ f"{self._api_domain}{path}",+ params=params,+ headers=request_headers,+ timeout=REQUEST_TIMEOUT_SECONDS,+ )++ response = _send()+ if response.status_code == 401:+ # Access tokens last an hour; a long sync outlives one.+ self.mint_access_token()+ response = _send()++ # 204 is Zoho's "nothing matched" — an empty body, not an error.+ if response.status_code != 204:+ response.raise_for_status()+ return response+++def readable_field_names(client: ZohoCRMClient, api_version: str, module: str) -> list[str]:+ """Field API names Get Records can project for `module`, from the fields metadata API."""+ response = client.get(f"/crm/{api_version}/settings/fields", params={"module": module})+ if response.status_code == 204:+ return []++ names: list[str] = []+ for field in response.json().get("fields") or []:+ api_name = field.get("api_name")+ if not api_name:+ continue+ view_type = field.get("view_type")+ # `view_type.view` marks the fields Zoho will actually return on a read.+ if isinstance(view_type, dict) and view_type.get("view") is False:+ continue+ names.append(str(api_name))+ return names+++def _fetch_page(+ client: ZohoCRMClient,+ api_version: str,+ config: ZohoCRMEndpointConfig,+ params: dict[str, str],+ headers: dict[str, str],+) -> tuple[list[dict[str, Any]], dict[str, Any]]:+ response = client.get(f"/crm/{api_version}/{config.path}", params=params, headers=headers)+ if response.status_code == 204:+ return [], {}++ body = response.json()+ return list(body.get(config.data_key) or []), dict(body.get("info") or {})+++def _merge_slice(rows: dict[str, dict[str, Any]], order: list[str], records: list[dict[str, Any]]) -> None:+ """Fold one field slice's records into the page under construction, keyed by record id."""+ for position, record in enumerate(records):+ record_id = record.get("id")+ key = str(record_id) if record_id is not None else f"__position_{position}"+ if key not in rows:+ rows[key] = {}+ order.append(key)+ rows[key].update(record)+++def _sort_params(+ config: ZohoCRMEndpointConfig,+ should_use_incremental_field: bool,+ incremental_field: Optional[str],+) -> dict[str, str]:+ if not config.is_module:+ return {}+ # Ascending order on the cursor field keeps the pipeline's watermark monotonic. Full+ # refreshes sort by the immutable id so page boundaries don't shift mid-sync.+ if config.incremental and should_use_incremental_field:+ return {"sort_by": incremental_field or MODIFIED_TIME_FIELD, "sort_order": "asc"}+ return {"sort_by": "id", "sort_order": "asc"}+++def get_rows(+ client: ZohoCRMClient,+ api_version: str,+ endpoint: str,+ resumable_source_manager: ResumableSourceManager[ZohoCRMResumeConfig],+ logger: FilteringBoundLogger,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: Optional[str] = None,+) -> Iterator[list[dict[str, Any]]]:+ config = ZOHO_CRM_ENDPOINTS[endpoint]++ headers: dict[str, str] = {}+ if config.incremental and should_use_incremental_field and db_incremental_field_last_value is not None:+ headers["If-Modified-Since"] = format_modified_since(db_incremental_field_last_value)++ base_params: dict[str, str] = {"per_page": str(PAGE_SIZE)}+ base_params.update(config.extra_params or {})+ base_params.update(_sort_params(config, should_use_incremental_field, incremental_field))++ field_slices: list[list[str]] = [[]]+ if config.is_module:+ field_slices = chunk_fields(readable_field_names(client, api_version, config.path))++ page = 1+ page_tokens: list[str] = []+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None:+ page = max(resume.page, 1)+ # Page tokens encode the exact query that produced them, so a changed slice count+ # (a field added or removed since the checkpoint) invalidates them.+ if len(resume.page_tokens) == len(field_slices) and all(resume.page_tokens):+ page_tokens = list(resume.page_tokens)+ elif page > MAX_PAGE:+ # Past the page window with no usable token there is no way back in — restart.+ page = 1++ while True:+ rows: dict[str, dict[str, Any]] = {}+ order: list[str] = []+ info: dict[str, Any] = {}+ next_tokens: list[str] = []++ for index, fields in enumerate(field_slices):+ params = dict(base_params)+ if fields:+ params["fields"] = ",".join(fields)+ token = page_tokens[index] if index < len(page_tokens) else ""+ if token:+ params["page_token"] = token+ else:+ params["page"] = str(page)++ records, slice_info = _fetch_page(client, api_version, config, params, headers)+ if index == 0:+ info = slice_info+ _merge_slice(rows, order, records)+ next_tokens.append(str(slice_info.get("next_page_token") or ""))++ page_rows = [rows[key] for key in order]+ if page_rows:+ yield page_rows++ if not page_rows or not info.get("more_records"):+ break++ page += 1+ # A token is only usable when every slice got one — a half-tokenized page would walk+ # the slices to different offsets and merge unrelated records.+ page_tokens = next_tokens if all(next_tokens) else []+ if not page_tokens and page > MAX_PAGE:+ logger.warning(+ "Zoho CRM stopped paginating at the 2000-record page limit without a next page token",+ endpoint=endpoint,+ page=page,+ )+ break++ resumable_source_manager.save_state(ZohoCRMResumeConfig(page=page, page_tokens=page_tokens))++ resumable_source_manager.clear_state()+++def validate_credentials(+ region: str,+ client_id: str,+ client_secret: str,+ refresh_token: str,+ api_version: str = DEFAULT_API_VERSION,+) -> tuple[bool, Optional[str]]:+ try:+ client = ZohoCRMClient(region, client_id, client_secret, refresh_token)+ except ValueError as e:+ return False, str(e)++ try:+ client.get(f"/crm/{api_version}/settings/modules")+ except ZohoCRMAuthError as e:+ return False, str(e)+ except Exception:+ return False, None+ return True, None+++def zoho_crm_source(+ region: str,+ client_id: str,+ client_secret: str,+ refresh_token: str,+ endpoint: str,+ api_version: str,+ resumable_source_manager: ResumableSourceManager[ZohoCRMResumeConfig],+ logger: FilteringBoundLogger,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: Optional[str] = None,+) -> SourceResponse:+ config = ZOHO_CRM_ENDPOINTS[endpoint]++ def items() -> Iterator[list[dict[str, Any]]]:+ return get_rows(+ client=ZohoCRMClient(region, client_id, client_secret, refresh_token),+ api_version=api_version,+ endpoint=endpoint,+ resumable_source_manager=resumable_source_manager,+ logger=logger,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ incremental_field=incremental_field,+ )++ return SourceResponse(+ name=endpoint,+ items=items,+ primary_keys=["id"],+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ sort_mode="asc",+ )