turbodocx

package module
v0.9.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 20, 2026 License: MIT Imports: 22 Imported by: 0

README

TurboDocx

turbodocx-sdk

Official Go SDK for TurboDocx

The most developer-friendly DocuSign & PandaDoc alternative for e-signatures, document generation, and partner management. Send documents for signature, automate document workflows, and manage partner organizations programmatically.

Go Reference Agent Skills Quickstart Skill

Documentation • API Reference • Examples • Discord


⚡ Skip the boilerplate — let an agent scaffold it for you

Have an AI coding agent (Claude Code, Cursor, Copilot, Codex, Gemini CLI, OpenCode) install this SDK, configure your env, write working route handlers, and wire them into your app:

npx skills add TurboDocx/quickstart

Then run /turbodocx-sdk inside your agent — or one of the focused shortcuts:

Shortcut What it scaffolds
/turbodocx-sdk turbosign Send documents for e-signature, check status, download signed PDF
/turbodocx-sdk deliverable Generate documents from templates with variable substitution
/turbodocx-sdk turbopartner Provision and manage customer organizations (partner accounts)
/turbodocx-sdk turbowebhooks Subscribe to signature.document.completed events + verify HMAC
/turbodocx-sdk turboquote Create and send quotes, manage products, price books, and bundles

The skill auto-detects your framework (net/http, Gin, Echo, Fiber, …) and follows your existing project conventions. Source: github.com/TurboDocx/quickstart.


Why TurboDocx?

A modern, developer-first alternative to legacy e-signature platforms:

Looking for... TurboDocx offers
DocuSign API alternative Simple REST API, transparent pricing
PandaDoc alternative Document generation + e-signatures in one SDK
HelloSign/Dropbox Sign alternative Full API access, modern DX
Adobe Sign alternative Quick integration, developer-friendly docs
SignNow alternative Predictable costs, responsive support
Documint alternative DOCX/PDF generation from templates
WebMerge alternative Data-driven document automation

Other platforms we compare to: SignRequest, SignEasy, Zoho Sign, Eversign, SignWell, Formstack Documents

TurboDocx Ecosystem
Package Description
@turbodocx/html-to-docx Convert HTML to DOCX - fastest JS library
@turbodocx/n8n-nodes-turbodocx n8n community nodes for TurboDocx
TurboDocx Writer Microsoft Word add-in

Features

  • 🚀 Production-Ready — Battle-tested, processing thousands of documents daily
  • ⚡ Context Support — Full context.Context support for cancellation and timeouts
  • 🔒 Type-Safe — Strongly typed request/response structs
  • 🧵 Concurrent Safe — Safe for use across goroutines
  • 📦 Zero Dependencies — Only standard library
  • 🤖 100% n8n Parity — Same operations as our n8n community nodes
  • 🏢 TurboPartner — Full partner portal API for managing organizations, users, API keys, and entitlements

Installation

go get github.com/TurboDocx/SDK/packages/go-sdk

Install via AI Agent Skill

Let an AI coding agent set up this SDK for you with the TurboDocx Quickstart Agent Skill:

npx skills add TurboDocx/quickstart

Works with Claude Code, GitHub Copilot, Cursor, OpenCode, and other AI coding agents. The skill detects your language, installs the package, and generates working integration code.


Quick Start

package main

import (
    "context"
    "fmt"
    "log"
    "os"

    turbodocx "github.com/TurboDocx/SDK/packages/go-sdk"
)

func main() {
    // 1. Create client with sender configuration
    client, err := turbodocx.NewClientWithConfig(turbodocx.ClientConfig{
        APIKey:      os.Getenv("TURBODOCX_API_KEY"),      // REQUIRED
        OrgID:       os.Getenv("TURBODOCX_ORG_ID"),       // REQUIRED
        SenderEmail: os.Getenv("TURBODOCX_SENDER_EMAIL"), // REQUIRED
        SenderName:  os.Getenv("TURBODOCX_SENDER_NAME"),  // OPTIONAL (but strongly recommended)
    })
    if err != nil {
        log.Fatal(err)
    }

    // 2. Read PDF file
    pdfFile, err := os.ReadFile("contract.pdf")
    if err != nil {
        log.Fatal(err)
    }

    // 3. Send document for signature
    result, err := client.TurboSign.SendSignature(context.Background(), &turbodocx.SendSignatureRequest{
        File:         pdfFile,
        FileName:     "contract.pdf",
        DocumentName: "Partnership Agreement",
        Recipients: []turbodocx.Recipient{
            {Name: "John Doe", Email: "john@example.com", SigningOrder: 1},
        },
        Fields: []turbodocx.Field{
            {
                Type:           "signature",
                RecipientEmail: "john@example.com",
                Template: &turbodocx.TemplateAnchor{
                    Anchor:    "{signature1}",
                    Placement: "replace",
                    Size:      &turbodocx.Size{Width: 100, Height: 30},
                },
            },
        },
    })
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Document ID: %s\n", result.DocumentID)
}

Configuration

// Basic client configuration (REQUIRED)
client, err := turbodocx.NewClientWithConfig(turbodocx.ClientConfig{
    APIKey:      "your-api-key",      // REQUIRED
    OrgID:       "your-org-id",       // REQUIRED
    SenderEmail: "you@company.com",   // REQUIRED - reply-to address for signature requests
    SenderName:  "Your Company",      // OPTIONAL but strongly recommended
})

// With environment variables (recommended)
client, err := turbodocx.NewClientWithConfig(turbodocx.ClientConfig{
    APIKey:      os.Getenv("TURBODOCX_API_KEY"),
    OrgID:       os.Getenv("TURBODOCX_ORG_ID"),
    SenderEmail: os.Getenv("TURBODOCX_SENDER_EMAIL"),
    SenderName:  os.Getenv("TURBODOCX_SENDER_NAME"),
})

// With custom options
client, err := turbodocx.NewClientWithConfig(turbodocx.ClientConfig{
    APIKey:      os.Getenv("TURBODOCX_API_KEY"),
    OrgID:       os.Getenv("TURBODOCX_ORG_ID"),
    SenderEmail: os.Getenv("TURBODOCX_SENDER_EMAIL"),
    SenderName:  os.Getenv("TURBODOCX_SENDER_NAME"),
    BaseURL:     "https://custom-api.example.com",  // Optional
})

// With OAuth2 access token (alternative to API key)
client, err := turbodocx.NewClientWithConfig(turbodocx.ClientConfig{
    AccessToken: os.Getenv("TURBODOCX_ACCESS_TOKEN"),  // Use instead of APIKey
    OrgID:       os.Getenv("TURBODOCX_ORG_ID"),
    SenderEmail: os.Getenv("TURBODOCX_SENDER_EMAIL"),
    SenderName:  os.Getenv("TURBODOCX_SENDER_NAME"),
})

Important: SenderEmail is REQUIRED. It is used as the reply-to address for signature request emails and recorded as the sender in the audit trail. An API key has no mailbox of its own, so the API rejects a send without it rather than mailing from an unmonitored address. SenderName is optional — it defaults to the name of your API key.

Environment Variables:

# .env or shell environment
export TURBODOCX_API_KEY=your-api-key
export TURBODOCX_ORG_ID=your-org-id
export TURBODOCX_SENDER_EMAIL=you@company.com
export TURBODOCX_SENDER_NAME="Your Company Name"

API Reference

TurboSign

Upload a document for review without sending signature emails.

result, err := client.TurboSign.CreateSignatureReviewLink(ctx, &turbodocx.CreateSignatureReviewLinkRequest{
    FileLink: "https://example.com/contract.pdf",
    Recipients: []turbodocx.Recipient{
        {Name: "John Doe", Email: "john@example.com", SigningOrder: 1},
    },
    Fields: []turbodocx.Field{
        {Type: "signature", Page: 1, X: 100, Y: 500, Width: 200, Height: 50, RecipientEmail: "john@example.com"},
    },
    DocumentName: "Service Agreement",       // Optional
    SenderName:   "Acme Corp",               // Optional
    SenderEmail:  "contracts@acme.com",      // Optional
})

fmt.Printf("Preview URL: %s\n", result.PreviewURL)
fmt.Printf("Document ID: %s\n", result.DocumentID)
SendSignature

Upload a document and send it for signature. Recipients are emailed their signing links unless you set SendEmail: turbodocx.BoolPtr(false).

Set FileName alongside File to name the stored file: any non-empty name up to 255 characters, with or without an extension. Without it (or with an empty one) the file is stored as document.<ext>. The document's display name is documentName when given, otherwise the stored file name up to its first ..

result, err := client.TurboSign.SendSignature(ctx, &turbodocx.SendSignatureRequest{
    FileLink: "https://example.com/contract.pdf",
    Recipients: []turbodocx.Recipient{
        {Name: "Alice", Email: "alice@example.com", SigningOrder: 1},
        {Name: "Bob", Email: "bob@example.com", SigningOrder: 2},
    },
    Fields: []turbodocx.Field{
        {Type: "signature", Page: 1, X: 100, Y: 500, Width: 200, Height: 50, RecipientEmail: "alice@example.com"},
        {Type: "signature", Page: 1, X: 100, Y: 600, Width: 200, Height: 50, RecipientEmail: "bob@example.com"},
    },
})

fmt.Printf("Document ID: %s\n", result.DocumentID)
fmt.Printf("Message: %s\n", result.Message)
Send a template set up in TurboDocx (signer roles)

Upload a PDF as a template in TurboDocx, add its signers as roles (e.g. "Client", "Countersigner"), drag their fields onto the page and save the signature setup. Then send it by setting each recipient's Role. The fields saved for that role come with it, so Fields can be left out.

// The role keys come from the template (also shown under "Use via API" on the template page)
setup, err := client.TurboSign.GetTemplateSignatureSetup(ctx, "your-template-id")
if err != nil {
    log.Fatal(err)
}
for _, role := range setup.Roles {
    fmt.Printf("%s (order %d, saved signer: %t)\n", role.Key, role.Order, role.HasSavedSigner)
}

result, err := client.TurboSign.SendSignature(ctx, &turbodocx.SendSignatureRequest{
    TemplateID: "your-template-id",
    Recipients: []turbodocx.Recipient{
        {Role: "client", Name: "Jane Doe", Email: "jane@client.com"},
        // "countersigner" left out: the signer saved on the template is used
    },
})
  • Roles sign in the order saved on the template; recipients without a Role sign after them, so a role recipient needs no SigningOrder.
  • A role left out uses the template's saved signer. If it has none, the API returns a 400 naming the role.
  • An unknown role returns a 400 (*turbodocx.ValidationError with Code "UnknownSignerRole") whose message lists the template's roles.
  • Any Fields you pass are added to the template's (for example an extra witness signature).
  • Roles work on PDF templates. Without roles, SendSignature needs Fields: a send without them gets a 400 FieldsRequired. A review link (CreateSignatureReviewLink) can be created with no fields; you place them in the preview.
  • GetTemplateSignatureSetup throws *NotFoundError (404, code SignatureSetupNotFound) when the template has no saved signature setup, or is not a template in your organization.
  • Role works the same way on CreateSignatureReviewLink and on EmbeddedSignatureRecipient for CreateEmbeddedSignature.
SendReminder

Send a standalone reminder to whoever's turn it is to sign. It is independent of the automatic reminder cadence — it works even when reminders are disabled or the per-signer cap is spent, does not consume that cap, and only emails signers at the current signing order. Pass nil for recipientIDs to remind everyone eligible; do not pass an empty slice, which the API rejects.

Recipients verified with external_idv or override sign only through a single-use CreateSigningURL link and are never emailed: they come back as skipped_requires_single_use_url. Naming only such recipients returns *ConflictError (409) with code RecipientRequiresSingleUseUrl.

resp, err := client.TurboSign.SendReminder(ctx, "doc-uuid-here", nil)
if err != nil {
    log.Fatal(err)
}

for _, r := range resp.Results {
    // "sent", "skipped_wrong_order", "skipped_completed", ...
    fmt.Printf("%s: %s\n", r.RecipientID, r.Status)
}

Reminders and expiration can also be scheduled when you send. The send request embeds a SignatureSchedule with optional RemindersEnabled / ReminderDelay / ReminderInterval / MaxReminders and ExpirationEnabled / ExpireAfter / ExpirationWarning / ExpirationWarningInterval fields — every field is a pointer, and both features are off by default, so omitting them preserves the original send behavior. The deadline is frozen onto the document at send time and is then readable via GetStatus(...).ExpiresAt.

result, err := client.TurboSign.SendSignature(ctx, &turbodocx.SendSignatureRequest{
    // ...file, recipients, fields, etc.
    SignatureSchedule: turbodocx.SignatureSchedule{
        RemindersEnabled:  turbodocx.BoolPtr(true),
        ReminderDelay:     &turbodocx.Duration{Value: 2, Unit: "days"},
        ExpirationEnabled: turbodocx.BoolPtr(true),
        ExpireAfter:       &turbodocx.Duration{Value: 14, Unit: "days"},
    },
})
GetStatus

Check the document-level status. For per-recipient detail, use GetRecipients.

status, err := client.TurboSign.GetStatus(ctx, "doc-uuid-here")

fmt.Printf("Status: %s\n", status.Status)  // "under_review", "completed", "voided", "expired", ...
// ExpiresAt is the signing-window deadline (ISO 8601), or "" when expiration is off.
fmt.Printf("Expires: %s\n", status.ExpiresAt)
GetRecipients

See who the document went to, who has signed, who you are still waiting on, and who sent it.

result, err := client.TurboSign.GetRecipients(ctx, "doc-uuid-here")
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Sent by %s <%s>\n", result.Document.SentBy.Name, result.Document.SentBy.Email)
fmt.Printf("%d of %d signed, still waiting on %d\n",
    result.Summary.Completed, result.Summary.Total, result.Summary.WaitingOn)

for _, r := range result.Recipients {
    // "pending" | "viewed" | "completed" | "voided" | "expired"
    fmt.Printf("%s <%s>: %s\n", r.Name, r.Email, r.EffectiveStatus)
    if r.SignedOn != nil {
        fmt.Printf("  signed %s\n", *r.SignedOn)
    }
    fmt.Printf("  emailed %dx\n", r.Delivery.TotalSent)
}

Two status fields, and they differ on purpose:

Field Values Use it for
Status pending, viewed, completed The raw database value
EffectiveStatus pending, viewed, completed, voided, expired Display

The database has no per-recipient declined/voided/expired state, so on a voided or expired document an unsigned signer still reads pending in Status. EffectiveStatus layers the document's outcome on top — that's the one to show a user. A completed signature is never revoked: someone who signed before the document was voided still reads completed.

Summary counts by effective status, and WaitingOn (pending + viewed) drops to zero once the document is terminal.

Delivery is that recipient's email history — FirstSentOn, LastSentOn, TotalSent, ReminderCount, LastRemindedAt, WarningCount, LastWarningAt. It counts the signature request, resends, reminders, expiry warnings and terminal notices. CC notifications are excluded, since a CC address is not a signer.

Two delivery fields are easy to misread:

Field What it actually means
ReminderCount Automatic (scheduled) reminders only — the counter maxReminders caps. A manual "remind now" does not increment it (it must not consume the cap budget), though it does land in TotalSent. So it can read 0 while reminder emails have genuinely been sent.
LastRemindedAt When the reminder cadence clock was last reset — not necessarily when a reminder was sent. The initial signature-request send, each scheduled reminder, each manual "remind now" and each expiry warning all stamp it. A freshly-sent document therefore normally reads a non-null LastRemindedAt alongside ReminderCount of 0.

WarningCount and LastWarningAt are touched only by an expiry warning.

Download

Download the signed document.

pdfBytes, err := client.TurboSign.Download(ctx, "doc-uuid-here")

// Save to file
err = os.WriteFile("signed-contract.pdf", pdfBytes, 0644)
VoidDocument

Cancel a signature request.

result, err := client.TurboSign.VoidDocument(ctx, "doc-uuid-here", "Contract terms changed")

fmt.Printf("Document %s voided at %s\n", result.ID, result.VoidedAt)
ResendEmail

Resend signature request emails.

Recipients verified with external_idv or override are skipped (they sign only through a single-use CreateSigningURL link), and naming only such recipients returns *ConflictError (409) with code RecipientRequiresSingleUseUrl.

result, err := client.TurboSign.ResendEmail(ctx, "doc-uuid-here", []string{"recipient-uuid-1"})

fmt.Printf("Resent to %d recipients\n", result.RecipientCount)
GetAuditTrail

Get the complete audit trail for a document, including all events and timestamps.

audit, err := client.TurboSign.GetAuditTrail(ctx, "doc-uuid-here")
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Document: %s\n", audit.Document.Name)

for _, entry := range audit.AuditTrail {
    fmt.Printf("%s - %s\n", entry.ActionType, entry.Timestamp)
    if entry.User != nil {
        fmt.Printf("  By: %s (%s)\n", entry.User.Name, entry.User.Email)
    }
    if entry.Recipient != nil {
        fmt.Printf("  Recipient: %s\n", entry.Recipient.Name)
    }
}

The audit trail includes a cryptographic hash chain for tamper-evidence verification.

TurboPartner

TurboPartner provides partner portal API access for managing organizations, users, API keys, and entitlements. It uses a separate client with partner-level authentication.

Configuration
partner, err := turbodocx.NewPartnerClient(turbodocx.PartnerConfig{
    PartnerAPIKey: os.Getenv("TURBODOCX_PARTNER_API_KEY"), // REQUIRED (TDXP-* prefix)
    PartnerID:     os.Getenv("TURBODOCX_PARTNER_ID"),      // REQUIRED
})

Environment Variables:

export TURBODOCX_PARTNER_API_KEY=TDXP-your-partner-key
export TURBODOCX_PARTNER_ID=your-partner-uuid
Organization Management
// Create organization with entitlements
org, err := partner.CreateOrganization(ctx, &turbodocx.CreateOrganizationRequest{
    Name: "Acme Corp",
    Features: &turbodocx.Features{
        MaxUsers:    turbodocx.IntPtr(25),
        MaxStorage:  turbodocx.Int64Ptr(5 * 1024 * 1024 * 1024), // 5 GB
        HasTDAI:     turbodocx.BoolPtr(true),
    },
})

// List organizations
orgs, err := partner.ListOrganizations(ctx, &turbodocx.ListOrganizationsRequest{
    Limit:  turbodocx.IntPtr(10),
    Search: "acme",
})

// Get full details (includes features + usage tracking)
details, err := partner.GetOrganizationDetails(ctx, orgID)

// Update organization name
updated, err := partner.UpdateOrganizationInfo(ctx, orgID, &turbodocx.UpdateOrganizationRequest{
    Name: "Acme Corporation",
})

// Update entitlements
entitlements, err := partner.UpdateOrganizationEntitlements(ctx, orgID, &turbodocx.UpdateEntitlementsRequest{
    Features: &turbodocx.Features{
        MaxUsers:      turbodocx.IntPtr(50),
        MaxSignatures: turbodocx.IntPtr(1000),
    },
})

// Read the org's TurboSign display preferences
// (returns only the partner-settable keys, with defaults applied)
prefs, err := partner.GetOrganizationPreferences(ctx, orgID)
fmt.Println(prefs.Data.Preferences.LockedFieldsBackground) // true by default

// Update them — every field is a *bool with omitempty, so a nil field is left
// untouched and an explicit false is still sent. Every other organization
// setting is preserved.
updated, err := partner.UpdateOrganizationPreferences(ctx, orgID,
    &turbodocx.UpdateOrgPreferencesRequest{
        LockedFieldsBackground: turbodocx.BoolPtr(false),
    })

// Delete organization
_, err := partner.DeleteOrganization(ctx, orgID)

Partner-settable display preferences

Field Default Effect
HideSignatureOutline false Hide the outline/label drawn around signed fields
HideSignatureHash false Hide the verification hash printed on signed fields
LockedFieldsBackground true Grey box behind locked fields (false = plain text)
AllowDownloadBeforeSigning false When enabled, a signer can download the unsigned PDF from the signing page before they sign it (for example, to review it with their legal team). Defaults to off.
Organization User Management

Org roles are not partner roles. Organization users and organization API keys accept admin, contributor, user, or viewer. Partner portal users use a different enum: admin, member, or viewer. member is not a valid organization role, and contributor / user are not valid partner roles — mixing them returns a 400.

// Add user to organization — role: admin | contributor | user | viewer
user, err := partner.AddUserToOrganization(ctx, orgID, &turbodocx.AddOrgUserRequest{
    Email: "admin@acme.com",
    Role:  "admin",
})

// List users
users, err := partner.ListOrganizationUsers(ctx, orgID, nil)

// Update user role
_, err := partner.UpdateOrganizationUserRole(ctx, orgID, userID, &turbodocx.UpdateOrgUserRequest{
    Role: "contributor",
})

// Remove user
_, err := partner.RemoveUserFromOrganization(ctx, orgID, userID)

// Resend invitation
_, err := partner.ResendOrganizationInvitationToUser(ctx, orgID, userID)
Organization API Key Management
// Create API key — role: admin | contributor | user | viewer (same enum as org users)
key, err := partner.CreateOrganizationAPIKey(ctx, orgID, &turbodocx.CreateOrgAPIKeyRequest{
    Name: "Production Key",
    Role: "admin",
})
fmt.Printf("API Key: %s\n", key.Data.Key)

// List API keys
keys, err := partner.ListOrganizationAPIKeys(ctx, orgID, nil)

// Update API key
_, err := partner.UpdateOrganizationAPIKey(ctx, orgID, keyID, &turbodocx.UpdateOrgAPIKeyRequest{
    Name: "Updated Key Name",
})

// Revoke API key
_, err := partner.RevokeOrganizationAPIKey(ctx, orgID, keyID)
Partner API Key Management
// Create scoped partner API key
key, err := partner.CreatePartnerAPIKey(ctx, &turbodocx.CreatePartnerAPIKeyRequest{
    Name:        "Monitoring Key",
    Description: "Read-only access for dashboard",
    Scopes:      []string{turbodocx.ScopeOrgRead, turbodocx.ScopeAuditRead},
})

// List partner API keys
keys, err := partner.ListPartnerAPIKeys(ctx, nil)

// Update partner API key
_, err := partner.UpdatePartnerAPIKey(ctx, keyID, &turbodocx.UpdatePartnerAPIKeyRequest{
    Name:   "Updated Key",
    Scopes: []string{turbodocx.ScopeOrgRead, turbodocx.ScopeOrgUpdate},
})

// Revoke partner API key
_, err := partner.RevokePartnerAPIKey(ctx, keyID)
Partner User Management

All 7 permission keys are required. The API rejects a partial permissions object with a 400 — there is no partial update. PartnerPermissions is a plain struct, so every key is always sent (omitted fields serialize as false); set each one explicitly so the grant is unambiguous.

// Add partner portal user — role: admin | member | viewer
user, err := partner.AddUserToPartnerPortal(ctx, &turbodocx.AddPartnerUserRequest{
    Email: "ops@yourcompany.com",
    Role:  "member",
    Permissions: turbodocx.PartnerPermissions{
        CanManageOrgs:           true,
        CanManageOrgUsers:       true,
        CanManagePartnerUsers:   false,
        CanManageOrgAPIKeys:     false,
        CanManagePartnerAPIKeys: false,
        CanUpdateEntitlements:   false,
        CanViewAuditLogs:        true,
    },
})

// List partner users
users, err := partner.ListPartnerPortalUsers(ctx, nil)

// Update permissions
_, err := partner.UpdatePartnerUserPermissions(ctx, userID, &turbodocx.UpdatePartnerUserRequest{
    Role: "admin",
    Permissions: &turbodocx.PartnerPermissions{
        CanManageOrgs:          true,
        CanManageOrgUsers:      true,
        CanManagePartnerUsers:  true,
        CanManageOrgAPIKeys:    true,
        CanManagePartnerAPIKeys: true,
        CanUpdateEntitlements:  true,
        CanViewAuditLogs:       true,
    },
})

// Remove partner user
_, err := partner.RemoveUserFromPartnerPortal(ctx, userID)

// Resend invitation
_, err := partner.ResendPartnerPortalInvitationToUser(ctx, userID)
Audit Logs
// Get recent audit logs
logs, err := partner.GetPartnerAuditLogs(ctx, &turbodocx.ListAuditLogsRequest{
    Limit: turbodocx.IntPtr(50),
})

// Filter by action and date range
logs, err := partner.GetPartnerAuditLogs(ctx, &turbodocx.ListAuditLogsRequest{
    Action:       "org:create",
    ResourceType: "organization",
    StartDate:    "2024-01-01",
    EndDate:      "2024-12-31",
    Success:      turbodocx.BoolPtr(true),
})
Available Scopes
Scope Description
org:create Create organizations
org:read View organizations
org:update Update organizations
org:delete Delete organizations
entitlements:update Update organization entitlements
org-users:create Add users to organizations
org-users:read View organization users
org-users:update Update organization users
org-users:delete Remove organization users
org-apikeys:create Create organization API keys
org-apikeys:read View organization API keys
org-apikeys:update Update organization API keys
org-apikeys:delete Revoke organization API keys
partner-apikeys:create Create partner API keys
partner-apikeys:read View partner API keys
partner-apikeys:update Update partner API keys
partner-apikeys:delete Revoke partner API keys
partner-users:create Add partner portal users
partner-users:read View partner portal users
partner-users:update Update partner portal users
partner-users:delete Remove partner portal users
audit:read View audit logs

TurboWebhooks (Signature Webhook)

The WebhooksClient manages your organization's signature webhook — a single subscription to TurboDocx signature events. The package also exposes VerifyWebhookSignature for incoming webhook receivers.

One webhook per org. The SDK manages a single fixed-name webhook (signature) per org so SDK-managed and UI-managed webhooks stay in sync — what you create here also appears in the dashboard's Signature Webhooks settings page. To manage multiple webhooks per org, call the REST API directly.

Requires administrator role. All webhook routes require an admin TDX- API key.

The 7 signature events

Use the typed WebhookEvent constants instead of hand-writing the wire strings — a typo becomes a compile error rather than a webhook that silently never fires.

Event Constant Fires when
signature.document.sent turbodocx.WebhookEventSent The document is dispatched to recipients
signature.document.viewed turbodocx.WebhookEventViewed A recipient opens the document for the first time
signature.document.recipient_signed turbodocx.WebhookEventRecipientSigned Any individual signer completes their signature — fires once per signer, and carries is_final_signer + remaining_signers
signature.document.signed turbodocx.WebhookEventSigned A signer signs but the document is not yet complete (document-level partial progress)
signature.document.completed turbodocx.WebhookEventCompleted All recipients have signed and the signed PDF is finalized
signature.document.finalization_failed turbodocx.WebhookEventFinalizationFailed The signed PDF fails to finalize (e.g. a KMS signing error); the document is not completed
signature.document.voided turbodocx.WebhookEventVoided The document is voided or cancelled

On every signature, recipient_signed fires first, then exactly one document-level event:

Recipient signs
   │
   ├─ signature.document.recipient_signed   (always — one per signer)
   │
   └─ more signers remaining?
        ├─ yes → signature.document.signed                 (partial progress)
        └─ no  → signature.document.completed              (finalized OK)
                 or signature.document.finalization_failed (finalization failed)

signed never fires on the final signature. To detect "the whole document is done", subscribe to completed (or to recipient_signed and check is_final_signer: true) — not signed.

A single-signer document never emits signed at all. It emits recipient_signed (with is_final_signer: true), then completed.

AllWebhookEvents is a []WebhookEvent of all 7, and WebhookEventStrings(...) converts typed events into the []string the request structs take. Events stays []string, so the backend can add events without an SDK release.

Configuration
import turbodocx "github.com/TurboDocx/SDK/packages/go-sdk"

client, err := turbodocx.NewWebhooksClientWithConfig(turbodocx.ClientConfig{
    APIKey:  os.Getenv("TURBODOCX_API_KEY"),
    OrgID:   os.Getenv("TURBODOCX_ORG_ID"),
    // BaseURL: "http://localhost:3000", // optional; defaults to https://api.turbodocx.com
})
if err != nil {
    log.Fatal(err)
}

Unlike the main NewClientWithConfig, this constructor does NOT require SenderEmail — webhook routes don't send signature emails.

Create the signature webhook (save the secret immediately)
ctx := context.Background()
created, err := client.CreateWebhook(ctx, turbodocx.CreateWebhookRequest{
    URLs: []string{"https://your-server.example.com/webhooks/turbodocx"}, // HTTPS only; 1-10 URLs
    Events: turbodocx.WebhookEventStrings( // at least 1
        turbodocx.WebhookEventSent,
        turbodocx.WebhookEventViewed,
        turbodocx.WebhookEventRecipientSigned,
        turbodocx.WebhookEventCompleted,
        turbodocx.WebhookEventVoided,
    ),
    // ...or subscribe to everything:
    // Events: turbodocx.WebhookEventStrings(turbodocx.AllWebhookEvents...),
})
// `created.Secret` is shown ONCE here. Store it securely.
fmt.Println("Save this secret:", created.Secret)

URLs accepts 1 to 10 HTTPS endpoints and Events requires at least 1 event. Empty lists return a 400.

