commit ff9a859d0b87286ec6d9af7c07a6ec4e752e1e57 Author: Andrew Bryant Date: Fri Oct 23 14:30:01 2026 -0400 Initial commit: async Rust client for the Invoice Ninja v5 API Covers Clients, Invoices, Quotes, Credits, Payments, Products, Expenses, Projects, Tasks, and Vendors, each with list, list_all, get, create, update, and delete, generated by the resource_methods! macro. Every model carries a #[serde(flatten)] extra map so fields the API returns but the crate does not model survive a get/update round-trip instead of being silently dropped. Includes a Nix dev shell (Rust via rust-overlay), a GitHub Actions CI workflow running build/test/fmt/clippy, and round-trip tests for the extra-preservation invariant. Co-Authored-By: Claude Opus 5 diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..2249a2a --- /dev/null +++ b/.editorconfig @@ -0,0 +1,18 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[*.rs] +indent_style = space +indent_size = 4 + +[*.{yml,yaml,toml,nix}] +indent_style = space +indent_size = 2 + +[*.md] +trim_trailing_whitespace = false diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..d7702f7 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,22 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +env: + CARGO_TERM_COLOR: always + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt, clippy + - run: cargo build --all-targets + - run: cargo test + - run: cargo fmt --check + - run: cargo clippy --all-targets -- -D warnings diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..212aab3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +/target +.devenv/ +.direnv/ +*.swp diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..8e2a65b --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,72 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## What this is + +An async Rust client for the [Invoice Ninja](https://www.invoiceninja.com/) v5 API. + +## Development environment + +This project uses Nix for toolchain management (Rust via `rust-overlay`): + +```sh +nix develop +``` + +## Common commands + +```sh +cargo build +cargo test +cargo test # run a single test +cargo check +cargo clippy +cargo fmt + +# Run the example (requires IN_API_TOKEN, optionally IN_BASE_URL) +IN_API_TOKEN=... cargo run --example list_clients +``` + +Tests live in `tests/` (integration-style, no network access required); +`src/` has no `#[test]` modules. + +## Architecture + +- `src/client.rs` — `InvoiceNinjaClient` holds a `reqwest::Client` (with the + `X-Api-Token` auth header baked in) and a `base_url`. Low-level helpers + (`get_list`, `get_one`, `post_one`, `put_one`, `delete_one`) handle request + dispatch and decode `ListResponse` / `ItemResponse` envelopes, mapping + non-2xx responses through `api_error` into `Error::Api`. +- Per-resource methods (`list_clients`, `get_invoice`, `create_product`, etc.) + are generated by the `resource_methods!` macro at the bottom of + `client.rs`, which expands to + `list`/`list_all`/`get`/`create`/`update`/`delete` for a given REST path and + model type. **To add a new resource**: add a model under `src/models/`, + re-export it from `src/models/mod.rs`, and add one `resource_methods!` + invocation in `client.rs`. Note the macro takes six method names before the + path and model — adding a resource means passing all six. +- `list_*` returns one page; `list_all_*` goes through `get_all_pages`, which + follows `page`/`per_page` until a page returns fewer rows than requested. +- `src/models/` — one file per resource (`client.rs`, `invoice.rs`, + `payment.rs`, `product.rs`, `expense.rs`, `project.rs`, `task.rs`, + `vendor.rs`), plus `common.rs` for shared envelope/pagination types + (`ListParams`, `ListResponse`, `ItemResponse`, `Meta`, `Pagination`). + Invoice Ninja stores quotes and credits in the same table as invoices (an + `entity_type` field distinguishes them), so `Quote` and `Credit` are type + aliases for `Invoice` (`src/models/invoice.rs`) and share the + `/quotes`, `/credits`, and `/invoices` paths via the macro. +- Every model struct has a `#[serde(flatten)] pub extra: Map` + field. This preserves any API fields not explicitly modeled, so a `get` + followed by an `update` round-trips without silently dropping data. Keep + this pattern when adding fields or new models. +- `src/error.rs` — `Error` enum (`thiserror`) covering transport, JSON + decode, API error responses (with per-field validation `errors` map), and + client construction errors. `ApiErrorBody` mirrors Invoice Ninja's error + JSON shape. + +## Coverage + +Clients, Invoices, Quotes, Credits, Payments, Products, Expenses, Projects, +Tasks, and Vendors, each with `list`, `list_all`, `get`, `create`, `update`, +and `delete`. diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..9353655 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,1169 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86e055fa6e3e40ad6187ba25b6855eeb635d5271f8e0f0e1e9a5826b8d75bea0" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +dependencies = [ + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-tls" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0" +dependencies = [ + "bytes", + "http-body-util", + "hyper", + "hyper-util", + "native-tls", + "tokio", + "tokio-native-tls", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "invoiceninjars" +version = "0.1.0" +dependencies = [ + "reqwest", + "serde", + "serde_json", + "thiserror", + "tokio", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys", +] + +[[package]] +name = "native-tls" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2" +dependencies = [ + "libc", + "log", + "openssl", + "openssl-probe", + "openssl-sys", + "schannel", + "security-framework", + "security-framework-sys", + "tempfile", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "openssl" +version = "0.10.81" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45" +dependencies = [ + "bitflags", + "cfg-if", + "foreign-types", + "libc", + "openssl-macros", + "openssl-sys", +] + +[[package]] +name = "openssl-macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "openssl-probe" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" + +[[package]] +name = "openssl-sys" +version = "0.9.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-tls", + "hyper-util", + "js-sys", + "log", + "native-tls", + "percent-encoding", + "pin-project-lite", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-native-tls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "rustix" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "socket2", + "tokio-macros", + "windows-sys", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tokio-native-tls" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" +dependencies = [ + "native-tls", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.9", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..b389343 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "invoiceninjars" +version = "0.1.0" +edition = "2021" +description = "An async Rust client for the Invoice Ninja v5 API" +license = "MIT" +repository = "https://github.com/bryant/invoiceninjars" + +[dependencies] +reqwest = { version = "0.12", default-features = false, features = ["json", "native-tls"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +thiserror = "2" + +[dev-dependencies] +tokio = { version = "1", features = ["rt-multi-thread", "macros"] } diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..e3ec1d1 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 bryant + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..04aedb7 --- /dev/null +++ b/README.md @@ -0,0 +1,44 @@ +# invoiceninjars + +An async Rust client for the [Invoice Ninja](https://www.invoiceninja.com/) v5 API. + +## Development + +Enter the dev shell (Rust toolchain via `rust-overlay`): + +```sh +nix develop +``` + +## Usage + +```rust +use invoiceninjars::{InvoiceNinjaClient, models::ListParams}; + +let client = InvoiceNinjaClient::new( + "https://invoicing.co/api/v1", // or your self-hosted base URL + std::env::var("IN_API_TOKEN")?, +)?; + +let clients = client.list_clients(&ListParams::new().per_page(50)).await?; +``` + +List endpoints are paginated. `list_*` returns a single page; `list_all_*` +follows pagination and returns every matching record: + +```rust +let all_clients = client.list_all_clients(&ListParams::new()).await?; +``` + +Run the example (requires `IN_API_TOKEN`, optionally `IN_BASE_URL`): + +```sh +IN_API_TOKEN=... cargo run --example list_clients +``` + +## Coverage + +Clients, Invoices, Quotes, Credits, Payments, Products, Expenses, Projects, +Tasks, and Vendors, each with `list`, `list_all`, `get`, `create`, `update`, +and `delete`. Add more resources by adding a model under `src/models/` and a +`resource_methods!` invocation in `src/client.rs`. diff --git a/examples/list_clients.rs b/examples/list_clients.rs new file mode 100644 index 0000000..e1aa925 --- /dev/null +++ b/examples/list_clients.rs @@ -0,0 +1,21 @@ +use invoiceninjars::models::ListParams; +use invoiceninjars::InvoiceNinjaClient; + +#[tokio::main] +async fn main() -> invoiceninjars::Result<()> { + let base_url = + std::env::var("IN_BASE_URL").unwrap_or_else(|_| "https://invoicing.co/api/v1".into()); + let token = std::env::var("IN_API_TOKEN").expect("set IN_API_TOKEN"); + + let client = InvoiceNinjaClient::new(base_url, token)?; + + let clients = client + .list_clients(&ListParams::new().per_page(10).sort("created_at|desc")) + .await?; + + for c in clients { + println!("{:?}\t{}", c.id, c.name); + } + + Ok(()) +} diff --git a/flake.lock b/flake.lock new file mode 100644 index 0000000..3e1f1ef --- /dev/null +++ b/flake.lock @@ -0,0 +1,82 @@ +{ + "nodes": { + "flake-utils": { + "inputs": { + "systems": "systems" + }, + "locked": { + "lastModified": 1791914995, + "narHash": "sha256-Zf/xfQEAasnwnmEfHqW/4hjDE/s44yn2hD4RuVIZRjA=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "b7a79d3fea1e214f6d668d521cecec0c01e26544", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "flake-utils", + "type": "github" + } + }, + "nixpkgs": { + "locked": { + "lastModified": 1792502884, + "narHash": "sha256-IoNisKcGbUjdd45qCqywGMCYmZ5EnkxezvLII0FWwNA=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "02c087f3fe673c9e317f206a627cb6b910336dbe", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixos-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "root": { + "inputs": { + "flake-utils": "flake-utils", + "nixpkgs": "nixpkgs", + "rust-overlay": "rust-overlay" + } + }, + "rust-overlay": { + "inputs": { + "nixpkgs": [ + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1792739799, + "narHash": "sha256-M2rr/yPbTHvgAzCyZ+zHJHflFM0XU7t42Sw2skA3TQM=", + "owner": "oxalica", + "repo": "rust-overlay", + "rev": "b0829a2cc9f7b596583331d78a942c1e5170d8a0", + "type": "github" + }, + "original": { + "owner": "oxalica", + "repo": "rust-overlay", + "type": "github" + } + }, + "systems": { + "locked": { + "lastModified": 1681028828, + "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=", + "owner": "nix-systems", + "repo": "default", + "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e", + "type": "github" + }, + "original": { + "owner": "nix-systems", + "repo": "default", + "type": "github" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 0000000..c3f49ee --- /dev/null +++ b/flake.nix @@ -0,0 +1,34 @@ +{ + description = "invoiceninjars: a Rust client for the Invoice Ninja v5 API"; + + inputs = { + nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; + rust-overlay.url = "github:oxalica/rust-overlay"; + rust-overlay.inputs.nixpkgs.follows = "nixpkgs"; + flake-utils.url = "github:numtide/flake-utils"; + }; + + outputs = { self, nixpkgs, rust-overlay, flake-utils, ... }: + flake-utils.lib.eachDefaultSystem (system: + let + pkgs = import nixpkgs { + inherit system; + overlays = [ rust-overlay.overlays.default ]; + }; + + rustToolchain = pkgs.rust-bin.stable.latest.default.override { + extensions = [ "rust-src" "rust-analyzer" "clippy" "rustfmt" ]; + }; + in + { + devShells.default = pkgs.mkShell { + packages = [ + rustToolchain + pkgs.pkg-config + pkgs.openssl + ]; + + RUST_SRC_PATH = "${rustToolchain}/lib/rustlib/src/rust/library"; + }; + }); +} diff --git a/src/client.rs b/src/client.rs new file mode 100644 index 0000000..f493c7b --- /dev/null +++ b/src/client.rs @@ -0,0 +1,300 @@ +use reqwest::{header, StatusCode}; +use serde::{de::DeserializeOwned, Serialize}; + +use crate::error::{ApiErrorBody, Error, Result}; +use crate::models::{ + Client as ClientModel, Credit, Expense, Invoice, ItemResponse, ListParams, ListResponse, + Payment, Product, Project, Quote, Task, Vendor, +}; + +/// An async client for the Invoice Ninja v5 API. +/// +/// `base_url` should point at the API root, e.g. `https://invoicing.co/api/v1` +/// for the hosted app, or `https://your-domain.example/api/v1` for a +/// self-hosted install. +#[derive(Debug, Clone)] +pub struct InvoiceNinjaClient { + http: reqwest::Client, + base_url: String, +} + +impl InvoiceNinjaClient { + pub fn new(base_url: impl Into, api_token: impl Into) -> Result { + let base_url = base_url.into(); + if base_url.trim().is_empty() { + return Err(Error::InvalidBaseUrl(base_url)); + } + let base_url = base_url.trim_end_matches('/').to_string(); + + let mut headers = header::HeaderMap::new(); + let mut token_value = header::HeaderValue::from_str(&api_token.into()) + .map_err(|e| Error::InvalidToken(e.to_string()))?; + token_value.set_sensitive(true); + headers.insert("X-Api-Token", token_value); + headers.insert( + header::ACCEPT, + header::HeaderValue::from_static("application/json"), + ); + headers.insert( + "X-Requested-With", + header::HeaderValue::from_static("XMLHttpRequest"), + ); + + let http = reqwest::Client::builder() + .default_headers(headers) + .build()?; + + Ok(Self { http, base_url }) + } + + fn url(&self, path: &str) -> String { + format!("{}/{}", self.base_url, path.trim_start_matches('/')) + } + + async fn decode(response: reqwest::Response) -> Result { + let status = response.status(); + let bytes = response.bytes().await?; + + if status.is_success() { + Ok(serde_json::from_slice(&bytes)?) + } else { + Err(Self::api_error(status, &bytes)) + } + } + + fn api_error(status: StatusCode, bytes: &[u8]) -> Error { + match serde_json::from_slice::(bytes) { + Ok(body) => Error::Api { + status, + message: body.message, + errors: body.errors, + }, + Err(_) => Error::Api { + status, + message: String::from_utf8_lossy(bytes).into_owned(), + errors: Default::default(), + }, + } + } + + async fn get_list( + &self, + path: &str, + params: &ListParams, + ) -> Result> { + let response = self.http.get(self.url(path)).query(params).send().await?; + let body: ListResponse = Self::decode(response).await?; + Ok(body.data) + } + + /// Pages through a list endpoint, following `page`/`per_page` until a + /// page comes back shorter than requested (or empty). + async fn get_all_pages( + &self, + path: &str, + params: &ListParams, + ) -> Result> { + const DEFAULT_PAGE_SIZE: u64 = 50; + + let per_page = params.per_page.unwrap_or(DEFAULT_PAGE_SIZE); + let mut page = params.page.unwrap_or(1); + let mut params = params.clone(); + params.per_page = Some(per_page); + + let mut all = Vec::new(); + loop { + params.page = Some(page); + let response = self.http.get(self.url(path)).query(¶ms).send().await?; + let body: ListResponse = Self::decode(response).await?; + let got = body.data.len() as u64; + all.extend(body.data); + + if got < per_page { + break; + } + page += 1; + } + Ok(all) + } + + async fn get_one(&self, path: &str) -> Result { + let response = self.http.get(self.url(path)).send().await?; + let body: ItemResponse = Self::decode(response).await?; + Ok(body.data) + } + + async fn post_one( + &self, + path: &str, + payload: &B, + ) -> Result { + let response = self.http.post(self.url(path)).json(payload).send().await?; + let body: ItemResponse = Self::decode(response).await?; + Ok(body.data) + } + + async fn put_one( + &self, + path: &str, + payload: &B, + ) -> Result { + let response = self.http.put(self.url(path)).json(payload).send().await?; + let body: ItemResponse = Self::decode(response).await?; + Ok(body.data) + } + + async fn delete_one(&self, path: &str) -> Result<()> { + let response = self.http.delete(self.url(path)).send().await?; + let status = response.status(); + let bytes = response.bytes().await?; + if status.is_success() { + Ok(()) + } else { + Err(Self::api_error(status, &bytes)) + } + } +} + +/// Generates typed list/list_all/get/create/update/delete methods for a +/// resource backed by a single Invoice Ninja REST endpoint (e.g. `/clients`). +macro_rules! resource_methods { + ($list:ident, $list_all:ident, $get:ident, $create:ident, $update:ident, $delete:ident, $path:literal, $model:ty) => { + pub async fn $list(&self, params: &ListParams) -> Result> { + self.get_list($path, params).await + } + + /// Like the paginated list method, but automatically follows + /// pagination and returns every matching record across all pages. + pub async fn $list_all(&self, params: &ListParams) -> Result> { + self.get_all_pages($path, params).await + } + + pub async fn $get(&self, id: &str) -> Result<$model> { + self.get_one(&format!("{}/{}", $path, id)).await + } + + pub async fn $create(&self, body: &$model) -> Result<$model> { + self.post_one($path, body).await + } + + pub async fn $update(&self, id: &str, body: &$model) -> Result<$model> { + self.put_one(&format!("{}/{}", $path, id), body).await + } + + pub async fn $delete(&self, id: &str) -> Result<()> { + self.delete_one(&format!("{}/{}", $path, id)).await + } + }; +} + +impl InvoiceNinjaClient { + resource_methods!( + list_clients, + list_all_clients, + get_client, + create_client, + update_client, + delete_client, + "clients", + ClientModel + ); + + resource_methods!( + list_invoices, + list_all_invoices, + get_invoice, + create_invoice, + update_invoice, + delete_invoice, + "invoices", + Invoice + ); + + resource_methods!( + list_quotes, + list_all_quotes, + get_quote, + create_quote, + update_quote, + delete_quote, + "quotes", + Quote + ); + + resource_methods!( + list_credits, + list_all_credits, + get_credit, + create_credit, + update_credit, + delete_credit, + "credits", + Credit + ); + + resource_methods!( + list_payments, + list_all_payments, + get_payment, + create_payment, + update_payment, + delete_payment, + "payments", + Payment + ); + + resource_methods!( + list_products, + list_all_products, + get_product, + create_product, + update_product, + delete_product, + "products", + Product + ); + + resource_methods!( + list_expenses, + list_all_expenses, + get_expense, + create_expense, + update_expense, + delete_expense, + "expenses", + Expense + ); + + resource_methods!( + list_projects, + list_all_projects, + get_project, + create_project, + update_project, + delete_project, + "projects", + Project + ); + + resource_methods!( + list_tasks, + list_all_tasks, + get_task, + create_task, + update_task, + delete_task, + "tasks", + Task + ); + + resource_methods!( + list_vendors, + list_all_vendors, + get_vendor, + create_vendor, + update_vendor, + delete_vendor, + "vendors", + Vendor + ); +} diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..8eecec6 --- /dev/null +++ b/src/error.rs @@ -0,0 +1,35 @@ +use serde::Deserialize; +use std::collections::HashMap; + +/// Error shape returned by the Invoice Ninja API for failed requests. +#[derive(Debug, Clone, Deserialize)] +pub struct ApiErrorBody { + #[serde(default)] + pub message: String, + #[serde(default)] + pub errors: HashMap>, +} + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("http transport error: {0}")] + Http(#[from] reqwest::Error), + + #[error("failed to decode JSON response: {0}")] + Json(#[from] serde_json::Error), + + #[error("api returned {status}: {message}")] + Api { + status: reqwest::StatusCode, + message: String, + errors: HashMap>, + }, + + #[error("invalid base url: {0}")] + InvalidBaseUrl(String), + + #[error("invalid api token: {0}")] + InvalidToken(String), +} + +pub type Result = std::result::Result; diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..de6756d --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,22 @@ +//! An async Rust client for the [Invoice Ninja](https://www.invoiceninja.com/) v5 API. +//! +//! ```no_run +//! use invoiceninjars::{InvoiceNinjaClient, models::ListParams}; +//! +//! # async fn run() -> invoiceninjars::Result<()> { +//! let client = InvoiceNinjaClient::new( +//! "https://invoicing.co/api/v1", +//! std::env::var("IN_API_TOKEN").unwrap(), +//! )?; +//! +//! let clients = client.list_clients(&ListParams::new().per_page(50)).await?; +//! # Ok(()) +//! # } +//! ``` + +mod client; +mod error; +pub mod models; + +pub use client::InvoiceNinjaClient; +pub use error::{ApiErrorBody, Error, Result}; diff --git a/src/models/client.rs b/src/models/client.rs new file mode 100644 index 0000000..2c882d6 --- /dev/null +++ b/src/models/client.rs @@ -0,0 +1,72 @@ +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct Client { + #[serde(skip_serializing_if = "Option::is_none")] + pub id: Option, + #[serde(default)] + pub name: String, + #[serde(default)] + pub id_number: String, + #[serde(default)] + pub vat_number: String, + #[serde(default)] + pub address1: String, + #[serde(default)] + pub address2: String, + #[serde(default)] + pub city: String, + #[serde(default)] + pub state: String, + #[serde(default)] + pub postal_code: String, + #[serde(default)] + pub country_id: String, + #[serde(default)] + pub phone: String, + #[serde(default)] + pub website: String, + #[serde(default)] + pub private_notes: String, + #[serde(default)] + pub balance: f64, + #[serde(default)] + pub paid_to_date: f64, + #[serde(default)] + pub credit_balance: f64, + #[serde(default)] + pub is_deleted: bool, + #[serde(default)] + pub archived_at: Option, + #[serde(default)] + pub created_at: Option, + #[serde(default)] + pub updated_at: Option, + #[serde(default)] + pub contacts: Vec, + + /// Any fields returned by the API that aren't modeled above are preserved here, + /// so a `get` followed by an `update` round-trips without data loss. + #[serde(flatten)] + pub extra: Map, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct ClientContact { + #[serde(skip_serializing_if = "Option::is_none")] + pub id: Option, + #[serde(default)] + pub first_name: String, + #[serde(default)] + pub last_name: String, + #[serde(default)] + pub email: String, + #[serde(default)] + pub phone: String, + #[serde(default)] + pub is_primary: bool, + + #[serde(flatten)] + pub extra: Map, +} diff --git a/src/models/common.rs b/src/models/common.rs new file mode 100644 index 0000000..c4e4973 --- /dev/null +++ b/src/models/common.rs @@ -0,0 +1,83 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Deserialize)] +pub struct ListResponse { + pub data: Vec, + #[serde(default)] + pub meta: Option, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct ItemResponse { + pub data: T, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct Meta { + #[serde(default)] + pub pagination: Option, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct Pagination { + pub total: u64, + pub count: u64, + pub per_page: u64, + pub current_page: u64, + pub total_pages: u64, +} + +/// Query parameters accepted by Invoice Ninja's list endpoints. +#[derive(Debug, Clone, Default, Serialize)] +pub struct ListParams { + #[serde(skip_serializing_if = "Option::is_none")] + pub page: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub per_page: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub filter: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub sort: Option, + /// Comma-separated list of relationships to eager-load, e.g. "client,payments". + #[serde(skip_serializing_if = "Option::is_none")] + pub include: Option, + /// Set to 1 to include archived/deleted records. + #[serde(skip_serializing_if = "Option::is_none")] + pub status: Option, +} + +impl ListParams { + pub fn new() -> Self { + Self::default() + } + + pub fn page(mut self, page: u64) -> Self { + self.page = Some(page); + self + } + + pub fn per_page(mut self, per_page: u64) -> Self { + self.per_page = Some(per_page); + self + } + + pub fn filter(mut self, filter: impl Into) -> Self { + self.filter = Some(filter.into()); + self + } + + pub fn sort(mut self, sort: impl Into) -> Self { + self.sort = Some(sort.into()); + self + } + + pub fn include(mut self, include: impl Into) -> Self { + self.include = Some(include.into()); + self + } + + pub fn status(mut self, status: impl Into) -> Self { + self.status = Some(status.into()); + self + } +} diff --git a/src/models/expense.rs b/src/models/expense.rs new file mode 100644 index 0000000..5e4e2d8 --- /dev/null +++ b/src/models/expense.rs @@ -0,0 +1,51 @@ +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct Expense { + #[serde(skip_serializing_if = "Option::is_none")] + pub id: Option, + #[serde(default)] + pub vendor_id: String, + #[serde(default)] + pub client_id: String, + #[serde(default)] + pub invoice_id: String, + #[serde(default)] + pub amount: f64, + #[serde(default)] + pub exchange_rate: f64, + #[serde(default)] + pub public_notes: String, + #[serde(default)] + pub private_notes: String, + #[serde(default)] + pub date: String, + #[serde(default)] + pub payment_date: String, + #[serde(default)] + pub transaction_reference: String, + #[serde(default)] + pub category_id: String, + #[serde(default)] + pub tax_name1: String, + #[serde(default)] + pub tax_rate1: f64, + #[serde(default)] + pub tax_name2: String, + #[serde(default)] + pub tax_rate2: f64, + #[serde(default)] + pub should_be_invoiced: bool, + #[serde(default)] + pub is_deleted: bool, + #[serde(default)] + pub archived_at: Option, + #[serde(default)] + pub created_at: Option, + #[serde(default)] + pub updated_at: Option, + + #[serde(flatten)] + pub extra: Map, +} diff --git a/src/models/invoice.rs b/src/models/invoice.rs new file mode 100644 index 0000000..63a7ef9 --- /dev/null +++ b/src/models/invoice.rs @@ -0,0 +1,85 @@ +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct Invoice { + #[serde(skip_serializing_if = "Option::is_none")] + pub id: Option, + #[serde(default)] + pub client_id: String, + #[serde(default)] + pub number: String, + #[serde(default)] + pub date: String, + #[serde(default)] + pub due_date: String, + #[serde(default)] + pub po_number: String, + #[serde(default)] + pub status_id: String, + #[serde(default)] + pub amount: f64, + #[serde(default)] + pub balance: f64, + #[serde(default)] + pub discount: f64, + #[serde(default)] + pub is_amount_discount: bool, + #[serde(default)] + pub public_notes: String, + #[serde(default)] + pub private_notes: String, + #[serde(default)] + pub terms: String, + #[serde(default)] + pub footer: String, + #[serde(default)] + pub is_deleted: bool, + #[serde(default)] + pub archived_at: Option, + #[serde(default)] + pub created_at: Option, + #[serde(default)] + pub updated_at: Option, + #[serde(default)] + pub line_items: Vec, + + #[serde(flatten)] + pub extra: Map, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct InvoiceItem { + #[serde(default)] + pub product_key: String, + #[serde(default)] + pub notes: String, + #[serde(default)] + pub cost: f64, + #[serde(default)] + pub quantity: f64, + #[serde(default)] + pub discount: f64, + #[serde(default)] + pub tax_name1: String, + #[serde(default)] + pub tax_rate1: f64, + #[serde(default)] + pub tax_name2: String, + #[serde(default)] + pub tax_rate2: f64, + #[serde(default)] + pub line_total: f64, + + #[serde(flatten)] + pub extra: Map, +} + +/// Invoice Ninja stores quotes in the same table/schema as invoices +/// (an `entity_type` distinguishes them), so the `/quotes` endpoint +/// returns the same JSON shape as `/invoices`. +pub type Quote = Invoice; + +/// Likewise, credits share the invoices table/schema, so the `/credits` +/// endpoint returns the same JSON shape as `/invoices`. +pub type Credit = Invoice; diff --git a/src/models/mod.rs b/src/models/mod.rs new file mode 100644 index 0000000..008502e --- /dev/null +++ b/src/models/mod.rs @@ -0,0 +1,19 @@ +mod client; +mod common; +mod expense; +mod invoice; +mod payment; +mod product; +mod project; +mod task; +mod vendor; + +pub use client::{Client, ClientContact}; +pub use common::{ItemResponse, ListParams, ListResponse, Meta, Pagination}; +pub use expense::Expense; +pub use invoice::{Credit, Invoice, InvoiceItem, Quote}; +pub use payment::{Payment, PaymentInvoice}; +pub use product::Product; +pub use project::Project; +pub use task::Task; +pub use vendor::{Vendor, VendorContact}; diff --git a/src/models/payment.rs b/src/models/payment.rs new file mode 100644 index 0000000..7c46260 --- /dev/null +++ b/src/models/payment.rs @@ -0,0 +1,46 @@ +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct Payment { + #[serde(skip_serializing_if = "Option::is_none")] + pub id: Option, + #[serde(default)] + pub client_id: String, + #[serde(default)] + pub amount: f64, + #[serde(default)] + pub applied: f64, + #[serde(default)] + pub refunded: f64, + #[serde(default)] + pub date: String, + #[serde(default)] + pub transaction_reference: String, + #[serde(default)] + pub type_id: String, + #[serde(default)] + pub private_notes: String, + #[serde(default)] + pub is_deleted: bool, + #[serde(default)] + pub archived_at: Option, + #[serde(default)] + pub created_at: Option, + #[serde(default)] + pub updated_at: Option, + #[serde(default)] + pub invoices: Vec, + + #[serde(flatten)] + pub extra: Map, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct PaymentInvoice { + pub invoice_id: String, + pub amount: f64, + + #[serde(flatten)] + pub extra: Map, +} diff --git a/src/models/product.rs b/src/models/product.rs new file mode 100644 index 0000000..30956d7 --- /dev/null +++ b/src/models/product.rs @@ -0,0 +1,37 @@ +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct Product { + #[serde(skip_serializing_if = "Option::is_none")] + pub id: Option, + #[serde(default)] + pub product_key: String, + #[serde(default)] + pub notes: String, + #[serde(default)] + pub cost: f64, + #[serde(default)] + pub price: f64, + #[serde(default)] + pub quantity: f64, + #[serde(default)] + pub tax_name1: String, + #[serde(default)] + pub tax_rate1: f64, + #[serde(default)] + pub tax_name2: String, + #[serde(default)] + pub tax_rate2: f64, + #[serde(default)] + pub is_deleted: bool, + #[serde(default)] + pub archived_at: Option, + #[serde(default)] + pub created_at: Option, + #[serde(default)] + pub updated_at: Option, + + #[serde(flatten)] + pub extra: Map, +} diff --git a/src/models/project.rs b/src/models/project.rs new file mode 100644 index 0000000..71f378d --- /dev/null +++ b/src/models/project.rs @@ -0,0 +1,37 @@ +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct Project { + #[serde(skip_serializing_if = "Option::is_none")] + pub id: Option, + #[serde(default)] + pub client_id: String, + #[serde(default)] + pub name: String, + #[serde(default)] + pub number: String, + #[serde(default)] + pub task_rate: f64, + #[serde(default)] + pub due_date: String, + #[serde(default)] + pub budgeted_hours: f64, + #[serde(default)] + pub color: String, + #[serde(default)] + pub public_notes: String, + #[serde(default)] + pub private_notes: String, + #[serde(default)] + pub is_deleted: bool, + #[serde(default)] + pub archived_at: Option, + #[serde(default)] + pub created_at: Option, + #[serde(default)] + pub updated_at: Option, + + #[serde(flatten)] + pub extra: Map, +} diff --git a/src/models/task.rs b/src/models/task.rs new file mode 100644 index 0000000..f1b1358 --- /dev/null +++ b/src/models/task.rs @@ -0,0 +1,36 @@ +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct Task { + #[serde(skip_serializing_if = "Option::is_none")] + pub id: Option, + #[serde(default)] + pub client_id: String, + #[serde(default)] + pub invoice_id: String, + #[serde(default)] + pub project_id: String, + #[serde(default)] + pub description: String, + #[serde(default)] + pub rate: f64, + #[serde(default)] + pub status_id: String, + #[serde(default)] + pub is_running: bool, + #[serde(default)] + pub is_deleted: bool, + /// JSON-encoded array of `[start_timestamp, end_timestamp]` pairs, as returned by the API. + #[serde(default)] + pub time_log: String, + #[serde(default)] + pub archived_at: Option, + #[serde(default)] + pub created_at: Option, + #[serde(default)] + pub updated_at: Option, + + #[serde(flatten)] + pub extra: Map, +} diff --git a/src/models/vendor.rs b/src/models/vendor.rs new file mode 100644 index 0000000..159cd99 --- /dev/null +++ b/src/models/vendor.rs @@ -0,0 +1,66 @@ +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct Vendor { + #[serde(skip_serializing_if = "Option::is_none")] + pub id: Option, + #[serde(default)] + pub name: String, + #[serde(default)] + pub id_number: String, + #[serde(default)] + pub vat_number: String, + #[serde(default)] + pub address1: String, + #[serde(default)] + pub address2: String, + #[serde(default)] + pub city: String, + #[serde(default)] + pub state: String, + #[serde(default)] + pub postal_code: String, + #[serde(default)] + pub country_id: String, + #[serde(default)] + pub phone: String, + #[serde(default)] + pub website: String, + #[serde(default)] + pub private_notes: String, + #[serde(default)] + pub is_deleted: bool, + #[serde(default)] + pub archived_at: Option, + #[serde(default)] + pub created_at: Option, + #[serde(default)] + pub updated_at: Option, + #[serde(default)] + pub contacts: Vec, + + /// Any fields returned by the API that aren't modeled above are preserved here, + /// so a `get` followed by an `update` round-trips without data loss. + #[serde(flatten)] + pub extra: Map, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct VendorContact { + #[serde(skip_serializing_if = "Option::is_none")] + pub id: Option, + #[serde(default)] + pub first_name: String, + #[serde(default)] + pub last_name: String, + #[serde(default)] + pub email: String, + #[serde(default)] + pub phone: String, + #[serde(default)] + pub is_primary: bool, + + #[serde(flatten)] + pub extra: Map, +} diff --git a/tests/model_roundtrip.rs b/tests/model_roundtrip.rs new file mode 100644 index 0000000..f9dc410 --- /dev/null +++ b/tests/model_roundtrip.rs @@ -0,0 +1,152 @@ +use invoiceninjars::models::{ + Client, Credit, Expense, Invoice, ListParams, Project, Quote, Task, Vendor, +}; +use serde_json::json; + +#[test] +fn client_round_trip_preserves_unknown_fields() { + let payload = json!({ + "id": "abc123", + "name": "Acme Inc", + "custom_value1": "unmodeled field", + }); + + let client: Client = serde_json::from_value(payload).unwrap(); + assert_eq!(client.name, "Acme Inc"); + assert_eq!( + client.extra.get("custom_value1").unwrap(), + "unmodeled field" + ); + + let round_tripped = serde_json::to_value(&client).unwrap(); + assert_eq!(round_tripped["custom_value1"], "unmodeled field"); +} + +#[test] +fn invoice_round_trip_preserves_unknown_fields() { + let payload = json!({ + "id": "inv1", + "client_id": "abc123", + "number": "INV-0001", + "custom_surcharge1": 12.5, + }); + + let invoice: Invoice = serde_json::from_value(payload).unwrap(); + assert_eq!(invoice.number, "INV-0001"); + assert_eq!(invoice.extra.get("custom_surcharge1").unwrap(), 12.5); + + let round_tripped = serde_json::to_value(&invoice).unwrap(); + assert_eq!(round_tripped["custom_surcharge1"], 12.5); +} + +#[test] +fn list_params_omits_unset_fields() { + let params = ListParams::new().per_page(25).sort("created_at|desc"); + + assert_eq!( + serde_json::to_value(¶ms).unwrap(), + json!({"per_page": 25, "sort": "created_at|desc"}) + ); +} + +#[test] +fn vendor_round_trip_preserves_nested_contact_fields() { + let payload = json!({ + "id": "ven1", + "name": "Supply Co", + "custom_value2": "unmodeled vendor field", + "contacts": [{ + "id": "vc1", + "first_name": "Ada", + "email": "ada@supply.example", + "is_primary": true, + "custom_value1": "unmodeled contact field", + }], + }); + + let vendor: Vendor = serde_json::from_value(payload).unwrap(); + assert_eq!(vendor.name, "Supply Co"); + assert_eq!(vendor.contacts.len(), 1); + assert_eq!(vendor.contacts[0].first_name, "Ada"); + assert!(vendor.contacts[0].is_primary); + + let round_tripped = serde_json::to_value(&vendor).unwrap(); + assert_eq!(round_tripped["custom_value2"], "unmodeled vendor field"); + assert_eq!( + round_tripped["contacts"][0]["custom_value1"], + "unmodeled contact field" + ); +} + +#[test] +fn expense_round_trip_preserves_unknown_fields() { + let payload = json!({ + "id": "exp1", + "vendor_id": "ven1", + "amount": 42.75, + "should_be_invoiced": true, + "custom_value3": "unmodeled field", + }); + + let expense: Expense = serde_json::from_value(payload).unwrap(); + assert_eq!(expense.vendor_id, "ven1"); + assert_eq!(expense.amount, 42.75); + assert!(expense.should_be_invoiced); + + let round_tripped = serde_json::to_value(&expense).unwrap(); + assert_eq!(round_tripped["custom_value3"], "unmodeled field"); +} + +#[test] +fn task_round_trip_preserves_unknown_fields() { + let payload = json!({ + "id": "task1", + "project_id": "proj1", + "description": "Design review", + "time_log": "[[1700000000,1700003600]]", + "custom_value1": "unmodeled field", + }); + + let task: Task = serde_json::from_value(payload).unwrap(); + assert_eq!(task.project_id, "proj1"); + assert_eq!(task.time_log, "[[1700000000,1700003600]]"); + + let round_tripped = serde_json::to_value(&task).unwrap(); + assert_eq!(round_tripped["custom_value1"], "unmodeled field"); +} + +#[test] +fn project_round_trip_preserves_unknown_fields() { + let payload = json!({ + "id": "proj1", + "client_id": "abc123", + "name": "Website rebuild", + "budgeted_hours": 120.0, + "custom_value4": "unmodeled field", + }); + + let project: Project = serde_json::from_value(payload).unwrap(); + assert_eq!(project.name, "Website rebuild"); + assert_eq!(project.budgeted_hours, 120.0); + + let round_tripped = serde_json::to_value(&project).unwrap(); + assert_eq!(round_tripped["custom_value4"], "unmodeled field"); +} + +/// `Quote` and `Credit` are type aliases for `Invoice`; this pins that the +/// aliased endpoints decode the shared invoice shape. +#[test] +fn quote_and_credit_share_the_invoice_shape() { + let payload = json!({ + "id": "q1", + "number": "QUO-0001", + "entity_type": "quote", + }); + + let quote: Quote = serde_json::from_value(payload.clone()).unwrap(); + assert_eq!(quote.number, "QUO-0001"); + assert_eq!(quote.extra.get("entity_type").unwrap(), "quote"); + + let credit: Credit = serde_json::from_value(payload).unwrap(); + assert_eq!(credit.number, "QUO-0001"); +}