Metadata-Version: 2.4
Name: syncfreedom
Version: 1.1.0
Summary: Use python-quickbooks with QuickBooks Online companies connected on SyncFreedom.com, without an OAuth flow 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,oauth,accounting
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Financial and Insurance Industry
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: intuit-oauth>=1.2.4
Requires-Dist: requests>=2.26
Requires-Dist: requests-oauthlib>=1.3
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 ask SyncFreedom for a current access token.

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

## Install

    pip install -U syncfreedom

`-U` also upgrades an existing 1.0 install. You need an active SyncFreedom QuickBooks Online plan and at least one connected company.

## Sign in

Pick one:

- **API key (recommended).** In the SyncFreedom dashboard, open **API keys**, check **Allow writes**, and create a key.
  It starts with `sf_live_`. You can revoke it without changing your password, and the wrong-password limit does not
  apply to it. Writes are required because an Intuit access token can always write.
- **Email and password.** Your syncfreedom.com email and password. A username from the old site also works.

Save it 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
# or, instead of api_key:
# username = you@example.com
# password = your_syncfreedom_password
```

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

1. The `SYNCFREEDOM_API_KEY` environment variable.
2. The `SYNCFREEDOM_USERNAME` and `SYNCFREEDOM_PASSWORD` environment variables.
3. 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:

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

qb = SyncFreedomQuickBooks(company_name="Acme Hardware")
customers = Customer.all(qb=qb)
```

Choose the company in any of these ways:

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

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

### 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)))
```

With an API key the list also includes companies that need reconnecting (`status` is `"needs_reauth"`); with an
email and password it holds only connected companies.

`connections.company_name_list` lists the names, and `get_from_company_name()` and `get_from_realm_id()` pick one.

## Long jobs

SyncFreedom refreshes each connection with Intuit itself, so you never handle a refresh token (the `refresh_token`
field holds a placeholder). `SyncFreedomQuickBooks` asks SyncFreedom for a new access token before any request made
with less than five minutes left on the current one, and once more if QuickBooks answers 401. A script can run for as
long as it needs to with one client.

If SyncFreedom or Intuit is briefly unavailable (a network error, or HTTP 502, 503 or 504), the package waits and
tries again up to 3 times. It 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. Wrong-password lockouts are never
retried.

## Errors

Every error from SyncFreedom is a `syncfreedom.SyncFreedomError`, with SyncFreedom's message in `.detail` and the HTTP
status in `.status_code`:

| Error | When |
| --- | --- |
| `AuthenticationError` | Wrong email or password, or a missing or revoked API key (401). |
| `SubscriptionInactiveError` | The QuickBooks Online plan is not active (402). |
| `PermissionDeniedError` | The API key is read-only; create one with **Allow writes** (403). |
| `CompanyNotFoundError` | The company is not connected under this account, or may need reconnecting. Also a `ValueError`. |
| `AmbiguousCompanyError` | Two companies share the name asked for; pass `company_id`. Also a `ValueError`. |
| `NeedsReauthorizationError` | Intuit refused the connection; reconnect it in the dashboard (409). |
| `RateLimitedError` | Too many wrong passwords from this network; wait `.retry_after` seconds (429). |
| `IntuitUnavailableError` | Intuit could not refresh the token just now; retry after `.retry_after` seconds (503). |

```python
from syncfreedom import NeedsReauthorizationError

try:
    qb = SyncFreedomQuickBooks(company_id=realm_id, credentials=credentials)
except NeedsReauthorizationError as error:
    print("Reconnect this company at syncfreedom.com:", error.detail)
```

Network problems that last past the retries raise the usual `requests` exceptions. Each request to SyncFreedom times
out after 30 seconds; change it with `timeout=`.

Errors from QuickBooks itself, such as a validation error on an invoice, are python-quickbooks' own exceptions, as
before.

## Sandbox and local servers

SyncFreedom says which QuickBooks environment its companies are in, and which minor version to use, so there is
nothing to set. Only against an older SyncFreedom server that leaves this out of its email-and-password responses do
you need `sandbox=True` for sandbox companies. The `sandbox` argument will be removed in 2.0.

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.

## Token API from other languages

The same tokens are available over plain HTTP with an API key. See
[QuickBooks Online from your own scripts](https://syncfreedom.com/docs/qbo-token-api/).

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

`tests/test_live.py` calls the real server and is skipped unless `SYNCFREEDOM_LIVE_REALM_ID` and either
`SYNCFREEDOM_API_KEY` or `SYNCFREEDOM_USERNAME` and `SYNCFREEDOM_PASSWORD` are set.

## 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.
- New access tokens come from SyncFreedom automatically during long jobs.
- Brief outages at SyncFreedom or Intuit are retried, honoring `Retry-After`.
- Clear exceptions instead of `AssertionError`, and a timeout on every request to SyncFreedom.
- Sends minor version 75, or the one SyncFreedom names, unless you pass `minorversion=`.
- `SyncFreedomQuickBooks.from_connection()`, `base_url=` and `SYNCFREEDOM_URL`.
- An account with no connected companies gives an empty list instead of an error.
- Creating a client no longer downloads Intuit's discovery document.