Get, update, delete
webhook, err := client.GetWebhook(ctx)
// webhook["deliveryStats"] and webhook["availableEvents"] are included

isActive := false
client.UpdateWebhook(ctx, turbodocx.UpdateWebhookRequest{IsActive: &isActive})

client.DeleteWebhook(ctx)

UpdateWebhook patches only the fields you set. The URLs / Events minimums still apply on update — leave a field nil to keep it unchanged. An empty list is not a "clear": it cannot be used to remove all URLs or events.

Test deliveries and replay
tested, _ := client.TestWebhook(ctx, turbodocx.TestWebhookRequest{
    EventType: "signature.document.completed",
    Payload:   map[string]interface{}{"documentId": "doc-xyz", "status": "completed"},
})

deliveries, _ := client.ListWebhookDeliveries(ctx, turbodocx.ListDeliveriesRequest{})
results := deliveries["results"].([]interface{})
firstID := results[0].(map[string]interface{})["id"].(string)
replayed, _ := client.ReplayWebhookDelivery(ctx, firstID)
Rotate the secret
rotated, _ := client.RegenerateWebhookSecret(ctx)
// rotated["secret"] is the new secret. Old signatures will fail immediately.
Aggregate stats
stats, _ := client.GetWebhookStats(ctx, 30) // last 30 days
// stats["summary"], stats["eventBreakdown"]
Verify incoming webhook signatures (net/http example)

Webhook deliveries from TurboDocx are signed with HMAC-SHA256 over timestamp + "." + rawBody using your webhook secret. Use VerifyWebhookSignature in your receiver:

import (
    "io"
    "net/http"
    "os"

    turbodocx "github.com/TurboDocx/SDK/packages/go-sdk"
)

func webhookHandler(w http.ResponseWriter, r *http.Request) {
    rawBody, err := io.ReadAll(r.Body) // raw bytes; do NOT parse JSON first
    if err != nil {
        http.Error(w, "bad body", http.StatusBadRequest)
        return
    }
    signature := r.Header.Get("X-TurboDocx-Signature")
    timestamp := r.Header.Get("X-TurboDocx-Timestamp")
    secret := os.Getenv("TURBODOCX_WEBHOOK_SECRET")

    if !turbodocx.VerifyWebhookSignature(rawBody, signature, timestamp, secret, nil) {
        http.Error(w, "invalid signature", http.StatusUnauthorized)
        return
    }

    // Now safe to parse and process
    w.WriteHeader(http.StatusOK)
}

By default the helper enforces a 300-second timestamp tolerance to prevent replay attacks. Override via &turbodocx.VerifyWebhookSignatureOptions{ToleranceSeconds: N} (0 means the default 300 seconds, so the Go helper cannot turn the check off; a negative value fails closed and rejects every delivery).


TurboQuote (CPQ — Configure, Price, Quote)

The QuoteClient manages your organization's quoting workflow — companies, contacts, products, bundles, price books, and quotes. Create quotes, attach line items, apply price-book discounts, and send to prospects.

Configuration
import turbodocx "github.com/TurboDocx/SDK/packages/go-sdk"

client, err := turbodocx.NewQuoteClient(turbodocx.QuoteClientConfig{
    APIKey: os.Getenv("TURBODOCX_API_KEY"),
    OrgID:  os.Getenv("TURBODOCX_ORG_ID"),
    // BaseURL: "http://localhost:3000", // optional; defaults to https://api.turbodocx.com
})
if err != nil {
    log.Fatal(err)
}

No SenderEmail on the client — but sending a quote does create a signature request and email the recipient. The sender comes from your organization's quote template (Quote Settings); configure one there, or create/duplicate/send returns 400 SenderEmailRequired.

Method Groups
Group Methods
Quotes ListQuotes, CreateQuote, GetQuote, UpdateQuote, DeleteQuote, DuplicateQuote, DownloadQuotePdf
Quote status SendQuote, SendQuoteWithDeliverable, DeclineQuote, VoidQuote, HandleExpiredQuote (void/decline an expired quote and reissue it)
Price book application ApplyPriceBook, RemovePriceBook
Line items ListLineItems, AddLineItems, AddBundleLineItems, UpdateLineItem, RemoveLineItem
Products ListProducts, CreateProduct, GetProduct, UpdateProduct, DeleteProduct, DuplicateProduct, GetProductPrimaryImages
Price books ListPriceBooks, CreatePriceBook, GetPriceBook, UpdatePriceBook, DeletePriceBook, DuplicatePriceBook, ListPriceBookProducts
Bundles ListBundles, CreateBundle, GetBundle, UpdateBundle, DeleteBundle, DuplicateBundle
Companies ListCompanies, CreateCompany, GetCompany, UpdateCompany, DeleteCompany, ListCompanyContacts
Contacts ListContacts, CreateContact, UpdateContact, DeleteContact
Templates ListTemplates, GetTemplate, GetTemplateByID, CreateTemplate, UpdateTemplate, DeleteTemplate
Types/categories ListTypes, CreateType, UpdateType, DeleteType
Convenience CreateAndSend
Create a quote and add line items
ctx := context.Background()

// Create the quote (TermDays defaults to 60 when omitted)
quote, err := client.CreateQuote(ctx, &turbodocx.CreateQuoteRequest{
    Name:      "Acme Annual Subscription",
    CompanyID: companyID,
    ContactID: contactID,
})
if err != nil {
    log.Fatal(err)
}

// Add product line items (variadic — pass one or many, max 50 per call).
// ProductName, UnitPrice and BillingFrequency are required. ProductID is a required
// key too, but its value may be nil — that marks an ad-hoc item with no catalog product.
qty := 3
items, err := client.AddLineItems(ctx, quote.ID, turbodocx.AddLineItemRequest{
    ProductID:        nil, // or &productID to link a catalog product
    ProductName:      "Professional License",
    UnitPrice:        499.00,
    BillingFrequency: "annual",
    Quantity:         &qty,
})
Send a quote — with reminder/expiration scheduling

SendQuote and SendQuoteWithDeliverable accept the same eight per-send reminder/expiration override fields as the signature send, via an embedded SignatureSchedule: RemindersEnabled / ReminderDelay / ReminderInterval / MaxReminders and ExpirationEnabled / ExpireAfter / ExpirationWarning / ExpirationWarningInterval. Every field is a pointer, both features are off by default, and durations are {value, unit} objects (turbodocx.Duration{Value, Unit}, unit "hours" or "days"). Omitted fields inherit the org defaults.

Quote expiry works a little differently from signature expiry: the backend pins the deadline to the quote's ValidUntil, so ExpireAfter is ignored when expiration is on — but ExpirationEnabled still toggles expiration on or off. The reminder and warning cadence is layered over the org defaults and must fit within ValidUntil, or the send is rejected.

validUntil := time.Now().AddDate(0, 0, 30).Format("2006-01-02")

resp, err := client.SendQuote(ctx, quote.ID, &turbodocx.SendQuoteRequest{
    ValidUntil: &validUntil,
    SignatureSchedule: turbodocx.SignatureSchedule{
        RemindersEnabled: turbodocx.BoolPtr(true),
        ReminderDelay:    &turbodocx.Duration{Value: 2, Unit: "days"},
        ExpirationEnabled: turbodocx.BoolPtr(true), // deadline comes from ValidUntil, not ExpireAfter
    },
})
Sender identity — "Prepared by"

The quote's "Prepared by" name and email are resolved by the server, not by whoever downloads or sends the quote. Precedence: the org quote template's sender fields first, then the quote's creator.

A quote created with an API key has no mailbox of its own — so its sender email can only come from the quote template. If your org's quote template has no sender email set, CreateQuote (and DuplicateQuote) return a ValidationError (400 SenderEmailRequired) for an API-key caller. Set a sender email on the template once (via UpdateTemplate) and every subsequent create/duplicate/send resolves cleanly. Human (JWT) callers are never blocked — their own email is the fallback.

GetQuote returns the resolved identity as PreparedBy — prefer it over Creator for any customer-facing display (Creator may be the internal API service account). Both fields are pointers and may be nil for an API-created quote:

quote, err := client.GetQuote(ctx, quoteID)
if err != nil {
    log.Fatal(err)
}
if quote.PreparedBy != nil && quote.PreparedBy.Name != nil {
    fmt.Println(*quote.PreparedBy.Name) // e.g. "Acme Billing Integration" or the template sender
}
Quote terms and auto-renewal

TermDays is optional and defaults to 60 (max 3650). The special value -1 means auto-renewal. RenewalPeriod is coupled to it:

  • TermDays: -1 → RenewalPeriod is required (weekly, monthly, quarterly, or annually)
  • any other TermDays → RenewalPeriod must be omitted; sending it returns a 400
termDays := -1
renewal := "annually"
quote, err := client.CreateQuote(ctx, &turbodocx.CreateQuoteRequest{
    Name:          "Auto-Renewing Subscription",
    CompanyID:     companyID,
    ContactID:     contactID,
    TermDays:      &termDays,
    RenewalPeriod: &renewal,
})
Resolve an expired quote

HandleExpiredQuote closes out a sent quote whose validUntil has passed — it voids or declines the original and returns a duplicate carrying the new validUntil date.

The only valid actions are void and decline; there is no "extend" or "re-send" action. Action, Reason, and NewValidUntil are all three required.

reissued, err := client.HandleExpiredQuote(ctx, quote.ID, &turbodocx.HandleExpiredQuoteRequest{
    Action:        "void",                                  // "void" or "decline" — nothing else
    Reason:        "Pricing refreshed for the new term",    // required, max 190 chars
    NewValidUntil: time.Now().AddDate(0, 0, 30).Format("2006-01-02"), // required
})
Apply a price book and download the PDF
// Apply an existing price book to get discounted pricing
applyResp, err := client.ApplyPriceBook(ctx, quote.ID, priceBookID)
fmt.Printf("Updated %d items, skipped %d\n", applyResp.UpdatedCount, applyResp.SkippedCount)

// Download as PDF
pdf, err := client.DownloadQuotePdf(ctx, quote.ID)
if err == nil {
    os.WriteFile("quote.pdf", pdf, 0600)
}

Field Types

Type Description
signature Signature field (draw or type)
initial Initials field
text Free-form text input
date Date stamp
checkbox Checkbox / agreement
full_name Full name
first_name First name
last_name Last name
email Email address
title Job title
company Company name

The checkbox type doubles as the controlling field for conditional logic (see below).

Conditional (IF/THEN) Fields

Any field may carry an optional Metadata (*FieldMetadata) that drives conditional logic. Set FieldKey on a controlling checkbox to give it a stable id, then set Conditional on a dependent field that references that id:

Fields: []turbodocx.Field{
    // Controlling checkbox — carries the FieldKey dependents reference
    {
        Type:           "checkbox",
        RecipientEmail: "john@example.com",
        Metadata:       &turbodocx.FieldMetadata{FieldKey: "request_changes"},
    },
    // Dependent text field — hidden until the checkbox is checked ("If checked, explain")
    {
        Type:           "text",
        RecipientEmail: "john@example.com",
        IsMultiline:    true,
        Metadata: &turbodocx.FieldMetadata{
            Conditional: &turbodocx.FieldConditional{
                ControllingFieldKey: "request_changes",                    // must equal the checkbox's FieldKey
                Operator:            turbodocx.ConditionalOperatorIsChecked, // IsChecked | IsNotChecked
                Action:              turbodocx.ConditionalActionShow,        // Show (hidden until met) | Unlock (read-only until met)
            },
        },
    },
}
Metadata field Set on Meaning
FieldKey controlling checkbox Stable client id (≤100 chars) that dependents reference
Conditional.ControllingFieldKey dependent field Must equal the controlling checkbox's FieldKey
Conditional.Operator dependent field ConditionalOperatorIsChecked ("is_checked") or ConditionalOperatorIsNotChecked ("is_not_checked")
Conditional.Action dependent field ConditionalActionShow (hidden until met) or ConditionalActionUnlock (visible but read-only until met)

Type Reference

Core Types
Recipient
type Recipient struct {
    Name         string `json:"name"`
    Email        string `json:"email"`
    SigningOrder int    `json:"signingOrder,omitempty"` // not needed when Role is set
    Role         string `json:"role,omitempty"`         // template signer role, e.g. "client"
    // ... Phone, ExternalID, IdentityVerification
}
Field
type Field struct {
    Type            string          `json:"type"`                      // signature, initial, text, date, checkbox
    Page            int             `json:"page,omitempty"`            // Page number (1-indexed)
    X               int             `json:"x,omitempty"`               // X coordinate
    Y               int             `json:"y,omitempty"`               // Y coordinate
    Width           int             `json:"width,omitempty"`           // Field width
    Height          int             `json:"height,omitempty"`          // Field height
    RecipientEmail  string          `json:"recipientEmail"`            // Email of the recipient who fills this field
    DefaultValue    string          `json:"defaultValue,omitempty"`    // Pre-filled value (text, identity, and date fields)
    IsMultiline     bool            `json:"isMultiline,omitempty"`     // Allow multiple lines (text fields)
    IsReadonly      bool            `json:"isReadonly,omitempty"`      // Read-only field
    Required        *bool           `json:"required,omitempty"`        // nil = required (default); BoolPtr(false) = optional for the signer (not allowed on signature/initial)
    BackgroundColor string          `json:"backgroundColor,omitempty"` // Background color (hex)
    Template        *TemplateAnchor `json:"template,omitempty"`        // Template anchor for dynamic positioning
    Metadata        *FieldMetadata  `json:"metadata,omitempty"`        // Conditional (IF/THEN) logic — see "Conditional Fields"
}
TemplateAnchor

Use template anchors for dynamic field positioning based on text in the document:

type TemplateAnchor struct {
    Anchor        string `json:"anchor,omitempty"`        // Text to search for
    SearchText    string `json:"searchText,omitempty"`    // Alternative to Anchor
    Placement     string `json:"placement,omitempty"`     // replace, before, after, above, below
    Size          *Size  `json:"size,omitempty"`          // Field dimensions
    Offset        *Point `json:"offset,omitempty"`        // Offset from anchor position
    CaseSensitive bool   `json:"caseSensitive,omitempty"` // Case-sensitive search
    UseRegex      bool   `json:"useRegex,omitempty"`      // Use regex for search
}
Size and Point
type Size struct {
    Width  int `json:"width"`
    Height int `json:"height"`
}

type Point struct {
    X int `json:"x"`
    Y int `json:"y"`
}
Alternative File Sources

Instead of providing File bytes, you can use these alternative file sources:

// From URL
request := &turbodocx.SendSignatureRequest{
    FileLink: "https://example.com/contract.pdf",
    // ...
}

// From TurboDocx Deliverable
request := &turbodocx.SendSignatureRequest{
    DeliverableID: "deliverable-uuid",
    // ...
}

// From TurboDocx Template
request := &turbodocx.SendSignatureRequest{
    TemplateID: "template-uuid",
    // ...
}
Response Types
SendSignatureResponse
type SendSignatureResponse struct {
    Success    bool              `json:"success"`
    DocumentID string            `json:"documentId"`
    Status     string            `json:"status"`
    Message    string            `json:"message"`
    Recipients []ReviewRecipient `json:"recipients,omitempty"`
}
CreateSignatureReviewLinkResponse
type CreateSignatureReviewLinkResponse struct {
    Success    bool              `json:"success"`
    DocumentID string            `json:"documentId"`
    Status     string            `json:"status"`
    PreviewURL string            `json:"previewUrl,omitempty"`
    Message    string            `json:"message"`
    Recipients []ReviewRecipient `json:"recipients,omitempty"`
}

type ReviewRecipient struct {
    ID       string                 `json:"id"`
    Name     string                 `json:"name"`
    Email    string                 `json:"email"`
    Metadata map[string]interface{} `json:"metadata,omitempty"`
}
VoidDocumentResponse
type VoidDocumentResponse struct {
    ID         string `json:"id"`
    Name       string `json:"name"`
    Status     string `json:"status"`
    VoidReason string `json:"voidReason,omitempty"`
    VoidedAt   string `json:"voidedAt,omitempty"`
}
ResendEmailResponse
type ResendEmailResponse struct {
    Success        bool `json:"success"`
    RecipientCount int  `json:"recipientCount"`
}

Examples

For complete, working examples see the examples/ directory:

TurboSign:

TurboPartner:

TurboQuote:

Sequential Signing
result, _ := client.TurboSign.SendSignature(ctx, &turbodocx.SendSignatureRequest{
    FileLink: "https://example.com/contract.pdf",
    Recipients: []turbodocx.Recipient{
        {Name: "Employee", Email: "employee@company.com", SigningOrder: 1},
        {Name: "Manager", Email: "manager@company.com", SigningOrder: 2},
        {Name: "HR", Email: "hr@company.com", SigningOrder: 3},
    },
    Fields: []turbodocx.Field{
        {Type: "signature", Page: 1, X: 100, Y: 400, Width: 200, Height: 50, RecipientEmail: "employee@company.com"},
        {Type: "date", Page: 1, X: 320, Y: 400, Width: 100, Height: 30, RecipientEmail: "employee@company.com"},
        {Type: "signature", Page: 1, X: 100, Y: 500, Width: 200, Height: 50, RecipientEmail: "manager@company.com"},
        {Type: "signature", Page: 1, X: 100, Y: 600, Width: 200, Height: 50, RecipientEmail: "hr@company.com"},
    },
})
With Context Timeout
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

result, err := client.TurboSign.SendSignature(ctx, request)
if err != nil {
    if errors.Is(err, context.DeadlineExceeded) {
        log.Println("Request timed out")
    }
}
Polling for Completion
func waitForCompletion(ctx context.Context, client *turbodocx.Client, documentID string) ([]byte, error) {
    ticker := time.NewTicker(30 * time.Second)
    defer ticker.Stop()

    for {
        select {
        case <-ctx.Done():
            return nil, ctx.Err()
        case <-ticker.C:
            status, err := client.TurboSign.GetStatus(ctx, documentID)
            if err != nil {
                return nil, err
            }

            switch status.Status {
            case "completed":
                return client.TurboSign.Download(ctx, documentID)
            case "voided":
                return nil, errors.New("document was voided")
            }
        }
    }
}
With HTTP Handler
func sendContractHandler(w http.ResponseWriter, r *http.Request) {
    client, err := turbodocx.NewClientWithConfig(turbodocx.ClientConfig{
        APIKey:      os.Getenv("TURBODOCX_API_KEY"),
        OrgID:       os.Getenv("TURBODOCX_ORG_ID"),
        SenderEmail: os.Getenv("TURBODOCX_SENDER_EMAIL"),
        SenderName:  os.Getenv("TURBODOCX_SENDER_NAME"),
    })
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    var req struct {
        PDFUrl     string               `json:"pdfUrl"`
        Recipients []turbodocx.Recipient `json:"recipients"`
        Fields     []turbodocx.Field     `json:"fields"`
    }
    json.NewDecoder(r.Body).Decode(&req)

    result, err := client.TurboSign.SendSignature(r.Context(), &turbodocx.SendSignatureRequest{
        FileLink:   req.PDFUrl,
        Recipients: req.Recipients,
        Fields:     req.Fields,
    })
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    json.NewEncoder(w).Encode(map[string]string{
        "documentId": result.DocumentID,
    })
}

Local Testing

The SDK includes a comprehensive manual test program to verify all functionality locally.

Running Manual Tests
# Navigate to the SDK directory
cd packages/go-sdk

# Run the manual test program
go run cmd/manual/main.go
What It Tests

The cmd/manual/main.go program tests all SDK methods:

  • ✅ CreateSignatureReviewLink() - Document upload for review
  • ✅ SendSignature() - Send for signature
  • ✅ GetStatus() - Check document status
  • ✅ GetRecipients() - Per-recipient signing status (who signed, who is pending)
  • ✅ Download() - Download signed document
  • ✅ VoidDocument() - Cancel signature request
  • ✅ ResendEmail() - Resend signature emails
  • ✅ GetAuditTrail() - Get document audit trail
Configuration

