tabscanner

package module
v0.0.0-...-6e574c8 Latest Latest
Warning

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

Go to latest
Published: Apr 23, 2019 License: MIT Imports: 13 Imported by: 0

README

tabscanner Build Status Go Report Card Test Coverage Go Docs

This package is a Go client for TabScanner. Use the straight Client for low level access to the API, or a Processor for simplified access (it automatically parses errors and polls for results).

c := tabscanner.NewClient("my_api_key")
p := tabscanner.NewProcessor(c)

buf, err := ioutil.ReadFile("my_receipt.jpg")
require.NoError(t, err)

result, err := p.Process(context.Background(), &tabscanner.ProcessRequest{
  ReceiptImage:  buf,
  DecimalPlaces: tabscanner.IntPtr(2),
  Language:      tabscanner.LanguageEnglish,
  LineExtract:   tabscanner.BoolPtr(true),
  DocumentType:  tabscanner.DocumentTypeReceipt,
})
if err != nil {
  return err
}

fmt.Println(result)

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultPollingStrategy = func(retry int) time.Duration {
	switch {
	case retry == 0:
		return 0
	case retry > 180:
		return -1
	default:
		return 5 * time.Second
	}
}

DefaultPollingStrategy tries every five seconds, for up to three minutes.

Functions

func BoolPtr

func BoolPtr(b bool) *bool

BoolPtr returns a pointer to the given bool.

func IntPtr

func IntPtr(i int) *int

IntPtr returns a pointer to the given int.

func ParseMoney

func ParseMoney(v string, decimals int) (int64, error)

ParseMoney parses a money amount assuming the given number of decimals. It returns an integer representing a fixed point money value (e.g. ("10.010", 2) -> 1001). Excess decimals are truncated.

Types

type Client

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

Client describes a TabScanner client.

func NewClient

func NewClient(apiKey string, options ...ClientOption) *Client

NewClient initializes a new Client.

func (*Client) Process

func (c *Client) Process(ctx context.Context, req *ProcessRequest) (*ProcessResponse, error)

Process uploads a receipt for processing.

func (*Client) Result

func (c *Client) Result(ctx context.Context, token string) (*ResultResponse, error)

Result fetches the processing result for a receipt.

type ClientOption

type ClientOption func(*Client)

ClientOption describes a configuration option for the Client.

func HTTPClientOption

func HTTPClientOption(httpClient *http.Client) ClientOption

HTTPClientOption allows to inject an HTTP client.

type Code

type Code int

Code represents an operation result code.

const (
	CodeImageUploadedSuccessfully                         Code = 200
	CodeAPIKeyAuthenticated                               Code = 201
	CodeResultAvailable                                   Code = 202
	CodeImageUploadedButDidNotMeetTheRecommendedDimension Code = 300
	CodeResultNotYetAvailable                             Code = 301
	CodeAPIKeyNotFound                                    Code = 400
	CodeNotEnoughCredit                                   Code = 401
	CodeTokenNotFound                                     Code = 402
	CodeNoFileDetected                                    Code = 403
	CodeMultipleFilesDetected                             Code = 404
	CodeUnsupportedMimeType                               Code = 405
	CodeFormParserError                                   Code = 406
	CodeUnsupportedFileExtension                          Code = 407
	CodeFileSystemError                                   Code = 408
	CodeOCRFailure                                        Code = 500
	CodeServerError                                       Code = 510
	CodeDatabaseConnectionError                           Code = 520
	CodeDatabaseQueryError                                Code = 521
)

Known codes.

type DocumentType

type DocumentType string

DocumentType describes a document type.

const (
	DocumentTypeReceipt DocumentType = "receipt"
	DocumentTypeInvoice DocumentType = "invoice"
	DocumentTypeAuto    DocumentType = "auto"
)

Known document types.

type ErrAPI

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

ErrAPI wraps the ResponseHeader for a failure response as an error.

func (*ErrAPI) Error

func (e *ErrAPI) Error() string

Error implements the error interface.

func (*ErrAPI) ResponseHeader

func (e *ErrAPI) ResponseHeader() *ResponseHeader

ResponseHeader returns the ResponseHeader for this error.

type ErrTimedOut

type ErrTimedOut struct {
}

ErrTimedOut is returned when the Processor cannot obtain a result after having exhausted all polling retries.

func (*ErrTimedOut) Error

func (e *ErrTimedOut) Error() string

Error implements the error interface.

