diff --git a/README.md b/README.md index c1b11f1..b0087aa 100644 --- a/README.md +++ b/README.md @@ -137,6 +137,7 @@ Uses the [QuickBooks Online Accounting API](https://developer.intuit.com/app/dev | `create --data ` | Create an entity from JSON | | `update --data ` | Update an entity | | `delete ` | Delete an entity by ID | +| `send invoice [--to ]` | Email an invoice (optionally replacing its billing email) | | `void ` | Zero a transaction's amounts and preserve its audit trail | | `query ""` | Raw QBO query | | `report ` | Financial reports (profit-and-loss, balance-sheet, etc.) | @@ -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 [--to ]` 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 diff --git a/go.mod b/go.mod index ffd0fd1..34ed492 100644 --- a/go.mod +++ b/go.mod @@ -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 ( @@ -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 ) diff --git a/internal/api/send.go b/internal/api/send.go new file mode 100644 index 0000000..ee0337a --- /dev/null +++ b/internal/api/send.go @@ -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) +} diff --git a/internal/api/send_test.go b/internal/api/send_test.go new file mode 100644 index 0000000..33f28bf --- /dev/null +++ b/internal/api/send_test.go @@ -0,0 +1,313 @@ +package api + +import ( + "context" + "crypto/tls" + "encoding/binary" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "net/url" + "reflect" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/voska/qbo-cli/internal/errfmt" +) + +const sentInvoice = `{"Invoice":{"Id":"5","DocNumber":"TEST-5","EmailStatus":"EmailSent","BillEmail":{"Address":"a+b@example.com"},"DeliveryInfo":{"DeliveryType":"Email","DeliveryTime":"2026-10-21T12:00:00Z"},"Line":[{"Description":"Fixture"}],"TotalAmt":25},"time":"fixture"}` + +func TestSendInvoiceRequest(t *testing.T) { + for _, to := range []string{"", "a+b@example.com", "a&b@example.com"} { + for _, minor := range []int{0, 75} { + t.Run(fmt.Sprintf("%s/minor=%d", to, minor), func(t *testing.T) { + var calls atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls.Add(1) + if r.Method != http.MethodPost || r.URL.Path != "/v3/company/123/invoice/5/send" { + t.Errorf("request = %s %s", r.Method, r.URL) + } + q := url.Values{} + if to != "" { + q.Set("sendTo", to) + } + if minor > 0 { + q.Set("minorversion", fmt.Sprint(minor)) + } + if !reflect.DeepEqual(r.URL.Query(), q) { + t.Errorf("query = %q, want %v", r.URL.RawQuery, q) + } + if to != "" && !strings.Contains(r.URL.RawQuery, "sendTo="+url.QueryEscape(to)) { + t.Errorf("unencoded recipient: %q", r.URL.RawQuery) + } + if r.Header.Get("Content-Type") != "application/octet-stream" || r.Header.Get("Accept") != "application/json" { + t.Errorf("headers = %v", r.Header) + } + body, err := io.ReadAll(r.Body) + if err != nil || len(body) != 0 { + t.Errorf("body = %q, err = %v", body, err) + } + response := strings.ReplaceAll(sentInvoice, "a+b@example.com", to) + if to == "" { + response = sentInvoice + } + _, _ = io.WriteString(w, response) + })) + defer srv.Close() + client := testClient(srv) + client.minorVersion = minor + got, err := client.SendInvoice(context.Background(), "5", to) + if err != nil || calls.Load() != 1 { + t.Fatalf("calls = %d, err = %v", calls.Load(), err) + } + invoice := got["Invoice"].(map[string]any) + if invoice["DocNumber"] != "TEST-5" || invoice["TotalAmt"] != float64(25) || invoice["Line"] == nil || got["time"] != "fixture" { + t.Errorf("response truncated: %v", got) + } + }) + } + } +} + +func TestSendInvoiceHTTPFailuresNeverRetry(t *testing.T) { + for _, status := range []int{400, 401, 403, 404, 408, 429, 500, 502, 503, 504} { + t.Run(fmt.Sprint(status), func(t *testing.T) { + var calls atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + calls.Add(1) + w.Header().Set("Retry-After", "0") + w.WriteHeader(status) + _, _ = io.WriteString(w, `{"Fault":{"type":"fixture"}}`) + })) + defer srv.Close() + _, err := testClient(srv).SendInvoice(context.Background(), "5", "") + want := errfmt.ExitError + switch status { + case 401: + want = errfmt.ExitAuth + case 403: + want = errfmt.ExitForbidden + case 404: + want = errfmt.ExitNotFound + } + var e *errfmt.Error + if !errors.As(err, &e) || e.Code != want || calls.Load() != 1 { + t.Fatalf("calls = %d, err = %v, want code %d", calls.Load(), err, want) + } + if status == 408 || status == 429 || status >= 500 { + assertUnknownSend(t, err) + } + if status == 400 && strings.Contains(err.Error(), "outcome unknown") { + t.Errorf("validation failure mislabeled: %v", err) + } + }) + } +} + +func assertUnknownSend(t *testing.T, err error) { + t.Helper() + var e *errfmt.Error + if !errors.As(err, &e) || e.Code != errfmt.ExitError { + t.Fatalf("err = %v, want code 1", err) + } + for _, text := range []string{"send outcome unknown", "invoice 5", "EmailStatus", "DeliveryInfo", "before sending again"} { + if !strings.Contains(err.Error(), text) { + t.Errorf("error missing %q: %v", text, err) + } + } + if strings.Contains(err.Error(), "retry later") || strings.Contains(err.Error(), "safe to retry") { + t.Errorf("unsafe retry hint: %v", err) + } +} + +func TestSendInvoiceUncertainResponse(t *testing.T) { + for name, body := range map[string]string{ + "invalid JSON": "not json", "missing invoice": `{}`, "null": `null`, + "wrong ID": strings.Replace(sentInvoice, `"Id":"5"`, `"Id":"6"`, 1), + "not sent": strings.Replace(sentInvoice, "EmailSent", "NeedToSend", 1), + "missing time": strings.Replace(sentInvoice, "2026-10-21T12:00:00Z", "", 1), + "wrong recipient": strings.Replace(sentInvoice, "a+b@example.com", "other@example.com", 1), + "missing recipient": strings.Replace(sentInvoice, "a+b@example.com", "", 1), + } { + t.Run(name, func(t *testing.T) { + var calls atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { calls.Add(1); _, _ = io.WriteString(w, body) })) + defer srv.Close() + _, err := testClient(srv).SendInvoice(context.Background(), "5", "a+b@example.com") + assertUnknownSend(t, err) + if calls.Load() != 1 { + t.Fatalf("calls = %d", calls.Load()) + } + }) + } +} + +func TestSendInvoiceTransportFailure(t *testing.T) { + for _, truncate := range []bool{false, true} { + t.Run(fmt.Sprint(truncate), func(t *testing.T) { + var calls atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + calls.Add(1) + conn, rw, err := w.(http.Hijacker).Hijack() + if err != nil { + t.Error(err) + return + } + defer func() { _ = conn.Close() }() + if truncate { + _, _ = rw.WriteString("HTTP/1.1 200 OK\r\nContent-Length: 10000\r\n\r\n{") + _ = rw.Flush() + } + })) + defer srv.Close() + _, err := testClient(srv).SendInvoice(context.Background(), "5", "") + assertUnknownSend(t, err) + if calls.Load() != 1 { + t.Errorf("calls = %d", calls.Load()) + } + }) + } +} + +func TestSendInvoiceDoesNotFollowRedirects(t *testing.T) { + for _, status := range []int{301, 302, 303, 307, 308} { + t.Run(fmt.Sprint(status), func(t *testing.T) { + var calls atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls.Add(1) + http.Redirect(w, r, "/second-send", status) + })) + defer srv.Close() + client := testClient(srv) + _, err := client.SendInvoice(context.Background(), "5", "") + assertUnknownSend(t, err) + if calls.Load() != 1 { + t.Errorf("calls = %d", calls.Load()) + } + if client.httpClient.CheckRedirect != nil { + t.Error("send changed the shared client's redirect policy") + } + }) + } +} + +// Older supported Go HTTP/2 transports replay even a POST when its Body is nil +// after a peer's PROTOCOL_ERROR. A send must not take that retry path. +func TestSendInvoiceHTTP2ResetNeverReplays(t *testing.T) { + certServer := httptest.NewTLSServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + certs := certServer.TLS.Certificates + certServer.Close() + listener, err := tls.Listen("tcp", "127.0.0.1:0", &tls.Config{Certificates: certs, NextProtos: []string{"h2"}}) + if err != nil { + t.Fatal(err) + } + var calls atomic.Int32 + var workers sync.WaitGroup + var mu sync.Mutex + var connections []net.Conn + workers.Add(1) + go func() { + defer workers.Done() + for { + conn, err := listener.Accept() + if err != nil { + return + } + mu.Lock() + connections = append(connections, conn) + mu.Unlock() + workers.Add(1) + go func() { + defer workers.Done() + defer func() { _ = conn.Close() }() + _ = conn.SetDeadline(time.Now().Add(5 * time.Second)) + preface := make([]byte, 24) + if _, err := io.ReadFull(conn, preface); err != nil { + return + } + if err := sendHTTP2Frame(conn, 4, 0, 0, nil); err != nil { + return + } // SETTINGS + for { + header := make([]byte, 9) + if _, err := io.ReadFull(conn, header); err != nil { + return + } + size := int(header[0])<<16 | int(header[1])<<8 | int(header[2]) + if _, err := io.CopyN(io.Discard, conn, int64(size)); err != nil { + return + } + if header[3] == 4 && header[4]&1 == 0 { // SETTINGS ACK + if err := sendHTTP2Frame(conn, 4, 1, 0, nil); err != nil { + return + } + } + if header[3] != 1 { + continue + } // HEADERS marks a dispatched request. + code := byte(1) // PROTOCOL_ERROR, retryable in Go 1.25/1.26. + if calls.Add(1) > 1 { + code = 8 + } // CANCEL stops an accidental replay promptly. + stream := binary.BigEndian.Uint32(header[5:]) & 0x7fffffff + if err := sendHTTP2Frame(conn, 3, 0, stream, []byte{0, 0, 0, code}); err != nil { + return + } + } + }() + } + }() + t.Cleanup(func() { + _ = listener.Close() + mu.Lock() + for _, conn := range connections { + _ = conn.Close() + } + mu.Unlock() + workers.Wait() + }) + transport := &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, ForceAttemptHTTP2: true} // Synthetic loopback TLS fixture. + t.Cleanup(transport.CloseIdleConnections) + client := &Client{httpClient: &http.Client{Transport: transport}, baseURL: "https://" + listener.Addr().String(), realmID: "123", minorVersion: 75} + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + _, err = client.SendInvoice(ctx, "5", "") + assertUnknownSend(t, err) + if calls.Load() != 1 { + t.Fatalf("send requests dispatched = %d, want exactly 1", calls.Load()) + } +} + +func sendHTTP2Frame(w io.Writer, kind, flags byte, stream uint32, payload []byte) error { + header := make([]byte, 9) + header[0], header[1], header[2] = byte(len(payload)>>16), byte(len(payload)>>8), byte(len(payload)) + header[3], header[4] = kind, flags + binary.BigEndian.PutUint32(header[5:], stream) + _, err := w.Write(append(header, payload...)) + return err +} + +func TestSendInvoiceHTTP2Success(t *testing.T) { + var calls atomic.Int32 + srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls.Add(1) + body, err := io.ReadAll(r.Body) + if r.ProtoMajor != 2 || err != nil || len(body) != 0 { + t.Errorf("protocol = %s, body = %q, err = %v", r.Proto, body, err) + } + _, _ = io.WriteString(w, sentInvoice) + })) + srv.EnableHTTP2 = true + srv.StartTLS() + defer srv.Close() + result, err := testClient(srv).SendInvoice(context.Background(), "5", "a+b@example.com") + if err != nil || result["Invoice"] == nil || calls.Load() != 1 { + t.Fatalf("result = %v, calls = %d, err = %v", result, calls.Load(), err) + } +} diff --git a/internal/cmd/root.go b/internal/cmd/root.go index 54e9b10..c572027 100644 --- a/internal/cmd/root.go +++ b/internal/cmd/root.go @@ -31,6 +31,7 @@ type CLI struct { Create CreateCmd `cmd:"" help:"Create an entity from JSON."` Update UpdateCmd `cmd:"" help:"Update an entity."` Delete DeleteCmd `cmd:"" help:"Delete an entity by ID."` + Send SendCmd `cmd:"" help:"Email an invoice to a third party. --to replaces its BillEmail.Address. Sends are never retried."` Void VoidCmd `cmd:"" help:"Void a transaction by ID, preserving its audit trail."` List ListCmd `cmd:"" help:"List entities (sugar for query)."` Batch BatchCmd `cmd:"" help:"Run batch operations."` diff --git a/internal/cmd/schema.go b/internal/cmd/schema.go index 671b8a6..54c062b 100644 --- a/internal/cmd/schema.go +++ b/internal/cmd/schema.go @@ -88,6 +88,14 @@ func fullSchema(version string) map[string]any { "help": "Delete an entity by ID", "args": []string{"entity", "id"}, }, + { + "name": "send", + "help": "Email an invoice to a third party. --to replaces its BillEmail.Address. Sends are never retried.", + "args": []string{"entity", "id"}, + "flags": []string{"--to"}, + "entities": []string{"invoice"}, + "retryable": false, + }, { "name": "void", "help": "Void a transaction by ID, preserving its audit trail", diff --git a/internal/cmd/send.go b/internal/cmd/send.go new file mode 100644 index 0000000..98b6457 --- /dev/null +++ b/internal/cmd/send.go @@ -0,0 +1,88 @@ +package cmd + +import ( + "fmt" + "net/mail" + "net/url" + "os" + + "github.com/voska/qbo-cli/internal/api" + "github.com/voska/qbo-cli/internal/errfmt" + "github.com/voska/qbo-cli/internal/output" + "golang.org/x/term" +) + +type SendCmd struct { + Entity string `arg:"" help:"Entity type (invoice only)."` + ID string `arg:"" help:"Numeric invoice Id, not its document number."` + To *string `name:"to" placeholder:"EMAIL" help:"Recipient email; replaces the invoice's BillEmail.Address."` +} + +func (c *SendCmd) Run(g *Globals) error { + entity, ok := api.LookupEntity(c.Entity) + if !ok || entity.Endpoint != "invoice" { + return errfmt.Usage("send supports invoice only") + } + if !numericID.MatchString(c.ID) { + return errfmt.Usage("id must be the numeric invoice Id, got: " + c.ID) + } + to := "" + recipient := "the invoice's BillEmail" + if c.To != nil { + address, err := mail.ParseAddress(*c.To) + if err != nil || address.Address != *c.To { + return errfmt.Usage("--to must be a single email address without a display name") + } + to = *c.To + recipient = to + " (replaces the invoice's BillEmail.Address)" + } + + recipient += " (plus any invoice Cc/Bcc)" + + if g.CLI.DryRun { + endpoint := "/v3/company/{id}/invoice/" + c.ID + "/send" + if to != "" { + endpoint += "?sendTo=" + url.QueryEscape(to) + } + DryRunLog(g.CLI, "POST", endpoint, nil) + output.Hint("Emails a third party: %s. Sends are never retried.", recipient) + return nil + } + + if !g.CLI.Force { + if g.CLI.NoInput || !term.IsTerminal(int(os.Stdin.Fd())) { + return errfmt.Usage("refusing to email a third party without --force in noninteractive mode") + } + if !confirmSend(c.ID, recipient) { + output.Hint("cancelled; no send submitted") + return nil + } + } + + client, _, err := g.NewAPIClient() + if err != nil { + return err + } + result, err := client.SendInvoice(g.Ctx, c.ID, to) + if err != nil { + return err + } + if opts := output.GetOptions(g.Ctx); opts.Mode != output.ModeJSON && len(opts.Select) == 0 { + fields := []string{"Id", "DocNumber", "EmailStatus", "BillEmail.Address", "DeliveryInfo.DeliveryTime"} + summary := output.ProjectFields(result["Invoice"], fields).(map[string]any) + for _, field := range fields { + if summary[field] == nil { + summary[field] = "" + } + } + return WriteOutput(g.Ctx, summary) + } + return WriteOutput(g.Ctx, result) +} + +func confirmSend(id, recipient string) bool { + fmt.Fprintf(os.Stderr, "Email invoice %s to %s? This emails a third party. [y/N] ", id, recipient) + var confirm string + _, err := fmt.Fscanln(os.Stdin, &confirm) + return err == nil && (confirm == "y" || confirm == "Y") +} diff --git a/internal/cmd/send_test.go b/internal/cmd/send_test.go new file mode 100644 index 0000000..b33db6f --- /dev/null +++ b/internal/cmd/send_test.go @@ -0,0 +1,225 @@ +package cmd + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "os" + "reflect" + "strings" + "testing" + + "github.com/alecthomas/kong" + "github.com/voska/qbo-cli/internal/errfmt" +) + +const sendResponse = `{"Invoice":{"Id":"5","DocNumber":"TEST-5","EmailStatus":"EmailSent","BillEmail":{"Address":"a+b@example.com"},"DeliveryInfo":{"DeliveryType":"Email","DeliveryTime":"2026-10-21T12:00:00Z"},"Line":[{"Description":"Fixture"}],"TotalAmt":25},"time":"fixture"}` + +func TestSendCommandAvailable(t *testing.T) { + var cli CLI + parser, err := kong.New(&cli) + if err != nil { + t.Fatal(err) + } + ctx, err := parser.Parse([]string{"send", "invoice", "5", "--to", "a+b@example.com", "--dry-run", "--no-input"}) + if err != nil { + t.Fatal(err) + } + if err := ctx.Run(testGlobals(&cli)); err != nil { + t.Fatal(err) + } +} + +func TestSendDryRunNoAuthOrNetwork(t *testing.T) { + requests := voidCommandServer(t, func(_ http.ResponseWriter, _ *http.Request) { t.Error("unexpected request") }) + for _, to := range []string{"", "a+b@example.com"} { + command := &SendCmd{Entity: "invoice", ID: "5"} + if to != "" { + command.To = &to + } + stdout, stderr, err := captureVoidOutput(t, func() error { return command.Run(testGlobals(&CLI{DryRun: true, NoInput: true})) }) + if err != nil || stdout != "" || requests.Load() != 0 { + t.Fatalf("stdout = %q, requests = %d, err = %v", stdout, requests.Load(), err) + } + for _, text := range []string{"POST /v3/company/{id}/invoice/5/send", "third party", "Cc/Bcc"} { + if !strings.Contains(stderr, text) { + t.Errorf("dry run missing %q: %s", text, stderr) + } + } + if to != "" { + if !strings.Contains(stderr, "sendTo=a%2Bb%40example.com") || !strings.Contains(stderr, "replaces") || !strings.Contains(stderr, "BillEmail.Address") { + t.Errorf("dry run = %q", stderr) + } + } else if strings.Contains(stderr, "sendTo=") || !strings.Contains(stderr, "invoice's BillEmail") { + t.Errorf("dry run = %q", stderr) + } + } +} + +func TestSendRejectsInputWithoutAuthOrNetwork(t *testing.T) { + requests := voidCommandServer(t, func(_ http.ResponseWriter, _ *http.Request) { t.Error("unexpected request") }) + for _, entity := range []string{"bogus", "customer", "estimate", "payment", "salesreceipt", "creditmemo"} { + if err := (&SendCmd{Entity: entity, ID: "5"}).Run(testGlobals(&CLI{Force: true})); exitCode(err) != errfmt.ExitUsage { + t.Errorf("entity %q: %v", entity, err) + } + } + for _, id := range []string{"", "INV-5", "5/../6", "5?sendTo=x@example.com", "5#", "%35", "5\n"} { + if err := (&SendCmd{Entity: "invoice", ID: id}).Run(testGlobals(&CLI{Force: true})); exitCode(err) != errfmt.ExitUsage { + t.Errorf("id %q: %v", id, err) + } + } + for _, to := range []string{"", "bad", "a@example.com,b@example.com", "Name ", " a@example.com", "a@example.com\r\nBcc:b@example.com"} { + if err := (&SendCmd{Entity: "invoice", ID: "5", To: &to}).Run(testGlobals(&CLI{Force: true})); exitCode(err) != errfmt.ExitUsage { + t.Errorf("to %q: %v", to, err) + } + } + for _, noInput := range []bool{false, true} { + withSendStdin(t, "y\n", func() { + err := (&SendCmd{Entity: "invoice", ID: "5"}).Run(testGlobals(&CLI{NoInput: noInput})) + if exitCode(err) != errfmt.ExitUsage || !strings.Contains(err.Error(), "--force") { + t.Errorf("no-input=%v: %v", noInput, err) + } + }) + } + if requests.Load() != 0 { + t.Errorf("requests = %d", requests.Load()) + } +} + +func withSendStdin(t *testing.T, text string, run func()) { + t.Helper() + file, err := os.CreateTemp(t.TempDir(), "stdin") + if err != nil { + t.Fatal(err) + } + defer func() { _ = file.Close() }() + if _, err = file.WriteString(text); err != nil { + t.Fatal(err) + } + if _, err = file.Seek(0, 0); err != nil { + t.Fatal(err) + } + original := os.Stdin + os.Stdin = file + defer func() { os.Stdin = original }() + run() +} + +func TestSendCommandOutput(t *testing.T) { + t.Setenv("QBO_AUTO_JSON", "0") + for _, mode := range []string{"human", "plain", "json", "select"} { + t.Run(mode, func(t *testing.T) { + requests := voidCommandServer(t, func(w http.ResponseWriter, r *http.Request) { + if r.Method != "POST" || r.URL.Path != "/v3/company/123/invoice/5/send" || r.URL.Query().Get("sendTo") != "a+b@example.com" { + t.Errorf("request = %s %s", r.Method, r.URL) + } + _, _ = io.WriteString(w, sendResponse) + }) + cli := &CLI{Force: true, NoInput: true, JSON: mode == "json" || mode == "select", Plain: mode == "plain", CompanyID: "123", MinorVer: 75} + if mode == "select" { + cli.Select = []string{"Invoice.Id", "Invoice.EmailStatus"} + } + g, err := NewGlobals(testGlobals(cli).Ctx, cli) + if err != nil { + t.Fatal(err) + } + to := "a+b@example.com" + stdout, stderr, err := captureVoidOutput(t, func() error { return (&SendCmd{Entity: "invoices", ID: "5", To: &to}).Run(g) }) + if err != nil || requests.Load() != 1 { + t.Fatalf("requests = %d, err = %v", requests.Load(), err) + } + if strings.Contains(stderr, "[y/N]") { + t.Errorf("force prompted: %q", stderr) + } + switch mode { + case "json": + var got, want any + if err := json.Unmarshal([]byte(stdout), &got); err != nil { + t.Fatal(err) + } + _ = json.Unmarshal([]byte(sendResponse), &want) + if !reflect.DeepEqual(got, want) { + t.Errorf("JSON truncated: %s", stdout) + } + case "select": + var got map[string]any + if err := json.Unmarshal([]byte(stdout), &got); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(got, map[string]any{"Invoice.Id": "5", "Invoice.EmailStatus": "EmailSent"}) { + t.Errorf("selection = %v", got) + } + default: + for _, text := range []string{"Id", "DocNumber", "EmailStatus", "BillEmail.Address", "DeliveryInfo.DeliveryTime", "TEST-5", "EmailSent", "a+b@example.com", "2026-10-21T12:00:00Z"} { + if !strings.Contains(stdout, text) { + t.Errorf("output missing %q: %s", text, stdout) + } + } + if mode == "plain" && !strings.Contains(stdout, "\t") { + t.Errorf("not TSV: %s", stdout) + } + } + }) + } +} + +func TestSendCommandFailureCodes(t *testing.T) { + for status, want := range map[int]int{400: 1, 401: 4, 403: 6, 404: 5, 429: 1, 500: 1} { + t.Run(fmt.Sprint(status), func(t *testing.T) { + requests := voidCommandServer(t, func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(status) }) + cli := &CLI{Force: true, NoInput: true, CompanyID: "123", MinorVer: 75} + g, err := NewGlobals(testGlobals(cli).Ctx, cli) + if err != nil { + t.Fatal(err) + } + err = (&SendCmd{Entity: "invoice", ID: "5"}).Run(g) + if exitCode(err) != want || requests.Load() != 1 { + t.Errorf("requests = %d, err = %v", requests.Load(), err) + } + }) + } +} + +func TestSendSchema(t *testing.T) { + schema, err := commandSchema("send", "test") + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(schema["args"], []string{"entity", "id"}) || !reflect.DeepEqual(schema["flags"], []string{"--to"}) { + t.Errorf("send schema = %v", schema) + } + if !reflect.DeepEqual(schema["entities"], []string{"invoice"}) || schema["retryable"] != false { + t.Errorf("send safety schema = %v", schema) + } + for _, text := range []string{"third party", "BillEmail.Address", "never retried"} { + if !strings.Contains(schema["help"].(string), text) { + t.Errorf("schema help missing %q: %v", text, schema) + } + } +} + +func TestSendConfirmation(t *testing.T) { + for _, recipient := range []string{"the invoice's BillEmail", "a+b@example.com (replaces the invoice's BillEmail.Address)"} { + for _, answer := range []string{"", "n\n", "yes\n", "y extra\n", "y\n", "Y\n"} { + t.Run(recipient+"/"+answer, func(t *testing.T) { + withSendStdin(t, answer, func() { + stdout, stderr, err := captureVoidOutput(t, func() error { + if got := confirmSend("5", recipient); got != (answer == "y\n" || answer == "Y\n") { + t.Errorf("confirmation for %q = %v", answer, got) + } + return nil + }) + if err != nil || stdout != "" { + t.Fatalf("stdout=%q, err=%v", stdout, err) + } + for _, text := range []string{"invoice 5", recipient, "third party", "[y/N]"} { + if !strings.Contains(stderr, text) { + t.Errorf("prompt missing %q: %s", text, stderr) + } + } + }) + }) + } + } +} diff --git a/skills/qbo/SKILL.md b/skills/qbo/SKILL.md index dcf78d7..88feab5 100644 --- a/skills/qbo/SKILL.md +++ b/skills/qbo/SKILL.md @@ -95,7 +95,7 @@ QBO wraps all responses. Know the shapes: - **`list`/`query`** returns `{"QueryResponse": {"Invoice": [...], "startPosition": 1, ...}}`. Use `--results-only` to unwrap to just the array. - **`get`** returns `{"Invoice": {...}}`. Use jq to drill in: `qbo get invoice 123 --json | jq '.Invoice'` -- **`create`/`update`/`void`** returns the same wrapper as `get`. +- **`create`/`update`/`void`/`send`** returns the same wrapper as `get`. - **`report`** returns `{"Header": {...}, "Rows": {...}}`. Always use `--json` when parsing output programmatically. @@ -182,6 +182,39 @@ expected value and fails without posting on a mismatch. Already-void records no POST. Dry runs make no API calls; a pinned token includes the exact body. Use `--force` with `--no-input`; otherwise the command prompts for confirmation. +## Sending Invoices + +`qbo send invoice [--to ]` emails a third party. Without `--to`, +QuickBooks uses the invoice's stored `BillEmail`. With `--to`, QuickBooks 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 | jq '.Invoice' +``` + +Dry runs print the POST and recipient to stderr with no authentication or HTTP. +The command prompts 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 +`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. JSON preserves the complete QBO +response, including its `Invoice` wrapper. Human/plain output shows `Id`, +`DocNumber`, `EmailStatus`, `BillEmail.Address` and `DeliveryInfo.DeliveryTime`. +A successful send response is QuickBooks' send record, not proof of arrival in +the recipient's inbox. Do not send production test emails. + ## Recurring Transactions Templates that auto-post transactions on a schedule (e.g. monthly amortization). @@ -201,6 +234,7 @@ qbo delete recurringtransaction # reads + echoes the full object for you qbo schema --json # Full CLI tree, all entities, all flags qbo schema get --json # Schema for a specific command qbo schema void --json # Void arguments and --sync-token flag +qbo schema send --json # Invoice sending and --to flag (never auto-retry) qbo exit-codes --json # Exit codes as JSON ``` diff --git a/skills/qbo/references/COMMANDS.md b/skills/qbo/references/COMMANDS.md index c69ef87..52e052c 100644 --- a/skills/qbo/references/COMMANDS.md +++ b/skills/qbo/references/COMMANDS.md @@ -35,6 +35,7 @@ All QBO responses are wrapped. Use `--json` for parsing. | `create`, `update` | `{"Entity": {...}}` | Same as `get` | | `delete` | `{"Entity": {"Id": "...", "status": "Deleted"}}` | | | `void` | `{"Entity": {...}}` | `TotalAmt` is zero; `PrivateNote` starts with `Voided` | +| `send` | `{"Invoice": {...}}` | Full returned Invoice; never automatically retry a send | | `report` | `{"Header": {...}, "Rows": {...}}` | Nested row structure | ## Commands @@ -144,6 +145,55 @@ qbo void invoice 145 --force --no-input --sandbox --json | jq '.Invoice' a pin, it says the SyncToken will be read at execution. With `--sync-token`, it prints the exact POST body. Normal output preserves the QBO response wrapper. +### send + +```bash +qbo send invoice [--to ] [--force] +``` + +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`**. The recipient must be a single email address without a +display name. Only invoices are supported; `` is the numeric invoice Id, +not its document number. Invoice Cc/Bcc settings still apply; `--to` replaces +only the main billing email. Invalid arguments or other entities exit 2 before +authentication or HTTP. + +The command prompts for confirmation unless `--force` is set. Noninteractive +stdin and `--no-input` without `--force` exit 2 without authentication or HTTP. +`--dry-run` prints the POST path and recipient to stderr with no authentication +or HTTP, even without `--force`. + +```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 | jq '.Invoice' +``` + +The send request is `POST /v3/company/{realmId}/invoice/{id}/send`, with an empty +body, `Content-Type: application/octet-stream`, and `Accept: application/json`. +`--to` adds the URL-encoded `sendTo` query parameter. + +**Never automatically retry a send.** There is at most one send POST per +invocation, with no backoff or redirects. 429, 5xx, timeout, transport failure, +and unverified responses exit **1**, never 7 or 8. These outcomes may have sent +an email. Read `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. A verified response must show the +requested invoice Id, `EmailStatus: EmailSent`, a nonempty billing email and +`DeliveryInfo.DeliveryTime`; with `--to`, the returned billing email must match. +This is QuickBooks' send record, not proof of inbox delivery. + +JSON preserves the complete returned QBO response with its `Invoice` wrapper. +Human/plain output defaults to `Id`, `DocNumber`, `EmailStatus`, +`BillEmail.Address` and `DeliveryInfo.DeliveryTime`. Explicit `--select` projects +from the complete wrapper in every output mode. Do not send production test +emails. + ### query ```bash @@ -221,6 +271,7 @@ transaction Id, not its document number. Defaults to `-.pdf`. qbo schema --json # Full CLI tree with all entities qbo schema get --json # Schema for a specific command qbo schema void --json # Void arguments and --sync-token flag +qbo schema send --json # Invoice sending and --to flag (never auto-retry) ``` ### exit-codes