Metadata-Version: 2.4
Name: syncfreedom
Version: 2.0.0
Summary: Use python-quickbooks with QuickBooks Online companies connected on SyncFreedom.com, with no OAuth flow or tokens of your own
Author-email: Jared Self <jared@quickbooksgg.com>
License-Expression: MIT
Project-URL: Homepage, https://syncfreedom.com
Project-URL: Documentation, https://syncfreedom.com/docs/qbo-token-api/
Project-URL: Source, https://github.com/selfjared1/syncfreedom-lib
Project-URL: Bug Tracker, https://github.com/selfjared1/syncfreedom-lib/issues
Keywords: quickbooks,quickbooks online,qbo,accounting
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Classifier: Intended Audience :: Developers
Classifier: Topic :: Office/Business :: Financial :: Accounting
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: python-quickbooks>=0.9.12
Requires-Dist: requests>=2.26
Dynamic: license-file

# syncfreedom

Use [python-quickbooks](https://pypi.org/project/python-quickbooks/) with the QuickBooks Online companies you have
connected on [SyncFreedom.com](https://syncfreedom.com), without building an OAuth flow of your own.

python-quickbooks is well documented, but before you can use it you normally need a web app that collects Intuit's
authorization codes and keeps refreshing tokens. SyncFreedom does that part. You connect a company once in the
SyncFreedom dashboard, and your scripts send their QuickBooks requests through SyncFreedom, which adds Intuit's token on
its own server. Your scripts never handle a token.

The goal is to make Python more accessible to accountants: write the accounting utility, not the OAuth plumbing.

## Install

    pip install -U syncfreedom

You need an active SyncFreedom QuickBooks Online plan and at least one connected company. Upgrading from 1.x? See
[Upgrading from 1.x](#upgrading-from-1x). The guide on syncfreedom.com,
[QuickBooks Online from your own scripts](https://syncfreedom.com/docs/qbo-token-api/), covers the same ground and
plain HTTP from other languages.

## Create an API key

1. Open [API keys](https://syncfreedom.com/app/keys/) in the SyncFreedom dashboard menu.
2. Name the key. Read is always on. Check the permissions your script needs, and leave them unchecked for a read-only
   key:

   | Permission | Lets a script |
   | --- | --- |
   | Read | Query, get records, run reports and change data capture, download PDFs. Always on. |
   | **Create records** | Add records and upload attachments. |
   | **Update records** | Change records (full or sparse), void them, and email them with `send`. |
   | **Delete transactions, deactivate list records** | Delete records. |

   A batch needs every permission its items need.
3. Click **Create key** and copy it. It starts with `sf_live_` and is shown only once.

A report-only script needs Read alone. You can revoke a key at any time without touching your password or other keys.
The same key works for SyncFreedom's MCP server.

Save the key once, outside your code, in a file named `config.ini` in the folder you run your scripts from, or
`.syncfreedom.ini` in your home folder (see
[config.ini.sample](https://github.com/selfjared1/syncfreedom-lib/blob/main/config.ini.sample)):

```ini
[SYNCFREEDOM_CREDENTIALS]
api_key = sf_live_XXXXXXXX
```

The package finds it on its own. When no key is passed in code, it looks in this order:

1. The `SYNCFREEDOM_API_KEY` environment variable.
2. The file named by `SYNCFREEDOM_CONFIG`, if set. Otherwise `config.ini` in the working folder, then
   `~/.syncfreedom.ini`. A file without a `[SYNCFREEDOM_CREDENTIALS]` section is skipped.

A config file that mentions `[SYNCFREEDOM_CREDENTIALS]` but can't be read is an error, never skipped, so a typo
can't quietly sign you in with a different file's account. Save the file as UTF-8. UTF-16, which PowerShell 5.1's
`>` writes, also works.

## Use it

Use `SyncFreedomQuickBooks` anywhere python-quickbooks expects its `QuickBooks` client. Name the company by its realm
id, which you can copy from the **Realm id** column under [Companies](https://syncfreedom.com/app/companies/) (each row
has a **Copy** button):

```python
from quickbooks.objects.customer import Customer
from syncfreedom import SyncFreedomQuickBooks

qb = SyncFreedomQuickBooks(company_id="4620816365170156840")
customers = Customer.all(qb=qb)
```

The realm id never changes. Two shortcuts are also available:

- `SyncFreedomQuickBooks(company_name="Acme Hardware")`: by name, ignoring case. Names can change and can be shared;
  if two companies share the name, it raises `AmbiguousCompanyError` with both realm ids rather than guess which books
  to write to.
- `SyncFreedomQuickBooks()`: the account's only connected company. With more than one, the error lists their names
  and realm ids.

To pass the key from code instead, use `api_key="sf_live_..."`, or `credentials=`: a dict, a ConfigParser section, or
the path of an ini file.

Everything python-quickbooks does works: queries, any QuickBooks report, change data capture, creating, updating, voiding and
deleting records, batches, attachments (`upload`), PDFs and `send`. The one exception is `get_current_user()`, which
reads Intuit's appcenter and isn't available through SyncFreedom.

### Work with several companies

```python
from quickbooks.objects.customer import Customer
from syncfreedom import SyncFreedomQBOConnections, SyncFreedomQuickBooks

for company in SyncFreedomQBOConnections():
    if company.status != "connected":
        continue  # needs reconnecting under Companies in the dashboard
    qb = SyncFreedomQuickBooks.from_connection(company)
    print(company.qbo_company_name, len(Customer.all(qb=qb)))
```

Each company has `realm_id`, `qbo_company_name`, `status` (`"connected"` or `"needs_reauth"`), `sandbox` and the
usage figures below. `get_from_realm_id()` and `get_from_company_name()` pick one, and `company_name_list` lists the
names.

## Reads, credits and budgets

Intuit charges SyncFreedom for each read, so SyncFreedom counts them per company:

- Each connected company includes **400 reads a month** with the QuickBooks Online plan.
- Reads beyond those cost **$0.014 each** from prepaid [credits](https://syncfreedom.com/docs/billing-faq/). Add
  credits, turn on autofill, and set monthly budgets for the account, a company or an API key in the dashboard.
- Queries, gets, reports, change data capture and PDFs are reads. Writes, uploads and sandbox companies are free, and
  writes are never refused for credits.
- A read that credits or a budget can't pay for is refused before it reaches QuickBooks, so it costs nothing. The
  package raises `InsufficientCreditsError` (included reads used up and no credits left) or `BudgetReachedError` (a
  monthly budget has no room; the message names which budget).

The company list shows where you stand:

```python
from syncfreedom import SyncFreedomQBOConnections

connections = SyncFreedomQBOConnections()
if connections.credit_balance is not None:  # a Decimal in dollars, e.g. Decimal("23.486")
    print("Credit balance: ${0}".format(connections.credit_balance))
for company in connections:
    print(company.qbo_company_name, company.reads_this_month, "reads this month,",
          company.included_left, "included left,", company.paid_reads_this_month, "paid from credits")
```

- `reads_this_month` counts this calendar month's reads, included and paid; `included_left` is what remains of the
  400 included reads; `paid_reads_this_month` is the reads paid from credits.
- `monthly_budget_cents` is the company's monthly budget in cents, or `None` when it has none.
- `credit_balance` is the account's balance in dollars as a `Decimal`, and `credit_balance_mills` the same amount as an
  int in thousandths of a dollar. It can be slightly below zero after a small overdraft.
- `qb.connection` gives the same figures for one client's company.

To spend fewer reads, fetch larger pages (`MAXRESULTS 1000`), use `batch` for up to 30 operations in one read, and pass
the `SyncToken` you already have instead of reading a record again. Every call is listed in the
[call log](https://syncfreedom.com/app/credits/calls/).

## Long jobs and retries

SyncFreedom refreshes each connection with Intuit itself, so a script can run for as long as it needs with one client.

If SyncFreedom or Intuit is briefly unavailable (a dropped connection, a timeout, HTTP 502, 503 or 504, or Intuit's
own 429), **reads** (GET requests and queries) are tried again up to 3 times. The package waits as long as the server's `Retry-After` asks, at
most 2 minutes, or else 2, 4 and 8 seconds. Change the number of tries with `retries=`; `retries=0` turns this off.
Certificate and proxy errors are not retried, because they don't fix themselves.

**Writes and batches are never retried**, because a write that reached QuickBooks before the connection dropped would
run twice. To retry a write safely yourself, give it python-quickbooks' `request_id`, which QuickBooks uses to
recognize a repeat:

```python
import uuid

customer.save(qb=qb, request_id=str(uuid.uuid4()))  # reuse the same request_id when you retry this save
```

The one exception is an attachment upload refused as `busy` (SyncFreedom is already handling as many large uploads as
it allows). That refusal comes before anything reaches QuickBooks, so the upload is tried again like a read.

A call can take up to 3 minutes at worst (SyncFreedom allows 180 seconds), so QuickBooks requests wait up to 190
seconds for an answer, and give up after 10 seconds if SyncFreedom can't be reached. `timeout=` sets one limit for
both. Redirects are never followed, so the API key only ever goes to the server you set.

## Errors

When SyncFreedom refuses a request itself, the package raises a `syncfreedom.SyncFreedomError`, with SyncFreedom's
message in `.detail`, its error code in `.error` and the HTTP status in `.status_code`:

| Error | Status and `error` | When |
| --- | --- | --- |
| `BadRequestError` | 400 `bad_request`, 405 `method_not_allowed`, 415 `unsupported_media_type` | SyncFreedom could not accept the request as sent: a body it can't read safely, a method other than GET and POST, or an unsupported content type. A bug in the request; never retried. |
| `AuthenticationError` | 401 `unauthorized` | The API key is missing, wrong or revoked. |
| `SubscriptionInactiveError` | 402 `subscription_inactive` | The QuickBooks Online plan is not active. |
| `InsufficientCreditsError` | 402 `insufficient_credits` | A read past the company's 400 included reads this month, with no credits to pay for it. Writes still work. |
| `BudgetReachedError` | 402 `budget_reached` | A read a monthly budget (account, company or this key) has no room for; the message names the budget. |
| `PermissionDeniedError` | 403 `insufficient_scope` | The key lacks a permission this request needs. `.missing_permissions` lists it, e.g. `["qbo:create"]`. |
| `RegulatedIndustryError` | 403 `regulated_industry` | The account declared a regulated industry, so QuickBooks Online can't be used. |
| `CompanyNotFoundError` | 404 `not_found` | The company is not connected under this account (it may need reconnecting), or SyncFreedom does not allow the path. Also a `ValueError`. |
| `AmbiguousCompanyError` | | Two companies share the name asked for; pass `company_id`. Also a `ValueError`. |
| `NeedsReauthorizationError` | 409 `needs_reauth` | Reconnect the company under [Companies](https://syncfreedom.com/app/companies/). |
| `RequestTooLargeError` | 413 `too_large` | The body is over 10 MB, or 100 MB for an attachment upload. |
| `IntuitUnavailableError` | 502, 503 or 504 `intuit_unavailable` | Intuit did not answer within 180 seconds or answered with a redirect, or SyncFreedom's proxy stopped answering, even after retries; try again after `.retry_after` seconds. A write may have been saved: retry it with the same `request_id`. |
| `SyncFreedomError` | 500 `server_error` | An error of SyncFreedom's own; never retried. A write may have been saved, so check before sending it again, or resend it with the same `request_id`. |
| `ServerBusyError` | 503 `busy` | Too many large uploads (over 10 MB) are in progress, even after retries; try again after `.retry_after` seconds. |

The exception is chosen by the `error` code, since 402 and 403 each have several meanings. SyncFreedom marks its own
refusals with the header `X-SyncFreedom-Error: 1`; anything without it is QuickBooks' answer. SyncFreedom never answers
429 itself, so a 429 is always Intuit's (python-quickbooks raises it; reads are retried first).

```python
from quickbooks.objects.customer import Customer
from syncfreedom import InsufficientCreditsError, NeedsReauthorizationError, SyncFreedomQuickBooks

qb = SyncFreedomQuickBooks(company_id="4620816365170156840")
try:
    customers = Customer.all(qb=qb)
except NeedsReauthorizationError:
    print("Reconnect this company at syncfreedom.com.")
except InsufficientCreditsError:
    print("Add credits at syncfreedom.com, or wait for next month's included reads.")
```

Errors from QuickBooks itself, such as a validation error on an invoice or Intuit's own rate limit, keep their
`Fault` body and raise python-quickbooks' own exceptions, exactly as without SyncFreedom. Network problems that last past the retries raise
the usual `requests` exceptions.

## Sandbox and local servers

Whether calls go to Intuit's production or sandbox API is set on the SyncFreedom server for the whole site
(syncfreedom.com uses production, so `sandbox` is always `False` there). There is nothing to set in your script.
SyncFreedom also chooses the QuickBooks minor version unless you pass `minorversion=`.

To point the package at another SyncFreedom server, such as one running locally, pass `base_url="http://127.0.0.1:8000"`,
set the `SYNCFREEDOM_URL` environment variable, or add `base_url = http://127.0.0.1:8000` to the config file's
`[SYNCFREEDOM_CREDENTIALS]` section. The API key is only ever sent to that server.

## Other languages

Any QuickBooks client that lets you set its base URL can use SyncFreedom's proxy with an API key. See
[QuickBooks Online from your own scripts](https://syncfreedom.com/docs/qbo-token-api/).

## Upgrading from 1.x

SyncFreedom no longer hands out QuickBooks tokens. In 2.0, every request goes through SyncFreedom instead, which is
what Intuit's developer terms require and what lets SyncFreedom count reads. Most scripts need only these changes:

1. **Use an API key.** Email-and-password sign-in ended. [Create a key](#create-an-api-key) and replace `username`
   and `password` with `api_key` in your config file, or set `SYNCFREEDOM_API_KEY`. A key created with **Allow writes**
   in 1.x has Create, Update and Delete.
2. **Remove `sandbox=`.** SyncFreedom chooses the environment on its server.
3. **Stop using tokens directly.** Remove any code that read `access_token`. `access_token`, `refresh_token`,
   `expires_at`, `renew()`, `renew_token()`, `get_token()`, `SyncFreedomAuthClient` and `SyncFreedomOAuth2Session` are
   gone. Use `SyncFreedomQuickBooks` for every request. Using a removed name raises an error that says what replaced
   it.
4. **Expect read limits.** Past a company's 400 included reads a month, reads use credits, and a read with none left
   raises `InsufficientCreditsError` or `BudgetReachedError`. See [Reads, credits and budgets](#reads-credits-and-budgets).

The old token endpoints that 1.x uses stop working on 2026-12-11.

Queries, saves and other python-quickbooks calls are unchanged.

## Development

    python -m venv .venv
    .venv/Scripts/python -m pip install -e .   # .venv/bin/python on macOS and Linux
    .venv/Scripts/python -m unittest discover -s tests -t .

The tests run against a fake SyncFreedom proxy that follows its contract. `tests/test_live.py` calls the real one
and is skipped unless both `SYNCFREEDOM_LIVE_TESTS=1` and `SYNCFREEDOM_API_KEY` are set, so a key set for your own
scripts never runs it by accident (`SYNCFREEDOM_LIVE_REALM_ID` picks the company). Each run uses about four reads and
writes nothing. Set `SYNCFREEDOM_LIVE_READ_ONLY_KEY` to a read-only key to check the refused create.

## Changes in 2.0

- Every QuickBooks request goes through SyncFreedom's proxy at `<SyncFreedom>/qbo/v3`. The package no longer gets,
  holds or renews Intuit tokens.
- API key sign-in only. A username and password raise an error that says how to create a key; the password is never
  sent.
- SyncFreedom's refusals raise an exception chosen by their `error` code. New: `BadRequestError`,
  `InsufficientCreditsError`, `BudgetReachedError`, `RegulatedIndustryError`, `RequestTooLargeError` and
  `ServerBusyError`. `PermissionDeniedError` gains `.missing_permissions`, and every error has `.error`.
- Companies show `sandbox`, this month's `reads_this_month`, `included_left` and `paid_reads_this_month`, and
  `monthly_budget_cents`. `SyncFreedomQBOConnections` shows `credit_balance` (a `Decimal` in dollars) and
  `credit_balance_mills`. `qb.connection` fetches them for one client.
- Only reads are retried (and uploads refused as `busy`); writes and batches never are. QuickBooks requests wait up to
  190 seconds for an answer.
- SyncFreedom chooses the minor version unless you pass `minorversion=`.
- `SyncFreedomQuickBooks(company_id=...)` sends nothing until the first request.
- Removed: `sandbox=`, `auth_client=`, `qbo_connection_dict=`, `get_token()`, `access_token` and the other token
  fields, `renew()`, `renew_token()`, `SyncFreedomAuthClient`, `SyncFreedomOAuth2Session`, `Environments` and
  `get_current_user()`. No longer depends on `intuit-oauth` or `requests-oauthlib` directly.

## Changes in 1.1

- Works on a fresh install: no longer imports `rauth` or `future`, which python-quickbooks stopped installing.
- API key sign-in, from `api_key=`, an `api_key` entry in your credentials, or `SYNCFREEDOM_API_KEY`.
- The sign-in is found on its own (environment variables, `config.ini`, `~/.syncfreedom.ini`), and the company can be
  chosen by `company_name=` or left out when the account has only one. Two companies with the same name raise
  `AmbiguousCompanyError` instead of picking one.
- Brief outages at SyncFreedom or Intuit are retried, honoring `Retry-After`.
- Clear exceptions instead of `AssertionError`, and a timeout on every request to SyncFreedom.
- `SyncFreedomQuickBooks.from_connection()`, `base_url=` and `SYNCFREEDOM_URL`.
