Skip to content

: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.

feat(data-warehouse): implement dynamics_365_business_central source (#73764)

Tom Owers56385b66a6d9
diff --git a/frontend/public/services/dynamics_365_business_central.png b/frontend/public/services/dynamics_365_business_central.png
index 198166f8fedc..d04883e8db2f 100644
Binary files a/frontend/public/services/dynamics_365_business_central.png and b/frontend/public/services/dynamics_365_business_central.png differ
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 439734371153..78f18e79cf1f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -248,6 +248,7 @@ the row lists both.
| drip | HTTP | requests | ✅ |
| dub | HTTP | requests + `rest_source.RESTClient` | ✅ |
| dynamics365 | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| dynamics_365_business_central | HTTP | requests + `rest_source.RESTClient` | ✅ |
| dynamodb | HTTP | requests | ✅ |
| dynatrace | HTTP | requests | ✅ |
| e2b | HTTP | requests | ✅ |
@@ -985,7 +986,6 @@ doesn't conflict with concurrent PRs.
- dubsado
- ducklake
- dwolla
-- dynamics_365_business_central
- e2b
- ebay
- eloqua
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dynamics_365_business_central/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dynamics_365_business_central/canonical_descriptions.py
new file mode 100644
index 000000000000..9f30d9bf19ea
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dynamics_365_business_central/canonical_descriptions.py
@@ -0,0 +1,461 @@
+"""Canonical, documentation-sourced descriptions for Dynamics 365 Business Central entities.
+
+Sourced from the official Business Central API (v2.0) reference on learn.microsoft.com. Keyed by the
+entity-set names in `settings.py` `BUSINESS_CENTRAL_ENDPOINTS`, which match the
+`ExternalDataSchema.name` of a synced table. Columns absent here fall back to LLM enrichment.
+
+`company_id` / `company_name` are not API fields: this source fans out over the environment's
+companies and stamps the parent company onto every child row so the primary key stays unique.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_API_REFERENCE = "https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/api-reference/v2.0"
+
+_COMPANY_COLUMNS = {
+ "company_id": "ID of the Business Central company this row was synced from (added by PostHog).",
+ "company_name": "Name of the Business Central company this row was synced from (added by PostHog).",
+}
+
+_DOCUMENT_LINE_COLUMNS = {
+ **_COMPANY_COLUMNS,
+ "id": "System ID of the document line.",
+ "documentId": "System ID of the document this line belongs to.",
+ "sequence": "Position of the line within its document.",
+ "lineType": "What the line represents: Comment, Account, Item, Resource, Fixed Asset or Charge.",
+ "lineObjectNumber": "Number of the item, account or resource the line posts to.",
+ "description": "Line description shown on the printed document.",
+ "unitOfMeasureCode": "Code of the unit of measure the quantity is expressed in.",
+ "quantity": "Number of units on the line.",
+ "discountAmount": "Discount applied to the line, in the document currency.",
+ "discountPercent": "Discount applied to the line, as a percentage.",
+ "netAmount": "Line amount excluding tax after discounts.",
+ "netTaxAmount": "Tax calculated on the line's net amount.",
+ "netAmountIncludingTax": "Line amount including tax after discounts.",
+ "itemId": "System ID of the item on the line, when the line is an item line.",
+ "accountId": "System ID of the G/L account on the line, when the line is an account line.",
+}
+
+_DOCUMENT_HEADER_COLUMNS = {
+ **_COMPANY_COLUMNS,
+ "id": "System ID of the document.",
+ "number": "Document number as shown in Business Central.",
+ "externalDocumentNumber": "Reference number supplied by the customer or vendor.",
+ "postingDate": "Date the document was or will be posted to the general ledger.",
+ "dueDate": "Date payment is due.",
+ "currencyCode": "Three-letter currency code the document is denominated in.",
+ "currencyId": "System ID of the document's currency.",
+ "pricesIncludeTax": "Whether the line prices already include tax.",
+ "discountAmount": "Invoice-level discount, in the document currency.",
+ "totalAmountExcludingTax": "Document total before tax.",
+ "totalTaxAmount": "Total tax on the document.",
+ "totalAmountIncludingTax": "Document total including tax.",
+ "status": "Workflow state of the document (for example Draft, Open, Paid, Canceled).",
+ "lastModifiedDateTime": "When the record was last changed. Used as the incremental sync cursor.",
+}
+
+_CUSTOMER_DOCUMENT_COLUMNS = {
+ **_DOCUMENT_HEADER_COLUMNS,
+ "customerId": "System ID of the customer the document is for.",
+ "customerNumber": "Customer number as shown in Business Central.",
+ "customerName": "Customer name captured on the document.",
+ "salesperson": "Code of the salesperson credited with the document.",
+}
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "companies": {
+ "description": "A company (legal entity with its own books) inside a Business Central environment.",
+ "docs_url": f"{_API_REFERENCE}/resources/dynamics_company",
+ "columns": {
+ "id": "System ID of the company. Every other table references it as company_id.",
+ "systemVersion": "Business Central platform version the company runs on.",
+ "timeZone": "Time zone configured for the company.",
+ "name": "Technical name of the company, used in API URLs.",
+ "displayName": "Human-readable company name.",
+ "businessProfileId": "Identifier of the linked business profile, when one exists.",
+ },
+ },
+ "accounts": {
+ "description": "A general ledger account from the company's chart of accounts.",
+ "docs_url": f"{_API_REFERENCE}/resources/dynamics_account",
+ "columns": {
+ **_COMPANY_COLUMNS,
+ "id": "System ID of the G/L account.",
+ "number": "Account number in the chart of accounts.",
+ "displayName": "Account name.",
+ "category": "Top-level account category (Assets, Liabilities, Income, Expense, Equity).",
+ "subCategory": "Account sub-category used for financial statement grouping.",
+ "accountType": "Whether the account is a Posting account or a structural Heading/Total row.",
+ "blocked": "Whether posting to the account is blocked.",
+ "directPosting": "Whether entries can be posted straight to the account from journals.",
+ "netChange": "Net change on the account for the current fiscal period.",
+ "lastModifiedDateTime": "When the record was last changed. Used as the incremental sync cursor.",
+ },
+ },
+ "customers": {
+ "description": "A customer the company sells to, with its balance and default posting setup.",
+ "docs_url": f"{_API_REFERENCE}/resources/dynamics_customer",
+ "columns": {
+ **_COMPANY_COLUMNS,
+ "id": "System ID of the customer.",
+ "number": "Customer number as shown in Business Central.",
+ "displayName": "Customer name.",
+ "type": "Whether the customer is a Company or a Person.",
+ "email": "Primary email address on the customer card.",
+ "phoneNumber": "Primary phone number on the customer card.",
+ "website": "Customer website.",
+ "currencyCode": "Default currency the customer is invoiced in.",
+ "paymentTermsId": "System ID of the customer's default payment terms.",
+ "paymentMethodId": "System ID of the customer's default payment method.",
+ "shipmentMethodId": "System ID of the customer's default shipment method.",
+ "taxLiable": "Whether the customer is liable for tax.",
+ "taxRegistrationNumber": "Customer's VAT or tax registration number.",
+ "blocked": "Whether the customer is blocked for shipping, invoicing or all activity.",
+ "balance": "Outstanding receivable balance, in the company's local currency.",
+ "overdueAmount": "Portion of the balance that is past due.",
+ "totalSalesExcludingTax": "Lifetime sales to the customer, excluding tax.",
+ "lastModifiedDateTime": "When the record was last changed. Used as the incremental sync cursor.",
+ },
+ },
+ "vendors": {
+ "description": "A vendor the company buys from, with its payable balance and posting setup.",
+ "docs_url": f"{_API_REFERENCE}/resources/dynamics_vendor",
+ "columns": {
+ **_COMPANY_COLUMNS,
+ "id": "System ID of the vendor.",
+ "number": "Vendor number as shown in Business Central.",
+ "displayName": "Vendor name.",
+ "email": "Primary email address on the vendor card.",
+ "phoneNumber": "Primary phone number on the vendor card.",
+ "currencyCode": "Default currency the vendor invoices in.",
+ "paymentTermsId": "System ID of the vendor's default payment terms.",
+ "paymentMethodId": "System ID of the vendor's default payment method.",
+ "taxLiable": "Whether the vendor is liable for tax.",
+ "blocked": "Whether the vendor is blocked for payment or all activity.",
+ "balance": "Outstanding payable balance, in the company's local currency.",
+ "lastModifiedDateTime": "When the record was last changed. Used as the incremental sync cursor.",
+ },
+ },
+ "items": {
+ "description": "An inventory or service item the company sells, with cost, price and stock level.",
+ "docs_url": f"{_API_REFERENCE}/resources/dynamics_item",
+ "columns": {
+ **_COMPANY_COLUMNS,
+ "id": "System ID of the item.",
+ "number": "Item number as shown in Business Central.",
+ "displayName": "Item description.",
+ "type": "Whether the item is Inventory, Service or Non-Inventory.",
+ "itemCategoryId": "System ID of the item's category.",
+ "itemCategoryCode": "Code of the item's category.",
+ "blocked": "Whether the item is blocked from being sold or purchased.",
+ "gtin": "Global Trade Item Number (barcode) for the item.",
+ "inventory": "Quantity currently on hand across all locations.",
+ "unitPrice": "Default sales price per base unit of measure.",
+ "unitCost": "Current unit cost used for inventory valuation.",
+ "priceIncludesTax": "Whether the unit price already includes tax.",
+ "baseUnitOfMeasureCode": "Code of the item's base unit of measure.",
+ "generalProductPostingGroupCode": "Product posting group that drives the item's G/L accounts.",
+ "inventoryPostingGroupCode": "Inventory posting group that drives the item's inventory accounts.",
+ "lastModifiedDateTime": "When the record was last changed. Used as the incremental sync cursor.",
+ },
+ },
+ "itemCategories": {
+ "description": "A category used to group items in the item list.",
+ "docs_url": f"{_API_REFERENCE}/resources/dynamics_itemcategory",
+ "columns": {
+ **_COMPANY_COLUMNS,
+ "id": "System ID of the item category.",
+ "code": "Item category code.",
+ "displayName": "Item category name.",
+ "lastModifiedDateTime": "When the record was last changed. Used as the incremental sync cursor.",
+ },
+ },
+ "employees": {
+ "description": "An employee registered in the company, used for time and expense posting.",
+ "docs_url": f"{_API_REFERENCE}/resources/dynamics_employee",
+ "columns": {
+ **_COMPANY_COLUMNS,
+ "id": "System ID of the employee.",
+ "number": "Employee number as shown in Business Central.",
+ "displayName": "Employee's full name.",
+ "givenName": "Employee's first name.",
+ "surname": "Employee's last name.",
+ "jobTitle": "Employee's job title.",
+ "email": "Work email address.",
+ "personalEmail": "Personal email address.",
+ "phoneNumber": "Work phone number.",
+ "employmentDate": "Date the employee was hired.",
+ "terminationDate": "Date the employment ended, when applicable.",
+ "status": "Employment status (for example Active, Inactive, Terminated).",
+ "lastModifiedDateTime": "When the record was last changed. Used as the incremental sync cursor.",
+ },
+ },
+ "bankAccounts": {
+ "description": "A bank account the company reconciles payments against.",
+ "docs_url": f"{_API_REFERENCE}/resources/dynamics_bankaccount",
+ "columns": {
+ **_COMPANY_COLUMNS,
+ "id": "System ID of the bank account.",
+ "number": "Bank account number as shown in Business Central.",
+ "displayName": "Bank account name.",
+ "bankAccountNumber": "Account number at the bank.",
+ "iban": "International Bank Account Number.",
+ "currencyCode": "Currency the bank account is held in.",
+ "blocked": "Whether the bank account is blocked for posting.",
+ "lastModifiedDateTime": "When the record was last changed. Used as the incremental sync cursor.",
+ },
+ },
+ "currencies": {
+ "description": "A currency the company can transact in, with its rounding rules.",
+ "docs_url": f"{_API_REFERENCE}/resources/dynamics_currency",
+ "columns": {
+ **_COMPANY_COLUMNS,
+ "id": "System ID of the currency.",
+ "code": "Three-letter currency code.",
+ "displayName": "Currency name.",
+ "symbol": "Symbol used when displaying amounts.",
+ "amountDecimalPlaces": "Number of decimal places amounts are shown with.",
+ "amountRoundingPrecision": "Precision amounts are rounded to.",
+ "lastModifiedDateTime": "When the record was last changed. Used as the incremental sync cursor.",
+ },
+ },
+ "paymentTerms": {
+ "description": "A set of payment terms controlling due dates and early-payment discounts.",
+ "docs_url": f"{_API_REFERENCE}/resources/dynamics_paymentterm",
+ "columns": {
+ **_COMPANY_COLUMNS,
+ "id": "System ID of the payment terms.",
+ "code": "Payment terms code.",
+ "displayName": "Payment terms description.",
+ "dueDateCalculation": "Date formula used to calculate the due date.",
+ "discountDateCalculation": "Date formula used to calculate the discount deadline.",
+ "discountPercent": "Early-payment discount percentage.",
+ "calculateDiscountOnCreditMemos": "Whether the discount also applies to credit memos.",
+ "lastModifiedDateTime": "When the record was last changed. Used as the incremental sync cursor.",
+ },
+ },
+ "paymentMethods": {
+ "description": "A payment method that can be set on customers, vendors and documents.",
+ "docs_url": f"{_API_REFERENCE}/resources/dynamics_paymentmethod",
+ "columns": {
+ **_COMPANY_COLUMNS,
+ "id": "System ID of the payment method.",
+ "code": "Payment method code.",
+ "displayName": "Payment method description.",
+ "lastModifiedDateTime": "When the record was last changed. Used as the incremental sync cursor.",
+ },
+ },
+ "shipmentMethods": {
+ "description": "A shipment method (delivery terms) that can be set on customers and documents.",
+ "docs_url": f"{_API_REFERENCE}/resources/dynamics_shipmentmethod",
+ "columns": {
+ **_COMPANY_COLUMNS,
+ "id": "System ID of the shipment method.",
+ "code": "Shipment method code.",
+ "displayName": "Shipment method description.",
+ "lastModifiedDateTime": "When the record was last changed. Used as the incremental sync cursor.",
+ },
+ },
+ "unitsOfMeasure": {
+ "description": "A unit of measure items can be counted, sold and purchased in.",
+ "docs_url": f"{_API_REFERENCE}/resources/dynamics_unitofmeasure",
+ "columns": {
+ **_COMPANY_COLUMNS,
+ "id": "System ID of the unit of measure.",
+ "code": "Unit of measure code.",
+ "displayName": "Unit of measure description.",
+ "internationalStandardCode": "UNECE standard code for the unit.",
+ "symbol": "Symbol used when displaying the unit.",
+ "lastModifiedDateTime": "When the record was last changed. Used as the incremental sync cursor.",
+ },
+ },
+ "locations": {
+ "description": "A warehouse or site inventory can be stored at and shipped from.",
+ "docs_url": f"{_API_REFERENCE}/resources/dynamics_location",
+ "columns": {
+ **_COMPANY_COLUMNS,
+ "id": "System ID of the location.",
+ "code": "Location code.",
+ "displayName": "Location name.",
+ "contact": "Contact person at the location.",
+ "addressLine1": "First line of the location's address.",
+ "city": "City the location is in.",
+ "country": "Country/region code of the location.",
+ "postalCode": "Postal code of the location.",
+ },
+ },
+ "dimensions": {
+ "description": "An analysis dimension (for example Department or Project) used to tag ledger entries.",
+ "docs_url": f"{_API_REFERENCE}/resources/dynamics_dimension",
+ "columns": {
+ **_COMPANY_COLUMNS,
+ "id": "System ID of the dimension.",
+ "code": "Dimension code.",
+ "displayName": "Dimension name.",
+ "lastModifiedDateTime": "When the record was last changed. Used as the incremental sync cursor.",
+ },
+ },
+ "dimensionValues": {
+ "description": "One allowed value of an analysis dimension.",
+ "docs_url": f"{_API_REFERENCE}/resources/dynamics_dimensionvalue",
+ "columns": {
+ **_COMPANY_COLUMNS,
+ "id": "System ID of the dimension value.",
+ "code": "Dimension value code.",
+ "dimensionId": "System ID of the dimension this value belongs to.",
+ "displayName": "Dimension value name.",
+ "lastModifiedDateTime": "When the record was last changed. Used as the incremental sync cursor.",
+ },
+ },
+ "salesInvoices": {
+ "description": "A sales invoice header, draft or posted, with its totals and customer.",
+ "docs_url": f"{_API_REFERENCE}/resources/dynamics_salesinvoice",
+ "columns": {
+ **_CUSTOMER_DOCUMENT_COLUMNS,
+ "invoiceDate": "Date the invoice was issued.",
+ "orderNumber": "Number of the sales order the invoice was created from.",
+ "remainingAmount": "Amount still outstanding on the invoice.",
+ },
+ },
+ "salesInvoiceLines": {
+ "description": "A line on a sales invoice: the item, resource or account being invoiced.",
+ "docs_url": f"{_API_REFERENCE}/resources/dynamics_salesinvoiceline",
+ "columns": {
+ **_DOCUMENT_LINE_COLUMNS,
+ "unitPrice": "Sales price per unit on the line.",
+ "amountExcludingTax": "Line amount before tax.",
+ "amountIncludingTax": "Line amount including tax.",
+ "taxPercent": "Tax rate applied to the line.",
+ "totalTaxAmount": "Tax amount on the line.",
+ "shipmentDate": "Date the line is expected to ship.",
+ },
+ },
+ "salesOrders": {
+ "description": "A sales order header, with its customer, totals and fulfilment status.",
+ "docs_url": f"{_API_REFERENCE}/resources/dynamics_salesorder",
+ "columns": {
+ **_CUSTOMER_DOCUMENT_COLUMNS,
+ "orderDate": "Date the order was placed.",
+ "requestedDeliveryDate": "Delivery date requested by the customer.",
+ "partialShipping": "Whether the order may ship in more than one shipment.",
+ "fullyShipped": "Whether every line on the order has shipped.",
+ },
+ },
+ "salesOrderLines": {
+ "description": "A line on a sales order: what is ordered, at what price, and how much has shipped.",
+ "docs_url": f"{_API_REFERENCE}/resources/dynamics_salesorderline",
+ "columns": {
+ **_DOCUMENT_LINE_COLUMNS,
+ "unitPrice": "Sales price per unit on the line.",
+ "amountExcludingTax": "Line amount before tax.",
+ "amountIncludingTax": "Line amount including tax.",
+ "shipmentDate": "Date the line is expected to ship.",
+ "shippedQuantity": "Quantity already shipped.",
+ "invoicedQuantity": "Quantity already invoiced.",
+ },
+ },
+ "salesQuotes": {
+ "description": "A sales quote header offered to a customer or contact.",
+ "docs_url": f"{_API_REFERENCE}/resources/dynamics_salesquote",
+ "columns": {
+ **_CUSTOMER_DOCUMENT_COLUMNS,
+ "documentDate": "Date the quote was created.",
+ "validUntilDate": "Last date the quote is valid.",
+ "acceptedDate": "Date the customer accepted the quote.",
+ },
+ },
+ "salesQuoteLines": {
+ "description": "A line on a sales quote: what is being offered, at what price.",
+ "docs_url": f"{_API_REFERENCE}/resources/dynamics_salesquoteline",
+ "columns": {
+ **_DOCUMENT_LINE_COLUMNS,
+ "unitPrice": "Quoted price per unit on the line.",
+ "amountExcludingTax": "Line amount before tax.",
+ "amountIncludingTax": "Line amount including tax.",
+ },
+ },
+ "salesCreditMemos": {
+ "description": "A sales credit memo header crediting a customer for returned or over-invoiced goods.",
+ "docs_url": f"{_API_REFERENCE}/resources/dynamics_salescreditmemo",
+ "columns": {
+ **_CUSTOMER_DOCUMENT_COLUMNS,
+ "creditMemoDate": "Date the credit memo was issued.",
+ "invoiceId": "System ID of the invoice the credit memo corrects, when linked.",
+ "invoiceNumber": "Number of the invoice the credit memo corrects, when linked.",
+ },
+ },
+ "salesCreditMemoLines": {
+ "description": "A line on a sales credit memo: what is being credited back to the customer.",
+ "docs_url": f"{_API_REFERENCE}/resources/dynamics_salescreditmemoline",
+ "columns": {
+ **_DOCUMENT_LINE_COLUMNS,
+ "unitPrice": "Credited price per unit on the line.",
+ "amountExcludingTax": "Line amount before tax.",
+ "amountIncludingTax": "Line amount including tax.",
+ },
+ },
+ "purchaseInvoices": {
+ "description": "A purchase invoice header received from a vendor, with its totals.",
+ "docs_url": f"{_API_REFERENCE}/resources/dynamics_purchaseinvoice",
+ "columns": {
+ **_DOCUMENT_HEADER_COLUMNS,
+ "invoiceDate": "Date the vendor issued the invoice.",
+ "vendorId": "System ID of the vendor the invoice came from.",
+ "vendorNumber": "Vendor number as shown in Business Central.",
+ "vendorName": "Vendor name captured on the invoice.",
+ "vendorInvoiceNumber": "The vendor's own invoice number.",
+ "payToVendorId": "System ID of the vendor the payment is made to, when different.",
+ },
+ },
+ "purchaseInvoiceLines": {
+ "description": "A line on a purchase invoice: the item, resource or account being purchased.",
+ "docs_url": f"{_API_REFERENCE}/resources/dynamics_purchaseinvoiceline",
+ "columns": {
+ **_DOCUMENT_LINE_COLUMNS,
+ "unitCost": "Purchase cost per unit on the line.",
+ "amountExcludingTax": "Line amount before tax.",
+ "amountIncludingTax": "Line amount including tax.",
+ "expectedReceiptDate": "Date the line is expected to be received.",
+ },
+ },
+ "generalLedgerEntries": {
+ "description": "A posted general ledger entry — the append-only record of every amount hitting a G/L account.",
+ "docs_url": f"{_API_REFERENCE}/resources/dynamics_generalledgerentry",
+ "columns": {
+ **_COMPANY_COLUMNS,
+ "id": "System ID of the ledger entry.",
+ "entryNumber": "Sequential entry number, unique within the company.",
+ "postingDate": "Date the entry was posted to the general ledger.",
+ "documentNumber": "Number of the document that produced the entry.",
+ "documentType": "Type of the source document (Invoice, Credit Memo, Payment, and so on).",
+ "accountId": "System ID of the G/L account the entry posts to.",
+ "accountNumber": "Number of the G/L account the entry posts to.",
+ "description": "Description carried from the source document or journal line.",
+ "debitAmount": "Amount posted to the debit side, in the company's local currency.",
+ "creditAmount": "Amount posted to the credit side, in the company's local currency.",
+ "lastModifiedDateTime": "When the record was last changed. Used as the incremental sync cursor.",
+ },
+ },
+ "customerPayments": {
+ "description": "A customer payment journal line recording money received against invoices.",
+ "docs_url": f"{_API_REFERENCE}/resources/dynamics_customerpayment",
+ "columns": {
+ **_COMPANY_COLUMNS,
+ "id": "System ID of the payment line.",
+ "journalDisplayName": "Name of the payment journal the line sits in.",
+ "lineNumber": "Position of the line within the journal.",
+ "customerId": "System ID of the paying customer.",
+ "customerNumber": "Customer number as shown in Business Central.",
+ "postingDate": "Date the payment is posted.",
+ "documentNumber": "Document number assigned to the payment.",
+ "externalDocumentNumber": "Reference supplied by the customer, such as a remittance number.",
+ "amount": "Payment amount. Customer payments are posted as negative amounts.",
+ "appliesToInvoiceId": "System ID of the invoice the payment is applied to.",
+ "appliesToInvoiceNumber": "Number of the invoice the payment is applied to.",
+ "description": "Payment description.",
+ "lastModifiedDateTime": "When the record was last changed. Used as the incremental sync cursor.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dynamics_365_business_central/dynamics_365_business_central.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dynamics_365_business_central/dynamics_365_business_central.py
new file mode 100644
index 000000000000..3a1233fdf23a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dynamics_365_business_central/dynamics_365_business_central.py
@@ -0,0 +1,338 @@
+import re
+import dataclasses
+from collections.abc import Callable
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+
+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.rest_source import (
+ RESTAPIConfig,
+ rest_api_resources,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import (
+ OAuth2Auth,
+ OAuth2AuthRequestError,
+ strip_oauth2_permanent_marker,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ JSONResponsePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ Endpoint,
+ EndpointResource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.dynamics_365_business_central.settings import (
+ BUSINESS_CENTRAL_ENDPOINTS,
+ COMPANIES_ENDPOINT,
+ BusinessCentralEndpoint,
+)
+
+BUSINESS_CENTRAL_HOST = "api.businesscentral.dynamics.com"
+BUSINESS_CENTRAL_BASE = f"https://{BUSINESS_CENTRAL_HOST}"
+# Entra ID (Azure AD) token endpoint. The tenant is a path segment; the host is fixed.
+ENTRA_TOKEN_URL_TEMPLATE = "https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token"
+# Client-credentials flow asks for the app's admin-consented Business Central permissions.
+BUSINESS_CENTRAL_SCOPE = f"{BUSINESS_CENTRAL_BASE}/.default"
+
+# `@odata.nextLink` is an absolute, self-contained URL, so the next-URL paginator follows it
+# directly. Quoted because the key contains a literal `.` that jsonpath would otherwise split.
+NEXT_LINK_PATH = "'@odata.nextLink'"
+# OData v4 list responses wrap rows in a `value` array.
+DATA_SELECTOR = "value"
+
+REQUEST_TIMEOUT_SECONDS = (10.0, 300.0)
+VALIDATE_TIMEOUT_SECONDS = 15.0
+# Business Central pages can carry thousands of wide rows; keep the source->Arrow conversion
+# smaller than the pipeline default so a page of documents doesn't spike worker memory.
+CHUNK_SIZE = 2000
+CHUNK_SIZE_BYTES = 100 * 1024 * 1024
+
+# The tenant, environment and API version are customer-supplied and land in the request path.
+# The host is fixed, so pinning these to safe characters is what stops a value like `../../`
+# retargeting the credentialed request to another path on the API.
+_TENANT_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$")
+_ENVIRONMENT_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9-]{0,29}$")
+_API_VERSION_RE = re.compile(r"^v[0-9]+(\.[0-9]+)?$")
+# The cursor field is interpolated into an OData `$filter` expression, so only a bare property
+# name is accepted — anything else falls back to the endpoint's advertised field.
+_FIELD_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
+
+
+class BusinessCentralConfigurationError(Exception):
+ """A tenant id, environment name or API version that can't be put in a request path."""
+
+
[email protected](frozen=True)
+class Dynamics365BusinessCentralResumeConfig:
+ # Framework resume snapshot for the current endpoint: `{"next_url": ...}` for the top-level
+ # `companies` walk, or the per-company fan-out shape
+ # `{"completed": [...], "current": ..., "child_state": {...}}` for everything else.
+ paginator_state: Optional[dict[str, Any]] = None
+
+
+def build_base_url(tenant_id: str, environment: str, api_version: str) -> str:
+ """Build the per-tenant, per-environment API root.
+
+ Business Central has no shared host path: every request goes to
+ `/v2.0/{tenant}/{environment}/api/{version}`.
+ """
+ if not _TENANT_ID_RE.match(tenant_id):
+ raise BusinessCentralConfigurationError(
+ "Business Central tenant ID must be the Microsoft Entra tenant GUID or domain, with no slashes or spaces."
+ )
+ if not _ENVIRONMENT_RE.match(environment):
+ raise BusinessCentralConfigurationError(
+ "Business Central environment name must be letters, numbers and hyphens only (for example `production`)."
+ )
+ if not _API_VERSION_RE.match(api_version):
+ raise BusinessCentralConfigurationError(f"Unsupported Business Central API version: {api_version}")
+
+ return f"{BUSINESS_CENTRAL_BASE}/v2.0/{tenant_id}/{environment}/api/{api_version}"
+
+
+def build_auth(tenant_id: str, client_id: str, client_secret: str) -> OAuth2Auth:
+ """Entra ID service-to-service auth: the framework mints a ~1h token and re-mints on expiry."""
+ if not _TENANT_ID_RE.match(tenant_id):
+ raise BusinessCentralConfigurationError(
+ "Business Central tenant ID must be the Microsoft Entra tenant GUID or domain, with no slashes or spaces."
+ )
+
+ return OAuth2Auth(
+ token_url=ENTRA_TOKEN_URL_TEMPLATE.format(tenant_id=tenant_id),
+ client_id=client_id,
+ client_secret=client_secret,
+ grant_type="client_credentials",
+ scopes=BUSINESS_CENTRAL_SCOPE,
+ )
+
+
+def _format_odata_datetime(value: Any) -> Optional[str]:
+ """Render an incremental watermark as an OData v4 Edm.DateTimeOffset literal."""
+ if isinstance(value, datetime):
+ moment = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+ elif isinstance(value, date):
+ moment = datetime.combine(value, datetime.min.time(), tzinfo=UTC)
+ elif isinstance(value, str) and value.strip():
+ try:
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ except ValueError:
+ return None
+ moment = parsed.replace(tzinfo=UTC) if parsed.tzinfo is None else parsed.astimezone(UTC)
+ else:
+ return None
+ return moment.strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def build_incremental_params(
+ endpoint: BusinessCentralEndpoint,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ incremental_field: Optional[str] = None,
+) -> dict[str, str]:
+ """Build the server-side `$filter` window for an incremental sync.
+
+ Honors the cursor field the user picked in the schema settings, falling back to the
+ endpoint's advertised one. Returns `{}` for a full refresh or a first sync — the OData
+ filter rides on `@odata.nextLink`, so once set it bounds every page, not just the first.
+ """
+ if endpoint.cursor_field is None or not should_use_incremental_field:
+ return {}
+
+ field = (
+ incremental_field if incremental_field and _FIELD_NAME_RE.match(incremental_field) else endpoint.cursor_field
+ )
+ watermark = _format_odata_datetime(db_incremental_field_last_value)
+ if watermark is None:
+ return {}
+
+ return {"$filter": f"{field} gt {watermark}"}
+
+
+def _strip_odata_annotations(row: dict[str, Any]) -> dict[str, Any]:
+ return {key: value for key, value in row.items() if not key.startswith("@")}
+
+
+def _row_transform(company_scoped: bool) -> Callable[[dict[str, Any]], dict[str, Any]]:
+ """Drop OData control annotations (`@odata.etag`) and, for fan-out children, rename the
+ injected parent fields to the `company_id` / `company_name` columns the primary key uses."""
+
+ def _transform(row: dict[str, Any]) -> dict[str, Any]:
+ out = _strip_odata_annotations(row)
+ if company_scoped:
+ out["company_id"] = out.pop("_companies_id", None)
+ out["company_name"] = out.pop("_companies_name", None)
+ return out
+
+ return _transform
+
+
+def _companies_resource(as_parent: bool) -> EndpointResource:
+ endpoint: Endpoint = {
+ "path": COMPANIES_ENDPOINT,
+ "data_selector": DATA_SELECTOR,
+ "paginator": JSONResponsePaginator(next_url_path=NEXT_LINK_PATH),
+ }
+ resource: EndpointResource = {"name": COMPANIES_ENDPOINT, "endpoint": endpoint}
+ if not as_parent:
+ # Only map when companies is the synced table: as a fan-out parent its rows are read only
+ # for the `id`/`name` bindings, so reshaping them would be wasted work.
+ resource["data_map"] = _row_transform(company_scoped=False)
+ return resource
+
+
+def _company_scoped_resource(endpoint_config: BusinessCentralEndpoint, params: dict[str, str]) -> EndpointResource:
+ endpoint: Endpoint = {
+ "path": f"companies({{company_id}})/{endpoint_config.name}",
+ "params": {
+ "company_id": {"type": "resolve", "resource": COMPANIES_ENDPOINT, "field": "id"},
+ **params,
+ },
+ "data_selector": DATA_SELECTOR,
+ "paginator": JSONResponsePaginator(next_url_path=NEXT_LINK_PATH),
+ # A company that doesn't have the extension backing this entity answers 404; skip it
+ # rather than failing the whole sync for the tenant's other companies.
+ "response_actions": [{"status_code": 404, "action": "ignore"}],
+ }
+ return {
+ "name": endpoint_config.name,
+ "endpoint": endpoint,
+ "include_from_parent": ["id", "name"],
+ "data_map": _row_transform(company_scoped=True),
+ }
+
+
+def _build_resources(endpoint_config: BusinessCentralEndpoint, params: dict[str, str]) -> list[EndpointResource | str]:
+ if not endpoint_config.company_scoped:
+ return [_companies_resource(as_parent=False)]
+ return [_companies_resource(as_parent=True), _company_scoped_resource(endpoint_config, params)]
+
+
+def dynamics_365_business_central_source(
+ tenant_id: str,
+ environment: str,
+ client_id: str,
+ client_secret: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[Dynamics365BusinessCentralResumeConfig],
+ api_version: str,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: Optional[str] = None,
+) -> SourceResponse:
+ endpoint_config = BUSINESS_CENTRAL_ENDPOINTS[endpoint]
+ base_url = build_base_url(tenant_id, environment, api_version)
+
+ params = build_incremental_params(
+ endpoint_config,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ incremental_field,
+ )
+
+ rest_config: RESTAPIConfig = {
+ "client": {
+ "base_url": base_url,
+ "headers": {"Accept": "application/json"},
+ "auth": build_auth(tenant_id, client_id, client_secret),
+ # The client secret only ever leaves the process in the Entra token exchange (which
+ # builds its own session), but redact it here too so it can never surface in a logged
+ # URL from the data requests. `capture=False`: these rows are ledger entries, payments,
+ # bank-account and tax fields the name-based scrubbers can't recognise, so the bodies
+ # stay out of the HTTP sample store (requests are still metered and logged) rather than
+ # becoming readable outside the warehouse table access path.
+ "session": make_tracked_session(redact_values=(client_secret,), capture=False),
+ "paginator": JSONResponsePaginator(next_url_path=NEXT_LINK_PATH),
+ # `@odata.nextLink` comes back from the API, so pin it (and any resumed URL) to the
+ # Business Central host and reject redirects — the bearer token must not follow a
+ # tampered link off-origin.
+ "allowed_hosts": [BUSINESS_CENTRAL_HOST],
+ "allow_redirects": False,
+ "request_timeout": REQUEST_TIMEOUT_SECONDS,
+ },
+ "resource_defaults": {},
+ "resources": _build_resources(endpoint_config, params),
+ }
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume = resumable_source_manager.load_state()
+ if resume is not None and resume.paginator_state is not None:
+ initial_paginator_state = resume.paginator_state
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # The framework checkpoints after a page is yielded, so a crash re-yields the last page
+ # (merge dedupes on the primary key) instead of skipping it.
+ if state:
+ resumable_source_manager.save_state(Dynamics365BusinessCentralResumeConfig(paginator_state=state))
+
+ resources = rest_api_resources(
+ rest_config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+ target = next(resource for resource in resources if resource.name == endpoint)
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: target,
+ primary_keys=list(endpoint_config.primary_keys),
+ # Business Central doesn't document the default order of its API pages and `$skiptoken`
+ # paging rejects an `$orderby` on some entities, so incremental endpoints must only
+ # persist their watermark at successful job end — which "desc" guarantees.
+ sort_mode="desc" if endpoint_config.cursor_field else "asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if endpoint_config.partition_key else None,
+ partition_format="month" if endpoint_config.partition_key else None,
+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
+ chunk_size=CHUNK_SIZE,
+ chunk_size_bytes=CHUNK_SIZE_BYTES,
+ column_hints=target.column_hints,
+ )
+
+
+def validate_credentials(
+ tenant_id: str,
+ environment: str,
+ client_id: str,
+ client_secret: str,
+ api_version: str,
+) -> tuple[bool, str | None]:
+ """Mint an Entra ID token and list companies — the cheapest proof the app can read the tenant."""
+ try:
+ base_url = build_base_url(tenant_id, environment, api_version)
+ auth = build_auth(tenant_id, client_id, client_secret)
+ except BusinessCentralConfigurationError as e:
+ return False, str(e)
+
+ session = make_tracked_session(redact_values=(client_secret,), allow_redirects=False)
+ try:
+ response = session.get(
+ f"{base_url}/{COMPANIES_ENDPOINT}",
+ auth=auth,
+ timeout=VALIDATE_TIMEOUT_SECONDS,
+ allow_redirects=False,
+ )
+ except OAuth2AuthRequestError as e:
+ return False, f"Microsoft Entra ID rejected the token request: {strip_oauth2_permanent_marker(str(e))}"
+ except Exception:
+ return False, "Could not reach Business Central. Please check the tenant ID and environment name."
+
+ if response.status_code == 200:
+ return True, None
+ if response.status_code in (401, 403):
+ return (
+ False,
+ "Business Central denied access. Grant your Entra app the API.ReadWrite.All permission with admin "
+ "consent, and add it as a Business Central user in this environment.",
+ )
+ if response.status_code == 404:
+ return False, f"No Business Central environment named `{environment}` was found for this tenant."
+ return False, f"Business Central returned HTTP {response.status_code}"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dynamics_365_business_central/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dynamics_365_business_central/settings.py
new file mode 100644
index 000000000000..cf92edee6417
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dynamics_365_business_central/settings.py
@@ -0,0 +1,101 @@
+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
+
+# Every Business Central API v2.0 entity except `companies` lives under a company, so the whole
+# catalog below is company-scoped fan-out with `companies` as the parent.
+COMPANIES_ENDPOINT = "companies"
+
+# Business Central stamps a `lastModifiedDateTime` on master data and documents; it is the only
+# server-side filterable change marker the standard API exposes.
+LAST_MODIFIED_FIELD = "lastModifiedDateTime"
+
+
+@dataclass(frozen=True)
+class BusinessCentralEndpoint:
+ """One Business Central API v2.0 entity set.
+
+ `name` doubles as the OData entity-set segment and the schema/table name, which is how the
+ standard API is documented (`/companies({id})/salesInvoices`).
+ """
+
+ name: str
+ # False only for `companies`, which is the fan-out parent and is not itself nested.
+ company_scoped: bool = True
+ primary_keys: tuple[str, ...] = ("company_id", "id")
+ # Field used for the `$filter ... gt` incremental window. None means full refresh.
+ cursor_field: Optional[str] = None
+ # Stable posting/document date used for datetime partitioning. Never `lastModifiedDateTime`,
+ # which moves on every edit and would rewrite partitions each sync.
+ partition_key: Optional[str] = None
+
+ @property
+ def incremental_fields(self) -> list[IncrementalField]:
+ return [incremental_field(self.cursor_field)] if self.cursor_field else []
+
+
+def _document(name: str, partition_key: str = "postingDate") -> BusinessCentralEndpoint:
+ return BusinessCentralEndpoint(name=name, cursor_field=LAST_MODIFIED_FIELD, partition_key=partition_key)
+
+
+def _document_lines(name: str) -> BusinessCentralEndpoint:
+ # Line entities carry no change marker of their own, so they full-refresh. `id` is a systemId
+ # GUID but the documented key is (documentId, sequence) — use it, plus the company.
+ return BusinessCentralEndpoint(name=name, primary_keys=("company_id", "documentId", "sequence"))
+
+
+def _master(name: str) -> BusinessCentralEndpoint:
+ return BusinessCentralEndpoint(name=name, cursor_field=LAST_MODIFIED_FIELD)
+
+
+BUSINESS_CENTRAL_ENDPOINTS: dict[str, BusinessCentralEndpoint] = {
+ COMPANIES_ENDPOINT: BusinessCentralEndpoint(
+ name=COMPANIES_ENDPOINT,
+ company_scoped=False,
+ primary_keys=("id",),
+ ),
+ # Master data / setup tables.
+ "accounts": _master("accounts"),
+ "bankAccounts": _master("bankAccounts"),
+ "currencies": _master("currencies"),
+ "customers": _master("customers"),
+ "dimensions": _master("dimensions"),
+ "dimensionValues": _master("dimensionValues"),
+ "employees": _master("employees"),
+ "itemCategories": _master("itemCategories"),
+ "items": _master("items"),
+ "paymentMethods": _master("paymentMethods"),
+ "paymentTerms": _master("paymentTerms"),
+ "shipmentMethods": _master("shipmentMethods"),
+ "unitsOfMeasure": _master("unitsOfMeasure"),
+ "vendors": _master("vendors"),
+ # `locations` has no documented lastModifiedDateTime, so it full-refreshes.
+ "locations": BusinessCentralEndpoint(name="locations"),
+ # Documents and their lines.
+ "salesInvoices": _document("salesInvoices"),
+ "salesInvoiceLines": _document_lines("salesInvoiceLines"),
+ "salesOrders": _document("salesOrders"),
+ "salesOrderLines": _document_lines("salesOrderLines"),
+ "salesQuotes": _document("salesQuotes", partition_key="documentDate"),
+ "salesQuoteLines": _document_lines("salesQuoteLines"),
+ "salesCreditMemos": _document("salesCreditMemos"),
+ "salesCreditMemoLines": _document_lines("salesCreditMemoLines"),
+ "purchaseInvoices": _document("purchaseInvoices"),
+ "purchaseInvoiceLines": _document_lines("purchaseInvoiceLines"),
+ # Ledger / payment entries.
+ "generalLedgerEntries": BusinessCentralEndpoint(
+ name="generalLedgerEntries",
+ primary_keys=("company_id", "entryNumber"),
+ cursor_field=LAST_MODIFIED_FIELD,
+ partition_key="postingDate",
+ ),
+ "customerPayments": _document("customerPayments"),
+}
+
+ENDPOINTS = tuple(BUSINESS_CENTRAL_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: endpoint.incremental_fields for name, endpoint in BUSINESS_CENTRAL_ENDPOINTS.items() if endpoint.cursor_field
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dynamics_365_business_central/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dynamics_365_business_central/source.py
index 39f5f1914896..3ee16732929a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dynamics_365_business_central/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dynamics_365_business_central/source.py
@@ -1,13 +1,34 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+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.common.typings import SourceInputs, SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.dynamics_365_business_central.dynamics_365_business_central import (
+ Dynamics365BusinessCentralResumeConfig,
+ dynamics_365_business_central_source,
+ validate_credentials as validate_business_central_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.dynamics_365_business_central.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.dynamics365businesscentral import (
Dynamics365BusinessCentralSourceConfig,
)
@@ -15,7 +36,20 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class Dynamics365BusinessCentralSource(SimpleSource[Dynamics365BusinessCentralSourceConfig]):
+class Dynamics365BusinessCentralSource(
+ ResumableSource[Dynamics365BusinessCentralSourceConfig, Dynamics365BusinessCentralResumeConfig]
+):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ # Business Central versions its API in the request path (`/api/v2.0/`); v2.0 is the standard API
+ # this source calls.
+ supported_versions = ("v2.0",)
+ default_version = "v2.0"
+ api_docs_url = "https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/api-reference/v2.0/"
+
+ @property
+ def connection_host_fields(self) -> list[str]:
+ return ["tenant_id", "environment"]
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.DYNAMICS365BUSINESSCENTRAL
@@ -26,7 +60,120 @@ class Dynamics365BusinessCentralSource(SimpleSource[Dynamics365BusinessCentralSo
name=SchemaExternalDataSourceType.DYNAMICS365_BUSINESS_CENTRAL,
category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,
label="Microsoft Dynamics 365 Business Central",
+ caption="""Sync your Business Central customers, vendors, items, documents and general ledger entries into the PostHog Data warehouse.
+
+Register an app in [Microsoft Entra ID](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/administration/automation-apis-using-s2s-authentication) and grant it the `API.ReadWrite.All` application permission with admin consent, then add it as a Business Central user in the environment you want to sync. Enter that app's client ID and secret below, along with your Entra tenant ID and the environment name (usually `production`).
+
+Every table except companies is synced for all companies in the environment, with the company ID kept on each row.""",
iconPath="/static/services/dynamics_365_business_central.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/dynamics-365-business-central",
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["business central", "dynamics 365", "erp", "microsoft", "bc"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="tenant_id",
+ label="Microsoft Entra tenant ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="00000000-0000-0000-0000-000000000000",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="environment",
+ label="Environment name",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="production",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="client_id",
+ label="Application (client) ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="00000000-0000-0000-0000-000000000000",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="client_secret",
+ label="Client secret",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.businesscentral.dynamics.com": "Business Central rejected the access token. Check that your Entra app is still added as a Business Central user in this environment.",
+ "403 Client Error: Forbidden for url: https://api.businesscentral.dynamics.com": "Business Central denied access. Grant your Entra app the API.ReadWrite.All permission with admin consent.",
+ "[oauth2_token_config_error]": "Microsoft Entra ID rejected the token request. Check your tenant ID, client ID and client secret — the secret may have expired.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.dynamics_365_business_central.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: Dynamics365BusinessCentralSourceConfig,
+ 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)
+
+ def validate_credentials(
+ self,
+ config: Dynamics365BusinessCentralSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_business_central_credentials(
+ tenant_id=config.tenant_id,
+ environment=config.environment,
+ client_id=config.client_id,
+ client_secret=config.client_secret,
+ api_version=self.resolve_api_version(api_version),
+ )
+
+ def get_resumable_source_manager(
+ self, inputs: SourceInputs
+ ) -> ResumableSourceManager[Dynamics365BusinessCentralResumeConfig]:
+ return ResumableSourceManager[Dynamics365BusinessCentralResumeConfig](
+ inputs, Dynamics365BusinessCentralResumeConfig
+ )
+
+ def source_for_pipeline(
+ self,
+ config: Dynamics365BusinessCentralSourceConfig,
+ resumable_source_manager: ResumableSourceManager[Dynamics365BusinessCentralResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return dynamics_365_business_central_source(
+ tenant_id=config.tenant_id,
+ environment=config.environment,
+ client_id=config.client_id,
+ client_secret=config.client_secret,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ resumable_source_manager=resumable_source_manager,
+ api_version=self.resolve_api_version(inputs.api_version),
+ 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/dynamics_365_business_central/tests/test_dynamics_365_business_central.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dynamics_365_business_central/tests/test_dynamics_365_business_central.py
new file mode 100644
index 000000000000..95bdcbfacaf2
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dynamics_365_business_central/tests/test_dynamics_365_business_central.py
@@ -0,0 +1,588 @@
+import json
+from datetime import UTC, date, datetime
+from typing import Any
+from urllib.parse import parse_qs, unquote_plus, urlparse
+
+import pytest
+from unittest import mock
+
+import requests
+from requests import Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.dynamics_365_business_central.dynamics_365_business_central import (
+ BUSINESS_CENTRAL_HOST,
+ BusinessCentralConfigurationError,
+ Dynamics365BusinessCentralResumeConfig,
+ build_base_url,
+ build_incremental_params,
+ dynamics_365_business_central_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.dynamics_365_business_central.settings import (
+ BUSINESS_CENTRAL_ENDPOINTS,
+ ENDPOINTS,
+ BusinessCentralEndpoint,
+)
+
+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.dynamics_365_business_central.dynamics_365_business_central"
+SESSION_PATCH = f"{MODULE}.make_tracked_session"
+# OAuth2Auth mints its Entra token through its own session, built inside the framework auth module.
+AUTH_SESSION_PATCH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth.make_tracked_session"
+)
+
+TENANT = "contoso.onmicrosoft.com"
+ENVIRONMENT = "production"
+API_VERSION = "v2.0"
+API_ROOT = f"https://{BUSINESS_CENTRAL_HOST}/v2.0/{TENANT}/{ENVIRONMENT}/api/{API_VERSION}"
+# The company enumeration carries no query string, so route on the bare path.
+COMPANIES_ROUTE = f"{API_ROOT}/companies"
+
+
+def _response(payload: Any, status_code: int = 200, url: str = f"{API_ROOT}/companies") -> Response:
+ resp = Response()
+ resp.status_code = status_code
+ resp._content = json.dumps(payload).encode()
+ resp.url = url
+ resp.reason = "Error"
+ return resp
+
+
+def _page(rows: list[dict[str, Any]], next_link: str | None = None) -> dict[str, Any]:
+ payload: dict[str, Any] = {"@odata.context": f"{API_ROOT}/$metadata", "value": rows}
+ if next_link:
+ payload["@odata.nextLink"] = next_link
+ return payload
+
+
+def _token_payload(token: str = "entra-token", expires_in: int = 3599) -> bytes:
+ return json.dumps({"access_token": token, "expires_in": expires_in, "token_type": "Bearer"}).encode()
+
+
+def _wire_token(mock_auth_session: mock.MagicMock, body: bytes = b"", status_code: int = 200) -> mock.MagicMock:
+ """Stub the Entra ID token exchange. `OAuth2Auth` streams the body, so `raw.read` supplies it."""
+ response = mock.MagicMock()
+ response.status_code = status_code
+ response.raw.read.return_value = body or _token_payload()
+ mock_auth_session.return_value.post.return_value = response
+ return mock_auth_session.return_value
+
+
+def _wire(session: mock.MagicMock, routes: list[tuple[str, Response]]) -> list[str]:
+ """Dispatch each request to the first still-unconsumed route whose substring appears in the
+ fully-prepared URL. Real `Request.prepare()` builds the URL and applies the OAuth2 auth (which
+ mints the token), so fan-out, pagination and auth all route deterministically. Returns the URLs
+ sent, in order."""
+ session.headers = {}
+ sent_urls: list[str] = []
+ remaining = list(routes)
+
+ def _dispatch(prepared: Any) -> Response:
+ sent_urls.append(prepared.url)
+ for i, (substr, response) in enumerate(remaining):
+ if substr in prepared.url:
+ remaining.pop(i)
+ return response
+ raise AssertionError(f"no route for {prepared.url}")
+
+ def _prepare(request: Any) -> Any:
+ return request.prepare()
+
+ def _send(prepared: Any, **kwargs: Any) -> Response:
+ return _dispatch(prepared)
+
+ def _get(url: str, **kwargs: Any) -> Response:
+ prepared = requests.Request("GET", url, params=kwargs.get("params"), auth=kwargs.get("auth")).prepare()
+ return _dispatch(prepared)
+
+ session.prepare_request.side_effect = _prepare
+ session.send.side_effect = _send
+ session.get.side_effect = _get
+ return sent_urls
+
+
+def _make_manager(resume_state: Dynamics365BusinessCentralResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+def _source(endpoint: str, manager: mock.MagicMock, **kwargs: Any) -> Any:
+ return dynamics_365_business_central_source(
+ tenant_id=TENANT,
+ environment=ENVIRONMENT,
+ client_id="client-id",
+ client_secret="client-secret",
+ endpoint=endpoint,
+ team_id=1,
+ job_id="job-1",
+ resumable_source_manager=manager,
+ api_version=API_VERSION,
+ **kwargs,
+ )
+
+
+def _rows(source_response: Any) -> list[dict[str, Any]]:
+ return [row for page in source_response.items() for row in page]
+
+
+def _query(url: str) -> dict[str, list[str]]:
+ return parse_qs(urlparse(url).query)
+
+
+class TestBuildBaseUrl:
+ def test_builds_per_tenant_per_environment_root(self) -> None:
+ assert build_base_url(TENANT, ENVIRONMENT, API_VERSION) == API_ROOT
+
+ @pytest.mark.parametrize(
+ "tenant_id, environment, api_version",
+ [
+ # A path segment that escapes the API root would retarget the credentialed request.
+ ("../../evil", ENVIRONMENT, API_VERSION),
+ ("tenant/extra", ENVIRONMENT, API_VERSION),
+ ("tenant id", ENVIRONMENT, API_VERSION),
+ ("", ENVIRONMENT, API_VERSION),
+ (TENANT, "prod/../admin", API_VERSION),
+ (TENANT, "prod uction", API_VERSION),
+ (TENANT, "", API_VERSION),
+ (TENANT, ENVIRONMENT, "beta"),
+ (TENANT, ENVIRONMENT, "../v1.0"),
+ ],
+ )
+ def test_rejects_path_escaping_values(self, tenant_id: str, environment: str, api_version: str) -> None:
+ with pytest.raises(BusinessCentralConfigurationError):
+ build_base_url(tenant_id, environment, api_version)
+
+
+class TestBuildIncrementalParams:
+ @pytest.mark.parametrize(
+ "last_value, expected",
+ [
+ (datetime(2026, 6, 1, 12, 30, 15, tzinfo=UTC), "lastModifiedDateTime gt 2026-06-01T12:30:15Z"),
+ (datetime(2026, 6, 1, 12, 30, 15), "lastModifiedDateTime gt 2026-06-01T12:30:15Z"),
+ (date(2026, 6, 1), "lastModifiedDateTime gt 2026-06-01T00:00:00Z"),
+ ("2026-06-01T12:30:15Z", "lastModifiedDateTime gt 2026-06-01T12:30:15Z"),
+ ],
+ )
+ def test_formats_watermark_as_odata_literal(self, last_value: Any, expected: str) -> None:
+ params = build_incremental_params(BUSINESS_CENTRAL_ENDPOINTS["customers"], True, last_value)
+ assert params == {"$filter": expected}
+
+ def test_honors_the_users_chosen_cursor_field(self) -> None:
+ params = build_incremental_params(
+ BUSINESS_CENTRAL_ENDPOINTS["generalLedgerEntries"],
+ True,
+ datetime(2026, 6, 1, tzinfo=UTC),
+ incremental_field="postingDate",
+ )
+ assert params == {"$filter": "postingDate gt 2026-06-01T00:00:00Z"}
+
+ @pytest.mark.parametrize("chosen_field", ["lastModifiedDateTime eq 1 or 1", "id) and (1", ""])
+ def test_falls_back_when_the_chosen_field_is_not_a_bare_property(self, chosen_field: str) -> None:
+ # The field is interpolated into an OData $filter, so a value carrying filter syntax must
+ # not reach the query.
+ params = build_incremental_params(
+ BUSINESS_CENTRAL_ENDPOINTS["customers"],
+ True,
+ datetime(2026, 6, 1, tzinfo=UTC),
+ incremental_field=chosen_field,
+ )
+ assert params == {"$filter": "lastModifiedDateTime gt 2026-06-01T00:00:00Z"}
+
+ @pytest.mark.parametrize(
+ "endpoint, should_use_incremental_field, last_value",
+ [
+ # First sync: no watermark yet.
+ ("customers", True, None),
+ ("customers", False, datetime(2026, 6, 1, tzinfo=UTC)),
+ # Full-refresh endpoints never window, even with a watermark present.
+ ("salesInvoiceLines", True, datetime(2026, 6, 1, tzinfo=UTC)),
+ ("companies", True, datetime(2026, 6, 1, tzinfo=UTC)),
+ # An unparseable stored watermark must not produce a broken $filter.
+ ("customers", True, "not-a-date"),
+ ],
+ )
+ def test_no_filter_without_a_usable_watermark(
+ self, endpoint: str, should_use_incremental_field: bool, last_value: Any
+ ) -> None:
+ assert (
+ build_incremental_params(BUSINESS_CENTRAL_ENDPOINTS[endpoint], should_use_incremental_field, last_value)
+ == {}
+ )
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status_code, expected_valid",
+ [(200, True), (401, False), (403, False), (404, False), (429, False), (500, False)],
+ )
+ @mock.patch(AUTH_SESSION_PATCH)
+ @mock.patch(SESSION_PATCH)
+ def test_status_mapping(
+ self,
+ mock_session: mock.MagicMock,
+ mock_auth_session: mock.MagicMock,
+ status_code: int,
+ expected_valid: bool,
+ ) -> None:
+ _wire_token(mock_auth_session)
+ _wire(mock_session.return_value, [("/companies", _response({"value": []}, status_code=status_code))])
+
+ valid, message = validate_credentials(TENANT, ENVIRONMENT, "client-id", "client-secret", API_VERSION)
+
+ assert valid is expected_valid
+ assert (message is None) is expected_valid
+
+ @mock.patch(AUTH_SESSION_PATCH)
+ @mock.patch(SESSION_PATCH)
+ def test_sends_the_minted_bearer_token(
+ self, mock_session: mock.MagicMock, mock_auth_session: mock.MagicMock
+ ) -> None:
+ auth_session = _wire_token(mock_auth_session, _token_payload("minted-token"))
+ _wire(mock_session.return_value, [("/companies", _response({"value": []}))])
+
+ assert validate_credentials(TENANT, ENVIRONMENT, "client-id", "client-secret", API_VERSION) == (True, None)
+ token_body = auth_session.post.call_args.kwargs["data"]
+ assert token_body["grant_type"] == "client_credentials"
+ assert token_body["scope"] == f"https://{BUSINESS_CENTRAL_HOST}/.default"
+ assert token_body["client_secret"] == "client-secret"
+ assert auth_session.post.call_args.args[0] == f"https://login.microsoftonline.com/{TENANT}/oauth2/v2.0/token"
+
+ @mock.patch(AUTH_SESSION_PATCH)
+ @mock.patch(SESSION_PATCH)
+ def test_entra_token_rejection_is_reported_without_the_internal_marker(
+ self, mock_session: mock.MagicMock, mock_auth_session: mock.MagicMock
+ ) -> None:
+ _wire_token(
+ mock_auth_session,
+ json.dumps({"error": "invalid_client", "error_description": "AADSTS7000215"}).encode(),
+ status_code=401,
+ )
+ _wire(mock_session.return_value, [])
+
+ valid, message = validate_credentials(TENANT, ENVIRONMENT, "client-id", "client-secret", API_VERSION)
+
+ assert valid is False
+ assert message is not None
+ assert "invalid_client" in message
+ assert "oauth2_token_config_error" not in message
+
+ @mock.patch(SESSION_PATCH)
+ def test_bad_environment_name_fails_before_any_request(self, mock_session: mock.MagicMock) -> None:
+ valid, message = validate_credentials(TENANT, "prod/../admin", "client-id", "client-secret", API_VERSION)
+
+ assert valid is False
+ assert message is not None and "environment name" in message
+ mock_session.assert_not_called()
+
+ @mock.patch(AUTH_SESSION_PATCH)
+ @mock.patch(SESSION_PATCH)
+ def test_transport_failure_is_not_valid(
+ self, mock_session: mock.MagicMock, mock_auth_session: mock.MagicMock
+ ) -> None:
+ _wire_token(mock_auth_session)
+ mock_session.return_value.get.side_effect = requests.ConnectionError("boom")
+
+ valid, message = validate_credentials(TENANT, ENVIRONMENT, "client-id", "client-secret", API_VERSION)
+
+ assert valid is False
+ assert message is not None and "Could not reach Business Central" in message
+
+
+class TestGetRows:
+ @mock.patch(AUTH_SESSION_PATCH)
+ @mock.patch(SESSION_PATCH)
+ def test_companies_is_top_level_and_strips_odata_annotations(
+ self, mock_session: mock.MagicMock, mock_auth_session: mock.MagicMock
+ ) -> None:
+ _wire_token(mock_auth_session)
+ urls = _wire(
+ mock_session.return_value,
+ [("/companies", _response(_page([{"id": "c-1", "name": "cronus", "@odata.etag": 'W/"1"'}])))],
+ )
+
+ manager = _make_manager()
+ rows = _rows(_source("companies", manager))
+
+ assert rows == [{"id": "c-1", "name": "cronus"}]
+ assert len(urls) == 1
+ assert urls[0].startswith(f"{API_ROOT}/companies")
+
+ @mock.patch(AUTH_SESSION_PATCH)
+ @mock.patch(SESSION_PATCH)
+ def test_row_bodies_are_kept_out_of_http_sample_capture(
+ self, mock_session: mock.MagicMock, mock_auth_session: mock.MagicMock
+ ) -> None:
+ # Rows carry ledger, payment, bank-account and tax fields the name-based scrubbers can't
+ # recognise, so the sync session must opt out of body capture. Dropping `capture=False`
+ # would persist raw financial records to the HTTP sample store.
+ _wire_token(mock_auth_session)
+ _wire(mock_session.return_value, [("/companies", _response(_page([])))])
+
+ _rows(_source("companies", _make_manager()))
+
+ assert mock_session.call_args.kwargs["capture"] is False
+ assert mock_session.call_args.kwargs["redact_values"] == ("client-secret",)
+
+ @mock.patch(AUTH_SESSION_PATCH)
+ @mock.patch(SESSION_PATCH)
+ def test_company_scoped_endpoint_fans_out_and_stamps_the_company(
+ self, mock_session: mock.MagicMock, mock_auth_session: mock.MagicMock
+ ) -> None:
+ _wire_token(mock_auth_session)
+ urls = _wire(
+ mock_session.return_value,
+ [
+ (
+ COMPANIES_ROUTE,
+ _response(_page([{"id": "c-1", "name": "cronus"}, {"id": "c-2", "name": "acme"}])),
+ ),
+ ("companies(c-1)/customers", _response(_page([{"id": "cust-1"}]))),
+ ("companies(c-2)/customers", _response(_page([{"id": "cust-2"}]))),
+ ],
+ )
+
+ manager = _make_manager()
+ rows = _rows(_source("customers", manager))
+
+ assert rows == [
+ {"id": "cust-1", "company_id": "c-1", "company_name": "cronus"},
+ {"id": "cust-2", "company_id": "c-2", "company_name": "acme"},
+ ]
+ # Single-hop fan-out stays resumable: per-company progress is checkpointed.
+ assert manager.save_state.called
+ assert "completed" in manager.save_state.call_args.args[0].paginator_state
+ assert len(urls) == 3
+
+ @mock.patch(AUTH_SESSION_PATCH)
+ @mock.patch(SESSION_PATCH)
+ def test_pagination_follows_odata_next_link_and_terminates(
+ self, mock_session: mock.MagicMock, mock_auth_session: mock.MagicMock
+ ) -> None:
+ _wire_token(mock_auth_session)
+ next_link = f"{API_ROOT}/companies(c-1)/items?$skiptoken=abc"
+ urls = _wire(
+ mock_session.return_value,
+ [
+ (COMPANIES_ROUTE, _response(_page([{"id": "c-1", "name": "cronus"}]))),
+ ("$skiptoken=abc", _response(_page([{"id": "item-2"}]))),
+ ("companies(c-1)/items", _response(_page([{"id": "item-1"}], next_link=next_link))),
+ ],
+ )
+
+ rows = _rows(_source("items", _make_manager()))
+
+ assert [row["id"] for row in rows] == ["item-1", "item-2"]
+ # The second page is fetched from the opaque nextLink; a page without one ends the walk.
+ assert urls[-1] == next_link
+ assert len(urls) == 3
+
+ @mock.patch(AUTH_SESSION_PATCH)
+ @mock.patch(SESSION_PATCH)
+ def test_incremental_filter_is_sent_on_the_child_requests(
+ self, mock_session: mock.MagicMock, mock_auth_session: mock.MagicMock
+ ) -> None:
+ _wire_token(mock_auth_session)
+ urls = _wire(
+ mock_session.return_value,
+ [
+ (COMPANIES_ROUTE, _response(_page([{"id": "c-1", "name": "cronus"}]))),
+ ("companies(c-1)/salesInvoices", _response(_page([{"id": "inv-1"}]))),
+ ],
+ )
+
+ _rows(
+ _source(
+ "salesInvoices",
+ _make_manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 6, 1, tzinfo=UTC),
+ incremental_field="lastModifiedDateTime",
+ )
+ )
+
+ child_query = _query(urls[-1])
+ assert unquote_plus(child_query["$filter"][0]) == "lastModifiedDateTime gt 2026-06-01T00:00:00Z"
+ # The company enumeration must not be windowed — a company row has no lastModifiedDateTime.
+ assert "$filter" not in _query(urls[0])
+
+ @mock.patch(AUTH_SESSION_PATCH)
+ @mock.patch(SESSION_PATCH)
+ def test_missing_entity_in_one_company_is_skipped(
+ self, mock_session: mock.MagicMock, mock_auth_session: mock.MagicMock
+ ) -> None:
+ _wire_token(mock_auth_session)
+ _wire(
+ mock_session.return_value,
+ [
+ (
+ COMPANIES_ROUTE,
+ _response(_page([{"id": "c-1", "name": "cronus"}, {"id": "c-2", "name": "acme"}])),
+ ),
+ # c-1 doesn't have the extension backing this entity.
+ ("companies(c-1)/employees", _response({"error": {"code": "NotFound"}}, status_code=404)),
+ ("companies(c-2)/employees", _response(_page([{"id": "emp-1"}]))),
+ ],
+ )
+
+ rows = _rows(_source("employees", _make_manager()))
+
+ assert [row["id"] for row in rows] == ["emp-1"]
+
+ @mock.patch(AUTH_SESSION_PATCH)
+ @mock.patch(SESSION_PATCH)
+ def test_permission_error_fails_the_sync(
+ self, mock_session: mock.MagicMock, mock_auth_session: mock.MagicMock
+ ) -> None:
+ _wire_token(mock_auth_session)
+ _wire(
+ mock_session.return_value,
+ [
+ (COMPANIES_ROUTE, _response(_page([{"id": "c-1", "name": "cronus"}]))),
+ ("companies(c-1)/vendors", _response({"error": {"code": "Forbidden"}}, status_code=403)),
+ ],
+ )
+
+ with pytest.raises(requests.HTTPError):
+ _rows(_source("vendors", _make_manager()))
+
+ @mock.patch(AUTH_SESSION_PATCH)
+ @mock.patch(SESSION_PATCH)
+ def test_next_link_pointing_off_host_is_rejected(
+ self, mock_session: mock.MagicMock, mock_auth_session: mock.MagicMock
+ ) -> None:
+ _wire_token(mock_auth_session)
+ _wire(
+ mock_session.return_value,
+ [
+ (
+ COMPANIES_ROUTE,
+ _response(_page([{"id": "c-1", "name": "cronus"}], next_link="https://evil.example/steal")),
+ ),
+ ],
+ )
+
+ # A tampered nextLink must not carry the bearer token to another host.
+ with pytest.raises(ValueError, match="disallowed host"):
+ _rows(_source("companies", _make_manager()))
+
+ @mock.patch(AUTH_SESSION_PATCH)
+ @mock.patch(SESSION_PATCH)
+ def test_resume_skips_companies_already_completed(
+ self, mock_session: mock.MagicMock, mock_auth_session: mock.MagicMock
+ ) -> None:
+ _wire_token(mock_auth_session)
+ urls = _wire(
+ mock_session.return_value,
+ [
+ (
+ COMPANIES_ROUTE,
+ _response(_page([{"id": "c-1", "name": "cronus"}, {"id": "c-2", "name": "acme"}])),
+ ),
+ ("companies(c-2)/customers", _response(_page([{"id": "cust-2"}]))),
+ ],
+ )
+
+ manager = _make_manager(
+ Dynamics365BusinessCentralResumeConfig(
+ paginator_state={"completed": ["companies(c-1)/customers"], "current": None, "child_state": None}
+ )
+ )
+ rows = _rows(_source("customers", manager))
+
+ assert [row["id"] for row in rows] == ["cust-2"]
+ assert len(urls) == 2
+ assert "companies(c-1)" not in urls[1]
+
+ @mock.patch(AUTH_SESSION_PATCH)
+ @mock.patch(SESSION_PATCH)
+ def test_resume_restarts_the_company_that_was_mid_page(
+ self, mock_session: mock.MagicMock, mock_auth_session: mock.MagicMock
+ ) -> None:
+ _wire_token(mock_auth_session)
+ saved_next = f"{API_ROOT}/companies(c-1)/items?$skiptoken=page-2"
+ urls = _wire(
+ mock_session.return_value,
+ [
+ (COMPANIES_ROUTE, _response(_page([{"id": "c-1", "name": "cronus"}]))),
+ ("$skiptoken=page-2", _response(_page([{"id": "item-2"}]))),
+ ],
+ )
+
+ manager = _make_manager(
+ Dynamics365BusinessCentralResumeConfig(
+ paginator_state={
+ "completed": [],
+ "current": "companies(c-1)/items",
+ "child_state": {"next_url": saved_next},
+ }
+ )
+ )
+ rows = _rows(_source("items", manager))
+
+ assert [row["id"] for row in rows] == ["item-2"]
+ # The saved link is used instead of the first page of c-1's items.
+ assert urls[-1] == saved_next
+
+ @mock.patch(AUTH_SESSION_PATCH)
+ @mock.patch(SESSION_PATCH)
+ def test_resume_state_from_the_other_endpoint_shape_starts_over(
+ self, mock_session: mock.MagicMock, mock_auth_session: mock.MagicMock
+ ) -> None:
+ _wire_token(mock_auth_session)
+ urls = _wire(
+ mock_session.return_value,
+ [(COMPANIES_ROUTE, _response(_page([{"id": "c-1", "name": "cronus"}])))],
+ )
+
+ # `companies` stores `{"next_url": ...}` while fan-out endpoints store `{"completed": ...}`.
+ # Seeding the wrong shape must restart cleanly rather than raise.
+ manager = _make_manager(
+ Dynamics365BusinessCentralResumeConfig(paginator_state={"completed": [], "current": None})
+ )
+ rows = _rows(_source("companies", manager))
+
+ assert [row["id"] for row in rows] == ["c-1"]
+ assert urls[0].startswith(f"{API_ROOT}/companies")
+
+
+class TestSourceResponseMetadata:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ @mock.patch(AUTH_SESSION_PATCH)
+ @mock.patch(SESSION_PATCH)
+ def test_metadata_per_endpoint(
+ self, mock_session: mock.MagicMock, mock_auth_session: mock.MagicMock, endpoint: str
+ ) -> None:
+ _wire_token(mock_auth_session)
+ _wire(mock_session.return_value, [])
+ endpoint_config = BUSINESS_CENTRAL_ENDPOINTS[endpoint]
+
+ response = _source(endpoint, _make_manager())
+
+ assert response.name == endpoint
+ assert response.primary_keys == list(endpoint_config.primary_keys)
+ # Business Central doesn't document its page ordering, so an incremental endpoint must only
+ # persist its watermark at successful job end — which "desc" guarantees.
+ assert response.sort_mode == ("desc" if endpoint_config.cursor_field else "asc")
+ if endpoint_config.partition_key:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [endpoint_config.partition_key]
+ else:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+
+ @pytest.mark.parametrize("endpoint_config", list(BUSINESS_CENTRAL_ENDPOINTS.values()))
+ def test_company_scoped_primary_keys_carry_the_company(self, endpoint_config: BusinessCentralEndpoint) -> None:
+ # Business Central ids are only unique within a company, so a fan-out child whose key omits
+ # the company would collide across companies and seed duplicate rows in the Delta table.
+ if endpoint_config.company_scoped:
+ assert endpoint_config.primary_keys[0] == "company_id"
+ assert len(endpoint_config.primary_keys) >= 2
+ else:
+ assert endpoint_config.primary_keys == ("id",)
+
+ @pytest.mark.parametrize("endpoint_config", list(BUSINESS_CENTRAL_ENDPOINTS.values()))
+ def test_partition_keys_are_never_the_mutable_cursor(self, endpoint_config: BusinessCentralEndpoint) -> None:
+ # Partitioning on lastModifiedDateTime would rewrite partitions on every edit.
+ assert endpoint_config.partition_key != "lastModifiedDateTime"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dynamics_365_business_central/tests/test_dynamics_365_business_central_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dynamics_365_business_central/tests/test_dynamics_365_business_central_source.py
new file mode 100644
index 000000000000..78a8e76ffd6b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dynamics_365_business_central/tests/test_dynamics_365_business_central_source.py
@@ -0,0 +1,206 @@
+from typing import Any
+
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.dynamics_365_business_central.dynamics_365_business_central import (
+ Dynamics365BusinessCentralResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.dynamics_365_business_central.settings import (
+ BUSINESS_CENTRAL_ENDPOINTS,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.dynamics_365_business_central.source import (
+ Dynamics365BusinessCentralSource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.dynamics365businesscentral import (
+ Dynamics365BusinessCentralSourceConfig,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.dynamics_365_business_central.source"
+
+
+class TestDynamics365BusinessCentralSource:
+ def setup_method(self) -> None:
+ self.source = Dynamics365BusinessCentralSource()
+ self.team_id = 123
+ self.config = Dynamics365BusinessCentralSourceConfig(
+ tenant_id="contoso.onmicrosoft.com",
+ environment="production",
+ client_id="client-id",
+ client_secret="client-secret",
+ )
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.DYNAMICS365BUSINESSCENTRAL
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "Dynamics365BusinessCentral"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/dynamics_365_business_central.png"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["tenant_id", "environment", "client_id", "client_secret"]
+
+ def test_connection_host_fields_force_credential_reentry(self) -> None:
+ # Both feed the request path (`/{tenant_id}/{environment}/api/...`), so editing either
+ # must re-require the client secret rather than retargeting the preserved credential.
+ assert set(self.source.connection_host_fields) == {"tenant_id", "environment"}
+
+ def test_only_the_client_secret_is_stored_as_a_secret(self) -> None:
+ fields = [f for f in self.source.get_source_config.fields if isinstance(f, SourceFieldInputConfig)]
+ secrets = {f.name for f in fields if f.secret}
+
+ assert secrets == {"client_secret"}
+ client_secret = next(f for f in fields if f.name == "client_secret")
+ assert client_secret.type == SourceFieldInputConfigType.PASSWORD
+ assert all(f.required for f in fields)
+
+ def test_api_version_matches_the_path_the_code_calls(self) -> None:
+ # The version is a request path segment, so the pin must be the one the transport builds.
+ assert self.source.supported_versions == ("v2.0",)
+ assert self.source.default_version == "v2.0"
+ assert self.source.api_docs_url.startswith("https://")
+ assert self.source.resolve_api_version(None) == "v2.0"
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.businesscentral.dynamics.com/v2.0/t/production/api/v2.0/companies",
+ "403 Client Error: Forbidden for url: https://api.businesscentral.dynamics.com/v2.0/t/production/api/v2.0/companies(c-1)/customers",
+ "HTTP 401 from the OAuth2 token endpoint: invalid_client [oauth2_token_config_error]",
+ ],
+ )
+ def test_non_retryable_errors_match_permanent_auth_failures(self, observed_error: str) -> None:
+ assert any(key in observed_error for key in self.source.get_non_retryable_errors())
+
+ @pytest.mark.parametrize(
+ "other_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",
+ "500 Server Error for url: https://api.businesscentral.dynamics.com/v2.0/t/production/api/v2.0/items",
+ # A throttled token exchange is transient and carries no permanent marker.
+ "HTTP 429 from the OAuth2 token endpoint",
+ ],
+ )
+ def test_non_retryable_errors_leave_transient_failures_retryable(self, other_error: str) -> None:
+ assert not any(key in other_error for key in self.source.get_non_retryable_errors())
+
+ def test_get_schemas_lists_the_whole_catalog(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+ incremental = {schema.name for schema in schemas if schema.supports_incremental}
+ assert incremental == set(INCREMENTAL_FIELDS)
+ # `companies` and the document line tables have no server-side change filter.
+ assert "companies" not in incremental
+ assert "salesInvoiceLines" not in incremental
+
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_incremental_schemas_advertise_only_their_cursor_field(self, endpoint: str) -> None:
+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)
+ cursor_field = BUSINESS_CENTRAL_ENDPOINTS[endpoint].cursor_field
+
+ assert [f["field"] for f in schema.incremental_fields] == ([cursor_field] if cursor_field else [])
+ assert schema.supports_append is (cursor_field is not None)
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["generalLedgerEntries"])
+
+ assert [schema.name for schema in schemas] == ["generalLedgerEntries"]
+
+ def test_documented_tables_are_published_without_credentials(self) -> None:
+ # `get_schemas` does no I/O, so the public docs can render the table catalog.
+ assert self.source.lists_tables_without_credentials is True
+ tables = {table["name"]: table for table in self.source.get_documented_tables()}
+
+ assert set(tables) == set(ENDPOINTS)
+ assert tables["customers"]["description"]
+
+ def test_canonical_descriptions_key_off_schema_names(self) -> None:
+ descriptions = self.source.get_canonical_descriptions()
+
+ assert set(descriptions).issubset(set(ENDPOINTS))
+ for name, entry in descriptions.items():
+ assert entry["docs_url"].startswith("https://learn.microsoft.com/"), name
+ if BUSINESS_CENTRAL_ENDPOINTS[name].company_scoped:
+ # Every fan-out table's key starts with the stamped company id, so it must be documented.
+ assert "company_id" in entry["columns"], name
+
+ @pytest.mark.parametrize(
+ "probe_result, expected",
+ [
+ ((True, None), (True, None)),
+ ((False, "Business Central returned HTTP 500"), (False, "Business Central returned HTTP 500")),
+ ],
+ )
+ @mock.patch(f"{SOURCE_MODULE}.validate_business_central_credentials")
+ def test_validate_credentials_passes_through_the_probe_result(
+ self,
+ mock_validate: mock.MagicMock,
+ probe_result: tuple[bool, str | None],
+ expected: tuple[bool, str | None],
+ ) -> None:
+ mock_validate.return_value = probe_result
+
+ assert self.source.validate_credentials(self.config, self.team_id) == expected
+ assert mock_validate.call_args.kwargs == {
+ "tenant_id": "contoso.onmicrosoft.com",
+ "environment": "production",
+ "client_id": "client-id",
+ "client_secret": "client-secret",
+ "api_version": "v2.0",
+ }
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is Dynamics365BusinessCentralResumeConfig
+
+ @mock.patch(f"{SOURCE_MODULE}.dynamics_365_business_central_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "salesInvoices"
+ inputs.team_id = self.team_id
+ inputs.job_id = "job-1"
+ inputs.api_version = None
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-06-01T00:00:00Z"
+ inputs.incremental_field = "lastModifiedDateTime"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ kwargs: dict[str, Any] = dict(mock_source.call_args.kwargs)
+ assert kwargs["tenant_id"] == "contoso.onmicrosoft.com"
+ assert kwargs["environment"] == "production"
+ assert kwargs["client_id"] == "client-id"
+ assert kwargs["client_secret"] == "client-secret"
+ assert kwargs["endpoint"] == "salesInvoices"
+ assert kwargs["resumable_source_manager"] is manager
+ # An unpinned source resolves to the default version rather than passing None through.
+ assert kwargs["api_version"] == "v2.0"
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2026-06-01T00:00:00Z"
+ assert kwargs["incremental_field"] == "lastModifiedDateTime"
+
+ @mock.patch(f"{SOURCE_MODULE}.dynamics_365_business_central_source")
+ def test_source_for_pipeline_drops_the_watermark_on_full_refresh(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "salesInvoiceLines"
+ inputs.api_version = "v2.0"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2026-06-01T00:00:00Z"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/dynamics365businesscentral.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/dynamics365businesscentral.py
index 054115bfe68b..579ee5cc67e8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/dynamics365businesscentral.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/dynamics365businesscentral.py
@@ -6,4 +6,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class Dynamics365BusinessCentralSourceConfig(config.Config):
- pass
+ tenant_id: str
+ environment: str
+ client_id: str
+ client_secret: str