type Language

type Language string

Language describes the language of a receipt.

const (
	LanguageEnglish Language = "english"
	LanguageSpanish Language = "spanish"
)

Known languages.

type PollingStrategy

type PollingStrategy func(retry int) time.Duration

PollingStrategy describes a polling strategy for results. Delay is called before each call to the result endpoint, with monotonically increasing values of retry, starting from 0. If the returned value is >= 0, the processor waits the returned duration and retries, otherwise it stops and returns an error.

type ProcessRequest

type ProcessRequest struct {
	ReceiptImage  []byte       // mime-type is automatically detected
	DecimalPlaces *int         // valid values: nil, 0, 2, 3
	Language      Language     // valid values: "", LanguageEnglish, LanguageSpanish
	Cents         *bool        // valid values: nil, false, true
	LineExtract   *bool        // valid values: nil, false, true
	DocumentType  DocumentType // valid values: "", DocumentTypeReceipt, DocumentTypeInvoice, DocumentTypeAuto
	TestMode      *bool        // valid values: nil, false, true
}

ProcessRequest describes a process request. Specify only one of ReceiptImageHeader or ReceiptImage data.

type ProcessResponse

type ProcessResponse struct {
	*ResponseHeader
	Duplicate      bool   `json:"duplicate"`
	DuplicateToken string `json:"duplicateToken"`
}

ProcessResponse describes a process response.

type Processor

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

Processor provides a simplified way to scan receipts, implementing automatic error handling an polling for results.

func NewProcessor

func NewProcessor(client *Client, options ...ProcessorOption) *Processor

NewProcessor initializes a new Processor.

func (*Processor) Process

Process uploads a receipt for processing, blocks until a result is available or an error occurs. Polling for results is performed according to the Processor's PollingStrategy.

type ProcessorOption

type ProcessorOption func(*Processor)

ProcessorOption describes a configuration option for the Processor.

func PollingStrategyProcessorOption

func PollingStrategyProcessorOption(pollingStrategy PollingStrategy) ProcessorOption

PollingStrategyProcessorOption allows to inject a PollingStrateg.

type ResponseHeader

type ResponseHeader struct {
	Message    string     `json:"message"`
	Status     string     `json:"status"`
	StatusCode StatusCode `json:"status_code"`
	Token      string     `json:"token"`
	Success    bool       `json:"success"`
	Code       Code       `json:"code"`
}

ResponseHeader describes the common fields in responses.

type ResultResponse

type ResultResponse struct {
	*ResponseHeader
	Result *ResultResponseResult `json:"result"`
}

ResultResponse describes a result response.

type ResultResponseResult

type ResultResponseResult struct {
	Establishment          string                          `json:"establishment"`
	ValidatedEstablishment bool                            `json:"validatedEstablishment"`
	Date                   string                          `json:"date"`
	Total                  string                          `json:"total"`
	URL                    string                          `json:"url"`
	PhoneNumber            string                          `json:"phoneNumber"`
	PaymentMethod          string                          `json:"paymentMethod"`
	Address                string                          `json:"address"`
	ValidatedTotal         bool                            `json:"validatedTotal"`
	SubTotal               string                          `json:"subTotal"`
	ValidatedSubTotal      bool                            `json:"validatedSubTotal"`
	Cash                   string                          `json:"cash"`
	Change                 string                          `json:"change"`
	Tax                    string                          `json:"tax"`
	Taxes                  []json.Number                   `json:"taxes"`
	Discount               string                          `json:"discount"`
	Discounts              []json.Number                   `json:"discounts"`
	LineItems              []*ResultResponseResultLineItem `json:"lineItems"`
}

ResultResponseResult describes the result field in a result response.

type ResultResponseResultLineItem

type ResultResponseResultLineItem struct {
	Quantity         json.Number `json:"qty"`
	Description      string      `json:"desc"`
	Unit             string      `json:"unit"`
	CleanDescription string      `json:"descClean"`
	LineTotal        string      `json:"lineTotal"`
	ProductCode      string      `json:"productCode"`
}

ResultResponseResultLineItem describes a line item in a result.

type StatusCode

type StatusCode int

StatusCode represents the status of an operation.

const (
	StatusCodePending StatusCode = 1
	StatusCodeSuccess StatusCode = 2
	StatusCodeDone    StatusCode = 3
	StatusCodeFailed  StatusCode = 4
)

Known status codes.

Jump to

Keyboard shortcuts

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