Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
- Fix `statistical-journals list` sending comma-separated ID filters (`--number`, `--account-id`, `--line-account-id`) in a form the API could not read
- Comma-separated ID filters now reject an empty value instead of silently listing every row, and can be repeated (`--id 1,2 --id 3`)
- The `list --all` resume hint now repeats every filter of commands with their own filters, and shell-quotes values with spaces
- Add `add-attachments` to the 13 transaction types whose API accepts file uploads, and `replace-attachments` to invoices. Files are checked against the 10 MiB limit before anything is sent
- Fix attachment uploads failing with "Idempotency-Key is only supported on JSON requests". Uploads are sent without the key and retried only after a 429, so a retry cannot attach files twice
- `statistical-journals add-attachments` now checks the 10 MiB limit before uploading, rejects folders, and rejects prefixes other than `SJ-`
- Line-item tables label the quantity column Quantity
- Update the CLI greeting logo to DualEntry
- Add `export-jobs` commands (`create`, `list`, `get`, `wait`) for on-demand destination data refreshes via the public API
Expand Down
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,16 @@ dualentry invoices create --file invoice.json
dualentry journal-entries list --start-date 2025-01-01 --end-date 2025-03-31 --format json
```

### Attach a receipt to a bill

```bash
# Pass the record number from the # column; repeat -f for several files (10 MiB max each)
dualentry bills add-attachments 1042 -f receipt.pdf -f approval.eml

# Invoices can also swap out every attachment at once
dualentry invoices replace-attachments 318 -f signed-invoice.pdf
```

### Automate in CI/CD

Set `X_API_KEY` in your environment for non-interactive authentication:
Expand Down Expand Up @@ -97,6 +107,7 @@ dualentry export-jobs wait 42 --interval 10 --timeout 1800

Most resources support `list`, `get`, `create`, and `update`; some (e.g. Bank Connections, Bank Match) expose a different verb set — see `--help`.
Export jobs support `create`, `list`, `get`, and `wait` (poll until finished).
Transactions that accept files support `add-attachments` (see `dualentry <resource> --help`); invoices also support `replace-attachments`.

## Output Formats

Expand Down
57 changes: 18 additions & 39 deletions src/dualentry_cli/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,35 +6,28 @@
import sys
import time
import uuid
from typing import Any
from typing import Any, TypeAlias

import httpx

from dualentry_cli import USER_AGENT

# Status codes that should be retried (transient errors)
_RETRYABLE_STATUS_CODES = {429, 502, 503, 504}
# Transient transport failures. Deliberately excludes LocalProtocolError,
# UnsupportedProtocol, DecodingError and TooManyRedirects: those fail the same
# way every time, so retrying only delays the error the user needs to see.
# Only errors that might succeed on retry (not protocol/decoding/redirect failures).
_RETRYABLE_EXCEPTIONS = (httpx.TimeoutException, httpx.NetworkError, httpx.RemoteProtocolError)
_RETRY_DELAYS = [1, 2, 4] # Exponential backoff: 1s, 2s, 4s
_RETRY_DELAYS = [1, 2, 4]
_MAX_RETRIES = len(_RETRY_DELAYS)

# The API replays the original response for a repeated Idempotency-Key instead of
# running the operation again, so a retried write cannot create a duplicate record.
# https://docs.dualentry.com/developers/release-notes/2026-08-12
_IDEMPOTENCY_HEADER = "Idempotency-Key"
_IDEMPOTENCY_METHODS = frozenset({"POST", "PUT", "PATCH", "DELETE"})

# 429 and the in-flight 409 both report exactly how long to wait.
# https://docs.dualentry.com/developers/guides/rate-limiting
_RETRY_AFTER_HEADER = "Retry-After"

_MAX_RETRY_AFTER = 60

# Hard ceiling for --all crawls: page_size 100 x 1000 pages = 100_000 items.
# Truncation must warn; never report the truncated length as the API total.
# Upload part: filename + bytes (not an open file), safe to resend on 429 retry.
Multipart: TypeAlias = list[tuple[str, tuple[str, bytes]]]

# Max pages for `list --all` (100 items x 1000 pages).
_MAX_PAGES = 1000


Expand All @@ -44,22 +37,14 @@ def _retry_after_seconds(response: httpx.Response) -> int | None:
if raw is None:
return None
try:
# RFC 9110 delay-seconds is a non-negative integer
seconds = int(raw.strip())
except (TypeError, ValueError):
return None
return seconds if seconds >= 0 else None


def _is_retryable(response: httpx.Response) -> bool:
"""
Whether this response should be retried with the same idempotency key.

409 means two different things, told apart by Retry-After:
with the header the first request is still running and we should retry;
without it the original response was too large to store, the write did not run again
https://docs.dualentry.com/developers/guides/idempotency-and-write-validation
"""
"""Retry 429/5xx; retry 409 only when Retry-After means the first write is still running."""
if response.status_code == 409:
return _RETRY_AFTER_HEADER in response.headers
return response.status_code in _RETRYABLE_STATUS_CODES
Expand Down Expand Up @@ -173,10 +158,11 @@ def _handle_response(self, response: httpx.Response, *, sent_idempotency_key: bo

def _request(self, method: str, path: str, **kwargs) -> dict:
method = method.upper()
keyed = method in _IDEMPOTENCY_METHODS
# Multipart POST cannot send Idempotency-Key; only retry 429, not 5xx/network.
unkeyed_write = method in _IDEMPOTENCY_METHODS and "files" in kwargs
keyed = method in _IDEMPOTENCY_METHODS and not unkeyed_write
if keyed:
# One key per logical request, deliberately generated here rather than
# per attempt: reusing it across retries is what makes a retry safe.
# Same key on every attempt so a retried JSON write stays idempotent.
headers = dict(kwargs.pop("headers", None) or {})
headers.setdefault(_IDEMPOTENCY_HEADER, str(uuid.uuid4()))
kwargs["headers"] = headers
Expand All @@ -185,25 +171,24 @@ def _request(self, method: str, path: str, **kwargs) -> dict:
response = self._client.request(method, path, **kwargs)
return self._handle_response(response, sent_idempotency_key=keyed)

# Retry logic with visible feedback
for attempt, backoff in enumerate(_RETRY_DELAYS):
retry_after = None
try:
response = self._client.request(method, path, **kwargs)
if not _is_retryable(response):
retryable = response.status_code == 429 if unkeyed_write else _is_retryable(response)
if not retryable:
return self._handle_response(response, sent_idempotency_key=keyed)
retry_after = _retry_after_seconds(response)
if retry_after is not None and retry_after > _MAX_RETRY_AFTER:
return self._handle_response(response, sent_idempotency_key=keyed)
except _RETRYABLE_EXCEPTIONS:
pass
if unkeyed_write:
raise

# every retry waits, including the one after the loop
delay = retry_after if retry_after is not None else backoff
print(f"\033[33mRetrying in {delay}s... (attempt {attempt + 2}/{_MAX_RETRIES + 1})\033[0m", file=sys.stderr)
time.sleep(delay)

# Final attempt
response = self._client.request(method, path, **kwargs)
return self._handle_response(response, sent_idempotency_key=keyed)

Expand All @@ -219,13 +204,7 @@ def paginate(
*,
start_offset: int = 0,
) -> dict:
"""
Fetch pages and return {items, count, next_offset?}.

``count`` is always the API total, regardless of truncation.
When the page ceiling (or ``max_items``) stops the crawl early,
``next_offset`` is set so callers can resume.
"""
"""Return {items, count, next_offset?}. ``count`` is the API total even when truncated."""
params = dict(params or {})
params["limit"] = page_size
params["offset"] = start_offset
Expand Down Expand Up @@ -254,7 +233,7 @@ def post(
path: str,
json: dict[str, Any] | None = None,
*,
files: list[tuple[str, tuple[str, bytes]]] | None = None,
files: Multipart | None = None,
) -> dict:
if files is not None:
return self._request("POST", path, files=files)
Expand Down
123 changes: 121 additions & 2 deletions src/dualentry_cli/commands/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@
import typer

from dualentry_cli.cli import HelpfulGroup, make_list_command_cls
from dualentry_cli.client import _MAX_PAGES
from dualentry_cli.output import _RECORD_PREFIX, format_output
from dualentry_cli.client import _MAX_PAGES, Multipart
from dualentry_cli.output import _NUMBER_PREFIXED, _RECORD_PREFIX, format_output, print_attachments

if TYPE_CHECKING:
from typer.models import OptionInfo
Expand Down Expand Up @@ -292,6 +292,111 @@ def _strip_to_writable(data: dict) -> dict:
return payload


# ── Attachment helpers ─────────────────────────────────────────────

# Validate every file before upload so one bad file does not leave prior files stored.
ATTACHMENT_MAX_BYTES = 10 * 1024 * 1024
_ATTACHMENT_MAX_LABEL = f"{ATTACHMENT_MAX_BYTES // 2**20} MiB"

AttachmentFiles = typer.Option(
...,
"--file",
"-f",
help=f"File to attach (max {_ATTACHMENT_MAX_LABEL}); repeat the flag for several",
exists=True,
dir_okay=False,
readable=True,
)


def _record_number_arg(value: str, resource: str) -> str:
"""Attachment URLs use record #, not display ID (`IN-42` is rejected except `SJ-3`)."""
prefix = _RECORD_PREFIX.get(resource)
number_prefixed = resource in _NUMBER_PREFIXED
if number_prefixed and prefix:
head, sep, rest = value.partition("-")
if sep and head.upper() == prefix:
value = rest
# isascii(): str.isdigit() also accepts "²" and "٤٢", which no record URL matches.
if value.isascii() and value.isdigit():
return value
raise typer.BadParameter(f"expected a record number{_record_number_hint(resource)}, got {value!r}", param_hint="'NUMBER'")


def _record_number_hint(resource: str) -> str:
"""Suffix for a bad record-number error."""
prefix = _RECORD_PREFIX.get(resource)
if not prefix:
return " from the # column"
if resource in _NUMBER_PREFIXED:
return f" such as 3 or {prefix}-3"
return f" from the # column (not the {prefix}-… ID)"


def _read_attachment(path: Path) -> bytes:
"""Read one `--file`; reject empty or over limit (read stops at limit+1 byte)."""
with path.open("rb") as fh:
content = fh.read(ATTACHMENT_MAX_BYTES + 1)
if not content:
raise typer.BadParameter(f"{path} is empty", param_hint="'--file'")
if len(content) > ATTACHMENT_MAX_BYTES:
raise typer.BadParameter(f"{path} is over the {_ATTACHMENT_MAX_LABEL} limit", param_hint="'--file'")
return content


def _read_attachments(files: Sequence[Path]) -> Multipart:
"""Read all `--file` paths in order; fail before POST if any file is invalid."""
contents = [_read_attachment(path) for path in files]
return [("files", (path.name, content)) for path, content in zip(files, contents, strict=True)]


def _upload_attachments(
path: str,
resource: str,
number: str,
files: Sequence[Path],
output: str,
*,
replace: bool,
) -> None:
from dualentry_cli.main import get_client

record_number = _record_number_arg(number, resource)
multipart = _read_attachments(files)
route = "attachments/replace/" if replace else "attachments/"
data = get_client().post(f"/{path}/{record_number}/{route}", files=multipart)
if output == "json":
format_output(data, resource=resource, fmt=output)
else:
print_attachments(data, label=f"{resource.replace('-', ' ')} {record_number}")


def _add_attachment_commands(app: typer.Typer, path: str, resource: str, *, replace: bool) -> None:
"""Add `add-attachments` and optionally `replace-attachments` to a resource app."""
prefix = _RECORD_PREFIX.get(resource)
number_help = f"Record number (the # column), e.g. 3 or {prefix}-3" if resource in _NUMBER_PREFIXED and prefix else "Record number (the # column)"

@app.command("add-attachments")
def add_attachments_cmd(
number: str = typer.Argument(help=number_help),
file: list[Path] = AttachmentFiles,
output: str = Format,
) -> None:
"""Attach file(s) to a record, keeping its existing attachments."""
_upload_attachments(path, resource, number, file, output, replace=False)

if replace:

@app.command("replace-attachments")
def replace_attachments_cmd(
number: str = typer.Argument(help=number_help),
file: list[Path] = AttachmentFiles,
output: str = Format,
) -> None:
"""Replace all attachments on a record. Its current attachments are deleted."""
_upload_attachments(path, resource, number, file, output, replace=True)


# ── Factory ─────────────────────────────────────────────────────────


Expand All @@ -306,6 +411,8 @@ def make_resource_app(
has_delete: bool = False,
has_number: bool = False,
has_post: bool = False,
has_attachments: bool = False,
has_replace_attachments: bool = False,
filters: set[str],
status_param: str = "record_status",
template: dict | None = None,
Expand All @@ -317,6 +424,9 @@ def make_resource_app(

`filters` lists the flags this resource's v2 list endpoint declares; the rest
are removed from `list` so the API cannot silently drop them.

`has_attachments` and `has_replace_attachments` mirror the v2 routes
`POST /{number}/attachments/` and `POST /{number}/attachments/replace/`.
"""
import inspect

Expand All @@ -325,6 +435,12 @@ def make_resource_app(
if unknown:
msg = f"{name}: unknown filter flags {sorted(unknown)}"
raise ValueError(msg)
if has_replace_attachments and not has_attachments:
msg = f"{name}: has_replace_attachments requires has_attachments"
raise ValueError(msg)
if has_attachments and not has_number:
msg = f"{name}: has_attachments requires has_number (attachment routes take the record number)"
raise ValueError(msg)
remove = ALL_FILTERS - filters

gated_options = {option for flag in remove for option in FILTER_OPTIONS[flag]}
Expand Down Expand Up @@ -543,6 +659,9 @@ def post_cmd(

post_cmd.__doc__ = f"Post a draft {resource}."

if has_attachments:
_add_attachment_commands(app, path, resource, replace=has_replace_attachments)

if template is not None:

@app.command("template")
Expand Down
16 changes: 2 additions & 14 deletions src/dualentry_cli/commands/statistical_journals.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
ResumeFlag,
Search,
Status,
_add_attachment_commands,
_load_json_file,
_strip_record_prefix,
csv_ints_option,
Expand Down Expand Up @@ -152,17 +153,4 @@ def update_cmd(
format_output(data, resource="statistical-journal", fmt=output)


@app.command("add-attachments")
def add_attachments_cmd(
number: str = typer.Argument(help="Record number of the journal"),
file: list[Path] = typer.Option(..., "--file", "-f", help="Attachment file(s) to upload", exists=True, readable=True),
output: str = Format,
):
"""Upload attachment file(s) to a statistical journal."""
from dualentry_cli.main import get_client

client = get_client()
stripped = _strip_record_prefix(number)
multipart = [("files", (path.name, path.read_bytes())) for path in file]
data = client.post(f"/statistical-journals/{stripped}/attachments/", files=multipart)
format_output(data, resource="statistical-journal", fmt=output)
_add_attachment_commands(app, "statistical-journals", "statistical-journal", replace=False)
Loading
Loading