Before running, update the hardcoded values in cmd/manual/main.go:

  • apiKey - Your TurboDocx API key
  • baseURL - API endpoint (default: http://localhost:3000)
  • orgID - Your organization UUID
  • testFilePath - Path to a test PDF/DOCX file
  • testEmail - Email address for testing
Expected Output

The test program will:

  1. Upload a test document
  2. Send it for signature
  3. Check the status
  4. Test void and resend operations
  5. Print results for each operation

Error Handling

The SDK provides typed errors for different failure scenarios:

result, err := client.TurboSign.GetStatus(ctx, "invalid-id")
if err != nil {
    // Check for specific error types
    var validationErr *turbodocx.ValidationError
    var authErr *turbodocx.AuthenticationError
    var notFoundErr *turbodocx.NotFoundError
    var rateLimitErr *turbodocx.RateLimitError
    var networkErr *turbodocx.NetworkError

    switch {
    case errors.As(err, &validationErr):
        fmt.Printf("Validation error: %s\n", validationErr.Message)
    case errors.As(err, &authErr):
        fmt.Printf("Authentication failed: %s\n", authErr.Message)
    case errors.As(err, &notFoundErr):
        fmt.Printf("Not found: %s\n", notFoundErr.Message)
    case errors.As(err, &rateLimitErr):
        fmt.Printf("Rate limited: %s\n", rateLimitErr.Message)
    case errors.As(err, &networkErr):
        fmt.Printf("Network error: %s\n", networkErr.Message)
    default:
        // Base error type
        var apiErr *turbodocx.TurboDocxError
        if errors.As(err, &apiErr) {
            fmt.Printf("Status: %d\n", apiErr.StatusCode)
            fmt.Printf("Message: %s\n", apiErr.Message)
            fmt.Printf("Code: %s\n", apiErr.Code)
        } else {
            fmt.Printf("Unexpected error: %v\n", err)
        }
    }
}
Error Types
Type HTTP Status Description
ValidationError 400 Invalid request parameters
AuthenticationError 401 Invalid API key or access token
NotFoundError 404 Document or resource not found
RateLimitError 429 Too many requests
NetworkError N/A Network or connection failure
TurboDocxError Any Base error type for other status codes
Error Codes

code is always populated — an API-supplied code when there is one, otherwise the error class's default (VALIDATION_ERROR, AUTHENTICATION_ERROR, AUTHORIZATION_ERROR, NOT_FOUND, CONFLICT, RATE_LIMIT_EXCEEDED, NETWORK_ERROR). Branch on it without a null check.

The API also returns more specific codes, passed through unchanged:

Code Status Meaning
SenderEmailRequired 400 No sender email resolvable. TurboSign: set senderEmail on the request. TurboQuote: configure one on the org quote template (Quote Settings).
SenderNameRequired 400 No sender name resolvable — the API key has no usable name.
OptionalNotSupported 400 A signature or initial field was sent with required: false. The signer must always complete those two types.
InvalidFieldRequired 400 A field's required is not a boolean. Send true, false, or leave it out (leaving it out means required).
NoEditableFieldsForRecipient 400 A recipient has no field they must fill in: all of their fields are read-only or optional. Give each recipient at least one required, editable field.
FieldsRequired 400 A send has no fields and no recipient names a role. Pass fields, or send a template whose recipients name roles. A review link can be created without fields.
FieldPageOutOfRange 400 A field is placed on a page past the end of the document.
UnknownSignerRole 400 A recipient's role is not one of the template's roles. The message lists them.
DuplicateSignerRole 400 More than one recipient was given for the same role.
SignerRoleUnfilled 400 A role has no recipient and no signer saved on the template.
TemplateHasNoSignerRoles 400 role was used on a template with no saved signature setup.
RoleRequiresTemplate 400 role was used without a templateId.
TemplateRolesNeedPdfTemplate 400 Roles can only be sent for a PDF signature template. For a Word template, generate a deliverable and send it with deliverableId.
DuplicateRoleEmail 400 Two roles resolve to the same email address (a recipient you passed or a signer saved on the template), or a recipient without a role uses a role's email address. Each signer needs their own email address.
SignerHasNoFields 400 On a role send, a signer has no field to sign: neither the template nor your fields assigns one to them. Raised when sending (SendSignature, embedded signing), not for a review link, where fields can be placed in the preview.
InvalidRecipient 400 An entry in recipients is not an object (for example null or a string).
SignatureSetupNotFound 404 GetTemplateSignatureSetup was called for a template with no saved signature setup, or one that is not in your organization. Thrown as *NotFoundError.
QuoteHasNoLineItems 400 The quote has no line items. Add at least one before sending.
QuoteExpired 400 The quote is past its validUntil date.
QuoteValidUntilRequired 400 The quote has no validUntil date set.
QuoteNotSendable 400 Only draft quotes can be sent.
QuoteContactRequired 400 The quote's contact is missing a name or email.
QuoteCustomerInactive 400 The quote's company or contact was deleted or deactivated.

Error messages carry the actionable reason, not a generic envelope — multiple field errors are joined with "; ", e.g. "name" is not allowed to be empty; "companyId" must be a valid GUID.

Common Error Codes
Status Meaning
400 Bad request — check your parameters
401 Unauthorized — check your API key
404 Document not found
429 Rate limited — slow down requests
500 Server error — retry with backoff

Requirements

  • Go 1.21+

Package Description
@turbodocx/sdk (JS) JavaScript/TypeScript SDK
turbodocx-sdk (Python) Python SDK
@turbodocx/n8n-nodes-turbodocx n8n community nodes

Support


License

MIT — see LICENSE


TurboDocx

Documentation

Overview

Package turbodocx provides the official Go SDK for TurboDocx API.

This SDK provides digital signatures, document generation, and AI-powered workflows.

Example usage:

client, err := turbodocx.NewClientWithConfig(turbodocx.ClientConfig{
	APIKey: "your-api-key",
	OrgID:  "your-org-id",
})

// Prepare document for signing
result, err := client.TurboSign.SendSignature(ctx, &turbodocx.SendSignatureRequest{
	FileLink: "https://example.com/contract.pdf",
	Recipients: []turbodocx.Recipient{
		{Name: "John Doe", Email: "john@example.com", SigningOrder: 1},
	},
	Fields: []turbodocx.Field{
		{Type: "signature", Page: 1, X: 100, Y: 500, Width: 200, Height: 50, RecipientEmail: "john@example.com"},
	},
})

Index

Constants

View Source
const (
	ScopeOrgCreate            = "org:create"
	ScopeOrgRead              = "org:read"
	ScopeOrgUpdate            = "org:update"
	ScopeOrgDelete            = "org:delete"
	ScopeEntitlementsUpdate   = "entitlements:update"
	ScopeOrgUsersCreate       = "org-users:create"
	ScopeOrgUsersRead         = "org-users:read"
	ScopeOrgUsersUpdate       = "org-users:update"
	ScopeOrgUsersDelete       = "org-users:delete"
	ScopePartnerUsersCreate   = "partner-users:create"
	ScopePartnerUsersRead     = "partner-users:read"
	ScopePartnerUsersUpdate   = "partner-users:update"
	ScopePartnerUsersDelete   = "partner-users:delete"
	ScopeOrgAPIKeysCreate     = "org-apikeys:create"
	ScopeOrgAPIKeysRead       = "org-apikeys:read"
	ScopeOrgAPIKeysUpdate     = "org-apikeys:update"
	ScopeOrgAPIKeysDelete     = "org-apikeys:delete"
	ScopePartnerAPIKeysCreate = "partner-apikeys:create"
	ScopePartnerAPIKeysRead   = "partner-apikeys:read"
	ScopePartnerAPIKeysUpdate = "partner-apikeys:update"
	ScopePartnerAPIKeysDelete = "partner-apikeys:delete"
	ScopeAuditRead            = "audit:read"
)
View Source
const DefaultWebhookToleranceSeconds = 300

DefaultWebhookToleranceSeconds is the default tolerance window for the X-TurboDocx-Timestamp header. Deliveries with a timestamp older or newer than this are rejected by VerifyWebhookSignature to prevent replay attacks.

View Source
const ScopeOrgApikeysCreate = ScopeOrgAPIKeysCreate

Deprecated: use ScopeOrgAPIKeysCreate.

View Source
const ScopeOrgApikeysDelete = ScopeOrgAPIKeysDelete

Deprecated: use ScopeOrgAPIKeysDelete.

View Source
const ScopeOrgApikeysRead = ScopeOrgAPIKeysRead

Deprecated: use ScopeOrgAPIKeysRead.

View Source
const ScopeOrgApikeysUpdate = ScopeOrgAPIKeysUpdate

Deprecated: use ScopeOrgAPIKeysUpdate.

View Source
const ScopePartnerApikeysCreate = ScopePartnerAPIKeysCreate

Deprecated: use ScopePartnerAPIKeysCreate.

View Source
const ScopePartnerApikeysDelete = ScopePartnerAPIKeysDelete

Deprecated: use ScopePartnerAPIKeysDelete.

View Source
const ScopePartnerApikeysRead = ScopePartnerAPIKeysRead

Deprecated: use ScopePartnerAPIKeysRead.

View Source
const ScopePartnerApikeysUpdate = ScopePartnerAPIKeysUpdate

Deprecated: use ScopePartnerAPIKeysUpdate.

View Source
const SignatureWebhookName = "signature"

SignatureWebhookName is the fixed name of the single SDK-managed webhook per org. Matches the UI's Signature Webhooks settings page.

View Source
const Version = "0.9.0"

Version is the current SDK version

Variables

AllWebhookEvents holds all 7 TurboSign webhook events, in lifecycle order.

Every signature fires recipient_signed first, then exactly one of completed / finalization_failed (that was the final signature) or signed (signers still remain).

Functions

func BoolPtr added in v0.2.0

func BoolPtr(v bool) *bool

BoolPtr returns a pointer to the given bool value (helper for optional bool fields)

func Int64Ptr added in v0.2.0

func Int64Ptr(v int64) *int64

Int64Ptr returns a pointer to the given int64 value (helper for optional int64 fields)

func IntPtr added in v0.2.0

func IntPtr(v int) *int

IntPtr returns a pointer to the given int value (helper for optional int fields)

func VerifyWebhookSignature added in v0.3.0

func VerifyWebhookSignature(rawBody []byte, signatureHeader, timestampHeader, secret string, opts *VerifyWebhookSignatureOptions) bool

VerifyWebhookSignature verifies a TurboDocx webhook delivery.

Format matches how TurboDocx signs each delivery:

Header:        X-TurboDocx-Signature: sha256=<hex>
Timestamp:     X-TurboDocx-Timestamp: <unix-seconds>
String signed: timestamp + "." + rawBody
Algorithm:     HMAC-SHA256

rawBody must be the raw request bytes AS RECEIVED. Do NOT parse JSON first; do NOT re-serialize. Whitespace must match exactly. Constant-time comparison via hmac.Equal.

Returns true iff the signature is valid AND the timestamp is within tolerance.

func WebhookEventStrings added in v0.6.0

func WebhookEventStrings(events ...WebhookEvent) []string

WebhookEventStrings converts typed events into the []string form taken by CreateWebhookRequest.Events and UpdateWebhookRequest.Events.

Events: turbodocx.WebhookEventStrings(
    turbodocx.WebhookEventRecipientSigned,
    turbodocx.WebhookEventCompleted,
)

// ...or subscribe to everything:
Events: turbodocx.WebhookEventStrings(turbodocx.AllWebhookEvents...)

Types

type AddBundleLineItemRequest added in v0.4.0

type AddBundleLineItemRequest struct {
	BundleID           string        `json:"bundleId"`
	BundleName         string        `json:"bundleName"`
	Quantity           *int          `json:"quantity,omitempty"`
	DiscountPercent    *float64      `json:"discountPercent,omitempty"`
	DiscountType       *DiscountType `json:"discountType,omitempty"`
	DiscountAmount     *float64      `json:"discountAmount,omitempty"`
	BundleDescription  *string       `json:"bundleDescription,omitempty"`
	ShowItemsToEndUser *bool         `json:"showItemsToEndUser,omitempty"`
}

AddBundleLineItemRequest is the request to add a bundle line item

type AddLineItemRequest added in v0.4.0

type AddLineItemRequest struct {
	// ProductID, ProductName, UnitPrice and BillingFrequency are all required by the API.
	// ProductID is deliberately not omitempty: the key must be present on the wire, but its
	// value may be null — a nil ProductID means an ad-hoc item with no catalog product behind it.
	ProductID          *string       `json:"productId"`
	ProductName        string        `json:"productName"`
	UnitPrice          float64       `json:"unitPrice"`
	BillingFrequency   string        `json:"billingFrequency"`
	Quantity           *int          `json:"quantity,omitempty"`
	DiscountPercent    *float64      `json:"discountPercent,omitempty"`
	DiscountType       *DiscountType `json:"discountType,omitempty"`
	DiscountAmount     *float64      `json:"discountAmount,omitempty"`
	CategoryID         *string       `json:"categoryId,omitempty"`
	CategoryName       *string       `json:"categoryName,omitempty"`
	Cost               *float64      `json:"cost,omitempty"`
	ProductSku         *string       `json:"productSku,omitempty"`
	ProductDescription *string       `json:"productDescription,omitempty"`
}

AddLineItemRequest is the request to add a product line item

type AddOrgUserRequest added in v0.2.0

type AddOrgUserRequest struct {
	Email string `json:"email"`
	Role  string `json:"role"` // admin | contributor | user | viewer ("member" is a partner role, not an org role)
}

AddOrgUserRequest is the request to add a user to an organization

type AddPartnerUserRequest added in v0.2.0

type AddPartnerUserRequest struct {
	Email       string             `json:"email"`
	Role        string             `json:"role"` // admin | member | viewer (partner roles differ from org roles)
	Permissions PartnerPermissions `json:"permissions"`
}

AddPartnerUserRequest is the request to add a user to the partner portal

type ApplyPriceBookResponse added in v0.4.0

type ApplyPriceBookResponse struct {
	QuoteResult  Quote  `json:"quote"`
	Message      string `json:"message"`
	UpdatedCount int    `json:"updatedCount"`
	SkippedCount int    `json:"skippedCount"`
}

ApplyPriceBookResponse is the response from applying a price book to a quote

type AuditLogEntry added in v0.2.0

type AuditLogEntry struct {
	ID              string                 `json:"id"`
	PartnerID       string                 `json:"partnerId"`
	PartnerAPIKeyID string                 `json:"partnerAPIKeyId,omitempty"`
	Action          string                 `json:"action,omitempty"`
	ResourceType    string                 `json:"resourceType,omitempty"`
	ResourceID      string                 `json:"resourceId,omitempty"`
	Details         map[string]interface{} `json:"details,omitempty"`
	Success         bool                   `json:"success,omitempty"`
	IPAddress       string                 `json:"ipAddress,omitempty"`
	UserAgent       string                 `json:"userAgent,omitempty"`
	CreatedOn       string                 `json:"createdOn,omitempty"`
}

AuditLogEntry represents a single audit log entry

type AuditLogListResponse added in v0.2.0

type AuditLogListResponse struct {
	Success bool `json:"success"`
	Data    struct {
		Results      []AuditLogEntry `json:"results"`
		TotalRecords int             `json:"totalRecords"`
		Limit        int             `json:"limit"`
		Offset       int             `json:"offset"`
	} `json:"data"`
}

AuditLogListResponse is the response for listing audit logs

type AuditTrailDocument

type AuditTrailDocument struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

AuditTrailDocument represents document info in audit trail response

type AuditTrailEntry

type AuditTrailEntry struct {
	ID           string                 `json:"id"`
	DocumentID   string                 `json:"documentId"`
	ActionType   string                 `json:"actionType"`
	Timestamp    string                 `json:"timestamp"`
	PreviousHash string                 `json:"previousHash,omitempty"`
	CurrentHash  string                 `json:"currentHash,omitempty"`
	CreatedOn    string                 `json:"createdOn,omitempty"`
	Details      map[string]interface{} `json:"details,omitempty"`
	User         *AuditTrailUser        `json:"user,omitempty"`
	UserID       string                 `json:"userId,omitempty"`
	Recipient    *AuditTrailUser        `json:"recipient,omitempty"`
	RecipientID  string                 `json:"recipientId,omitempty"`
}

AuditTrailEntry represents a single audit trail entry

type AuditTrailResponse

type AuditTrailResponse struct {
	Document   AuditTrailDocument `json:"document"`
	AuditTrail []AuditTrailEntry  `json:"auditTrail"`
}

AuditTrailResponse is the response from GetAuditTrail Note: HTTP client auto-unwraps "data" wrapper, so this matches the inner structure

type AuditTrailUser

type AuditTrailUser struct {
	Name  string `json:"name"`
	Email string `json:"email"`
}

AuditTrailUser represents user info in audit trail

type AuthenticationError

type AuthenticationError struct {
	TurboDocxError
}

AuthenticationError is raised when authentication fails (HTTP 401)

type AuthorizationError added in v0.3.0

type AuthorizationError struct {
	TurboDocxError
}

AuthorizationError is raised when the caller is authenticated but lacks the permissions required by the route (HTTP 403).

type BillingFrequency added in v0.4.0

type BillingFrequency string

BillingFrequency represents a billing interval

const (
	BillingFrequencyMonthly   BillingFrequency = "monthly"
	BillingFrequencyQuarterly BillingFrequency = "quarterly"
	BillingFrequencyAnnual    BillingFrequency = "annual"
	BillingFrequencyOneTime   BillingFrequency = "one-time"
)

type BulkImportResult added in v0.6.0

type BulkImportResult struct {
	Imported int                  `json:"imported"`
	Failed   []BulkImportRowIssue `json:"failed"`
	Adjusted []BulkImportRowIssue `json:"adjusted"`
}

BulkImportResult is the outcome of a bulk create. Rows process sequentially with partial success: Failed rows did not import (no error is returned for them), Adjusted rows imported with a server-side adjustment.

type BulkImportRowIssue added in v0.6.0

type BulkImportRowIssue struct {
	Row    int    `json:"row"`
	Reason string `json:"reason"`
}

BulkImportRowIssue describes a per-row problem reported by a bulk create. Row is the 1-indexed position of the row in the request payload.

type Bundle added in v0.4.0

type Bundle struct {
	ID                    string          `json:"id"`
	OrgID                 string          `json:"orgId"`
	Name                  string          `json:"name"`
	Description           *string         `json:"description"`
	Sku                   *string         `json:"sku"`
	CategoryID            *string         `json:"categoryId"`
	BundleDiscountPercent float64         `json:"bundleDiscountPercent"`
	TotalListPrice        float64         `json:"totalListPrice"`
	TotalFinalPrice       float64         `json:"totalFinalPrice"`
	TotalCost             float64         `json:"totalCost"`
	CurrencyCode          Currency        `json:"currency"`
	ShowItemsToEndUser    bool            `json:"showItemsToEndUser"`
	ShowInCatalog         bool            `json:"showInCatalog"`
	SyncWithProducts      bool            `json:"syncWithProducts"`
	IsActive              bool            `json:"isActive"`
	CreatedBy             *string         `json:"createdBy"`
	CreatedOn             string          `json:"createdOn"`
	UpdatedOn             string          `json:"updatedOn"`
	Items                 []BundleItem    `json:"items,omitempty"`
	Category              *BundleCategory `json:"category,omitempty"`
}

Bundle represents a bundle entity

type BundleCategory added in v0.4.0

type BundleCategory struct {
	ID           string `json:"id"`
	Name         string `json:"name"`
	CategoryType string `json:"categoryType"`
}

BundleCategory represents an inline category reference for bundles

type BundleItem added in v0.4.0

type BundleItem struct {
	ID               string   `json:"id"`
	OrgID            string   `json:"orgId"`
	BundleID         string   `json:"bundleId"`
	ProductID        string   `json:"productId"`
	Quantity         int      `json:"quantity"`
	UnitPrice        float64  `json:"unitPrice"`
	DiscountPercent  float64  `json:"discountPercent"`
	FinalPrice       float64  `json:"finalPrice"`
	Cost             *float64 `json:"cost"`
	BillingFrequency string   `json:"billingFrequency"`
	ItemStatus       string   `json:"itemStatus"`
	IsActive         bool     `json:"isActive"`
	CreatedBy        *string  `json:"createdBy"`
	CreatedOn        string   `json:"createdOn"`
	UpdatedOn        string   `json:"updatedOn"`
	Product          *Product `json:"product,omitempty"`
}

BundleItem represents a product within a bundle

type BundleItemInput added in v0.4.0

type BundleItemInput struct {
	ProductID        string        `json:"productId"`
	UnitPrice        float64       `json:"unitPrice"`
	BillingFrequency string        `json:"billingFrequency"`
	Quantity         *int          `json:"quantity,omitempty"`
	DiscountPercent  *float64      `json:"discountPercent,omitempty"`
	DiscountType     *DiscountType `json:"discountType,omitempty"`
	DiscountAmount   *float64      `json:"discountAmount,omitempty"`
	FinalPrice       *float64      `json:"finalPrice,omitempty"`
	Cost             *float64      `json:"cost,omitempty"`
}

BundleItemInput represents a bundle item entry for create/update

type BundleItemStatus added in v0.4.0

type BundleItemStatus string

BundleItemStatus represents the status of a bundle item

const (
	BundleItemStatusActive             BundleItemStatus = "active"
	BundleItemStatusProductDeleted     BundleItemStatus = "product_deleted"
	BundleItemStatusProductUnavailable BundleItemStatus = "product_unavailable"
	BundleItemStatusCurrencyMismatch   BundleItemStatus = "currency_mismatch"
)

type BundleListResponse added in v0.4.0

type BundleListResponse struct {
	Results         []Bundle `json:"results"`
	TotalRecords    int      `json:"totalRecords"`
	TotalBundles    int      `json:"totalBundles"`
	ActiveBundles   int      `json:"activeBundles"`
	TotalCategories int      `json:"totalCategories"`
	CatalogValue    float64  `json:"catalogValue"`
}

BundleListResponse is the response from listing bundles

type CategoryType added in v0.4.0

type CategoryType string

CategoryType represents a category classification

const (
	CategoryTypeProductCategory CategoryType = "product_category"
	CategoryTypePricebookType   CategoryType = "pricebook_type"
	CategoryTypeCompanyIndustry CategoryType = "company_industry"
	CategoryTypeBundleCategory  CategoryType = "bundle_category"
)

type Client

type Client struct {
	// TurboSign provides digital signature operations
	TurboSign *TurboSignClient

	// Deliverable provides document generation and management operations
	Deliverable *DeliverableClient
	// contains filtered or unexported fields
}

Client is the main TurboDocx API client

func NewClient

func NewClient(apiKey, orgID string) (*Client, error)

NewClient creates a new TurboDocx client with the given API key and org ID

func NewClientWithConfig

func NewClientWithConfig(config ClientConfig) (*Client, error)

NewClientWithConfig creates a new TurboDocx client with custom configuration

type ClientConfig

type ClientConfig struct {
	// APIKey is your TurboDocx API key (required)
	APIKey string

	// OrgID is your Organization ID (required)
	OrgID string

	// AccessToken is an OAuth2 access token (alternative to APIKey)
	AccessToken string

	// BaseURL is the API base URL (optional, default: https://api.turbodocx.com)
	BaseURL string

	// SenderEmail is the reply-to email address for signature requests (required).
	// Used as the reply-to address on signature request emails and recorded as the sender
	// in the audit trail. An API key has no mailbox of its own, so the API rejects a send
	// without it rather than mailing from an unmonitored address.
	SenderEmail string

	// SenderName is the sender name for signature requests (optional). Appears in signature
	// request emails and the audit trail. Defaults to the name of your API key.
	SenderName string

	// ClientContext describes the calling environment for the signature audit
	// trail. The SDK auto-detects a descriptive User-Agent, timezone, language,
	// and device fingerprint from the host; set its fields to override them or
	// to report a client IP (IPAddress) for geolocation. See ClientContext.
	ClientContext ClientContext
}

ClientConfig holds configuration options for the client

type ClientContext added in v0.6.0

type ClientContext struct {
	// UserAgent overrides the auto-generated descriptive User-Agent.
	UserAgent string

	// IPAddress is the client IP to report as X-Forwarded-For to drive
	// geolocation. Opt-in: omitted by default so a container's private IP never
	// overrides the production load balancer's real public IP (X-Forwarded-For
	// is leftmost-wins).
	IPAddress string

	// Timezone overrides the auto-detected timezone (sent as X-Timezone).
	Timezone string

	// Language overrides the auto-detected BCP-47 language tag (Accept-Language).
	Language string

	// DeviceFingerprint overrides the auto-generated device fingerprint.
	DeviceFingerprint string
}

ClientContext describes the calling environment for the signature audit trail. The SDK auto-detects a descriptive User-Agent, timezone, language, and device fingerprint from the host; set these fields to override them or to report a client IP (IPAddress) so the audit trail can geolocate the caller.

The TurboDocx backend derives the audit trail's device + location from the request's User-Agent, X-Timezone, Accept-Language, X-Forwarded-For and X-Device-Fingerprint headers, and only classifies a request as an SDK call when the User-Agent starts with the canonical "@turbodocx/sdk/<version>" token (which the auto-generated User-Agent always uses).

type Company added in v0.4.0

type Company struct {
	ID               string     `json:"id"`
	OrgID            string     `json:"orgId"`
	Name             string     `json:"name"`
	Phone            *string    `json:"phone"`
	City             *string    `json:"city"`
	State            *string    `json:"state"`
	Country          *string    `json:"country"`
	IndustryID       *string    `json:"industryId"`
	LastActivityDate *string    `json:"lastActivityDate"`
	IsActive         bool       `json:"isActive"`
	CreatedBy        *string    `json:"createdBy"`
	CreatedOn        string     `json:"createdOn"`
	UpdatedOn        string     `json:"updatedOn"`
	ContactCount     *int       `json:"contactCount,omitempty"`
	Industry         *QuoteType `json:"industry,omitempty"`
}

Company represents a company entity

type CompanyListResponse added in v0.4.0

type CompanyListResponse struct {
	Results      []Company `json:"results"`
	TotalRecords int       `json:"totalRecords"`
}

CompanyListResponse is the response from listing companies

type ConditionalAction added in v0.8.0

type ConditionalAction string

ConditionalAction is what happens to a dependent field until its condition is met.

const (
	// ConditionalActionShow keeps the field hidden until the condition is met.
	ConditionalActionShow ConditionalAction = "show"
	// ConditionalActionUnlock keeps the field visible but read-only until the condition is met.
	ConditionalActionUnlock ConditionalAction = "unlock"
)

type ConditionalOperator added in v0.8.0

type ConditionalOperator string

ConditionalOperator is how a dependent field's controlling checkbox is tested.

const (
	// ConditionalOperatorIsChecked fires while the controlling checkbox is checked.
	ConditionalOperatorIsChecked ConditionalOperator = "is_checked"
	// ConditionalOperatorIsNotChecked fires while the controlling checkbox is unchecked.
	ConditionalOperatorIsNotChecked ConditionalOperator = "is_not_checked"
)

type ConflictError added in v0.3.0

type ConflictError struct {
	TurboDocxError
}

ConflictError is raised when a request conflicts with the current state of the target resource (HTTP 409). The most common case for the webhook routes is attempting to create or rename a webhook to a name that already exists for the org.

type Contact added in v0.4.0

type Contact struct {
	ID        string   `json:"id"`
	OrgID     string   `json:"orgId"`
	CompanyID string   `json:"companyId"`
	Name      string   `json:"name"`
	Email     *string  `json:"email"`
	Phone     *string  `json:"phone"`
	Title     *string  `json:"title"`
	IsActive  bool     `json:"isActive"`
	CreatedBy *string  `json:"createdBy"`
	CreatedOn string   `json:"createdOn"`
	UpdatedOn string   `json:"updatedOn"`
	Company   *Company `json:"company,omitempty"`
}

Contact represents a contact entity

type ContactListResponse added in v0.4.0

type ContactListResponse struct {
	Results      []Contact `json:"results"`
	TotalRecords int       `json:"totalRecords"`
}

ContactListResponse is the response from listing contacts

type CreateAndSendRequest added in v0.4.0

type CreateAndSendRequest struct {
	// Quote fields
	Name          string   `json:"name"`
	CompanyID     string   `json:"companyId"`
	ContactID     string   `json:"contactId"`
	CurrencyCode  *string  `json:"currency,omitempty"`
	TermDays      *int     `json:"termDays,omitempty"`      // default 60; -1 = auto-renewal
	RenewalPeriod *string  `json:"renewalPeriod,omitempty"` // weekly|monthly|quarterly|annually; only with TermDays -1
	ValidUntil    *string  `json:"validUntil,omitempty"`
	TaxRate       *float64 `json:"taxRate,omitempty"`
	PriceBookID   *string  `json:"priceBookId,omitempty"`

	// Line items
	Items       []AddLineItemRequest       `json:"-"`
	BundleItems []AddBundleLineItemRequest `json:"-"`

	// Send options
	Send *SendQuoteRequest `json:"-"`
}

CreateAndSendRequest is the convenience request to create, add items, and send a quote.

TermDays defaults to 60 when omitted; RenewalPeriod is required only when TermDays is -1.

type CreateAndSendResponse added in v0.4.0

type CreateAndSendResponse struct {
	Quote Quote `json:"quote"`
}

CreateAndSendResponse is the response from the createAndSend convenience method

type CreateBundleRequest added in v0.4.0

type CreateBundleRequest struct {
	Name                  string            `json:"name"`
	CategoryID            string            `json:"categoryId"`
	Items                 []BundleItemInput `json:"items,omitempty"`
	Description           *string           `json:"description,omitempty"`
	Sku                   *string           `json:"sku,omitempty"`
	BundleDiscountPercent *float64          `json:"bundleDiscountPercent,omitempty"`
	BundleDiscountType    *DiscountType     `json:"bundleDiscountType,omitempty"`
	BundleDiscountAmount  *float64          `json:"bundleDiscountAmount,omitempty"`
	CurrencyCode          *string           `json:"currency,omitempty"`
	ShowItemsToEndUser    *bool             `json:"showItemsToEndUser,omitempty"`
	ShowInCatalog         *bool             `json:"showInCatalog,omitempty"`
	SyncWithProducts      *bool             `json:"syncWithProducts,omitempty"`
}

CreateBundleRequest is the request to create a bundle

type CreateCompanyContactInput added in v0.4.0

type CreateCompanyContactInput struct {
	Name  string  `json:"name"`
	Email string  `json:"email"`
	Phone *string `json:"phone,omitempty"`
	Title *string `json:"title,omitempty"`
}

CreateCompanyContactInput represents an inline contact for company creation

type CreateCompanyRequest added in v0.4.0

type CreateCompanyRequest struct {
	Name       string                      `json:"name"`
	Contacts   []CreateCompanyContactInput `json:"contacts"`
	Phone      *string                     `json:"phone,omitempty"`
	City       *string                     `json:"city,omitempty"`
	State      *string                     `json:"state,omitempty"`
	Country    *string                     `json:"country,omitempty"`
	IndustryID *string                     `json:"industryId,omitempty"`
}

CreateCompanyRequest is the request to create a company

type CreateContactRequest added in v0.4.0

type CreateContactRequest struct {
	Name      string  `json:"name"`
	CompanyID string  `json:"companyId"`
	Email     *string `json:"email,omitempty"`
	Phone     *string `json:"phone,omitempty"`
	Title     *string `json:"title,omitempty"`
}

CreateContactRequest is the request to create a contact

type CreateDeliverableRequest added in v0.3.0

type CreateDeliverableRequest struct {
	// Deliverable name (3-255 characters)
	Name string `json:"name"`
	// Template ID to generate from
	TemplateID string `json:"templateId"`
	// Array of variable objects for substitution
	Variables []DeliverableVariable `json:"variables"`
	// Description (up to 65,535 characters)
	Description string `json:"description,omitempty"`
	// Array of tag strings to associate
	Tags []string `json:"tags,omitempty"`
}

CreateDeliverableRequest is the request for GenerateDeliverable

type CreateDeliverableResponse added in v0.3.0

type CreateDeliverableResponse struct {
	Results struct {
		Deliverable DeliverableRecord `json:"deliverable"`
	} `json:"results"`
}

CreateDeliverableResponse is the response from GenerateDeliverable

type CreateEmbeddedSignatureRequest added in v0.8.0

type CreateEmbeddedSignatureRequest struct {
	// File content (use this OR FileLink/DeliverableID/TemplateID).
	File []byte
	// FileName sets the stored file name for an uploaded File (max 255 chars; no extension
	// needed). Sent as a "fileName" form field; the uploaded part itself is always named
	// document.<ext>, because the API checks that extension. Empty: document.<ext> is stored.
	FileName string

	// Alternative file sources.
	FileLink      string
	DeliverableID string
	TemplateID    string

	DocumentName        string
	DocumentDescription string
	SenderName          string
	SenderEmail         string
	CCEmails            []string

	Recipients []EmbeddedSignatureRecipient
	// Fields optionally overrides the per-recipient Fields shorthand with full field control. An empty
	// slice counts as not set, so the shorthand still applies.
	Fields []Field
	// SendEmail defaults to false for this flow: your app shows the signing page, so the
	// signing-link emails (and the initial CC notice) are suppressed. Passcode and completed-copy
	// emails are still sent. Set a pointer to override.
	SendEmail *bool
	// ReturnURL is an optional completion fallback (https). Passed to each embed URL when set.
	ReturnURL string
}

CreateEmbeddedSignatureRequest creates a signature request and mints a per-recipient embed URL in one call.

type CreateEmbeddedSignatureResponse added in v0.8.0

type CreateEmbeddedSignatureResponse struct {
	DocumentID string
	Recipients []EmbeddedSignatureRecipientResult
}

CreateEmbeddedSignatureResponse is the document plus a per-recipient embed URL.

type CreateOrgAPIKeyRequest added in v0.4.0

type CreateOrgAPIKeyRequest struct {
	Name string `json:"name"`
	Role string `json:"role"` // admin | contributor | user | viewer
}

CreateOrgAPIKeyRequest is the request to create an organization API key

type CreateOrgApiKeyRequest deprecated added in v0.2.0

type CreateOrgApiKeyRequest = CreateOrgAPIKeyRequest

Deprecated: use CreateOrgAPIKeyRequest.

type CreateOrganizationRequest added in v0.2.0

type CreateOrganizationRequest struct {
	Name     string                 `json:"name"`
	Metadata map[string]interface{} `json:"metadata,omitempty"`
	Features *Features              `json:"features,omitempty"`
}

CreateOrganizationRequest is the request to create an organization

type CreatePartnerAPIKeyRequest added in v0.4.0

type CreatePartnerAPIKeyRequest struct {
	Name        string   `json:"name"`
	Scopes      []string `json:"scopes"`
	Description string   `json:"description,omitempty"`
}

CreatePartnerAPIKeyRequest is the request to create a partner API key

type CreatePartnerApiKeyRequest deprecated added in v0.2.0

type CreatePartnerApiKeyRequest = CreatePartnerAPIKeyRequest

Deprecated: use CreatePartnerAPIKeyRequest.

type CreatePriceBookRequest added in v0.4.0

type CreatePriceBookRequest struct {
	Name               string                         `json:"name"`
	PriceBookTypeID    string                         `json:"priceBookTypeId"`
	ValidFrom          string                         `json:"validFrom"`
	DiscountPercent    *float64                       `json:"discountPercent,omitempty"`
	Description        *string                        `json:"description,omitempty"`
	ValidTo            *string                        `json:"validTo,omitempty"`
	IsDefault          *bool                          `json:"isDefault,omitempty"`
	ShowInQuoteBuilder *bool                          `json:"showInQuoteBuilder,omitempty"`
	ProductPricing     []PriceBookProductPricingInput `json:"productPricing,omitempty"`
}

CreatePriceBookRequest is the request to create a price book

type CreateProductRequest added in v0.4.0

type CreateProductRequest struct {
	Name                  string   `json:"name"`
	ListPrice             float64  `json:"listPrice"`
	BillingFrequency      string   `json:"billingFrequency"`
	CategoryID            string   `json:"categoryId"`
	Sku                   *string  `json:"sku,omitempty"`
	Description           *string  `json:"description,omitempty"`
	DetailedSpecification *string  `json:"detailedSpecification,omitempty"`
	InternalNotes         *string  `json:"internalNotes,omitempty"`
	Cost                  *float64 `json:"cost,omitempty"`
	MinimumOrderQuantity  *int     `json:"minimumOrderQuantity,omitempty"`
	CurrencyCode          *string  `json:"currency,omitempty"`
	ShowInCatalog         *bool    `json:"showInCatalog,omitempty"`

	// Images for multipart upload (file paths or byte slices)
	Images []ProductImageInput `json:"-"`
}

CreateProductRequest is the request to create a product

type CreateQuoteRequest added in v0.4.0

type CreateQuoteRequest struct {
	Name          string   `json:"name"`
	CompanyID     string   `json:"companyId"`
	ContactID     string   `json:"contactId"`
	CurrencyCode  *string  `json:"currency,omitempty"`
	TermDays      *int     `json:"termDays,omitempty"`      // default 60; -1 = auto-renewal
	RenewalPeriod *string  `json:"renewalPeriod,omitempty"` // weekly|monthly|quarterly|annually; only with TermDays -1
	ValidUntil    *string  `json:"validUntil,omitempty"`
	TaxRate       *float64 `json:"taxRate,omitempty"`
	PriceBookID   *string  `json:"priceBookId,omitempty"`
}

CreateQuoteRequest is the request to create a new quote.

TermDays defaults to 60 when omitted (max 3650). The special value -1 means auto-renewal: RenewalPeriod is required when TermDays is -1, and must be omitted for any other term — sending it alongside a fixed term is a 400.

type CreateQuoteTemplateRequest added in v0.4.0

type CreateQuoteTemplateRequest struct {
	LogoURL            *string `json:"logoUrl,omitempty"`
	PrimaryColor       *string `json:"primaryColor,omitempty"`
	PrimaryTextColor   *string `json:"primaryTextColor,omitempty"`
	Disclaimer         *string `json:"disclaimer,omitempty"`
	TermsAndConditions *string `json:"termsAndConditions,omitempty"`
	ClosingMessage     *string `json:"closingMessage,omitempty"`
	SenderName         *string `json:"senderName,omitempty"`
	SenderPhone        *string `json:"senderPhone,omitempty"`
	SenderEmail        *string `json:"senderEmail,omitempty"`
	ContactEmail       *string `json:"contactEmail,omitempty"`
}

CreateQuoteTemplateRequest is the request to create a quote template

type CreateQuoteTypeRequest added in v0.4.0

type CreateQuoteTypeRequest struct {
	Name         string       `json:"name"`
	CategoryType CategoryType `json:"categoryType"`
}

CreateQuoteTypeRequest is the request to create a type/category

type CreateSignatureReviewLinkRequest

type CreateSignatureReviewLinkRequest struct {
	// File content (use this OR FileLink/DeliverableID/TemplateID)
	File []byte
	// FileName sets the stored file name for an uploaded File (max 255 chars; no extension
	// needed). Sent as a "fileName" form field; the uploaded part itself is always named
	// document.<ext>, because the API checks that extension. Empty: document.<ext> is stored.
	FileName string

	// Alternative file sources
	FileLink      string
	DeliverableID string
	TemplateID    string

	// Required
	Recipients []Recipient

	// Fields configures the signature fields. Optional when sending a template set up in
	// TurboDocx with signer roles: give each recipient a Role and the fields saved for that role
	// are used (any fields passed here are added to them).
	Fields []Field

	// Optional
	DocumentName        string
	DocumentDescription string
	SenderName          string
	SenderEmail         string
	CCEmails            []string

	// Per-document reminder + expiration overrides; omitted fields inherit the org defaults.
	SignatureSchedule
}

type CreateSignatureReviewLinkResponse

type CreateSignatureReviewLinkResponse struct {
	Success    bool              `json:"success"`
	DocumentID string            `json:"documentId"`
	Status     string            `json:"status"`
	PreviewURL string            `json:"previewUrl,omitempty"`
	Message    string            `json:"message"`
	Recipients []ReviewRecipient `json:"recipients"` // the API always sends it on a successful response
}

CreateSignatureReviewLinkResponse is the response from CreateSignatureReviewLink

type CreateSigningURLRequest added in v0.8.0

type CreateSigningURLRequest struct {
	// RecipientID selects the recipient by TurboDocx recipient id...
	RecipientID string `json:"recipientId,omitempty"`
	// ExternalID ...or by the externalId you set when creating the recipient. Provide exactly one.
	ExternalID string `json:"externalId,omitempty"`
	// IdentityAssertion is required only when the recipient's mode is external_idv.
	IdentityAssertion *IdentityAssertion `json:"identityAssertion,omitempty"`
	// ReturnURL is where TurboSign returns the signer after completion (https only).
	ReturnURL string `json:"returnUrl,omitempty"`
}

CreateSigningURLRequest requests an embedded signing URL for one recipient. Provide exactly one of RecipientID or ExternalID.

type CreateSigningURLResponse added in v0.8.0

type CreateSigningURLResponse struct {
	// URL is the URL to open (new tab / redirect) or embed for the signer.
	URL string `json:"url"`
	// ExpiresAt is when the URL stops working (ISO 8601). Single-use links (external_idv /
	// override) expire 5 minutes after issue. For otp/no-verification recipients the URL is the
	// reusable signing link, so this is the document's own expiry, or nil when it doesn't expire.
	ExpiresAt   *string `json:"expiresAt"`
	RecipientID string  `json:"recipientId"`
	ExternalID  string  `json:"externalId,omitempty"`
	// IdentityVerificationMode is "otp", "external_idv", "override", or "" when the recipient has
	// no verification.
	IdentityVerificationMode string `json:"identityVerificationMode,omitempty"`
	// PendingChecks are the passcode steps the signer must clear on the page (e.g. "email_otp",
	// "sms_otp"). Non-empty only for otp recipients.
	PendingChecks []string `json:"pendingChecks"`
}

CreateSigningURLResponse is the embedded signing URL and its metadata: the reusable signing link for otp / no-verification recipients, or a single-use link for external_idv / override recipients.

type CreateWebhookRequest added in v0.3.0

type CreateWebhookRequest struct {
	URLs   []string `json:"urls"`   // HTTPS only (HTTP is a 400); min 1, max 10
	Events []string `json:"events"` // min 1; see WebhookEventStrings + AllWebhookEvents
}

CreateWebhookRequest is the payload for CreateWebhook. The `name` field is hardcoded by the SDK and is not part of this struct.

Events stays []string so raw strings keep working, but prefer the typed WebhookEvent constants via WebhookEventStrings — see webhook_events.go for all 7 events and what each fires on.

type CreateWebhookResponse added in v0.3.0

type CreateWebhookResponse struct {
	ID     string `json:"id"`
	Secret string `json:"secret"`
}

CreateWebhookResponse is the data unwrapped from the create envelope.

type Currency added in v0.4.0

type Currency string

Currency represents a supported currency

const (
	CurrencyUSD Currency = "USD"
	CurrencyEUR Currency = "EUR"
	CurrencyGBP Currency = "GBP"
	CurrencyCAD Currency = "CAD"
	CurrencyAUD Currency = "AUD"
	CurrencyINR Currency = "INR"
)

type CurrencyTotalEntry added in v0.4.0

type CurrencyTotalEntry struct {
	CurrencyCode string  `json:"currency"`
	Total        float64 `json:"total"`
}

CurrencyTotalEntry represents a currency-specific total

type DeclineQuoteRequest added in v0.4.0

type DeclineQuoteRequest struct {
	Reason string `json:"reason,omitempty"` // optional on a draft quote; still required once the quote is sent
}

DeclineQuoteRequest is the request to decline a quote

type DeleteDeliverableResponse added in v0.3.0

type DeleteDeliverableResponse struct {
	Message       string `json:"message"`
	DeliverableID string `json:"deliverableId"`
}

DeleteDeliverableResponse is the response from DeleteDeliverable

type DeliverableClient added in v0.3.0

type DeliverableClient struct {
	// contains filtered or unexported fields
}

DeliverableClient provides document generation and management operations

func NewDeliverableClient added in v0.3.0

func NewDeliverableClient(http *HTTPClient) *DeliverableClient

NewDeliverableClient creates a new Deliverable client

func NewDeliverableClientOnly added in v0.3.0

func NewDeliverableClientOnly(config ClientConfig) (*DeliverableClient, error)

NewDeliverableClientOnly creates a client configured only for Deliverable operations. Unlike NewClientWithConfig, this does NOT require SenderEmail (which is only needed for TurboSign).

func (*DeliverableClient) DeleteDeliverable added in v0.3.0

func (c *DeliverableClient) DeleteDeliverable(ctx context.Context, id string) (*DeleteDeliverableResponse, error)

DeleteDeliverable soft-deletes a deliverable

func (*DeliverableClient) DownloadPDF added in v0.3.0

func (c *DeliverableClient) DownloadPDF(ctx context.Context, deliverableID string) ([]byte, error)

DownloadPDF downloads the PDF version of a deliverable

func (*DeliverableClient) DownloadSourceFile added in v0.3.0

func (c *DeliverableClient) DownloadSourceFile(ctx context.Context, deliverableID string) ([]byte, error)

DownloadSourceFile downloads the original source file (DOCX or PPTX) of a deliverable

func (*DeliverableClient) GenerateDeliverable added in v0.3.0

GenerateDeliverable generates a new deliverable document from a template with variable substitution

func (*DeliverableClient) GetDeliverableDetails added in v0.3.0

func (c *DeliverableClient) GetDeliverableDetails(ctx context.Context, id string, opts *GetDeliverableOptions) (*DeliverableRecord, error)

GetDeliverableDetails gets full details of a single deliverable

func (*DeliverableClient) ListDeliverables added in v0.3.0

ListDeliverables lists deliverables with pagination, search, and filtering

func (*DeliverableClient) UpdateDeliverableInfo added in v0.3.0

UpdateDeliverableInfo updates a deliverable's name, description, or tags

type DeliverableListResponse added in v0.3.0

type DeliverableListResponse struct {
	Results      []DeliverableRecord `json:"results"`
	TotalRecords int                 `json:"totalRecords"`
}

DeliverableListResponse is the response from ListDeliverables

type DeliverableRecord added in v0.3.0

type DeliverableRecord struct {
	ID                 string                `json:"id"`
	Name               string                `json:"name"`
	Description        string                `json:"description"`
	TemplateID         string                `json:"templateId"`
	TemplateName       string                `json:"templateName"`
	TemplateNotDeleted *FlexBool             `json:"templateNotDeleted"`
	CreatedBy          string                `json:"createdBy"`
	Email              string                `json:"email"`
	FileSize           int64                 `json:"fileSize"`
	FileType           string                `json:"fileType"`
	DefaultFont        string                `json:"defaultFont"`
	Fonts              []Font                `json:"fonts"`
	IsActive           FlexBool              `json:"isActive"`
	CreatedOn          string                `json:"createdOn"`
	UpdatedOn          string                `json:"updatedOn"`
	Variables          []DeliverableVariable `json:"variables"`
	Tags               []Tag                 `json:"tags"`
}

DeliverableRecord represents a deliverable document

type DeliverableVariable added in v0.3.0

type DeliverableVariable struct {
	// Template placeholder (e.g., "{CompanyName}")
	Placeholder string `json:"placeholder"`
	// Value to inject
	Text string `json:"text,omitempty"`
	// Content type: text, html, image, or markdown
	MimeType string `json:"mimeType"`
	// Skip this variable during generation
	IsDisabled FlexBool `json:"isDisabled,omitempty"`
	// Nested sub-variables for HTML content
	Subvariables []DeliverableVariable `json:"subvariables,omitempty"`
	// Multiple instances for repeating content
	VariableStack interface{} `json:"variableStack,omitempty"`
	// AI prompt for content generation (max 16,000 chars)
	AIPrompt string `json:"aiPrompt,omitempty"`
	// Whether to allow rich text injection
	AllowRichTextInjection FlexBool `json:"allowRichTextInjection,omitempty"`
}

DeliverableVariable represents a variable for template substitution

type DiscountType added in v0.4.0

type DiscountType string

DiscountType represents the type of discount applied to a line item or bundle

const (
	DiscountTypePercent DiscountType = "percent"
	DiscountTypeAmount  DiscountType = "amount"
)

type DocumentRecipientsResponse added in v0.6.2

type DocumentRecipientsResponse struct {
	Document   RecipientsDocument         `json:"document"`
	Recipients []RecipientSignatureStatus `json:"recipients"`
	Summary    RecipientStatusSummary     `json:"summary"`
}

DocumentRecipientsResponse is the response from GetRecipients

type DocumentSender added in v0.6.2

type DocumentSender struct {
	Name  string `json:"name"`
	Email string `json:"email"`
}

DocumentSender is the identity that sent a document for signature. Never the synthetic API service account.

type DocumentStatusResponse

type DocumentStatusResponse struct {
	Status string `json:"status"`
	// ExpiresAt is when the signing window closes, if the document has a deadline. Empty when
	// expiration is off (the default), which means the document never expires.
	ExpiresAt string `json:"expiresAt,omitempty"`
}

DocumentStatusResponse is the response from GetStatus

type DownloadResponse

type DownloadResponse struct {
	DownloadURL string `json:"downloadUrl"`
	FileName    string `json:"fileName"`
}

DownloadResponse is the API response for download request

type Duration added in v0.7.0

type Duration struct {
	// Value is a whole number of units. Minimum 1, except ExpirationWarning where 0 means
	// "never warn".
	Value int `json:"value"`
	// Unit is "hours" or "days".
	Unit string `json:"unit"`
}

CreateSignatureReviewLinkRequest is the request for CreateSignatureReviewLink Duration is a configured length of time.

The unit is carried alongside the value rather than normalised away, so "48 hours" stays "48 hours" instead of reading back as "2 days".

type EmbeddedRecipientAuth added in v0.8.0

type EmbeddedRecipientAuth struct {
	// EmailOTP requires an email OTP before signing. Maps to
	// IdentityVerification{Mode:"otp", Channel:"email"}.
	EmailOTP bool
	// SMS requires an SMS OTP to the given number. Maps to
	// IdentityVerification{Mode:"otp", Channel:"sms"} and sets the recipient's Phone.
	SMS *EmbeddedRecipientSMS
}

EmbeddedRecipientAuth is the ergonomic per-recipient identity shorthand for embedded signing. It expands to the recipient's IdentityVerification. Leave both zero to take the org's default channel (no verification when that default is "none"). EmailOTP wins if both are set. Email and SMS passcodes only: for external_idv or override, use SendSignature + CreateSigningURL instead.

type EmbeddedRecipientFields added in v0.8.0

type EmbeddedRecipientFields struct {
	Signature string // anchor text, e.g. "{signature1}"
	Date      string
	Initials  string
	FullName  string
}

EmbeddedRecipientFields is shorthand field placement by text anchor; it expands to full Field objects (Placement "replace" + a default size). Each value is the anchor text to replace; leave a field empty to skip it.

type EmbeddedRecipientSMS added in v0.8.0

type EmbeddedRecipientSMS struct {
	PhoneNumber string
}

EmbeddedRecipientSMS carries the phone number for SMS OTP shorthand.

type EmbeddedSignatureRecipient added in v0.8.0

type EmbeddedSignatureRecipient struct {
	Name  string
	Email string
	// Role is the template signer role this recipient fills, when sending a TemplateID set up with
	// signer roles. Its saved fields are used, so Fields can be omitted. A role left out
	// falls back to the template's saved signer, who also gets an embed URL in the result.
	Role  string
	Phone string
	// SigningOrder defaults to the recipient's index + 1 (sequential) when 0. 0 is never a valid
	// 1-indexed order, so a zero value unambiguously means "use the default".
	SigningOrder int
	Auth         *EmbeddedRecipientAuth
	Fields       *EmbeddedRecipientFields
}

EmbeddedSignatureRecipient is one signer in a CreateEmbeddedSignatureRequest.

type EmbeddedSignatureRecipientResult added in v0.8.0

type EmbeddedSignatureRecipientResult struct {
	RecipientID string
	Name        string
	Email       string
	// EmbedURL is the embeddable signing URL — present only when it is this recipient's turn
	// (Status "ready"). Empty for a recipient who cannot sign yet (Status "pending") or has
	// already signed (Status "completed"); mint it later with CreateSigningURL.
	EmbedURL string
	// Status is "ready" (their turn; EmbedURL set), "pending" (an earlier signer hasn't signed
	// yet) or "completed" (already signed).
	Status string
	// IdentityVerificationMode is "otp", "external_idv", "override", or "" when unverified. For a
	// "ready" signer it is the mode the backend resolved for the signing URL. For "pending" /
	// "completed" no URL was minted, so it is the mode you requested via Auth: "" when you set
	// none, even if the org's default channel applies. CreateSigningURL reports the effective
	// mode once you mint the URL. From CreateEmbeddedSignature it is only ever "otp" or "".
	IdentityVerificationMode string
}

EmbeddedSignatureRecipientResult is one resolved signer in a CreateEmbeddedSignatureResponse.

type EmbeddedSigningDefaultChannel added in v0.8.0

type EmbeddedSigningDefaultChannel = string

EmbeddedSigningDefaultChannel is the org-level default OTP channel for recipients that don't set one: "none", "email" or "sms".

type EmbeddedSigningSettings added in v0.8.0

type EmbeddedSigningSettings struct {
	// Enabled reports that embedded signing (and OTP identity verification) is on for the org.
	Enabled bool `json:"enabled"`
	// AllowExternalIDV reports that you may assert a signer's identity with your own provider.
	AllowExternalIDV bool `json:"allowExternalIdv"`
	// AllowIdentityOverride reports that a sender may issue a link that skips identity
	// verification (development/testing).
	AllowIdentityOverride bool `json:"allowIdentityOverride"`
	// DefaultChannel is the org's default OTP channel. While embedded signing is enabled it applies
	// to every recipient that doesn't set one, SDK/API sends included. "none" means verify only when
	// a request asks for it. See AllowChannelOverride for whether you may pick a different one.
	DefaultChannel EmbeddedSigningDefaultChannel `json:"defaultChannel,omitempty"`
	// AllowChannelOverride reports whether a request may give a recipient a channel other than
	// DefaultChannel. false means the org locked the method: an explicit different channel is
	// rejected with OtpOverrideNotAllowed, so omit it to take the default. Always true for a "none"
	// default or when embedded signing is off. Nil when the API did not report it.
	AllowChannelOverride *bool `json:"allowChannelOverride,omitempty"`
	// AllowedFrameAncestors are the origins allowed to embed the signing page in an iframe.
	// Empty means framing is denied everywhere.
	AllowedFrameAncestors []string `json:"allowedFrameAncestors"`
}

EmbeddedSigningSettings is the org's embedded-signing configuration, read via GetEmbeddedSigningSettings.

These are the set-once, org-wide gates plus the default channel. The per-recipient identity mode is chosen when you create each recipient (see IdentityVerification), not here.

type EntitlementsResponse added in v0.2.0

type EntitlementsResponse struct {
	Success bool `json:"success"`
	Data    struct {
		Features *Features `json:"features,omitempty"`
		Tracking *Tracking `json:"tracking,omitempty"`
	} `json:"data"`
}

EntitlementsResponse is the response for entitlement updates

type Features added in v0.2.0

type Features struct {
	OrgID                    string `json:"orgId,omitempty"`
	MaxUsers                 *int   `json:"maxUsers,omitempty"`
	MaxProjectspaces         *int   `json:"maxProjectspaces,omitempty"`
	MaxTemplates             *int   `json:"maxTemplates,omitempty"`
	MaxStorage               *int64 `json:"maxStorage,omitempty"`
	MaxGeneratedDeliverables *int   `json:"maxGeneratedDeliverables,omitempty"`
	MaxSignatures            *int   `json:"maxSignatures,omitempty"`
	MaxAICredits             *int   `json:"maxAICredits,omitempty"`
	RdWatermark              *bool  `json:"rdWatermark,omitempty"`
	HasFileDownload          *bool  `json:"hasFileDownload,omitempty"`
	HasAdvancedDateFormats   *bool  `json:"hasAdvancedDateFormats,omitempty"`
	HasGDrive                *bool  `json:"hasGDrive,omitempty"`
	HasSharepoint            *bool  `json:"hasSharepoint,omitempty"`
	HasSharepointOnly        *bool  `json:"hasSharepointOnly,omitempty"`
	HasTDAI                  *bool  `json:"hasTDAI,omitempty"`
	HasPptx                  *bool  `json:"hasPptx,omitempty"`
	HasTDWriter              *bool  `json:"hasTDWriter,omitempty"`
	HasSalesforce            *bool  `json:"hasSalesforce,omitempty"`
	HasWrike                 *bool  `json:"hasWrike,omitempty"`
	HasVariableStack         *bool  `json:"hasVariableStack,omitempty"`
	HasSubvariables          *bool  `json:"hasSubvariables,omitempty"`
	HasZapier                *bool  `json:"hasZapier,omitempty"`
	HasBYOM                  *bool  `json:"hasBYOM,omitempty"`
	HasBYOVS                 *bool  `json:"hasBYOVS,omitempty"`
	HasBetaFeatures          *bool  `json:"hasBetaFeatures,omitempty"`
	EnableBulkSending        *bool  `json:"enableBulkSending,omitempty"`
	CreatedBy                string `json:"createdBy,omitempty"`
}

Features represents settable entitlement limits for an organization

type Field

type Field struct {
	Type            string          `json:"type"`
	Page            int             `json:"page,omitempty"`
	X               int             `json:"x,omitempty"`
	Y               int             `json:"y,omitempty"`
	Width           int             `json:"width,omitempty"`
	Height          int             `json:"height,omitempty"`
	RecipientEmail  string          `json:"recipientEmail"`
	DefaultValue    string          `json:"defaultValue,omitempty"`
	IsMultiline     bool            `json:"isMultiline,omitempty"`
	IsReadonly      bool            `json:"isReadonly,omitempty"`
	Required        *bool           `json:"required,omitempty"` // nil (default) = required; BoolPtr(false) = optional for the signer (rejected on signature/initial fields)
	BackgroundColor string          `json:"backgroundColor,omitempty"`
	Template        *TemplateAnchor `json:"template,omitempty"`
	// Metadata carries optional conditional (IF/THEN) logic — a FieldKey on a controlling
	// checkbox, or a Conditional rule on a dependent field. Omitted when nil.
	Metadata *FieldMetadata `json:"metadata,omitempty"`
}

Field represents a signature field

type FieldConditional added in v0.8.0

type FieldConditional struct {
	// ControllingFieldKey must equal the controlling checkbox's Metadata.FieldKey.
	ControllingFieldKey string `json:"controllingFieldKey"`
	// Operator is whether the rule fires when the checkbox is checked or unchecked.
	Operator ConditionalOperator `json:"operator"`
	// Action is whether the dependent field is hidden ("show") or read-only ("unlock") until met.
	Action ConditionalAction `json:"action"`
}

FieldConditional is a conditional (IF/THEN) rule set on a DEPENDENT field.

The dependent field reacts to a CONTROLLING checkbox elsewhere in the same Fields slice. The controlling field must be Type "checkbox" and carry Metadata.FieldKey; this rule references it by that exact key.

type FieldMetadata added in v0.8.0

type FieldMetadata struct {
	// FieldKey is a stable client id (<=100 chars) for a controlling checkbox, referenced by dependents.
	FieldKey string `json:"fieldKey,omitempty"`
	// Conditional is the rule set on a dependent field.
	Conditional *FieldConditional `json:"conditional,omitempty"`
}

FieldMetadata is optional per-field metadata for conditional (IF/THEN) logic.

Set FieldKey on a CONTROLLING checkbox to give it a stable client id; set Conditional on a DEPENDENT field to make it react to that checkbox. Both sides are authored by the caller in the same payload.

type FileTypeInfo

type FileTypeInfo struct {
	MimeType  string
	Extension string
}

FileTypeInfo contains detected file type information

func DetectFileType

func DetectFileType(fileBytes []byte) FileTypeInfo

DetectFileType detects file type from magic bytes

type FlexBool added in v0.3.0

type FlexBool bool

FlexBool is a bool that can unmarshal from both JSON booleans (true/false) and numbers (1/0). MySQL returns tinyint(1) for boolean columns, which some APIs pass through as 0/1.

func (FlexBool) MarshalJSON added in v0.3.0

func (b FlexBool) MarshalJSON() ([]byte, error)

func (*FlexBool) UnmarshalJSON added in v0.3.0

func (b *FlexBool) UnmarshalJSON(data []byte) error

type Font added in v0.3.0

type Font struct {
	Name  string      `json:"name"`
	Usage interface{} `json:"usage"`
}

Font represents a font used in a deliverable

type GetDeliverableOptions added in v0.3.0

type GetDeliverableOptions struct {
	ShowTags bool
}

GetDeliverableOptions holds query parameters for getting a single deliverable

type GetDeliverableResponse added in v0.3.0

type GetDeliverableResponse struct {
	Results DeliverableRecord `json:"results"`
}

GetDeliverableResponse wraps the results for getDeliverableDetails

type HTTPClient

type HTTPClient struct {
	// contains filtered or unexported fields
}

HTTPClient handles HTTP requests to the TurboDocx API

func NewHTTPClient

func NewHTTPClient(config ClientConfig) *HTTPClient

NewHTTPClient creates a new HTTP client

func (*HTTPClient) Delete added in v0.2.0

func (c *HTTPClient) Delete(ctx context.Context, path string, result interface{}) error

Delete performs a DELETE request

func (*HTTPClient) Get

func (c *HTTPClient) Get(ctx context.Context, path string, result interface{}) error

Get performs a GET request

func (*HTTPClient) GetRaw

func (c *HTTPClient) GetRaw(ctx context.Context, path string) ([]byte, error)

GetRaw performs a GET request and returns raw bytes (for file downloads)

func (*HTTPClient) GetSenderConfig

func (c *HTTPClient) GetSenderConfig() (senderEmail, senderName string)

GetSenderConfig returns the sender email and name configuration

func (*HTTPClient) Patch added in v0.2.0

func (c *HTTPClient) Patch(ctx context.Context, path string, data interface{}, result interface{}) error

Patch performs a PATCH request with JSON body

func (*HTTPClient) PatchProductMultipart added in v0.4.0

func (c *HTTPClient) PatchProductMultipart(ctx context.Context, path string, dataJSON []byte, images []ProductImageFile, result interface{}) error

PatchProductMultipart performs a PATCH multipart request with a "data" JSON field and "images" file parts

func (*HTTPClient) Post

func (c *HTTPClient) Post(ctx context.Context, path string, data interface{}, result interface{}) error

Post performs a POST request with JSON body

func (*HTTPClient) PostProductMultipart added in v0.4.0

func (c *HTTPClient) PostProductMultipart(ctx context.Context, path string, dataJSON []byte, images []ProductImageFile, result interface{}) error

PostProductMultipart performs a POST multipart request with a "data" JSON field and "images" file parts

func (*HTTPClient) UploadFile

func (c *HTTPClient) UploadFile(ctx context.Context, path string, file interface{}, fileName string, additionalData map[string]string, result interface{}) error

UploadFile performs a multipart file upload file can be either a file path (string) or file content ([]byte)

func (*HTTPClient) UploadFileBytes

func (c *HTTPClient) UploadFileBytes(ctx context.Context, path string, fileBytes []byte, fileName string, additionalData map[string]string, result interface{}) error

UploadFileBytes is a convenience method for uploading file bytes

func (*HTTPClient) UploadFilePath

func (c *HTTPClient) UploadFilePath(ctx context.Context, path string, filePath string, additionalData map[string]string, result interface{}) error

UploadFilePath is a convenience method for uploading a file from disk

type HandleExpiredQuoteRequest added in v0.4.0

type HandleExpiredQuoteRequest struct {
	Action        string `json:"action"`        // "void" or "decline" — no other value is accepted
	Reason        string `json:"reason"`        // max 190 characters
	NewValidUntil string `json:"newValidUntil"` // ISO date carried onto the reissued duplicate
}

HandleExpiredQuoteRequest is the request to handle an expired sent quote. All three fields are required by the API.

type IdentityAssertion added in v0.8.0

type IdentityAssertion struct {
	// Provider must match the recipient's configured provider.
	Provider string `json:"provider"`
	// VerificationID is your provider's unique id for this verification (used to detect replay).
	VerificationID string `json:"verificationId"`
	// VerifiedAt is when your provider verified the signer (ISO 8601). Rejected if in the future
	// or too old.
	VerifiedAt string `json:"verifiedAt"`
	// SubjectEmail is the email your provider verified — must match the recipient's email.
	SubjectEmail string `json:"subjectEmail"`

	// Method is how your provider verified the signer: "id_document", "id_document_liveness",
	// "kba", "database", "sso" or "other" (describe "other" in MethodDetail).
	Method string `json:"method,omitempty"`
	// MethodDetail is a free-text description of the method. Required when Method is "other".
	MethodDetail string `json:"methodDetail,omitempty"`
	// AssuranceLevel is the level your provider attests to, e.g. "ial2_aal2" (NIST 800-63),
	// "eidas_substantial" or "eidas_high".
	AssuranceLevel string `json:"assuranceLevel,omitempty"`
	// VerifiedName is the signer's legal name as verified by your provider.
	VerifiedName string `json:"verifiedName,omitempty"`
	// EvidenceURL is an https link to your provider's verification record.
	EvidenceURL string `json:"evidenceUrl,omitempty"`
	// OverrideEmailMatching skips the check that SubjectEmail equals the recipient's email. Set it
	// only when you have confirmed the verified identity is this signer although the emails differ;
	// the override is recorded on the audit trail.
	OverrideEmailMatching bool `json:"overrideEmailMatching,omitempty"`
}

IdentityAssertion is an assertion from your own provider, passed when requesting an external_idv signing URL.

type IdentityVerification added in v0.8.0

type IdentityVerification struct {
	// Mode is "otp", "external_idv" or "override".
	Mode string `json:"mode"`
	// Channel is "email" or "sms", only for Mode "otp". Empty takes the org's default channel, or
	// "email" when that default is "none".
	Channel string `json:"channel,omitempty"`
	// Provider is the identity provider name — only for Mode "external_idv".
	Provider string `json:"provider,omitempty"`
	// MaxAgeMinutes bounds how old an external assertion may be — only for Mode "external_idv".
	MaxAgeMinutes int `json:"maxAgeMinutes,omitempty"`
	// OverrideIdentityVerification acknowledges skipping verification — only for Mode "override".
	OverrideIdentityVerification bool `json:"overrideIdentityVerification,omitempty"`
	// Reason records why verification was skipped — only for Mode "override".
	Reason string `json:"reason,omitempty"`
}

IdentityVerification describes how an embedded recipient's identity is verified before they can sign. It mirrors the JS SDK's discriminated union on Mode; in Go the mode-specific fields live alongside each other and are populated per mode:

  • Mode "otp": TurboSign emails or texts a one-time passcode. Channel is "email" or "sms" (SMS requires the recipient's Phone in E.164). An empty Channel takes the org's default channel, or "email" when that default is "none", so Mode "otp" always verifies. On an org with embedded signing off it returns a *AuthorizationError (403) with Code "EmbeddedSigningNotEnabled".
  • Mode "external_idv": your own identity provider verifies the signer. Set Provider (and optionally MaxAgeMinutes); pass the assertion to CreateSigningURL via IdentityAssertion.
  • Mode "override": skip identity verification entirely (development/testing; your org admin must enable it). Set OverrideIdentityVerification=true and a non-empty Reason.

external_idv and override recipients sign only through a single-use CreateSigningURL link. TurboSign never sends them signing, reminder or resend emails.

type LineItem added in v0.4.0

type LineItem struct {
	ID                  string     `json:"id"`
	OrgID               string     `json:"orgId"`
	QuoteID             string     `json:"quoteId"`
	LineItemTypeField   string     `json:"lineItemType"`
	ParentLineItemID    *string    `json:"parentLineItemId"`
	ProductID           *string    `json:"productId"`
	ProductName         *string    `json:"productName"`
	ProductSku          *string    `json:"productSku"`
	ProductDescription  *string    `json:"productDescription"`
	BundleID            *string    `json:"bundleId"`
	BundleName          *string    `json:"bundleName"`
	BundleDescription   *string    `json:"bundleDescription"`
	Quantity            int        `json:"quantity"`
	UnitPrice           float64    `json:"unitPrice"`
	DiscountPercent     float64    `json:"discountPercent"`
	Subtotal            float64    `json:"subtotal"`
	Cost                *float64   `json:"cost"`
	MarginPercent       *float64   `json:"marginPercent"`
	CategoryID          *string    `json:"categoryId"`
	CategoryName        *string    `json:"categoryName"`
	BillingFrequencyVal *string    `json:"billingFrequency"`
	ShowItemsToEndUser  bool       `json:"showItemsToEndUser"`
	IsActive            bool       `json:"isActive"`
	CreatedBy           *string    `json:"createdBy"`
	CreatedOn           string     `json:"createdOn"`
	UpdatedOn           string     `json:"updatedOn"`
	Product             *Product   `json:"product,omitempty"`
	ChildLineItems      []LineItem `json:"childLineItems,omitempty"`
}

LineItem represents a line item on a quote

type LineItemListResponse added in v0.4.0

type LineItemListResponse struct {
	Results      []LineItem `json:"results"`
	TotalRecords int        `json:"totalRecords"`
}

LineItemListResponse is the response from listing line items

type LineItemType added in v0.4.0

type LineItemType string

LineItemType represents line item types

const (
	LineItemTypeProduct LineItemType = "product"
	LineItemTypeBundle  LineItemType = "bundle"
)

type ListAuditLogsRequest added in v0.2.0

type ListAuditLogsRequest struct {
	Limit        *int
	Offset       *int
	Search       string
	Action       string
	ResourceType string
	ResourceID   string
	Success      *bool
	StartDate    string
	EndDate      string
}

ListAuditLogsRequest is the request to list audit logs

type ListBundlesOptions added in v0.4.0

type ListBundlesOptions struct {
	Limit         *int     `json:"limit,omitempty"`
	Offset        *int     `json:"offset,omitempty"`
	Query         *string  `json:"query,omitempty"`
	CategoryIDs   []string `json:"categoryIds,omitempty"`
	CurrencyCode  *string  `json:"currency,omitempty"`
	ShowInCatalog *bool    `json:"showInCatalog,omitempty"`
}

ListBundlesOptions holds the filter/pagination options for listing bundles

type ListCompaniesOptions added in v0.4.0

type ListCompaniesOptions struct {
	Limit       *int     `json:"limit,omitempty"`
	Offset      *int     `json:"offset,omitempty"`
	Query       *string  `json:"query,omitempty"`
	IndustryIDs []string `json:"industryIds,omitempty"`
}

ListCompaniesOptions holds the filter/pagination options for listing companies

type ListContactsOptions added in v0.4.0

type ListContactsOptions struct {
	Limit     *int    `json:"limit,omitempty"`
	Offset    *int    `json:"offset,omitempty"`
	Query     *string `json:"query,omitempty"`
	CompanyID *string `json:"companyId,omitempty"`
}

ListContactsOptions holds the filter/pagination options for listing contacts

type ListDeliverablesOptions added in v0.3.0

type ListDeliverablesOptions struct {
	Limit    int
	Offset   int
	Query    string
	ShowTags bool
}

ListDeliverablesOptions holds query parameters for listing deliverables

type ListDeliveriesRequest added in v0.3.0

type ListDeliveriesRequest struct {
	Limit       *int
	Offset      *int
	EventType   string
	IsDelivered *bool
	HTTPStatus  *int
}

ListDeliveriesRequest holds optional filters for ListWebhookDeliveries. Use nil for any field to skip that filter.

type ListLineItemsOptions added in v0.4.0

type ListLineItemsOptions struct {
	Limit            *int    `json:"limit,omitempty"`
	Offset           *int    `json:"offset,omitempty"`
	LineItemType     *string `json:"lineItemType,omitempty"`
	BillingFrequency *string `json:"billingFrequency,omitempty"`
	ParentLineItemID *string `json:"parentLineItemId,omitempty"`
}

ListLineItemsOptions holds the filter/pagination options for listing line items

type ListOrgAPIKeysRequest added in v0.4.0

type ListOrgAPIKeysRequest struct {
	Limit  *int
	Offset *int
	Search string
}

ListOrgAPIKeysRequest is the request to list organization API keys

type ListOrgApiKeysRequest deprecated added in v0.2.0

type ListOrgApiKeysRequest = ListOrgAPIKeysRequest

Deprecated: use ListOrgAPIKeysRequest.

type ListOrgUsersRequest added in v0.2.0

type ListOrgUsersRequest struct {
	Limit  *int
	Offset *int
	Search string
}

ListOrgUsersRequest is the request to list organization users

type ListOrganizationsRequest added in v0.2.0

type ListOrganizationsRequest struct {
	Limit  *int
	Offset *int
	Search string
}

ListOrganizationsRequest is the request to list organizations

type ListPartnerAPIKeysRequest added in v0.4.0

type ListPartnerAPIKeysRequest struct {
	Limit  *int
	Offset *int
	Search string
}

ListPartnerAPIKeysRequest is the request to list partner API keys

type ListPartnerApiKeysRequest deprecated added in v0.2.0

type ListPartnerApiKeysRequest = ListPartnerAPIKeysRequest

Deprecated: use ListPartnerAPIKeysRequest.

type ListPartnerUsersRequest added in v0.2.0

type ListPartnerUsersRequest struct {
	Limit  *int
	Offset *int
	Search string
}

ListPartnerUsersRequest is the request to list partner portal users

type ListPriceBookProductsOptions added in v0.4.0

type ListPriceBookProductsOptions struct {
	Limit       *int     `json:"limit,omitempty"`
	Offset      *int     `json:"offset,omitempty"`
	Query       *string  `json:"query,omitempty"`
	CategoryIDs []string `json:"categoryIds,omitempty"`
}

ListPriceBookProductsOptions holds the filter/pagination options for listing price book products

type ListPriceBooksOptions added in v0.4.0

type ListPriceBooksOptions struct {
	Limit              *int     `json:"limit,omitempty"`
	Offset             *int     `json:"offset,omitempty"`
	Query              *string  `json:"query,omitempty"`
	PriceBookTypeIDs   []string `json:"priceBookTypeIds,omitempty"`
	ShowInQuoteBuilder *bool    `json:"showInQuoteBuilder,omitempty"`
}

ListPriceBooksOptions holds the filter/pagination options for listing price books

type ListProductsOptions added in v0.4.0

type ListProductsOptions struct {
	Limit            *int     `json:"limit,omitempty"`
	Offset           *int     `json:"offset,omitempty"`
	Query            *string  `json:"query,omitempty"`
	CategoryIDs      []string `json:"categoryIds,omitempty"`
	BillingFrequency *string  `json:"billingFrequency,omitempty"`
	CurrencyCode     *string  `json:"currency,omitempty"`
	ShowInCatalog    *bool    `json:"showInCatalog,omitempty"`
}

ListProductsOptions holds the filter/pagination options for listing products

type ListQuotesOptions added in v0.4.0

type ListQuotesOptions struct {
	Limit        *int     `json:"limit,omitempty"`
	Offset       *int     `json:"offset,omitempty"`
	Query        *string  `json:"query,omitempty"`
	Statuses     []string `json:"statuses,omitempty"`
	CompanyID    *string  `json:"companyId,omitempty"`
	ContactID    *string  `json:"contactId,omitempty"`
	CurrencyCode *string  `json:"currency,omitempty"`
}

ListQuotesOptions holds the filter/pagination options for listing quotes

type ListTypesOptions added in v0.4.0

type ListTypesOptions struct {
	Limit        *int    `json:"limit,omitempty"`
	Offset       *int    `json:"offset,omitempty"`
	Query        *string `json:"query,omitempty"`
	CategoryType *string `json:"categoryType,omitempty"`
	IncludeUsage *bool   `json:"includeUsage,omitempty"`
}

ListTypesOptions holds the filter/pagination options for listing types

type NetworkError

type NetworkError struct {
	TurboDocxError
}

NetworkError is raised when network request fails

type NotFoundError

type NotFoundError struct {
	TurboDocxError
}

NotFoundError is raised when resource is not found (HTTP 404)

type OrgAPIKey added in v0.4.0

type OrgAPIKey struct {
	ID         string   `json:"id"`
	Name       string   `json:"name"`
	Key        string   `json:"key,omitempty"`
	Role       string   `json:"role,omitempty"`
	Scopes     []string `json:"scopes,omitempty"`
	CreatedOn  string   `json:"createdOn,omitempty"`
	CreatedBy  string   `json:"createdBy,omitempty"`
	LastUsedOn string   `json:"lastUsedOn,omitempty"`
	LastUsedIP string   `json:"lastUsedIP,omitempty"`
	UpdatedOn  string   `json:"updatedOn,omitempty"`
}

OrgAPIKey represents an organization API key

type OrgAPIKeyListResponse added in v0.4.0

type OrgAPIKeyListResponse struct {
	Success bool `json:"success"`
	Data    struct {
		Results      []OrgAPIKey `json:"results"`
		TotalRecords int         `json:"totalRecords"`
		Limit        int         `json:"limit"`
		Offset       int         `json:"offset"`
	} `json:"data"`
}

OrgAPIKeyListResponse is the response for listing organization API keys

type OrgAPIKeyResponse added in v0.4.0

type OrgAPIKeyResponse struct {
	Success bool      `json:"success"`
	Data    OrgAPIKey `json:"data"`
	Message string    `json:"message,omitempty"`
}

OrgAPIKeyResponse is the response for organization API key creation

type OrgAPIKeyUpdateResponse added in v0.4.0

type OrgAPIKeyUpdateResponse struct {
	Success bool   `json:"success"`
	Message string `json:"message,omitempty"`
	// ApiKey keeps the v0.3.0 field name (not APIKey) — a struct-field rename is a breaking
	// change that a type alias cannot bridge. The JSON tag is unchanged.
	ApiKey struct {
		ID        string `json:"id"`
		Name      string `json:"name"`
		Role      string `json:"role,omitempty"`
		UpdatedOn string `json:"updatedOn,omitempty"`
	} `json:"apiKey"`
}

OrgAPIKeyUpdateResponse is the response for organization API key updates

type OrgApiKey deprecated added in v0.2.0

type OrgApiKey = OrgAPIKey

Deprecated: use OrgAPIKey.

type OrgApiKeyListResponse deprecated added in v0.2.0

type OrgApiKeyListResponse = OrgAPIKeyListResponse

Deprecated: use OrgAPIKeyListResponse.

type OrgApiKeyResponse deprecated added in v0.2.0

type OrgApiKeyResponse = OrgAPIKeyResponse

Deprecated: use OrgAPIKeyResponse.

type OrgApiKeyUpdateResponse deprecated added in v0.2.0

type OrgApiKeyUpdateResponse = OrgAPIKeyUpdateResponse

Deprecated: use OrgAPIKeyUpdateResponse.

type OrgUserListResponse added in v0.2.0

type OrgUserListResponse struct {
	Success bool `json:"success"`
	Data    struct {
		Results      []OrganizationUser `json:"results"`
		TotalRecords int                `json:"totalRecords"`
		Limit        int                `json:"limit"`
		Offset       int                `json:"offset"`
	} `json:"data"`
	UserLimit map[string]interface{} `json:"userLimit,omitempty"`
}

OrgUserListResponse is the response for listing organization users

type OrgUserResponse added in v0.2.0

type OrgUserResponse struct {
	Success bool             `json:"success"`
	Data    OrganizationUser `json:"data"`
}

OrgUserResponse is the response for organization user operations

type Organization added in v0.2.0

type Organization struct {
	ID          string                 `json:"id"`
	Name        string                 `json:"name"`
	PartnerID   string                 `json:"partnerId,omitempty"`
	CreatedOn   string                 `json:"createdOn,omitempty"`
	UpdatedOn   string                 `json:"updatedOn,omitempty"`
	CreatedBy   string                 `json:"createdBy,omitempty"`
	IsActive    bool                   `json:"isActive,omitempty"`
	UserCount   int                    `json:"userCount,omitempty"`
	StorageUsed int64                  `json:"storageUsed,omitempty"`
	Metadata    map[string]interface{} `json:"metadata,omitempty"`
}

Organization represents a partner organization

type OrganizationDetailResponse added in v0.2.0

type OrganizationDetailResponse struct {
	Success bool `json:"success"`
	Data    struct {
		Organization
		Features *Features `json:"features,omitempty"`
		Tracking *Tracking `json:"tracking,omitempty"`
	} `json:"data"`
}

OrganizationDetailResponse is the response for getting organization details

type OrganizationListResponse added in v0.2.0

type OrganizationListResponse struct {
	Success bool `json:"success"`
	Data    struct {
		Results      []Organization `json:"results"`
		TotalRecords int            `json:"totalRecords"`
		Limit        int            `json:"limit"`
		Offset       int            `json:"offset"`
	} `json:"data"`
}

OrganizationListResponse is the response for listing organizations

type OrganizationResponse added in v0.2.0

type OrganizationResponse struct {
	Success bool         `json:"success"`
	Data    Organization `json:"data"`
}

OrganizationResponse is the response for organization create/update

type OrganizationUser added in v0.2.0

type OrganizationUser struct {
	ID        string `json:"id"`
	Email     string `json:"email"`
	FirstName string `json:"firstName,omitempty"`
	LastName  string `json:"lastName,omitempty"`
	SsoID     string `json:"ssoId,omitempty"`
	Role      string `json:"role,omitempty"`
	CreatedOn string `json:"createdOn,omitempty"`
	IsActive  bool   `json:"isActive,omitempty"`
}

OrganizationUser represents a user in an organization

type PaginationParams added in v0.4.0

type PaginationParams struct {
	Limit  *int    `json:"limit,omitempty"`
	Offset *int    `json:"offset,omitempty"`
	Query  *string `json:"query,omitempty"`
}

PaginationParams holds standard pagination/search options

type PartnerAPIKey added in v0.4.0

type PartnerAPIKey struct {
	ID          string   `json:"id"`
	Name        string   `json:"name"`
	Key         string   `json:"key,omitempty"`
	Description string   `json:"description,omitempty"`
	Scopes      []string `json:"scopes,omitempty"`
	CreatedOn   string   `json:"createdOn,omitempty"`
	CreatedBy   string   `json:"createdBy,omitempty"`
	LastUsedOn  string   `json:"lastUsedOn,omitempty"`
	LastUsedIP  string   `json:"lastUsedIP,omitempty"`
	UpdatedOn   string   `json:"updatedOn,omitempty"`
}

PartnerAPIKey represents a partner-level API key

type PartnerAPIKeyListResponse added in v0.4.0

type PartnerAPIKeyListResponse struct {
	Success bool `json:"success"`
	Data    struct {
		Results      []PartnerAPIKey `json:"results"`
		TotalRecords int             `json:"totalRecords"`
		Limit        int             `json:"limit"`
		Offset       int             `json:"offset"`
	} `json:"data"`
}

PartnerAPIKeyListResponse is the response for listing partner API keys

type PartnerAPIKeyResponse added in v0.4.0

type PartnerAPIKeyResponse struct {
	Success bool          `json:"success"`
	Data    PartnerAPIKey `json:"data"`
	Message string        `json:"message,omitempty"`
}

PartnerAPIKeyResponse is the response for partner API key creation

type PartnerAPIKeyUpdateResponse added in v0.4.0

type PartnerAPIKeyUpdateResponse struct {
	Success bool   `json:"success"`
	Message string `json:"message,omitempty"`
	// ApiKey keeps the v0.3.0 field name (not APIKey) — a struct-field rename is a breaking
	// change that a type alias cannot bridge. The JSON tag is unchanged.
	ApiKey struct {
		ID          string   `json:"id"`
		Name        string   `json:"name"`
		Description string   `json:"description,omitempty"`
		Scopes      []string `json:"scopes,omitempty"`
		UpdatedOn   string   `json:"updatedOn,omitempty"`
	} `json:"apiKey"`
}

PartnerAPIKeyUpdateResponse is the response for partner API key updates

type PartnerApiKey deprecated added in v0.2.0

type PartnerApiKey = PartnerAPIKey

Deprecated: use PartnerAPIKey.

type PartnerApiKeyListResponse deprecated added in v0.2.0

type PartnerApiKeyListResponse = PartnerAPIKeyListResponse

Deprecated: use PartnerAPIKeyListResponse.

type PartnerApiKeyResponse deprecated added in v0.2.0

type PartnerApiKeyResponse = PartnerAPIKeyResponse

Deprecated: use PartnerAPIKeyResponse.

type PartnerApiKeyUpdateResponse deprecated added in v0.2.0

type PartnerApiKeyUpdateResponse = PartnerAPIKeyUpdateResponse

Deprecated: use PartnerAPIKeyUpdateResponse.

type PartnerClient added in v0.2.0

type PartnerClient struct {
	// contains filtered or unexported fields
}

PartnerClient provides TurboPartner partner management operations

func NewPartnerClient added in v0.2.0

func NewPartnerClient(config PartnerConfig) (*PartnerClient, error)

NewPartnerClient creates a new TurboPartner client with the given config

func (*PartnerClient) AddUserToOrganization added in v0.2.0

func (c *PartnerClient) AddUserToOrganization(ctx context.Context, organizationID string, req *AddOrgUserRequest) (*OrgUserResponse, error)

AddUserToOrganization adds a user to an organization with a specific role

func (*PartnerClient) AddUserToPartnerPortal added in v0.2.0

func (c *PartnerClient) AddUserToPartnerPortal(ctx context.Context, req *AddPartnerUserRequest) (*PartnerUserResponse, error)

AddUserToPartnerPortal adds a user to the partner portal with specific permissions

func (*PartnerClient) CreateOrganization added in v0.2.0

CreateOrganization creates a new organization under the partner account

func (*PartnerClient) CreateOrganizationAPIKey added in v0.4.0

func (c *PartnerClient) CreateOrganizationAPIKey(ctx context.Context, organizationID string, req *CreateOrgAPIKeyRequest) (*OrgAPIKeyResponse, error)

CreateOrganizationAPIKey creates an API key for an organization

func (*PartnerClient) CreateOrganizationApiKey deprecated added in v0.2.0

func (c *PartnerClient) CreateOrganizationApiKey(ctx context.Context, organizationID string, req *CreateOrgApiKeyRequest) (*OrgApiKeyResponse, error)

Deprecated: use CreateOrganizationAPIKey.

func (*PartnerClient) CreatePartnerAPIKey added in v0.4.0

CreatePartnerAPIKey creates a new partner-level API key with specific scopes

func (*PartnerClient) CreatePartnerApiKey deprecated added in v0.2.0

Deprecated: use CreatePartnerAPIKey.

func (*PartnerClient) DeleteOrganization added in v0.2.0

func (c *PartnerClient) DeleteOrganization(ctx context.Context, organizationID string) (*SuccessResponse, error)

DeleteOrganization soft-deletes an organization

func (*PartnerClient) GetOrganizationDetails added in v0.2.0

func (c *PartnerClient) GetOrganizationDetails(ctx context.Context, organizationID string) (*OrganizationDetailResponse, error)

GetOrganizationDetails gets full details for an organization including features and tracking

func (*PartnerClient) GetOrganizationPreferences added in v0.8.0

func (c *PartnerClient) GetOrganizationPreferences(ctx context.Context, organizationID string) (*PartnerOrgPreferencesResponse, error)

GetOrganizationPreferences reads the TurboSign display preferences for one of the partner's organizations. Returns each partner-settable key with its effective value.

func (*PartnerClient) GetPartnerAuditLogs added in v0.2.0

func (c *PartnerClient) GetPartnerAuditLogs(ctx context.Context, req *ListAuditLogsRequest) (*AuditLogListResponse, error)

GetPartnerAuditLogs gets audit logs for all partner activities with filtering

func (*PartnerClient) ListOrganizationAPIKeys added in v0.4.0

func (c *PartnerClient) ListOrganizationAPIKeys(ctx context.Context, organizationID string, req *ListOrgAPIKeysRequest) (*OrgAPIKeyListResponse, error)

ListOrganizationAPIKeys lists all API keys for an organization

func (*PartnerClient) ListOrganizationApiKeys deprecated added in v0.2.0

func (c *PartnerClient) ListOrganizationApiKeys(ctx context.Context, organizationID string, req *ListOrgApiKeysRequest) (*OrgApiKeyListResponse, error)

Deprecated: use ListOrganizationAPIKeys.

func (*PartnerClient) ListOrganizationUsers added in v0.2.0

func (c *PartnerClient) ListOrganizationUsers(ctx context.Context, organizationID string, req *ListOrgUsersRequest) (*OrgUserListResponse, error)

ListOrganizationUsers lists all users in an organization

func (*PartnerClient) ListOrganizations added in v0.2.0

ListOrganizations lists all organizations with optional pagination and search

func (*PartnerClient) ListPartnerAPIKeys added in v0.4.0

ListPartnerAPIKeys lists all partner API keys

func (*PartnerClient) ListPartnerApiKeys deprecated added in v0.2.0

Deprecated: use ListPartnerAPIKeys.

func (*PartnerClient) ListPartnerPortalUsers added in v0.2.0

func (c *PartnerClient) ListPartnerPortalUsers(ctx context.Context, req *ListPartnerUsersRequest) (*PartnerUserListResponse, error)

ListPartnerPortalUsers lists all partner portal users

func (*PartnerClient) RemoveUserFromOrganization added in v0.2.0

func (c *PartnerClient) RemoveUserFromOrganization(ctx context.Context, organizationID, userID string) (*SuccessResponse, error)

RemoveUserFromOrganization removes a user from an organization

func (*PartnerClient) RemoveUserFromPartnerPortal added in v0.2.0

func (c *PartnerClient) RemoveUserFromPartnerPortal(ctx context.Context, userID string) (*SuccessResponse, error)

RemoveUserFromPartnerPortal removes a user from the partner portal

func (*PartnerClient) ResendOrganizationInvitationToUser added in v0.2.0

func (c *PartnerClient) ResendOrganizationInvitationToUser(ctx context.Context, organizationID, userID string) (*SuccessResponse, error)

ResendOrganizationInvitationToUser resends the invitation email to a pending user

func (*PartnerClient) ResendPartnerPortalInvitationToUser added in v0.2.0

func (c *PartnerClient) ResendPartnerPortalInvitationToUser(ctx context.Context, userID string) (*SuccessResponse, error)

ResendPartnerPortalInvitationToUser resends the invitation email to a pending partner user

func (*PartnerClient) RevokeOrganizationAPIKey added in v0.4.0

func (c *PartnerClient) RevokeOrganizationAPIKey(ctx context.Context, organizationID, apiKeyID string) (*SuccessResponse, error)

RevokeOrganizationAPIKey revokes an organization API key

func (*PartnerClient) RevokeOrganizationApiKey deprecated added in v0.2.0

func (c *PartnerClient) RevokeOrganizationApiKey(ctx context.Context, organizationID, apiKeyID string) (*SuccessResponse, error)

Deprecated: use RevokeOrganizationAPIKey.

func (*PartnerClient) RevokePartnerAPIKey added in v0.4.0

func (c *PartnerClient) RevokePartnerAPIKey(ctx context.Context, keyID string) (*SuccessResponse, error)

RevokePartnerAPIKey revokes a partner API key

func (*PartnerClient) RevokePartnerApiKey deprecated added in v0.2.0

func (c *PartnerClient) RevokePartnerApiKey(ctx context.Context, keyID string) (*SuccessResponse, error)

Deprecated: use RevokePartnerAPIKey.

func (*PartnerClient) UpdateOrganizationAPIKey added in v0.4.0

func (c *PartnerClient) UpdateOrganizationAPIKey(ctx context.Context, organizationID, apiKeyID string, req *UpdateOrgAPIKeyRequest) (*OrgAPIKeyUpdateResponse, error)

UpdateOrganizationAPIKey updates an organization API key

func (*PartnerClient) UpdateOrganizationApiKey deprecated added in v0.2.0

func (c *PartnerClient) UpdateOrganizationApiKey(ctx context.Context, organizationID, apiKeyID string, req *UpdateOrgApiKeyRequest) (*OrgApiKeyUpdateResponse, error)

Deprecated: use UpdateOrganizationAPIKey.

func (*PartnerClient) UpdateOrganizationEntitlements added in v0.2.0

func (c *PartnerClient) UpdateOrganizationEntitlements(ctx context.Context, organizationID string, req *UpdateEntitlementsRequest) (*EntitlementsResponse, error)

UpdateOrganizationEntitlements updates an organization's feature limits and capabilities

func (*PartnerClient) UpdateOrganizationInfo added in v0.2.0

func (c *PartnerClient) UpdateOrganizationInfo(ctx context.Context, organizationID string, req *UpdateOrganizationRequest) (*OrganizationResponse, error)

UpdateOrganizationInfo updates an organization's name

func (*PartnerClient) UpdateOrganizationPreferences added in v0.8.0

func (c *PartnerClient) UpdateOrganizationPreferences(ctx context.Context, organizationID string, preferences *UpdateOrgPreferencesRequest) (*PartnerOrgPreferencesResponse, error)

UpdateOrganizationPreferences sets TurboSign display preferences for one of the partner's organizations. Only the keys set on preferences are sent, wrapped under a "preferences" key.

func (*PartnerClient) UpdateOrganizationUserRole added in v0.2.0

func (c *PartnerClient) UpdateOrganizationUserRole(ctx context.Context, organizationID, userID string, req *UpdateOrgUserRequest) (*OrgUserResponse, error)

UpdateOrganizationUserRole updates a user's role within an organization

func (*PartnerClient) UpdatePartnerAPIKey added in v0.4.0

UpdatePartnerAPIKey updates a partner API key

func (*PartnerClient) UpdatePartnerApiKey deprecated added in v0.2.0

Deprecated: use UpdatePartnerAPIKey.

func (*PartnerClient) UpdatePartnerUserPermissions added in v0.2.0

func (c *PartnerClient) UpdatePartnerUserPermissions(ctx context.Context, userID string, req *UpdatePartnerUserRequest) (*PartnerUserUpdateResponse, error)

UpdatePartnerUserPermissions updates a partner user's role and permissions

type PartnerConfig added in v0.2.0

type PartnerConfig struct {
	// PartnerAPIKey is your partner API key (required, must start with TDXP-)
	PartnerAPIKey string

	// PartnerID is your partner UUID (required)
	PartnerID string

	// BaseURL is the API base URL (optional, default: https://api.turbodocx.com)
	BaseURL string
}

PartnerConfig holds configuration for the TurboPartner client

type PartnerOrgPreferences added in v0.8.0

type PartnerOrgPreferences struct {
	HideSignatureOutline       bool `json:"hideSignatureOutline"`
	HideSignatureHash          bool `json:"hideSignatureHash"`
	LockedFieldsBackground     bool `json:"lockedFieldsBackground"`
	AllowDownloadBeforeSigning bool `json:"allowDownloadBeforeSigning"`
}

PartnerOrgPreferences is the partner-settable slice of an organization's TurboSign display preferences. Every key is present with its effective boolean value when read.

type PartnerOrgPreferencesResponse added in v0.8.0

type PartnerOrgPreferencesResponse struct {
	Success bool `json:"success"`
	Data    struct {
		Preferences PartnerOrgPreferences `json:"preferences"`
	} `json:"data"`
}

PartnerOrgPreferencesResponse is the response for reading or updating an organization's partner-settable preferences.

type PartnerPermissions added in v0.2.0

type PartnerPermissions struct {
	CanManageOrgs           bool `json:"canManageOrgs"`
	CanManageOrgUsers       bool `json:"canManageOrgUsers"`
	CanManagePartnerUsers   bool `json:"canManagePartnerUsers"`
	CanManageOrgAPIKeys     bool `json:"canManageOrgAPIKeys"`
	CanManagePartnerAPIKeys bool `json:"canManagePartnerAPIKeys"`
	CanUpdateEntitlements   bool `json:"canUpdateEntitlements"`
	CanViewAuditLogs        bool `json:"canViewAuditLogs"`
}

PartnerPermissions represents the permissions for a partner portal user.

The API requires all 7 keys on every request that carries a permissions object — there is no partial update. None of the fields are omitempty, so the zero value of an unset field is still sent as false; set each one explicitly.

type PartnerUser added in v0.2.0

type PartnerUser struct {
	ID             string              `json:"id"`
	Email          string              `json:"email"`
	FirstName      string              `json:"firstName,omitempty"`
	LastName       string              `json:"lastName,omitempty"`
	SsoID          string              `json:"ssoId,omitempty"`
	Role           string              `json:"role,omitempty"`
	Permissions    *PartnerPermissions `json:"permissions,omitempty"`
	IsPrimaryAdmin bool                `json:"isPrimaryAdmin,omitempty"`
	CreatedOn      string              `json:"createdOn,omitempty"`
	IsActive       bool                `json:"isActive,omitempty"`
}

PartnerUser represents a user in the partner portal

type PartnerUserListResponse added in v0.2.0

type PartnerUserListResponse struct {
	Success bool `json:"success"`
	Data    struct {
		Results      []PartnerUser `json:"results"`
		TotalRecords int           `json:"totalRecords"`
		Limit        int           `json:"limit"`
		Offset       int           `json:"offset"`
	} `json:"data"`
}

PartnerUserListResponse is the response for listing partner users

type PartnerUserResponse added in v0.2.0

type PartnerUserResponse struct {
	Success bool        `json:"success"`
	Data    PartnerUser `json:"data"`
}

PartnerUserResponse is the response for partner user operations

type PartnerUserUpdateResponse added in v0.2.0

type PartnerUserUpdateResponse struct {
	Success bool `json:"success"`
	Data    struct {
		UserID      string             `json:"userId"`
		Role        string             `json:"role"`
		Permissions PartnerPermissions `json:"permissions"`
	} `json:"data"`
}

PartnerUserUpdateResponse is the response for partner user updates

type Point

type Point struct {
	X int `json:"x"`
	Y int `json:"y"`
}

Point represents x and y coordinates

type PriceBook added in v0.4.0

type PriceBook struct {
	ID                 string                    `json:"id"`
	OrgID              string                    `json:"orgId"`
	Name               string                    `json:"name"`
	Description        *string                   `json:"description"`
	PriceBookTypeID    string                    `json:"priceBookTypeId"`
	DiscountPercent    float64                   `json:"discountPercent"`
	ValidFrom          string                    `json:"validFrom"`
	ValidTo            *string                   `json:"validTo"`
	IsDefault          bool                      `json:"isDefault"`
	ShowInQuoteBuilder bool                      `json:"showInQuoteBuilder"`
	IsActive           bool                      `json:"isActive"`
	CreatedBy          *string                   `json:"createdBy"`
	CreatedOn          string                    `json:"createdOn"`
	UpdatedOn          string                    `json:"updatedOn"`
	ProductPricing     []PriceBookProductPricing `json:"productPricing,omitempty"`
	PriceBookType      *PriceBookType            `json:"priceBookType,omitempty"`
	ProductCount       *int                      `json:"productCount,omitempty"`
}

PriceBook represents a price book entity

type PriceBookListResponse added in v0.4.0

type PriceBookListResponse struct {
	Results              []PriceBook `json:"results"`
	TotalRecords         int         `json:"totalRecords"`
	TotalPriceBooks      int         `json:"totalPriceBooks"`
	ActiveInBuilder      int         `json:"activeInBuilder"`
	TotalProducts        int         `json:"totalProducts"`
	DefaultPriceBookName *string     `json:"defaultPriceBookName"`
}

PriceBookListResponse is the response from listing price books

type PriceBookProductListResponse added in v0.4.0

type PriceBookProductListResponse struct {
	Results      []PriceBookProductPricing `json:"results"`
	TotalRecords int                       `json:"totalRecords"`
}

PriceBookProductListResponse is the response from listing price book products

type PriceBookProductPricing added in v0.4.0

type PriceBookProductPricing struct {
	ID              *string  `json:"id,omitempty"`
	PriceBookID     *string  `json:"priceBookId,omitempty"`
	ProductID       string   `json:"productId"`
	DiscountPercent float64  `json:"discountPercent"`
	FinalPrice      float64  `json:"finalPrice"`
	OrgID           *string  `json:"orgId,omitempty"`
	IsActive        *bool    `json:"isActive,omitempty"`
	CreatedBy       *string  `json:"createdBy,omitempty"`
	CreatedOn       *string  `json:"createdOn,omitempty"`
	UpdatedOn       *string  `json:"updatedOn,omitempty"`
	Product         *Product `json:"product,omitempty"`
}

PriceBookProductPricing represents product pricing within a price book

type PriceBookProductPricingInput added in v0.4.0

type PriceBookProductPricingInput struct {
	ProductID       string        `json:"productId"`
	DiscountPercent *float64      `json:"discountPercent,omitempty"`
	DiscountType    *DiscountType `json:"discountType,omitempty"`
	DiscountAmount  *float64      `json:"discountAmount,omitempty"`
	FinalPrice      *float64      `json:"finalPrice,omitempty"`
}

PriceBookProductPricingInput represents a product pricing entry for create/update

type PriceBookType added in v0.4.0

type PriceBookType struct {
	ID           string `json:"id"`
	Name         string `json:"name"`
	CategoryType string `json:"categoryType"`
}

PriceBookType represents an inline price book type reference

type Product added in v0.4.0

type Product struct {
	ID                    string           `json:"id"`
	OrgID                 string           `json:"orgId"`
	Name                  string           `json:"name"`
	Sku                   *string          `json:"sku"`
	Description           *string          `json:"description"`
	DetailedSpecification *string          `json:"detailedSpecification"`
	InternalNotes         *string          `json:"internalNotes"`
	CategoryID            string           `json:"categoryId"`
	ListPrice             float64          `json:"listPrice"`
	Cost                  *float64         `json:"cost"`
	MinimumOrderQuantity  int              `json:"minimumOrderQuantity"`
	BillingFrequency      string           `json:"billingFrequency"`
	CurrencyCode          Currency         `json:"currency"`
	ShowInCatalog         bool             `json:"showInCatalog"`
	IsActive              bool             `json:"isActive"`
	CreatedBy             *string          `json:"createdBy"`
	CreatedOn             string           `json:"createdOn"`
	UpdatedOn             string           `json:"updatedOn"`
	Images                []ProductImage   `json:"images,omitempty"`
	Category              *ProductCategory `json:"category,omitempty"`
}

Product represents a product entity

type ProductCategory added in v0.4.0

type ProductCategory struct {
	ID           string `json:"id"`
	Name         string `json:"name"`
	CategoryType string `json:"categoryType"`
}

ProductCategory represents an inline category reference

type ProductImage added in v0.4.0

type ProductImage struct {
	ID           string `json:"id"`
	ProductID    string `json:"productId"`
	FileID       string `json:"fileId"`
	FileName     string `json:"fileName"`
	FileType     string `json:"fileType"`
	DisplayOrder int    `json:"displayOrder"`
	ImageData    string `json:"imageData,omitempty"`
}

ProductImage represents an image attached to a product

type ProductImageFile added in v0.4.0

type ProductImageFile struct {
	Data     []byte
	FileName string
}

ProductImageFile represents an image to attach in a multipart product request

type ProductImageInput added in v0.4.0

type ProductImageInput struct {
	FilePath string // local file path
	Data     []byte // raw image bytes
	FileName string // optional filename (used with Data)
}

ProductImageInput represents an image to upload (either file path or raw bytes)

type ProductListResponse added in v0.4.0

type ProductListResponse struct {
	Results         []Product `json:"results"`
	TotalRecords    int       `json:"totalRecords"`
	TotalProducts   int       `json:"totalProducts"`
	ActiveProducts  int       `json:"activeProducts"`
	TotalCategories int       `json:"totalCategories"`
	CatalogValue    float64   `json:"catalogValue"`
}

ProductListResponse is the response from listing products

type ProductPrimaryImagesResponse added in v0.4.0

type ProductPrimaryImagesResponse map[string]*ProductImage

ProductPrimaryImagesResponse maps product IDs to their primary image (or null)

type Quote added in v0.4.0

type Quote struct {
	ID                string           `json:"id"`
	OrgID             string           `json:"orgId"`
	QuoteNumber       string           `json:"quoteNumber"`
	Name              string           `json:"name"`
	Status            QuoteStatus      `json:"status"`
	CompanyID         string           `json:"companyId"`
	ContactID         string           `json:"contactId"`
	PriceBookID       *string          `json:"priceBookId"`
	TermDays          int              `json:"termDays"`
	RenewalPeriod     *string          `json:"renewalPeriod"`
	SentAt            *string          `json:"sentAt"`
	ValidUntil        *string          `json:"validUntil"`
	TaxRate           *float64         `json:"taxRate"`
	CurrencyCode      Currency         `json:"currency"`
	SubtotalMonthly   float64          `json:"subtotalMonthly"`
	SubtotalQuarterly float64          `json:"subtotalQuarterly"`
	SubtotalAnnual    float64          `json:"subtotalAnnual"`
	SubtotalOneTime   float64          `json:"subtotalOneTime"`
	TaxAmount         float64          `json:"taxAmount"`
	GrandTotal        float64          `json:"grandTotal"`
	IsActive          bool             `json:"isActive"`
	CreatedBy         *string          `json:"createdBy"`
	CreatedOn         string           `json:"createdOn"`
	UpdatedOn         string           `json:"updatedOn"`
	Company           *Company         `json:"company,omitempty"`
	Contact           *Contact         `json:"contact,omitempty"`
	LineItems         []LineItem       `json:"lineItems,omitempty"`
	PriceBook         *PriceBook       `json:"priceBook,omitempty"`
	Creator           *QuoteCreator    `json:"creator,omitempty"`
	StatusInfo        *QuoteStatusInfo `json:"statusInfo,omitempty"`
	// PreparedBy is folded on by GetQuote from the response's sibling "preparedBy".
	PreparedBy *QuotePreparedBy `json:"preparedBy,omitempty"`
}

Quote represents a quote entity

type QuoteClient added in v0.4.0

type QuoteClient struct {
	// contains filtered or unexported fields
}

QuoteClient provides TurboQuote quoting operations

func NewQuoteClient added in v0.4.0

func NewQuoteClient(config QuoteClientConfig) (*QuoteClient, error)

NewQuoteClient creates a new TurboQuote client with the given config

func (*QuoteClient) AddBundleLineItems added in v0.4.0

func (c *QuoteClient) AddBundleLineItems(ctx context.Context, quoteID string, items ...AddBundleLineItemRequest) ([]LineItem, error)

AddBundleLineItems adds one or more bundle line items to a quote

func (*QuoteClient) AddLineItems added in v0.4.0

func (c *QuoteClient) AddLineItems(ctx context.Context, quoteID string, items ...AddLineItemRequest) ([]LineItem, error)

AddLineItems adds one or more product line items to a quote. Accepts a single item or a slice of items.

func (*QuoteClient) ApplyPriceBook added in v0.4.0

func (c *QuoteClient) ApplyPriceBook(ctx context.Context, quoteID string, priceBookID string) (*ApplyPriceBookResponse, error)

ApplyPriceBook applies a price book to a quote

func (*QuoteClient) BulkCreateBundles added in v0.6.0

func (c *QuoteClient) BulkCreateBundles(ctx context.Context, rows []CreateBundleRequest) (*BulkImportResult, error)

BulkCreateBundles imports multiple bundles in one call with partial success: failed rows are reported in the result, not returned as an error. A bundle item whose product isn't found is dropped and reported as adjusted.

func (*QuoteClient) BulkCreateCompanies added in v0.6.0

func (c *QuoteClient) BulkCreateCompanies(ctx context.Context, rows []CreateCompanyRequest) (*BulkImportResult, error)

BulkCreateCompanies imports multiple companies in one call with partial success: failed rows are reported in the result, not returned as an error. Each row requires a Contacts slice with at least one contact.

func (*QuoteClient) BulkCreateContacts added in v0.6.0

func (c *QuoteClient) BulkCreateContacts(ctx context.Context, rows []CreateContactRequest) (*BulkImportResult, error)

BulkCreateContacts imports multiple contacts in one call with partial success: failed rows are reported in the result, not returned as an error. Each row requires a CompanyID.

func (*QuoteClient) BulkCreatePriceBooks added in v0.6.0

func (c *QuoteClient) BulkCreatePriceBooks(ctx context.Context, rows []CreatePriceBookRequest) (*BulkImportResult, error)

BulkCreatePriceBooks imports multiple price books in one call with partial success: failed rows are reported in the result, not returned as an error.

func (*QuoteClient) BulkCreateProducts added in v0.6.0

func (c *QuoteClient) BulkCreateProducts(ctx context.Context, rows []CreateProductRequest) (*BulkImportResult, error)

BulkCreateProducts imports multiple products in one call with partial success: failed rows are reported in the result, not returned as an error.

func (*QuoteClient) BulkCreateTypes added in v0.6.0

func (c *QuoteClient) BulkCreateTypes(ctx context.Context, rows []CreateQuoteTypeRequest) (*BulkImportResult, error)

BulkCreateTypes imports multiple quote types/categories in one call with partial success: failed rows are reported in the result, not returned as an error.

func (*QuoteClient) CreateAndSend added in v0.4.0

func (c *QuoteClient) CreateAndSend(ctx context.Context, request *CreateAndSendRequest) (*CreateAndSendResponse, error)

CreateAndSend creates a quote, adds line items, and sends it in one call. This is a convenience method that performs 2-4 sequential API calls.

func (*QuoteClient) CreateBundle added in v0.4.0

func (c *QuoteClient) CreateBundle(ctx context.Context, request *CreateBundleRequest) (*Bundle, error)

CreateBundle creates a new bundle

func (*QuoteClient) CreateCompany added in v0.4.0

func (c *QuoteClient) CreateCompany(ctx context.Context, request *CreateCompanyRequest) (*Company, error)

CreateCompany creates a new company

func (*QuoteClient) CreateContact added in v0.4.0

func (c *QuoteClient) CreateContact(ctx context.Context, request *CreateContactRequest) (*Contact, error)

CreateContact creates a new contact

func (*QuoteClient) CreatePriceBook added in v0.4.0

func (c *QuoteClient) CreatePriceBook(ctx context.Context, request *CreatePriceBookRequest) (*PriceBook, error)

CreatePriceBook creates a new price book

func (*QuoteClient) CreateProduct added in v0.4.0

func (c *QuoteClient) CreateProduct(ctx context.Context, request *CreateProductRequest) (*Product, error)

CreateProduct creates a new product. If images are provided, uses multipart upload.

func (*QuoteClient) CreateQuote added in v0.4.0

func (c *QuoteClient) CreateQuote(ctx context.Context, request *CreateQuoteRequest) (*Quote, error)

CreateQuote creates a new quote

func (*QuoteClient) CreateTemplate added in v0.4.0

func (c *QuoteClient) CreateTemplate(ctx context.Context, request *CreateQuoteTemplateRequest) (*QuoteTemplate, error)

CreateTemplate creates a new quote template

func (*QuoteClient) CreateType added in v0.4.0

func (c *QuoteClient) CreateType(ctx context.Context, request *CreateQuoteTypeRequest) (*QuoteType, error)

CreateType creates a new quote type/category

func (*QuoteClient) DeclineQuote added in v0.4.0

func (c *QuoteClient) DeclineQuote(ctx context.Context, id string, request *DeclineQuoteRequest) (*Quote, error)

DeclineQuote declines a quote

func (*QuoteClient) DeleteBundle added in v0.4.0

func (c *QuoteClient) DeleteBundle(ctx context.Context, id string) (*QuoteSuccessResponse, error)

DeleteBundle deletes a bundle by ID

func (*QuoteClient) DeleteCompany added in v0.4.0

func (c *QuoteClient) DeleteCompany(ctx context.Context, id string) (*QuoteSuccessResponse, error)

DeleteCompany deletes a company by ID

func (*QuoteClient) DeleteContact added in v0.4.0

func (c *QuoteClient) DeleteContact(ctx context.Context, id string) (*QuoteSuccessResponse, error)

DeleteContact deletes a contact by ID

func (*QuoteClient) DeletePriceBook added in v0.4.0

func (c *QuoteClient) DeletePriceBook(ctx context.Context, id string) (*QuoteSuccessResponse, error)

DeletePriceBook deletes a price book by ID

func (*QuoteClient) DeleteProduct added in v0.4.0

func (c *QuoteClient) DeleteProduct(ctx context.Context, id string) (*QuoteSuccessResponse, error)

DeleteProduct deletes a product by ID

func (*QuoteClient) DeleteQuote added in v0.4.0

func (c *QuoteClient) DeleteQuote(ctx context.Context, id string) (*QuoteSuccessResponse, error)

DeleteQuote deletes a quote by ID

func (*QuoteClient) DeleteTemplate added in v0.4.0

func (c *QuoteClient) DeleteTemplate(ctx context.Context, id string) (*QuoteSuccessResponse, error)

DeleteTemplate deletes a quote template by ID

func (*QuoteClient) DeleteType added in v0.4.0

func (c *QuoteClient) DeleteType(ctx context.Context, id string) (*QuoteSuccessResponse, error)

DeleteType deletes a quote type/category by ID

func (*QuoteClient) DownloadQuotePdf added in v0.4.0

func (c *QuoteClient) DownloadQuotePdf(ctx context.Context, id string) ([]byte, error)

DownloadQuotePdf downloads the PDF for a quote

func (*QuoteClient) DuplicateBundle added in v0.4.0

func (c *QuoteClient) DuplicateBundle(ctx context.Context, id string) (*Bundle, error)

DuplicateBundle duplicates a bundle

func (*QuoteClient) DuplicatePriceBook added in v0.4.0

func (c *QuoteClient) DuplicatePriceBook(ctx context.Context, id string) (*PriceBook, error)

DuplicatePriceBook duplicates a price book

func (*QuoteClient) DuplicateProduct added in v0.4.0

func (c *QuoteClient) DuplicateProduct(ctx context.Context, id string) (*Product, error)

DuplicateProduct duplicates a product

func (*QuoteClient) DuplicateQuote added in v0.4.0

func (c *QuoteClient) DuplicateQuote(ctx context.Context, id string) (*Quote, error)

DuplicateQuote duplicates a quote

func (*QuoteClient) GetBundle added in v0.4.0

func (c *QuoteClient) GetBundle(ctx context.Context, id string) (*Bundle, error)

GetBundle retrieves a bundle by ID

func (*QuoteClient) GetCompany added in v0.4.0

func (c *QuoteClient) GetCompany(ctx context.Context, id string) (*Company, error)

GetCompany retrieves a company by ID

func (*QuoteClient) GetPriceBook added in v0.4.0

func (c *QuoteClient) GetPriceBook(ctx context.Context, id string) (*PriceBook, error)

GetPriceBook retrieves a price book by ID

func (*QuoteClient) GetProduct added in v0.4.0

func (c *QuoteClient) GetProduct(ctx context.Context, id string) (*Product, error)

GetProduct retrieves a product by ID

func (*QuoteClient) GetProductPrimaryImages added in v0.4.0

func (c *QuoteClient) GetProductPrimaryImages(ctx context.Context, productIDs []string) (ProductPrimaryImagesResponse, error)

GetProductPrimaryImages retrieves primary images for the given product IDs

func (*QuoteClient) GetQuote added in v0.4.0

func (c *QuoteClient) GetQuote(ctx context.Context, id string) (*Quote, error)

GetQuote retrieves a quote by ID, including statusInfo when available

func (*QuoteClient) GetQuoteNumberConfig added in v0.6.0

func (c *QuoteClient) GetQuoteNumberConfig(ctx context.Context) (*QuoteNumberConfig, error)

GetQuoteNumberConfig retrieves the per-org quote numbering configuration (format + currentFloor). Requires an administrator API key.

func (*QuoteClient) GetTemplate added in v0.4.0

func (c *QuoteClient) GetTemplate(ctx context.Context) (*QuoteTemplate, error)

GetTemplate retrieves the default (active) quote template

func (*QuoteClient) GetTemplateByID added in v0.4.0

func (c *QuoteClient) GetTemplateByID(ctx context.Context, id string) (*QuoteTemplate, error)

GetTemplateByID retrieves a specific quote template by ID

func (*QuoteClient) HandleExpiredQuote added in v0.4.0

func (c *QuoteClient) HandleExpiredQuote(ctx context.Context, id string, request *HandleExpiredQuoteRequest) (*Quote, error)

HandleExpiredQuote resolves an expired sent quote: it voids or declines the original and returns a duplicate carrying the new validUntil date.

Action must be "void" or "decline"; Reason and NewValidUntil are both required.

func (*QuoteClient) ListBundles added in v0.4.0

func (c *QuoteClient) ListBundles(ctx context.Context, options *ListBundlesOptions) (*BundleListResponse, error)

ListBundles retrieves a paginated list of bundles

func (*QuoteClient) ListCompanies added in v0.4.0

func (c *QuoteClient) ListCompanies(ctx context.Context, options *ListCompaniesOptions) (*CompanyListResponse, error)

ListCompanies retrieves a paginated list of companies

func (*QuoteClient) ListCompanyContacts added in v0.4.0

func (c *QuoteClient) ListCompanyContacts(ctx context.Context, companyID string, options *PaginationParams) (*ContactListResponse, error)

ListCompanyContacts retrieves contacts for a specific company

func (*QuoteClient) ListContacts added in v0.4.0

func (c *QuoteClient) ListContacts(ctx context.Context, options *ListContactsOptions) (*ContactListResponse, error)

ListContacts retrieves a paginated list of contacts

func (*QuoteClient) ListLineItems added in v0.4.0

func (c *QuoteClient) ListLineItems(ctx context.Context, quoteID string, options *ListLineItemsOptions) (*LineItemListResponse, error)

ListLineItems retrieves line items for a quote

func (*QuoteClient) ListPriceBookProducts added in v0.4.0

func (c *QuoteClient) ListPriceBookProducts(ctx context.Context, id string, options *ListPriceBookProductsOptions) (*PriceBookProductListResponse, error)

ListPriceBookProducts retrieves products associated with a price book

func (*QuoteClient) ListPriceBooks added in v0.4.0

func (c *QuoteClient) ListPriceBooks(ctx context.Context, options *ListPriceBooksOptions) (*PriceBookListResponse, error)

ListPriceBooks retrieves a paginated list of price books

func (*QuoteClient) ListProducts added in v0.4.0

func (c *QuoteClient) ListProducts(ctx context.Context, options *ListProductsOptions) (*ProductListResponse, error)

ListProducts retrieves a paginated list of products

func (*QuoteClient) ListQuotes added in v0.4.0

func (c *QuoteClient) ListQuotes(ctx context.Context, options *ListQuotesOptions) (*QuoteListResponse, error)

ListQuotes retrieves a paginated list of quotes

func (*QuoteClient) ListTemplates added in v0.4.0

func (c *QuoteClient) ListTemplates(ctx context.Context, options *PaginationParams) (*QuoteTemplateListResponse, error)

ListTemplates retrieves a paginated list of quote templates

func (*QuoteClient) ListTypes added in v0.4.0

func (c *QuoteClient) ListTypes(ctx context.Context, options *ListTypesOptions) (*QuoteTypeListResponse, error)

ListTypes retrieves a paginated list of quote types/categories

func (*QuoteClient) RemoveLineItem added in v0.4.0

func (c *QuoteClient) RemoveLineItem(ctx context.Context, quoteID string, itemID string) (*QuoteSuccessResponse, error)

RemoveLineItem removes a line item from a quote

func (*QuoteClient) RemovePriceBook added in v0.4.0

func (c *QuoteClient) RemovePriceBook(ctx context.Context, quoteID string) (*Quote, error)

RemovePriceBook removes a price book from a quote

func (*QuoteClient) SendQuote added in v0.4.0

func (c *QuoteClient) SendQuote(ctx context.Context, id string, request *SendQuoteRequest) (*SendQuoteResponse, error)

SendQuote sends a quote for approval

func (*QuoteClient) SendQuoteWithDeliverable added in v0.4.0

func (c *QuoteClient) SendQuoteWithDeliverable(ctx context.Context, id string, request *SendQuoteWithDeliverableRequest) (*SendQuoteWithDeliverableResponse, error)

SendQuoteWithDeliverable sends a quote with a deliverable attachment

func (*QuoteClient) UpdateBundle added in v0.4.0

func (c *QuoteClient) UpdateBundle(ctx context.Context, id string, request *UpdateBundleRequest) (*Bundle, error)

UpdateBundle updates an existing bundle

func (*QuoteClient) UpdateCompany added in v0.4.0

func (c *QuoteClient) UpdateCompany(ctx context.Context, id string, request *UpdateCompanyRequest) (*Company, error)

UpdateCompany updates an existing company

func (*QuoteClient) UpdateContact added in v0.4.0

func (c *QuoteClient) UpdateContact(ctx context.Context, id string, request *UpdateContactRequest) (*Contact, error)

UpdateContact updates an existing contact

func (*QuoteClient) UpdateLineItem added in v0.4.0

func (c *QuoteClient) UpdateLineItem(ctx context.Context, quoteID string, itemID string, request *UpdateLineItemRequest) (*LineItem, error)

UpdateLineItem updates a line item on a quote

func (*QuoteClient) UpdatePriceBook added in v0.4.0

func (c *QuoteClient) UpdatePriceBook(ctx context.Context, id string, request *UpdatePriceBookRequest) (*PriceBook, error)

UpdatePriceBook updates an existing price book

func (*QuoteClient) UpdateProduct added in v0.4.0

func (c *QuoteClient) UpdateProduct(ctx context.Context, id string, request *UpdateProductRequest) (*Product, error)

UpdateProduct updates an existing product. If images are provided, uses multipart upload.

func (*QuoteClient) UpdateQuote added in v0.4.0

func (c *QuoteClient) UpdateQuote(ctx context.Context, id string, request *UpdateQuoteRequest) (*Quote, error)

UpdateQuote updates an existing quote

func (*QuoteClient) UpdateQuoteNumberConfig added in v0.6.0

func (c *QuoteClient) UpdateQuoteNumberConfig(ctx context.Context, format *QuoteNumberFormat) (*QuoteNumberConfig, error)

UpdateQuoteNumberConfig updates the per-org quote numbering format and returns the resulting configuration (format + currentFloor). The full format object (all eight fields) is sent as the request body. Requires an administrator API key.

func (*QuoteClient) UpdateTemplate added in v0.4.0

func (c *QuoteClient) UpdateTemplate(ctx context.Context, id string, request *UpdateQuoteTemplateRequest) (*QuoteTemplate, error)

UpdateTemplate updates an existing quote template

func (*QuoteClient) UpdateType added in v0.4.0

func (c *QuoteClient) UpdateType(ctx context.Context, id string, request *UpdateQuoteTypeRequest) (*QuoteType, error)

UpdateType updates an existing quote type/category

func (*QuoteClient) VoidQuote added in v0.4.0

func (c *QuoteClient) VoidQuote(ctx context.Context, id string, request *VoidQuoteRequest) (*Quote, error)

VoidQuote voids a quote

type QuoteClientConfig added in v0.4.0

type QuoteClientConfig struct {
	// APIKey is your TurboDocx API key
	APIKey string

	// AccessToken is an OAuth2 access token (alternative to APIKey)
	AccessToken string

	// OrgID is your Organization ID
	OrgID string

	// BaseURL is the API base URL (optional, default: https://api.turbodocx.com)
	BaseURL string
}

QuoteClientConfig holds configuration for the TurboQuote client

type QuoteCreator added in v0.4.0

type QuoteCreator struct {
	ID        string `json:"id"`
	FirstName string `json:"firstName"`
	LastName  string `json:"lastName"`
}

QuoteCreator represents the creator of a quote

type QuoteListResponse added in v0.4.0

type QuoteListResponse struct {
	Results      []Quote        `json:"results"`
	TotalRecords int            `json:"totalRecords"`
	Stats        QuoteListStats `json:"stats"`
}

QuoteListResponse is the response from listing quotes

type QuoteListStats added in v0.4.0

type QuoteListStats struct {
	Total                   int                  `json:"total"`
	Draft                   int                  `json:"draft"`
	Sent                    int                  `json:"sent"`
	Accepted                int                  `json:"accepted"`
	Declined                int                  `json:"declined"`
	Voided                  int                  `json:"voided"`
	TotalPipeline           []CurrencyTotalEntry `json:"totalPipeline"`
	ActiveQuotes            int                  `json:"activeQuotes"`
	MonthlyRecurringRevenue []CurrencyTotalEntry `json:"monthlyRecurringRevenue"`
	WinRate                 float64              `json:"winRate"`
	AvgMargin               float64              `json:"avgMargin"`
	QuotesThisMonth         int                  `json:"quotesThisMonth"`
}

QuoteListStats holds aggregate statistics returned with a quote list

type QuoteNumberConfig added in v0.6.0

type QuoteNumberConfig struct {
	Format QuoteNumberFormat `json:"format"`
	// CurrentFloor is the per-period issued floor; startNumber can't be set below this.
	CurrentFloor int `json:"currentFloor"`
}

QuoteNumberConfig is the per-org quote numbering configuration.

type QuoteNumberFormat added in v0.6.0

type QuoteNumberFormat struct {
	Prefix       string                  `json:"prefix"`
	YearToken    QuoteNumberYearToken    `json:"yearToken"`
	MonthToken   QuoteNumberMonthToken   `json:"monthToken"`
	Separator    string                  `json:"separator"`
	PadWidth     int                     `json:"padWidth"`
	Suffix       string                  `json:"suffix"`
	StartNumber  int                     `json:"startNumber"`
	ResetCadence QuoteNumberResetCadence `json:"resetCadence"`
}

QuoteNumberFormat is the per-org quote numbering format. All eight fields are required by the backend; they are sent verbatim (camelCase) on PATCH, so none use omitempty -- zero values like padWidth: 0 or an empty prefix are meaningful and must be transmitted.

type QuoteNumberMonthToken added in v0.6.0

type QuoteNumberMonthToken string

QuoteNumberMonthToken represents the month token portion of a quote number format

const (
	QuoteNumberMonthTokenOff QuoteNumberMonthToken = "off"
	QuoteNumberMonthTokenTwo QuoteNumberMonthToken = "two"
)

type QuoteNumberResetCadence added in v0.6.0

type QuoteNumberResetCadence string

QuoteNumberResetCadence represents how often the quote number sequence resets

const (
	QuoteNumberResetCadenceNever   QuoteNumberResetCadence = "never"
	QuoteNumberResetCadenceYearly  QuoteNumberResetCadence = "yearly"
	QuoteNumberResetCadenceMonthly QuoteNumberResetCadence = "monthly"
)

type QuoteNumberYearToken added in v0.6.0

type QuoteNumberYearToken string

QuoteNumberYearToken represents the year token portion of a quote number format

const (
	QuoteNumberYearTokenNone QuoteNumberYearToken = "none"
	QuoteNumberYearTokenTwo  QuoteNumberYearToken = "two"
	QuoteNumberYearTokenFour QuoteNumberYearToken = "four"
)

type QuotePaginatedResponse added in v0.4.0

type QuotePaginatedResponse struct {
	TotalRecords int `json:"totalRecords"`
}

QuotePaginatedResponse is the generic paginated response shape

type QuotePreparedBy added in v0.6.0

type QuotePreparedBy struct {
	Name  *string `json:"name,omitempty"`
	Email *string `json:"email,omitempty"`
}

QuotePreparedBy is the resolved "Prepared by" identity shown on the quote PDF and preview, returned by GetQuote alongside the quote.

Resolved server-side, not derived from Creator: it applies the org quote template first, then the creator, and for a quote created by an API key it yields the API key's label with no email (an API key has no mailbox). Prefer this over Creator for any customer-facing display — Creator may be the internal API service account.

Both fields are optional (pointers): a quote can have no resolvable sender email (e.g. an API-created quote whose org template has no sender email). Render a placeholder for a nil.

type QuoteStatus added in v0.4.0

type QuoteStatus string

QuoteStatus represents the status of a quote

const (
	QuoteStatusDraft           QuoteStatus = "draft"
	QuoteStatusPendingApproval QuoteStatus = "pending_approval"
	QuoteStatusSent            QuoteStatus = "sent"
	QuoteStatusAccepted        QuoteStatus = "accepted"
	QuoteStatusDeclined        QuoteStatus = "declined"
	QuoteStatusVoided          QuoteStatus = "voided"
)

type QuoteStatusInfo added in v0.4.0

type QuoteStatusInfo struct {
	CurrentStatus string `json:"currentStatus"`
	CanSend       bool   `json:"canSend"`
	CanAccept     bool   `json:"canAccept"`
	CanDecline    bool   `json:"canDecline"`
	CanVoid       bool   `json:"canVoid"`
	IsTerminal    bool   `json:"isTerminal"`
}

QuoteStatusInfo describes the current status capabilities of a quote

type QuoteSuccessResponse added in v0.4.0

type QuoteSuccessResponse struct {
	Message string `json:"message"`
}

QuoteSuccessResponse is a generic success response

type QuoteTemplate added in v0.4.0

type QuoteTemplate struct {
	ID                 string  `json:"id"`
	OrgID              string  `json:"orgId"`
	LogoURL            *string `json:"logoUrl"`
	PrimaryColor       string  `json:"primaryColor"`
	PrimaryTextColor   string  `json:"primaryTextColor"`
	Disclaimer         *string `json:"disclaimer"`
	TermsAndConditions *string `json:"termsAndConditions"`
	ClosingMessage     *string `json:"closingMessage"`
	SenderName         *string `json:"senderName"`
	SenderPhone        *string `json:"senderPhone"`
	SenderEmail        *string `json:"senderEmail"`
	ContactEmail       *string `json:"contactEmail"`
	IsActive           bool    `json:"isActive"`
	CreatedBy          *string `json:"createdBy"`
	CreatedOn          string  `json:"createdOn"`
	UpdatedOn          string  `json:"updatedOn"`
}

QuoteTemplate represents a quote template entity

type QuoteTemplateListResponse added in v0.4.0

type QuoteTemplateListResponse struct {
	Results      []QuoteTemplate `json:"results"`
	TotalRecords int             `json:"totalRecords"`
}

QuoteTemplateListResponse is the response from listing templates

type QuoteType added in v0.4.0

type QuoteType struct {
	ID           string          `json:"id"`
	OrgID        string          `json:"orgId"`
	Name         string          `json:"name"`
	CategoryType CategoryType    `json:"categoryType"`
	IsDefault    bool            `json:"isDefault"`
	IsActive     bool            `json:"isActive"`
	CreatedBy    *string         `json:"createdBy"`
	CreatedOn    string          `json:"createdOn"`
	UpdatedOn    string          `json:"updatedOn"`
	Usage        *QuoteTypeUsage `json:"usage,omitempty"`
}

QuoteType represents a type/category entity (product_category, pricebook_type, etc.)

type QuoteTypeListResponse added in v0.4.0

type QuoteTypeListResponse struct {
	Results      []QuoteType `json:"results"`
	TotalRecords int         `json:"totalRecords"`
}

QuoteTypeListResponse is the response from listing types

type QuoteTypeUsage added in v0.4.0

type QuoteTypeUsage struct {
	InUse      bool     `json:"inUse"`
	UsageCount int      `json:"usageCount"`
	UsedIn     []string `json:"usedIn"`
}

QuoteTypeUsage represents usage information for a type/category

type RateLimitError

type RateLimitError struct {
	TurboDocxError
}

RateLimitError is raised when rate limit is exceeded (HTTP 429)

type Recipient

type Recipient struct {
	Name  string `json:"name"`
	Email string `json:"email"`
	// SigningOrder is the 1-indexed signing order. Required, except for a recipient with a Role:
	// a template's roles sign in the order saved on the template, and recipients without a role
	// sign after them. 0 is never a valid order, so it is left off the wire.
	SigningOrder int `json:"signingOrder,omitempty"`
	// Role is the template signer role this recipient fills (e.g. "client"), when sending a
	// TemplateID whose signers and fields were set up in TurboDocx. The recipient gets every field
	// saved for that role. A role you leave out uses the signer saved on the template, if it has
	// one. List a template's roles with GetTemplateSignatureSetup.
	Role string `json:"role,omitempty"`
	// Phone is an E.164 phone number (e.g. +13055551234). Required when identity
	// verification uses SMS OTP. Optional otherwise.
	Phone string `json:"phone,omitempty"`
	// ExternalID is your own identifier for this signer (e.g. an Airtable record id), unique
	// within the document. Lets you request a signing URL by your key instead of storing
	// TurboDocx's recipient id. A whitespace-only value counts as absent (stored as null, so it
	// never collides with another blank and cannot be used to look the recipient up).
	ExternalID string `json:"externalId,omitempty"`
	// IdentityVerification configures identity verification for embedded signing. Leave nil to
	// take the org's default (EmbeddedSigningSettings.DefaultChannel): no verification when that is
	// "none", otherwise a passcode on the default channel.
	//
	// This is a POINTER on purpose: a non-pointer struct with `omitempty` would still serialize
	// as `{"mode":""}` on every existing send, changing the wire format for callers that never
	// use embedded signing. Nil omits the key entirely.
	IdentityVerification *IdentityVerification `json:"identityVerification,omitempty"`
}

Recipient represents a document recipient

type RecipientDelivery added in v0.6.2

type RecipientDelivery struct {
	// FirstSentOn is nil if this recipient has never been emailed.
	FirstSentOn *string `json:"firstSentOn"`
	LastSentOn  *string `json:"lastSentOn"`
	// TotalSent counts the request, resends, reminders, warnings and terminal notices.
	TotalSent int `json:"totalSent"`
	// ReminderCount counts AUTOMATIC (scheduled) reminders only — the counter maxReminders
	// caps. A manual "remind now" does not increment it (it must not consume the cap
	// budget), though it does land in TotalSent. So this can read 0 while reminder emails
	// have genuinely been sent.
	ReminderCount int `json:"reminderCount"`
	// LastRemindedAt is when the reminder CADENCE CLOCK was last reset — not necessarily
	// when a reminder was sent. Stamped by the initial signature-request send, each
	// scheduled reminder, each manual "remind now", and each expiry warning. Only
	// scheduled reminders bump ReminderCount, so a freshly-sent document normally shows a
	// non-nil value here alongside ReminderCount 0. Nil means "never emailed on this cadence".
	LastRemindedAt *string `json:"lastRemindedAt"`
	// WarningCount and LastWarningAt are touched only by an expiry warning.
	WarningCount  int     `json:"warningCount"`
	LastWarningAt *string `json:"lastWarningAt"`
}

RecipientDelivery is the email history for one recipient — every notification actually sent to them. CC notifications are excluded; a CC address is not a signer.

type RecipientResponse

type RecipientResponse struct {
	ID       string `json:"id"`
	Email    string `json:"email"`
	Name     string `json:"name"`
	SignURL  string `json:"signUrl,omitempty"`
	SignedAt string `json:"signedAt,omitempty"`
}

RecipientResponse represents a recipient in the response

type RecipientSignatureStatus added in v0.6.2

type RecipientSignatureStatus struct {
	ID    string `json:"id"`
	Name  string `json:"name"`
	Email string `json:"email"`
	// Status is the raw database status — only ever "pending", "viewed" or "completed".
	Status string `json:"status"`
	// EffectiveStatus is Status with the document's terminal state layered on:
	// "pending", "viewed", "completed", "voided" or "expired". Use this for display — a
	// signer on a voided document reads "voided" here but still "pending" in Status.
	// A completed signature is never revoked.
	EffectiveStatus string `json:"effectiveStatus"`
	// SignedOn is nil while the recipient is pending or has only viewed the document.
	SignedOn     *string           `json:"signedOn"`
	SigningOrder int               `json:"signingOrder"`
	Delivery     RecipientDelivery `json:"delivery"`
}

RecipientSignatureStatus is where a single recipient is in the signing process.

type RecipientStatusSummary added in v0.6.2

type RecipientStatusSummary struct {
	Total     int `json:"total"`
	Pending   int `json:"pending"`
	Viewed    int `json:"viewed"`
	Completed int `json:"completed"`
	// Voided and Expired count signers stranded by the document's terminal state.
	Voided  int `json:"voided"`
	Expired int `json:"expired"`
	// WaitingOn is who can still act (pending + viewed). Zero once the document is terminal.
	WaitingOn int `json:"waitingOn"`
}

RecipientStatusSummary rolls the roster up by effective status so callers can answer "how many are we waiting on" without looping.

type RecipientsDocument added in v0.6.2

type RecipientsDocument struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	// Status is the document-level status — the full SignatureDocumentStatus set
	// ("draft", "under_review", "completed", "voided", "expired", …).
	//
	// For per-recipient display you do NOT need to overlay this yourself: each
	// RecipientSignatureStatus already carries EffectiveStatus, which is the raw
	// recipient status with this document-level outcome layered on.
	Status    string `json:"status"`
	CreatedOn string `json:"createdOn"`
	// SentOn is when the document was dispatched to recipients; nil while it is a draft.
	SentOn    *string        `json:"sentOn"`
	ExpiresAt *string        `json:"expiresAt"`
	SentBy    DocumentSender `json:"sentBy"`
}

RecipientsDocument is the document the recipients belong to.

type ReminderResult added in v0.7.0

type ReminderResult struct {
	RecipientID string `json:"recipientId"`
	// Status is e.g. "sent", "skipped_wrong_order", "skipped_completed", or
	// "skipped_requires_single_use_url" for an external_idv or override recipient, who signs only
	// through a single-use CreateSigningURL link and is never emailed.
	Status string `json:"status"`
	// ReminderCount is the count after the send; only meaningful when Status is "sent".
	ReminderCount int `json:"reminderCount,omitempty"`
	// Phase is "reminder" or "expiring" — which email was sent.
	Phase string `json:"phase,omitempty"`
}

ReminderResult is the outcome for one recipient of a reminder request.

type RenewalPeriod added in v0.4.0

type RenewalPeriod string

RenewalPeriod represents a renewal interval

const (
	RenewalPeriodWeekly    RenewalPeriod = "weekly"
	RenewalPeriodMonthly   RenewalPeriod = "monthly"
	RenewalPeriodQuarterly RenewalPeriod = "quarterly"
	RenewalPeriodAnnually  RenewalPeriod = "annually"
)

type ResendEmailResponse

type ResendEmailResponse struct {
	Success        bool `json:"success"`
	RecipientCount int  `json:"recipientCount"`
}

ResendEmailResponse is the response from ResendEmail

type ReviewRecipient

type ReviewRecipient struct {
	ID       string                 `json:"id"`
	Name     string                 `json:"name"`
	Email    string                 `json:"email"`
	Metadata map[string]interface{} `json:"metadata,omitempty"`
}

ReviewRecipient represents a recipient in the review link response

type SendQuoteRequest added in v0.4.0

type SendQuoteRequest struct {
	CCEmails   []string `json:"ccEmails,omitempty"`
	ValidUntil *string  `json:"validUntil,omitempty"`

	// Per-send reminder + expiration overrides; omitted fields inherit the org defaults.
	SignatureSchedule
}

SendQuoteRequest is the request to send a quote.

The embedded SignatureSchedule carries the same eight reminder/expiration override fields the signature send accepts. This is a JSON endpoint, so the fields serialize FLAT on the body (camelCase) with plain {value, unit} duration objects — Go promotes the anonymous embedded struct's fields, and omitted (nil) fields inherit the org defaults.

Quote expiry is pinned to ValidUntil: ExpireAfter is ignored when expiration is on, though ExpirationEnabled still toggles it. The reminder/warning cadence must fit within ValidUntil.

type SendQuoteResponse added in v0.4.0

type SendQuoteResponse struct {
	QuoteResult Quote  `json:"quote"`
	Message     string `json:"message"`
}

SendQuoteResponse is the response from sending a quote

type SendQuoteWithDeliverableRequest added in v0.4.0

type SendQuoteWithDeliverableRequest struct {
	DeliverableID string   `json:"deliverableId"`
	MergePosition string   `json:"mergePosition"`
	CCEmails      []string `json:"ccEmails,omitempty"`

	// Per-send reminder + expiration overrides; omitted fields inherit the org defaults.
	SignatureSchedule
}

SendQuoteWithDeliverableRequest is the request to send a quote with a deliverable.

Like SendQuoteRequest, the embedded SignatureSchedule adds the eight reminder/expiration override fields; they serialize FLAT (camelCase) with {value, unit} durations on this JSON body, and the same ValidUntil-pinned expiry constraint applies.

type SendQuoteWithDeliverableResponse added in v0.4.0

type SendQuoteWithDeliverableResponse struct {
	QuoteResult Quote  `json:"quote"`
	Message     string `json:"message"`
	DocumentID  string `json:"documentId"`
}

SendQuoteWithDeliverableResponse is the response from sending a quote with a deliverable

type SendReminderResponse added in v0.7.0

type SendReminderResponse struct {
	// Results holds one entry per recipient considered, including those skipped and why.
	Results []ReminderResult `json:"results"`
}

SendReminderResponse is the response from SendReminder.

type SendSignatureRequest

type SendSignatureRequest struct {
	// File content (use this OR FileLink/DeliverableID/TemplateID)
	File []byte
	// FileName sets the stored file name for an uploaded File (max 255 chars; no extension
	// needed). Sent as a "fileName" form field; the uploaded part itself is always named
	// document.<ext>, because the API checks that extension. Empty: document.<ext> is stored.
	FileName string

	// Alternative file sources
	FileLink      string
	DeliverableID string
	TemplateID    string

	// Required
	Recipients []Recipient

	// Fields configures the signature fields. Optional when sending a template set up in
	// TurboDocx with signer roles: give each recipient a Role and the fields saved for that role
	// are used (any fields passed here are added to them).
	Fields []Field

	// Optional
	DocumentName        string
	DocumentDescription string
	SenderName          string
	SenderEmail         string
	CCEmails            []string

	// SendEmail controls whether the backend emails the recipients their signing link (and the
	// initial CC notice). Leave nil to keep the default (emails are sent). Set to false for
	// embedded signing, where your app shows the signing page: the document still goes out for
	// signing, and passcode and completed-copy emails are still sent.
	//
	// A POINTER on purpose: false ("do not email") is a meaningful value, and a truthiness/zero
	// check would drop it and silently let the backend email the recipients. Nil is not
	// forwarded, so existing callers send a byte-identical request.
	SendEmail *bool

	// Per-document reminder + expiration overrides; omitted fields inherit the org defaults.
	SignatureSchedule
}

SendSignatureRequest is the request for SendSignature

type SendSignatureResponse

type SendSignatureResponse struct {
	Success    bool              `json:"success"`
	DocumentID string            `json:"documentId"`
	Status     string            `json:"status"`
	Message    string            `json:"message"`
	Recipients []ReviewRecipient `json:"recipients"` // the API always sends it on a successful response
}

SendSignatureResponse is the response from SendSignature

type SignatureSchedule added in v0.7.0

type SignatureSchedule struct {
	// RemindersEnabled turns reminder emails on for this document.
	RemindersEnabled *bool `json:"remindersEnabled,omitempty"`
	// ReminderDelay is how long after the invitation before the FIRST reminder.
	ReminderDelay *Duration `json:"reminderDelay,omitempty"`
	// ReminderInterval is the gap between subsequent reminders.
	ReminderInterval *Duration `json:"reminderInterval,omitempty"`
	// MaxReminders caps reminders per signer. -1 means unlimited, 0 means none. Never caps
	// expiry warnings.
	MaxReminders *int `json:"maxReminders,omitempty"`
	// ExpirationEnabled closes the signing window after ExpireAfter.
	ExpirationEnabled *bool `json:"expirationEnabled,omitempty"`
	// ExpireAfter is how long the document stays signable, counted from sending.
	ExpireAfter *Duration `json:"expireAfter,omitempty"`
	// ExpirationWarning is how far BEFORE expiry warning emails start. A zero value means no
	// warnings at all.
	ExpirationWarning *Duration `json:"expirationWarning,omitempty"`
	// ExpirationWarningInterval is the gap between warnings once the window is open.
	ExpirationWarningInterval *Duration `json:"expirationWarningInterval,omitempty"`
}

SignatureSchedule holds per-document reminder + expiration overrides.

Every field is a POINTER because "unset" must stay distinguishable from a deliberate false or 0: RemindersEnabled=false (feature off), MaxReminders=0 (no reminders) and MaxReminders=-1 (unlimited) are all meaningful, and Go's zero values would otherwise silently fall back to the organization's default — the opposite of what the caller asked for.

An omitted field inherits the org default; omitting the whole set means "use the org policy as it stands at send time". Both features are off by default.

The json tags exist for the JSON send paths (e.g. TurboQuote's quote send, a JSON endpoint) where the struct is embedded and marshalled directly: the fields must land FLAT and camelCase with plain {value, unit} duration objects. The signature send paths do NOT rely on them — they copy the fields onto a multipart formData map via applyScheduleOverrides, so the tags are inert there. omitempty + pointer fields keep an unset field off the wire so it inherits the org default.

type Size

type Size struct {
	Width  int `json:"width"`
	Height int `json:"height"`
}

Size represents width and height

type SuccessResponse added in v0.2.0

type SuccessResponse struct {
	Success bool   `json:"success"`
	Message string `json:"message,omitempty"`
}

SuccessResponse is a generic success response

type Tag added in v0.3.0

type Tag struct {
	ID        string   `json:"id"`
	Label     string   `json:"label"`
	IsActive  FlexBool `json:"isActive"`
	UpdatedOn string   `json:"updatedOn"`
	CreatedOn string   `json:"createdOn"`
	CreatedBy string   `json:"createdBy"`
	OrgID     string   `json:"orgId"`
}

Tag represents a tag attached to a deliverable

type TemplateAnchor

type TemplateAnchor struct {
	Anchor        string `json:"anchor,omitempty"`
	SearchText    string `json:"searchText,omitempty"`
	Placement     string `json:"placement,omitempty"` // replace, before, after, above, below
	Size          *Size  `json:"size,omitempty"`
	Offset        *Point `json:"offset,omitempty"`
	CaseSensitive bool   `json:"caseSensitive,omitempty"`
	UseRegex      bool   `json:"useRegex,omitempty"`
}

TemplateAnchor represents template anchor configuration for dynamic field positioning

type TemplateSignatureRole added in v0.9.0

type TemplateSignatureRole struct {
	// Key is the value to pass as Recipient.Role.
	Key string `json:"key"`
	// Label is the role's name in the TurboDocx UI.
	Label string `json:"label"`
	// Order is the signing order of this role.
	Order int `json:"order"`
	// HasSavedSigner is true when the template has a saved signer for this role, used if you
	// leave the role out.
	HasSavedSigner bool `json:"hasSavedSigner"`
	// DefaultName is the saved signer's name (only when HasSavedSigner).
	DefaultName string `json:"defaultName,omitempty"`
	// DefaultEmail is the saved signer's email (only when HasSavedSigner).
	DefaultEmail string `json:"defaultEmail,omitempty"`
	// FieldCount is how many fields are saved for this role.
	FieldCount int `json:"fieldCount"`
}

TemplateSignatureRole is one signer role of a template, as returned by GetTemplateSignatureSetup.

type TemplateSignatureSetup added in v0.9.0

type TemplateSignatureSetup struct {
	TemplateID string `json:"templateId"`
	// Roles in signing order.
	Roles []TemplateSignatureRole `json:"roles"`
}

TemplateSignatureSetup is a template's signer roles, for sending it with Recipient.Role.

type TestWebhookRequest added in v0.3.0

type TestWebhookRequest struct {
	EventType string                 `json:"eventType"`
	Payload   map[string]interface{} `json:"payload"`
}

TestWebhookRequest is the payload for TestWebhook and NotifyWebhook.

type Tracking added in v0.2.0

type Tracking struct {
	NumUsers                 int   `json:"numUsers,omitempty"`
	NumProjectspaces         int   `json:"numProjectspaces,omitempty"`
	NumTemplates             int   `json:"numTemplates,omitempty"`
	StorageUsed              int64 `json:"storageUsed,omitempty"`
	NumGeneratedDeliverables int   `json:"numGeneratedDeliverables,omitempty"`
	NumSignaturesUsed        int   `json:"numSignaturesUsed,omitempty"`
	NumQuotesSent            int   `json:"numQuotesSent,omitempty"`
	// CurrentAICredits: -1 means unlimited. Every other counter floors at 0.
	CurrentAICredits int `json:"currentAICredits,omitempty"`
}

Tracking represents an organization's usage counters. These are writable via UpdateOrganizationEntitlements — unlike Features, which hold the org's limits.

The counters are maintained by database triggers, so patching one shifts a running count rather than setting a quota. Note the omitempty tags: a 0 you set is dropped rather than sent, so a counter cannot be zeroed through this struct.

type TurboDocxError

type TurboDocxError struct {
	Message    string `json:"message"`
	StatusCode int    `json:"statusCode"`
	Code       string `json:"code,omitempty"`
}

TurboDocxError represents a base API error

func (*TurboDocxError) Error

func (e *TurboDocxError) Error() string

type TurboSignClient

type TurboSignClient struct {
	// contains filtered or unexported fields
}

TurboSignClient provides digital signature operations

func NewTurboSignClient

func NewTurboSignClient(http *HTTPClient) *TurboSignClient

NewTurboSignClient creates a new TurboSign client

func (*TurboSignClient) CreateEmbeddedSignature added in v0.8.0

CreateEmbeddedSignature creates a signature request AND mints a per-recipient embedded signing URL in one call — the embedded-signing counterpart of DocuSeal's create-with-embed and Dropbox Sign's embedded flow. It is a thin WRAPPER over SendSignature + CreateSigningURL (no new endpoint), mapping the ergonomic request (per-recipient Auth + Fields shorthand) onto those calls, then assembling a per-recipient result carrying the embed URL and resolved identity mode.

Mapping:

  • Auth.EmailOTP → IdentityVerification{Mode:"otp", Channel:"email"}; Auth.SMS.PhoneNumber → {Mode:"otp", Channel:"sms"} and sets the recipient's Phone. No Auth → the org's default channel applies (GetEmbeddedSigningSettings DefaultChannel); when AllowChannelOverride is false, a different channel is rejected with OtpOverrideNotAllowed. Auth supports email or SMS passcodes only. For an external_idv or override recipient, call SendSignature with IdentityVerification on the recipient, then CreateSigningURL for each signer (with IdentityAssertion for external_idv).
  • Fields shorthand → []Field (Placement "replace" + a default size). Provide the top-level Fields to override the shorthand with full field control.
  • SigningOrder defaults to each recipient's index + 1.
  • SendEmail defaults to false (you own the UX; forwarded to the backend).
  • ReturnURL is passed through to each embed URL only when provided.

Turn-aware: with a real (sequential) signing order the backend only mints a URL for the signer whose turn it is. Rather than throw the whole call away, each result carries a Status:

  • "ready": it's their turn; EmbedURL is set, frame it now.
  • "pending": an earlier signer hasn't finished; EmbedURL is empty. Re-mint with CreateSigningURL once earlier signers complete.
  • "completed": they've already signed; EmbedURL is empty.

A genuine error (anything other than not-in-turn / already-signed) still returns.

CreateSignatureReviewLink prepares a document for review without sending emails. Use this to preview field placement before sending.

func (*TurboSignClient) CreateSigningURL added in v0.8.0

func (c *TurboSignClient) CreateSigningURL(ctx context.Context, documentID string, req *CreateSigningURLRequest) (*CreateSigningURLResponse, error)

CreateSigningURL mints an embedded signing URL for one recipient — request it the moment the signer is ready (never store it). For otp / no-verification recipients it is the reusable signing link, valid until the document expires; only external_idv / override recipients get a single-use link that expires 5 minutes after issue. The Go counterpart of the JS SDK's createSigningUrl.

Provide exactly one of RecipientID or ExternalID (both or neither is a client-side ValidationError). IdentityAssertion is only for external_idv recipients; ReturnURL, when set, must be an https URL.

func (*TurboSignClient) Download

func (c *TurboSignClient) Download(ctx context.Context, documentID string) ([]byte, error)

Download downloads the signed document as bytes. The backend returns a presigned S3 URL, which this method fetches.

func (*TurboSignClient) GetAuditTrail

func (c *TurboSignClient) GetAuditTrail(ctx context.Context, documentID string) (*AuditTrailResponse, error)

GetAuditTrail gets the audit trail for a document

func (*TurboSignClient) GetEmbeddedSigningSettings added in v0.8.0

func (c *TurboSignClient) GetEmbeddedSigningSettings(ctx context.Context) (*EmbeddedSigningSettings, error)

GetEmbeddedSigningSettings reads the org's embedded-signing settings: the set-once, org-wide gates (embedded signing enabled, external identity verification allowed, override allowed), the default OTP channel, and the allowed iframe embedding origins. Read-only.

func (*TurboSignClient) GetRecipients added in v0.6.2

func (c *TurboSignClient) GetRecipients(ctx context.Context, documentID string) (*DocumentRecipientsResponse, error)

GetRecipients gets every recipient on a document with their signing status.

Answers "who has signed and who are we still waiting on" in one call, and reports who sent the document. Summary carries the pending/viewed/completed counts.

func (*TurboSignClient) GetStatus

func (c *TurboSignClient) GetStatus(ctx context.Context, documentID string) (*DocumentStatusResponse, error)

GetStatus gets the status of a document

func (*TurboSignClient) GetTemplateSignatureSetup added in v0.9.0

func (c *TurboSignClient) GetTemplateSignatureSetup(ctx context.Context, templateID string) (*TemplateSignatureSetup, error)

GetTemplateSignatureSetup lists a template's signer roles, to send it with Recipient.Role.

A template whose signers and fields were set up in TurboDocx (upload a PDF, drag fields for each signer, save the signature setup) is sent by naming each recipient's role: the fields saved for that role come with it. This returns each role's Key (the value for Role), in signing order, whether the template has a saved signer used when you leave the role out, and its field count.

It returns a *NotFoundError (404, code SignatureSetupNotFound) when the template has no saved signature setup, or is not a template in your organization.

func (*TurboSignClient) ResendEmail

func (c *TurboSignClient) ResendEmail(ctx context.Context, documentID string, recipientIDs []string) (*ResendEmailResponse, error)

ResendEmail resends signature request email to recipients.

Recipients whose identity mode is external_idv or override sign only through a single-use CreateSigningURL link, so they are never emailed. They are skipped, and RecipientCount counts only the recipients actually emailed. When every named recipient is such a recipient, nothing can be sent and the call returns a *ConflictError (409) with Code "RecipientRequiresSingleUseUrl"; mint a link with CreateSigningURL instead.

func (*TurboSignClient) SendReminder added in v0.7.0

func (c *TurboSignClient) SendReminder(ctx context.Context, documentID string, recipientIDs []string) (*SendReminderResponse, error)

SendReminder sends a reminder email to a document's outstanding signers.

This is a standalone nudge, deliberately decoupled from the automatic reminder schedule: it ignores the configured cadence, works even when reminders are disabled or the per-signer cap is already spent, and does not consume that cap.

Only signers at the CURRENT signing order are emailed. A recipient at a later order (or one who has already signed) is reported back as skipped rather than silently dropped, so the caller can tell that nobody was emailed.

Pass nil (or an empty slice) for recipientIDs to remind every eligible signer. When ids are supplied the request is all-or-nothing: if any is not a current-order pending signer the API rejects the whole call and sends nothing.

Recipients whose identity mode is external_idv or override sign only through a single-use CreateSigningURL link, so they are never emailed and come back as "skipped_requires_single_use_url". Naming only such recipients returns a *ConflictError (409) with Code "RecipientRequiresSingleUseUrl"; mint a link with CreateSigningURL instead.

func (*TurboSignClient) SendSignature

SendSignature prepares a document for signing and sends emails in a single call.

func (*TurboSignClient) VoidDocument

func (c *TurboSignClient) VoidDocument(ctx context.Context, documentID string, reason string) (*VoidDocumentResponse, error)

VoidDocument voids a document (cancels signature request)

type UpdateBundleRequest added in v0.4.0

type UpdateBundleRequest struct {
	Name                  *string           `json:"name,omitempty"`
	Items                 []BundleItemInput `json:"items,omitempty"`
	Description           *string           `json:"description,omitempty"`
	Sku                   *string           `json:"sku,omitempty"`
	CategoryID            *string           `json:"categoryId,omitempty"`
	BundleDiscountPercent *float64          `json:"bundleDiscountPercent,omitempty"`
	BundleDiscountType    *DiscountType     `json:"bundleDiscountType,omitempty"`
	BundleDiscountAmount  *float64          `json:"bundleDiscountAmount,omitempty"`
	CurrencyCode          *string           `json:"currency,omitempty"`
	ShowItemsToEndUser    *bool             `json:"showItemsToEndUser,omitempty"`
	ShowInCatalog         *bool             `json:"showInCatalog,omitempty"`
	SyncWithProducts      *bool             `json:"syncWithProducts,omitempty"`
	// contains filtered or unexported fields
}

UpdateBundleRequest is the request to update a bundle

func (*UpdateBundleRequest) ClearCategoryID added in v0.4.0

func (r *UpdateBundleRequest) ClearCategoryID()

ClearCategoryID explicitly sets categoryId to null in the JSON payload.

func (*UpdateBundleRequest) ClearDescription added in v0.4.0

func (r *UpdateBundleRequest) ClearDescription()

ClearDescription explicitly sets description to null in the JSON payload.

func (*UpdateBundleRequest) ClearSku added in v0.4.0

func (r *UpdateBundleRequest) ClearSku()

ClearSku explicitly sets sku to null in the JSON payload.

func (UpdateBundleRequest) MarshalJSON added in v0.4.0

func (r UpdateBundleRequest) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshaling to include explicitly-nulled fields.

type UpdateCompanyRequest added in v0.4.0

type UpdateCompanyRequest struct {
	Name       *string `json:"name,omitempty"`
	Phone      *string `json:"phone,omitempty"`
	City       *string `json:"city,omitempty"`
	State      *string `json:"state,omitempty"`
	Country    *string `json:"country,omitempty"`
	IndustryID *string `json:"industryId,omitempty"`
	// contains filtered or unexported fields
}

UpdateCompanyRequest is the request to update a company

func (*UpdateCompanyRequest) ClearCity added in v0.4.0

func (r *UpdateCompanyRequest) ClearCity()

ClearCity explicitly sets city to null in the JSON payload.

func (*UpdateCompanyRequest) ClearCountry added in v0.4.0

func (r *UpdateCompanyRequest) ClearCountry()

ClearCountry explicitly sets country to null in the JSON payload.

func (*UpdateCompanyRequest) ClearIndustryID added in v0.4.0

func (r *UpdateCompanyRequest) ClearIndustryID()

ClearIndustryID explicitly sets industryId to null in the JSON payload.

func (*UpdateCompanyRequest) ClearPhone added in v0.4.0

func (r *UpdateCompanyRequest) ClearPhone()

ClearPhone explicitly sets phone to null in the JSON payload.

func (*UpdateCompanyRequest) ClearState added in v0.4.0

func (r *UpdateCompanyRequest) ClearState()

ClearState explicitly sets state to null in the JSON payload.

func (UpdateCompanyRequest) MarshalJSON added in v0.4.0

func (r UpdateCompanyRequest) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshaling to include explicitly-nulled fields.

type UpdateContactRequest added in v0.4.0

type UpdateContactRequest struct {
	Name  *string `json:"name,omitempty"`
	Email *string `json:"email,omitempty"`
	Phone *string `json:"phone,omitempty"`
	Title *string `json:"title,omitempty"`
	// contains filtered or unexported fields
}

UpdateContactRequest is the request to update a contact

func (*UpdateContactRequest) ClearEmail added in v0.4.0

func (r *UpdateContactRequest) ClearEmail()

ClearEmail explicitly sets email to null in the JSON payload.

func (*UpdateContactRequest) ClearPhone added in v0.4.0

func (r *UpdateContactRequest) ClearPhone()

ClearPhone explicitly sets phone to null in the JSON payload.

func (*UpdateContactRequest) ClearTitle added in v0.4.0

func (r *UpdateContactRequest) ClearTitle()

ClearTitle explicitly sets title to null in the JSON payload.

func (UpdateContactRequest) MarshalJSON added in v0.4.0

func (r UpdateContactRequest) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshaling to include explicitly-nulled fields.

type UpdateDeliverableRequest added in v0.3.0

type UpdateDeliverableRequest struct {
	// Updated name (3-255 characters)
	Name string `json:"name,omitempty"`
	// Updated description
	Description string `json:"description,omitempty"`
	// Replace all tags (pass empty slice to remove all)
	Tags *[]string `json:"tags,omitempty"`
}

UpdateDeliverableRequest is the request for UpdateDeliverableInfo

type UpdateDeliverableResponse added in v0.3.0

type UpdateDeliverableResponse struct {
	Message       string `json:"message"`
	DeliverableID string `json:"deliverableId"`
}

UpdateDeliverableResponse is the response from UpdateDeliverableInfo

type UpdateEntitlementsRequest added in v0.2.0

type UpdateEntitlementsRequest struct {
	Features *Features `json:"features,omitempty"`
	Tracking *Tracking `json:"tracking,omitempty"`
}

UpdateEntitlementsRequest is the request to update organization entitlements

type UpdateLineItemRequest added in v0.4.0

type UpdateLineItemRequest struct {
	Quantity           *int          `json:"quantity,omitempty"`
	UnitPrice          *float64      `json:"unitPrice,omitempty"`
	DiscountPercent    *float64      `json:"discountPercent,omitempty"`
	DiscountType       *DiscountType `json:"discountType,omitempty"`
	DiscountAmount     *float64      `json:"discountAmount,omitempty"`
	DisplayOrder       *int          `json:"displayOrder,omitempty"`
	BillingFrequency   *string       `json:"billingFrequency,omitempty"`
	CategoryID         *string       `json:"categoryId,omitempty"`
	CategoryName       *string       `json:"categoryName,omitempty"`
	Cost               *float64      `json:"cost,omitempty"`
	ShowItemsToEndUser *bool         `json:"showItemsToEndUser,omitempty"`
	ProductName        *string       `json:"productName,omitempty"`
	ProductSku         *string       `json:"productSku,omitempty"`
	ProductDescription *string       `json:"productDescription,omitempty"`
	// contains filtered or unexported fields
}

UpdateLineItemRequest is the request to update a line item

func (*UpdateLineItemRequest) ClearCategoryID added in v0.4.0

func (r *UpdateLineItemRequest) ClearCategoryID()

ClearCategoryID explicitly sets categoryId to null in the JSON payload.

func (*UpdateLineItemRequest) ClearCategoryName added in v0.4.0

func (r *UpdateLineItemRequest) ClearCategoryName()

ClearCategoryName explicitly sets categoryName to null in the JSON payload.

func (*UpdateLineItemRequest) ClearCost added in v0.4.0

func (r *UpdateLineItemRequest) ClearCost()

ClearCost explicitly sets cost to null in the JSON payload.

func (*UpdateLineItemRequest) ClearDisplayOrder added in v0.4.0

func (r *UpdateLineItemRequest) ClearDisplayOrder()

ClearDisplayOrder explicitly sets displayOrder to null in the JSON payload.

func (*UpdateLineItemRequest) ClearProductDescription added in v0.4.0

func (r *UpdateLineItemRequest) ClearProductDescription()

ClearProductDescription explicitly sets productDescription to null in the JSON payload.

func (*UpdateLineItemRequest) ClearProductSku added in v0.4.0

func (r *UpdateLineItemRequest) ClearProductSku()

ClearProductSku explicitly sets productSku to null in the JSON payload.

func (UpdateLineItemRequest) MarshalJSON added in v0.4.0

func (r UpdateLineItemRequest) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshaling to include explicitly-nulled fields.

type UpdateOrgAPIKeyRequest added in v0.4.0

type UpdateOrgAPIKeyRequest struct {
	Name string `json:"name,omitempty"`
	Role string `json:"role,omitempty"` // admin | contributor | user | viewer
}

UpdateOrgAPIKeyRequest is the request to update an organization API key

type UpdateOrgApiKeyRequest deprecated added in v0.2.0

type UpdateOrgApiKeyRequest = UpdateOrgAPIKeyRequest

Deprecated: use UpdateOrgAPIKeyRequest.

type UpdateOrgPreferencesRequest added in v0.8.0

type UpdateOrgPreferencesRequest struct {
	HideSignatureOutline       *bool `json:"hideSignatureOutline,omitempty"`
	HideSignatureHash          *bool `json:"hideSignatureHash,omitempty"`
	LockedFieldsBackground     *bool `json:"lockedFieldsBackground,omitempty"`
	AllowDownloadBeforeSigning *bool `json:"allowDownloadBeforeSigning,omitempty"`
}

UpdateOrgPreferencesRequest is the partial set of TurboSign display preferences to change. Only the keys you set are sent (pointers with omitempty); a nil field is left untouched.

type UpdateOrgUserRequest added in v0.2.0

type UpdateOrgUserRequest struct {
	Role string `json:"role"` // admin | contributor | user | viewer
}

UpdateOrgUserRequest is the request to update an organization user's role

type UpdateOrganizationRequest added in v0.2.0

type UpdateOrganizationRequest struct {
	Name string `json:"name"`
}

UpdateOrganizationRequest is the request to update an organization

type UpdatePartnerAPIKeyRequest added in v0.4.0

type UpdatePartnerAPIKeyRequest struct {
	Name        string   `json:"name,omitempty"`
	Description string   `json:"description,omitempty"`
	Scopes      []string `json:"scopes,omitempty"`
}

UpdatePartnerAPIKeyRequest is the request to update a partner API key

type UpdatePartnerApiKeyRequest deprecated added in v0.2.0

type UpdatePartnerApiKeyRequest = UpdatePartnerAPIKeyRequest

Deprecated: use UpdatePartnerAPIKeyRequest.

type UpdatePartnerUserRequest added in v0.2.0

type UpdatePartnerUserRequest struct {
	Role        string              `json:"role,omitempty"` // admin | member | viewer
	Permissions *PartnerPermissions `json:"permissions,omitempty"`
}

UpdatePartnerUserRequest is the request to update a partner user.

Permissions is optional, but when set it must carry all 7 keys — see PartnerPermissions.

type UpdatePriceBookRequest added in v0.4.0

type UpdatePriceBookRequest struct {
	Name               *string                        `json:"name,omitempty"`
	PriceBookTypeID    *string                        `json:"priceBookTypeId,omitempty"`
	Description        *string                        `json:"description,omitempty"`
	DiscountPercent    *float64                       `json:"discountPercent,omitempty"`
	ValidFrom          *string                        `json:"validFrom,omitempty"`
	ValidTo            *string                        `json:"validTo,omitempty"`
	IsDefault          *bool                          `json:"isDefault,omitempty"`
	ShowInQuoteBuilder *bool                          `json:"showInQuoteBuilder,omitempty"`
	ProductPricing     []PriceBookProductPricingInput `json:"productPricing,omitempty"`
	// contains filtered or unexported fields
}

UpdatePriceBookRequest is the request to update a price book

func (*UpdatePriceBookRequest) ClearDescription added in v0.4.0

func (r *UpdatePriceBookRequest) ClearDescription()

ClearDescription explicitly sets description to null in the JSON payload.

func (*UpdatePriceBookRequest) ClearValidTo added in v0.4.0

func (r *UpdatePriceBookRequest) ClearValidTo()

ClearValidTo explicitly sets validTo to null in the JSON payload.

func (UpdatePriceBookRequest) MarshalJSON added in v0.4.0

func (r UpdatePriceBookRequest) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshaling to include explicitly-nulled fields.

type UpdateProductRequest added in v0.4.0

type UpdateProductRequest struct {
	Name                  *string  `json:"name,omitempty"`
	ListPrice             *float64 `json:"listPrice,omitempty"`
	BillingFrequency      *string  `json:"billingFrequency,omitempty"`
	Sku                   *string  `json:"sku,omitempty"`
	Description           *string  `json:"description,omitempty"`
	DetailedSpecification *string  `json:"detailedSpecification,omitempty"`
	InternalNotes         *string  `json:"internalNotes,omitempty"`
	CategoryID            *string  `json:"categoryId,omitempty"`
	Cost                  *float64 `json:"cost,omitempty"`
	MinimumOrderQuantity  *int     `json:"minimumOrderQuantity,omitempty"`
	CurrencyCode          *string  `json:"currency,omitempty"`
	ShowInCatalog         *bool    `json:"showInCatalog,omitempty"`
	ImageIDsToKeep        []string `json:"imageIdsToKeep,omitempty"`
	ImageOrder            []string `json:"imageOrder,omitempty"`

	// Images for multipart upload
	Images []ProductImageInput `json:"-"`
	// contains filtered or unexported fields
}

UpdateProductRequest is the request to update a product

func (*UpdateProductRequest) ClearCost added in v0.4.0

func (r *UpdateProductRequest) ClearCost()

ClearCost explicitly sets cost to null in the JSON payload.

func (*UpdateProductRequest) ClearDescription added in v0.4.0

func (r *UpdateProductRequest) ClearDescription()

ClearDescription explicitly sets description to null in the JSON payload.

func (*UpdateProductRequest) ClearDetailedSpecification added in v0.4.0

func (r *UpdateProductRequest) ClearDetailedSpecification()

ClearDetailedSpecification explicitly sets detailedSpecification to null in the JSON payload.

func (*UpdateProductRequest) ClearInternalNotes added in v0.4.0

func (r *UpdateProductRequest) ClearInternalNotes()

ClearInternalNotes explicitly sets internalNotes to null in the JSON payload.

func (*UpdateProductRequest) ClearSku added in v0.4.0

func (r *UpdateProductRequest) ClearSku()

ClearSku explicitly sets sku to null in the JSON payload.

func (UpdateProductRequest) MarshalJSON added in v0.4.0

func (r UpdateProductRequest) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshaling to include explicitly-nulled fields.

type UpdateQuoteRequest added in v0.4.0

type UpdateQuoteRequest struct {
	Name          *string  `json:"name,omitempty"`
	CompanyID     *string  `json:"companyId,omitempty"`
	ContactID     *string  `json:"contactId,omitempty"`
	TermDays      *int     `json:"termDays,omitempty"`      // max 3650; -1 = auto-renewal
	RenewalPeriod *string  `json:"renewalPeriod,omitempty"` // weekly|monthly|quarterly|annually; only with TermDays -1
	ValidUntil    *string  `json:"validUntil,omitempty"`
	TaxRate       *float64 `json:"taxRate,omitempty"`
	CurrencyCode  *string  `json:"currency,omitempty"`
	PriceBookID   *string  `json:"priceBookId,omitempty"`
	// contains filtered or unexported fields
}

UpdateQuoteRequest is the request to update a quote.

RenewalPeriod is required when TermDays is -1 (auto-renewal) and must be absent otherwise. Use ClearRenewalPeriod to explicitly null it out when moving a quote off auto-renewal.

func (*UpdateQuoteRequest) ClearPriceBookID added in v0.4.0

func (r *UpdateQuoteRequest) ClearPriceBookID()

ClearPriceBookID explicitly sets priceBookId to null in the JSON payload.

func (*UpdateQuoteRequest) ClearRenewalPeriod added in v0.4.0

func (r *UpdateQuoteRequest) ClearRenewalPeriod()

ClearRenewalPeriod explicitly sets renewalPeriod to null in the JSON payload.

func (*UpdateQuoteRequest) ClearTaxRate added in v0.4.0

func (r *UpdateQuoteRequest) ClearTaxRate()

ClearTaxRate explicitly sets taxRate to null in the JSON payload.

func (*UpdateQuoteRequest) ClearValidUntil added in v0.4.0

func (r *UpdateQuoteRequest) ClearValidUntil()

ClearValidUntil explicitly sets validUntil to null in the JSON payload.

func (UpdateQuoteRequest) MarshalJSON added in v0.4.0

func (r UpdateQuoteRequest) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshaling to include explicitly-nulled fields.

type UpdateQuoteTemplateRequest added in v0.4.0

type UpdateQuoteTemplateRequest struct {
	LogoURL            *string `json:"logoUrl,omitempty"`
	PrimaryColor       *string `json:"primaryColor,omitempty"`
	PrimaryTextColor   *string `json:"primaryTextColor,omitempty"`
	Disclaimer         *string `json:"disclaimer,omitempty"`
	TermsAndConditions *string `json:"termsAndConditions,omitempty"`
	ClosingMessage     *string `json:"closingMessage,omitempty"`
	SenderName         *string `json:"senderName,omitempty"`
	SenderPhone        *string `json:"senderPhone,omitempty"`
	SenderEmail        *string `json:"senderEmail,omitempty"`
	ContactEmail       *string `json:"contactEmail,omitempty"`
	// contains filtered or unexported fields
}

UpdateQuoteTemplateRequest is the request to update a quote template

func (*UpdateQuoteTemplateRequest) ClearClosingMessage added in v0.4.0

func (r *UpdateQuoteTemplateRequest) ClearClosingMessage()

ClearClosingMessage explicitly sets closingMessage to null in the JSON payload.

func (*UpdateQuoteTemplateRequest) ClearContactEmail added in v0.4.0

func (r *UpdateQuoteTemplateRequest) ClearContactEmail()

ClearContactEmail explicitly sets contactEmail to null in the JSON payload.

func (*UpdateQuoteTemplateRequest) ClearDisclaimer added in v0.4.0

func (r *UpdateQuoteTemplateRequest) ClearDisclaimer()

ClearDisclaimer explicitly sets disclaimer to null in the JSON payload.

func (*UpdateQuoteTemplateRequest) ClearLogoURL added in v0.4.0

func (r *UpdateQuoteTemplateRequest) ClearLogoURL()

ClearLogoURL explicitly sets logoUrl to null in the JSON payload.

func (*UpdateQuoteTemplateRequest) ClearSenderName added in v0.4.0

func (r *UpdateQuoteTemplateRequest) ClearSenderName()

ClearSenderName explicitly sets senderName to null in the JSON payload.

func (*UpdateQuoteTemplateRequest) ClearSenderPhone added in v0.4.0

func (r *UpdateQuoteTemplateRequest) ClearSenderPhone()

ClearSenderPhone explicitly sets senderPhone to null in the JSON payload.

func (*UpdateQuoteTemplateRequest) ClearTermsAndConditions added in v0.4.0

func (r *UpdateQuoteTemplateRequest) ClearTermsAndConditions()

ClearTermsAndConditions explicitly sets termsAndConditions to null in the JSON payload.

func (UpdateQuoteTemplateRequest) MarshalJSON added in v0.4.0

func (r UpdateQuoteTemplateRequest) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshaling to include explicitly-nulled fields.

type UpdateQuoteTypeRequest added in v0.4.0

type UpdateQuoteTypeRequest struct {
	Name *string `json:"name,omitempty"`
}

UpdateQuoteTypeRequest is the request to update a type/category

type UpdateWebhookRequest added in v0.3.0

type UpdateWebhookRequest struct {
	URLs     []string `json:"urls,omitempty"`   // nil to leave unchanged; otherwise min 1, max 10
	Events   []string `json:"events,omitempty"` // nil to leave unchanged; otherwise min 1
	IsActive *bool    `json:"isActive,omitempty"`
}

UpdateWebhookRequest contains the fields that can be patched on the signature webhook. Renaming is not supported — the SDK manages a fixed name. Use a pointer or nil to leave a field unchanged.

The list minimums survive the patch: a list you do send must be non-empty (and URLs at most 10). An empty slice is omitted from the payload rather than sent as [], so it leaves the existing list untouched — there is no way to clear all URLs or events.

type ValidationError

type ValidationError struct {
	TurboDocxError
}

ValidationError is raised when validation fails (HTTP 400)

type VariableStackEntry added in v0.3.0

type VariableStackEntry struct {
	Text     string `json:"text"`
	MimeType string `json:"mimeType"`
}

VariableStackEntry represents a single entry in a variable stack

type VerifyWebhookSignatureOptions added in v0.3.0

type VerifyWebhookSignatureOptions struct {
	// ToleranceSeconds is the maximum acceptable age of the timestamp header,
	// in seconds. 0 (the zero value) means use DefaultWebhookToleranceSeconds,
	// so the Go helper has no way to turn the timestamp check off. A negative
	// value fails closed: every delivery is rejected.
	ToleranceSeconds int

	// Now overrides the "current time" function for deterministic testing.
	// Returns Unix epoch seconds. If nil, time.Now().Unix() is used.
	Now func() int64
}

VerifyWebhookSignatureOptions configures VerifyWebhookSignature.

type VoidDocumentResponse

type VoidDocumentResponse struct {
	ID         string `json:"id"`
	Name       string `json:"name"`
	Status     string `json:"status"`
	VoidReason string `json:"voidReason,omitempty"`
	VoidedAt   string `json:"voidedAt,omitempty"`
}

VoidDocumentResponse is the response from VoidDocument

type VoidQuoteRequest added in v0.4.0

type VoidQuoteRequest struct {
	Reason string `json:"reason"`
}

VoidQuoteRequest is the request to void a quote

type WebhookEvent added in v0.6.0

type WebhookEvent string

WebhookEvent is the wire string for a TurboSign webhook event.

The Events fields on CreateWebhookRequest and UpdateWebhookRequest remain []string, so code that already passes raw strings keeps compiling and the backend can add events without an SDK release. Convert a typed event with string(event), or build the whole slice with WebhookEventStrings.

const (
	// WebhookEventSent fires when the document is dispatched to recipients.
	WebhookEventSent WebhookEvent = "signature.document.sent"

	// WebhookEventViewed fires when a recipient opens the document for the
	// first time.
	WebhookEventViewed WebhookEvent = "signature.document.viewed"

	// WebhookEventRecipientSigned fires when any individual signer completes
	// their signature — once PER SIGNER, including the last one. The payload
	// carries the signer's identity plus is_final_signer (true only on the last
	// signature) and remaining_signers.
	//
	// This is the per-person event, and it always fires before the
	// document-level outcome (signed, completed, or finalization_failed).
	WebhookEventRecipientSigned WebhookEvent = "signature.document.recipient_signed"

	// WebhookEventSigned fires when a signer signs but the document is NOT yet
	// complete — document-level partial progress.
	//
	// Two consequences worth internalizing:
	//   - It NEVER fires on the final signature. To detect "the whole document
	//     is done", use WebhookEventCompleted (or WebhookEventRecipientSigned
	//     with is_final_signer: true) — NOT this event.
	//   - A single-signer document never emits it at all. That document emits
	//     recipient_signed (is_final_signer: true) then completed.
	WebhookEventSigned WebhookEvent = "signature.document.signed"

	// WebhookEventCompleted fires when all recipients have signed and the
	// signed PDF is finalized.
	WebhookEventCompleted WebhookEvent = "signature.document.completed"

	// WebhookEventFinalizationFailed fires when the signed PDF fails to
	// finalize (e.g. a KMS signing error). The document is NOT completed —
	// this fires INSTEAD OF completed on the final signature.
	WebhookEventFinalizationFailed WebhookEvent = "signature.document.finalization_failed"

	// WebhookEventVoided fires when the document is voided or cancelled.
	WebhookEventVoided WebhookEvent = "signature.document.voided"
)

func (WebhookEvent) String added in v0.6.0

func (e WebhookEvent) String() string

String returns the event's wire string.

type WebhooksClient added in v0.3.0

type WebhooksClient struct {
	// contains filtered or unexported fields
}

WebhooksClient provides org-scoped management of the org's "signature" webhook.

The SDK is intentionally locked to a single webhook per org, identified by the fixed name `signature`. This matches the UI's Signature Webhooks settings page so SDK-managed and UI-managed webhooks stay in sync. To manage multiple webhooks per org, call the REST API directly.

Construct via NewWebhooksClient or NewWebhooksClientWithConfig.

func NewWebhooksClient added in v0.3.0

func NewWebhooksClient(apiKey, orgID string) (*WebhooksClient, error)

NewWebhooksClient creates a WebhooksClient with the given API key + org ID.

func NewWebhooksClientWithConfig added in v0.3.0

func NewWebhooksClientWithConfig(config ClientConfig) (*WebhooksClient, error)

NewWebhooksClientWithConfig creates a WebhooksClient. Unlike NewClientWithConfig, this does NOT require SenderEmail since webhook routes don't send signature emails.

func (*WebhooksClient) CreateWebhook added in v0.3.0

CreateWebhook creates the org's signature webhook. The returned Secret is shown ONCE; store it on receipt — it cannot be retrieved later.

Returns *ConflictError (HTTP 409) if a webhook with the signature name already exists for the org.

func (*WebhooksClient) DeleteWebhook added in v0.3.0

func (c *WebhooksClient) DeleteWebhook(ctx context.Context) (map[string]interface{}, error)

DeleteWebhook soft-deletes the signature webhook and its delivery history.

func (*WebhooksClient) GetWebhook added in v0.3.0

func (c *WebhooksClient) GetWebhook(ctx context.Context) (map[string]interface{}, error)

GetWebhook fetches the org's signature webhook with current delivery stats and the server-provided list of subscribable events. Returns the raw JSON as a map so callers can read evolving fields without SDK upgrades.

func (*WebhooksClient) GetWebhookStats added in v0.3.0

func (c *WebhooksClient) GetWebhookStats(ctx context.Context, days int) (map[string]interface{}, error)

GetWebhookStats returns aggregate delivery stats for the signature webhook over a sliding window. Pass 0 for days to use the backend default (30).

func (*WebhooksClient) ListWebhookDeliveries added in v0.3.0

func (c *WebhooksClient) ListWebhookDeliveries(ctx context.Context, req ListDeliveriesRequest) (map[string]interface{}, error)

ListWebhookDeliveries returns historical delivery attempts for the signature webhook, with optional filters.

func (*WebhooksClient) NotifyWebhook added in v0.3.0

func (c *WebhooksClient) NotifyWebhook(ctx context.Context, req TestWebhookRequest) (map[string]interface{}, error)

NotifyWebhook sends a manual notification to all URLs configured on the signature webhook.

NOTE: Routes through the same backend handler as TestWebhook and returns the same shape; only the response/error message strings differ. Prefer TestWebhook in new code.

func (*WebhooksClient) RegenerateWebhookSecret added in v0.3.0

func (c *WebhooksClient) RegenerateWebhookSecret(ctx context.Context) (map[string]interface{}, error)

RegenerateWebhookSecret rotates the webhook's HMAC secret. The new secret is shown ONCE in the response and must be saved; old signatures will fail immediately.

func (*WebhooksClient) ReplayWebhookDelivery added in v0.3.0

func (c *WebhooksClient) ReplayWebhookDelivery(ctx context.Context, deliveryID string) (map[string]interface{}, error)

ReplayWebhookDelivery manually retries a specific past delivery by ID.

func (*WebhooksClient) TestWebhook added in v0.3.0

func (c *WebhooksClient) TestWebhook(ctx context.Context, req TestWebhookRequest) (map[string]interface{}, error)

TestWebhook sends a test delivery to all URLs configured on the signature webhook.

func (*WebhooksClient) UpdateWebhook added in v0.3.0

func (c *WebhooksClient) UpdateWebhook(ctx context.Context, req UpdateWebhookRequest) (map[string]interface{}, error)

UpdateWebhook patches one or more fields on the signature webhook.

Returns *ConflictError (HTTP 409) if the patch conflicts with an existing webhook name for the org.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL