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
35 changes: 35 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ Uses the [QuickBooks Online Accounting API](https://developer.intuit.com/app/dev
| `create <entity> --data <json>` | Create an entity from JSON |
| `update <entity> --data <json>` | Update an entity |
| `delete <entity> <id>` | Delete an entity by ID |
| `send invoice <id> [--to <email>]` | Email an invoice (optionally replacing its billing email) |
| `void <entity> <id>` | Zero a transaction's amounts and preserve its audit trail |
| `query "<sql>"` | Raw QBO query |
| `report <type>` | Financial reports (profit-and-loss, balance-sheet, etc.) |
Expand All @@ -148,6 +149,40 @@ Uses the [QuickBooks Online Accounting API](https://developer.intuit.com/app/dev

All commands support `--dry-run`, `--no-input`, and `--sandbox`.

### Email an invoice

`qbo send invoice <id> [--to <email>]` emails a third party. Without `--to`,
QuickBooks uses the invoice's stored `BillEmail`. With `--to`, it sends to that
address **and replaces the invoice's `BillEmail.Address`**. Only invoices are
supported. Use the numeric `Id`, not the document number. Invoice Cc/Bcc settings
still apply; `--to` replaces only the main billing email.

```bash
qbo send invoice 145 --dry-run
qbo send invoice 145 --to 'a+b@example.com' --dry-run
qbo send invoice 145 --force --no-input --sandbox --json
```

Dry runs print the POST and recipient to stderr without authentication or HTTP.
The command prompts for confirmation unless `--force` is set. Noninteractive
stdin and `--no-input` both require `--force`.

**Never automatically retry a send.** Each invocation makes at most one send
POST, without backoff or redirects. A 429, 5xx, timeout, transport failure, or
unverified response exits **1**, never the retryable codes 7 or 8. Read the
invoice's `EmailStatus` and `DeliveryInfo` before deciding to send again:

```bash
qbo get invoice 145 --json | jq '.Invoice | {EmailStatus, DeliveryInfo}'
```

401, 403 and 404 retain exit codes 4, 6 and 5. Successful output requires the
returned invoice to show `EmailSent`, a delivery timestamp and its recipient;
this is QuickBooks' send record, not proof of arrival in the recipient's inbox.
Human and plain output show `Id`, `DocNumber`, `EmailStatus`, `BillEmail.Address`
and `DeliveryInfo.DeliveryTime`. JSON preserves the complete QBO response,
including its `Invoice` wrapper. `--select` remains available for projection.

### Void a transaction

`qbo void` supports Invoice, Payment, SalesReceipt, and BillPayment. QBO zeroes
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ require (
github.com/alecthomas/kong v1.15.0
github.com/muesli/termenv v0.16.0
golang.org/x/oauth2 v0.36.0
golang.org/x/term v0.44.0
)

require (
Expand All @@ -21,5 +22,4 @@ require (
github.com/mtibben/percent v0.2.1 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
golang.org/x/sys v0.46.0 // indirect
golang.org/x/term v0.44.0 // indirect
)
79 changes: 79 additions & 0 deletions internal/api/send.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package api

import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"

"github.com/voska/qbo-cli/internal/errfmt"
)

// SendInvoice emails an invoice once. QuickBooks does not deduplicate sends,
// so neither redirects nor retryable error codes are safe for this operation.
func (c *Client) SendInvoice(ctx context.Context, id, to string) (map[string]any, error) {
endpoint := c.addMinorVersion(c.url("invoice/" + url.PathEscape(id) + "/send"))
if to != "" {
separator := "?"
if c.minorVersion > 0 {
separator = "&"
}
endpoint += separator + "sendTo=" + url.QueryEscape(to)
}
// A nil/NoBody POST can be replayed by Go 1.25/1.26's HTTP/2 transport.
// This empty, non-rewindable reader sends no bytes but prevents that replay.
// Do not set GetBody or an idempotency key on a send.
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, io.NopCloser(strings.NewReader("")))
if err != nil {
return nil, errfmt.Wrap(errfmt.ExitError, "cannot build send request", err)
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/octet-stream")

// Copy the client so other commands keep their existing redirect policy.
client := *c.httpClient
client.CheckRedirect = func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }
resp, err := client.Do(req)
if err != nil {
return nil, unknownSend(id, err)
}
defer func() { _ = resp.Body.Close() }()
body, readErr := io.ReadAll(resp.Body)
switch resp.StatusCode {
case http.StatusUnauthorized, http.StatusForbidden, http.StatusNotFound:
return nil, mapHTTPError(resp.StatusCode, body)
}
if readErr != nil {
return nil, unknownSend(id, readErr)
}
if resp.StatusCode == http.StatusRequestTimeout || resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= 500 {
return nil, unknownSend(id, fmt.Errorf("HTTP %d: %s", resp.StatusCode, body))
}
if resp.StatusCode >= 400 {
return nil, mapHTTPError(resp.StatusCode, body)
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return nil, unknownSend(id, fmt.Errorf("unexpected HTTP %d (redirects are not followed)", resp.StatusCode))
}

var result map[string]any
if err := json.Unmarshal(body, &result); err != nil {
return nil, unknownSend(id, err)
}
invoice, _ := result["Invoice"].(map[string]any)
delivery, _ := invoice["DeliveryInfo"].(map[string]any)
deliveryTime, _ := delivery["DeliveryTime"].(string)
email, _ := invoice["BillEmail"].(map[string]any)
address, _ := email["Address"].(string)
if invoice["Id"] != id || invoice["EmailStatus"] != "EmailSent" || deliveryTime == "" || address == "" || (to != "" && address != to) {
return nil, unknownSend(id, fmt.Errorf("response does not verify the invoice ID, EmailStatus, BillEmail.Address and DeliveryInfo.DeliveryTime"))
}
return result, nil
}

func unknownSend(id string, cause error) error {
return errfmt.Wrap(errfmt.ExitError, "send outcome unknown: read invoice "+id+" (EmailStatus, DeliveryInfo) before sending again", cause)
}
Loading
Loading