intacct

package module
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2022 License: BSD-3-Clause Imports: 14 Imported by: 1

README

Intacct Web Services Rest Api version 3 in Go

GoDoc

The intacct package provides a service to execute and evaluate the generic Sage Intacct Web Service functions to read/update/describe Sage Intacct objects/tables. The following example demonstrates how an operation is performed.

ctx := context.Background()
// create Service
sv := &intacct.Service{
    SenderID: "YOUR_SENDER_ID",
    Password: "****",
    Authenticator: intacct.SessionID("YOUR_SESSION_ID"),
}
// create function
f := intacct.ReadByQuery("CONTACT", "NAME LIKE '%MITCHELL%'")
// exec function(s) into Response
resp, err := sv.Exec(ctx, f)
if err != nil {
    log.Fatalf("Exec err: %v", err)
}
// define result as either pointer to struct or slice
var result []intacct.Contact
if err = resp.Decode(&result); err != nil {
    log.Fatalf("Decode error: %v", err)
}
for _, contact := range result {
    log.Print
}

The generic functions are:

  • Read - list using key value or list of key values
  • ReadByName - read by a name key or list of names
  • ReadByQuery - read using Sage Intacct query
  • ReadMore - read additional results of a query
  • ReadRelated - read records related to custom object
  • Create
  • Update
  • Delete
  • Inspect - list object details
  • LegacyFunction - use v2.1 dtd functions

Examples may be found in the examples_test.go file.

To define a transaction, add control id, add policy id for asynchronous call, etc, create an intacct.ControlConfig and use Service.ExecWithControl.

Authentication

The Authenticator interface should return an intacct.SessionID or any object that will xml marshal into an Intacct login or sessionid element

The package provide three Authenticators (Login, SessionID and Session). Each are safe to use concurrently, although a developer may write her own.

Loading a Service from a json file using the ServerFromConfig funcs is the simplest way to create/implement authentication. Below are json examples of service configurations.

  • login only
{
    "sender_id": "Your SenderID",
    "password": "Your Password",
    "login": {
        "user_id": "xml_gateway",
        "company": "Company Name",
        "password": "User Password",
        "location_id": "XYZ"
    }
}
  • Session ID
{
    "sender_id": "Your SenderID",
    "password": "Your Password",
    "session": {
        "sessionId": "*******",
    }
}
  • Session ID w/ refresh
{
    "sender_id": "Your SenderID",
    "password": "Your Password",
    "login": {
        "user_id": "xml_gateway",
        "company": "Company Name",
        "password": "User Password",
        "location_id": "XYZ"
    },
    "session": {}
}

Data Types

The following types have been created to properly unmarshal the xml responses from intacct.

  • intacct.Date (Pt_FieldDate) YYYY-MM-DD and YYYY/MM/DD formats
  • intacct.Datetime (Pt_FieldDateTime) RFC3339 and 01/02/2006 15:04:05 formats
  • intacct.Int (Pt_FieldInt)
  • intacct.Float (Pt_FieldDouble)
  • intacct.Bool (Pt_FieldBoolean)

Each type contains a Val() to return native values or *time.Time

Objects

Object definitions are not provided by this package due to the lack of a canonical list from Sage Intacct. Custom fields differ between installations, and the inspect function does not indicate which fields are standard. Also, difference occur between the Read/ReadByName and ReadByQuery functions when handling related records.

When defining an object struct, DO NOT include an xml.Name field.

The genobject package contains a utility to create a struct definition for objects.

To list objects:

$ cd $GOPATH/src/github.org/jfcote87/intacct/genobject
$ go run main.go -cfg config.json
Objects:
APADJUSTMENT: AP Adjustment
APADJUSTMENTITEM: AP Adjustment Detail
APBILL: AP Bill
....

To generate a definition for an object or list objects

$ cd $GOPATH/src/github.org/jfcote87/intacct/genobject
$ go run main.go -cfg config.json VENDOR APBILL GLDETAIL
// VENDOR (VENDOR)
type VENDOR struct {
RecordNumber intacct.Int `xml:"RECORDNO,omitempty"`
VendorID string `xml:"VENDORID,omitempty"`// Required
...

An ResultMap type may be used as a result for decoding a function. The function response xml is unmarshalled into a map[string]interface{}. An example is below

f := Read("CUSTOMER")
resp, _ := sv.Exec(ctx, f)
var resmap = make(intacct.ResultMap)
_ := resp.Decode(&resmap)
for k, v := range resmap {
    log.Printf("%s: %v", k, v)
}

Paste the snippet into code and gofmt.

Legacy Functions

The v21 package contains the version 2.1DTD definitions. Try not to use it. Documentation seems mostly unavailable or sparse. Examples are provided for accessing and creating documents (supdoc).

TODO

  1. Add readViews
  2. Add custom reports functions
  3. Add asynchronous examples

Documentation

Overview

Package intacct implements the intacct webservices protocol for accessing intacct data https://developer.intacct.com/web-services/

Example (Create_doc)

create document with attachments https://developer.intacct.com/api/company-console/attachments/#create-attachment-legacy

package main

import (
	"bytes"
	"context"
	"log"

	"github.com/jfcote87/intacct"
	v21 "github.com/jfcote87/intacct/v21"
)

// Example Config file.
var sessionConfig = `{
    "sender_id": "Your SenderID",
    "sender_pwd": "Your Password",
    "login": {
        "user_id": "xml_gateway",
        "company": "Company Name",
        "password": "User Password",
		"location_id": "XYZ"
	},
	"session": {}
}`

func main() {
	var ctx context.Context = context.Background()

	configReader := bytes.NewReader([]byte(sessionConfig))
	sv, err := intacct.ServiceFromConfigJSON(configReader)
	if err != nil {
		log.Fatalf("Configuration error: %v", err)
	}
	var buffer []byte
	// copy file bytes to buffer
	_, err = sv.Exec(ctx, intacct.LegacyFunction{
		Payload: &v21.CreateSupdoc{
			SupdocID:         "NewDocumentID",
			SupdocName:       "Doc Name",
			SupdocfolderName: "FolderName",
			Attachments: []v21.Attachment{
				{
					AttachmentName: "New PDF File",
					AttachmentType: "pdf",
					AttachmentData: buffer,
				},
			},
		},
	})

	if err != nil {
		log.Fatalf("create supdoc failed: %v", err)
	}
	log.Printf("attachment added")
}
Output:

Example (Read_supdoc)

Read documents with attachments https://developer.intacct.com/api/company-console/attachments/#list-attachments-legacy

package main

import (
	"bytes"
	"context"
	"encoding/xml"
	"log"

	"github.com/jfcote87/intacct"
	v21 "github.com/jfcote87/intacct/v21"
)

// Example Config file.
var sessionConfig = `{
    "sender_id": "Your SenderID",
    "sender_pwd": "Your Password",
    "login": {
        "user_id": "xml_gateway",
        "company": "Company Name",
        "password": "User Password",
		"location_id": "XYZ"
	},
	"session": {}
}`

func main() {
	var ctx context.Context = context.Background()

	configReader := bytes.NewReader([]byte(sessionConfig))
	sv, err := intacct.ServiceFromConfigJSON(configReader)
	if err != nil {
		log.Fatalf("Configuration error: %v", err)
	}
	// Read documents with attachment data
	resp, err := sv.Exec(ctx, intacct.LegacyFunction{
		Payload: &v21.GetList{
			ObjectName: "supdoc",
			MaxItems:   1,
			Filter: &v21.Expression{
				Type:  v21.ExpressionEqual,
				Field: "supdocid",
				Value: "DocumentID",
			},
		},
	})

	if err != nil {
		log.Fatalf("exec err: %v", err)
	}
	var supDoc = struct {
		XMLName           xml.Name         `xml:"supdoc"`
		SupdocID          string           `xml:"supdocid"`
		SupdocName        string           `xml:"supdocname,omitempty"`
		SupdocfolderName  string           `xml:"supdocfoldername,omitempty"`
		Supdocdescription string           `xml:"supdocdescription,omitempty"`
		Attachments       []v21.Attachment `xml:"attachments>attachment,omitempty"`
	}{}
	if err = resp.Decode(&supDoc); err != nil {
		log.Fatalf("decode error: %v", err)
	}
	for idx, a := range supDoc.Attachments {
		log.Printf("Document %s: attachment %d %s total bytes %d", supDoc.SupdocName, idx, a.AttachmentName, len(a.AttachmentData))
	}
}
Output:

Index

Examples

Constants

View Source
const DefaultDTDVersion = "3.0"

DefaultDTDVersion used for requests. May be overridden by using CustomControl struct in Service.ExecWithControl.

View Source
const DefaultEndpoint = "https://api.intacct.com/ia/xml/xmlgw.phtml"

DefaultEndpoint used until an Authenticator returns a different one

Variables

This section is empty.

Functions

This section is empty.

Types

type Ack

type Ack struct {
	Status string        `xml:"status"`
	Error  *ControlError `xml:"errormessage>error"`
}

Ack is returned for asynchronous calls. https://developer.intacct.com/web-services/sync-vs-async/

type AuthResponseChecker

type AuthResponseChecker interface {
	Authenticator
	CheckResponse(context.Context, *Response)
}

AuthResponseChecker is an Authenticator that checks the response after each exec. May be used for caching and updating session settings.

type AuthenticationConfig

type AuthenticationConfig struct {
	SenderID       string   `xml:"sender_id" json:"sender_id,omitempty"`   // Intacct SenderID
	SenderPassword string   `xml:"sender_pwd" json:"sender_pwd,omitempty"` // Intacct Password
	Login          *Login   `xml:"login,omitempty" json:"login,omitempty"`
	Session        *Session `xml:"session,omitempty" json:"session,omitempty"`
}

AuthenticationConfig provides a format for serializing a Service definition

type Authenticator

type Authenticator interface {
	GetAuthElement(ctx context.Context) (interface{}, error)
}

Authenticator returns an interface{} that will xml marshal into a valid login or sessionid element for a request

type AutoFill

type AutoFill struct {
	DimensionRelationship
	Type string `xml:"type"`
}

AutoFill describes auto fill relationships for a dimension

type Bool

type Bool bool

Bool handles intacct xml bool values

func (*Bool) UnmarshalXML

func (b *Bool) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML decodes bool values and sets value to false on any parse errors

func (Bool) Val

func (b Bool) Val() bool

Val checks for default true values, false for all others

type ConfigOption

type ConfigOption interface {
	// contains filtered or unexported methods
}

A ConfigOption is passed to ServiceFrom... funcs. ConfigOptions may be created using the ConfigHTTPClientFunc and ConfigControlIDFunc funcs.

func ConfigControlIDFunc

func ConfigControlIDFunc(f ControlIDFunc) ConfigOption

ConfigControlIDFunc sets the ControlIDFunc for the Service created by the ServiceFrom... funcs

func ConfigHTTPClientFunc

func ConfigHTTPClientFunc(f ctxclient.Func) ConfigOption

ConfigHTTPClientFunc sets the HTTPClientFunc for the Service created by the ServiceFrom... funcs

type Contact

type Contact struct {
	RecordNumber            Int           `xml:"RECORDNO,omitempty"`
	ContactName             string        `xml:"CONTACTNAME,omitempty"`
	Prefix                  string        `xml:"PREFIX,omitempty"`
	FirstName               string        `xml:"FIRSTNAME,omitempty"`
	LastName                string        `xml:"LASTNAME,omitempty"`
	MI                      string        `xml:"INITIAL,omitempty"`
	CompanyName             string        `xml:"COMPANYNAME,omitempty"`
	PrintAs                 string        `xml:"PRINTAS,omitempty"`
	Taxable                 Bool          `xml:"TAXABLE,omitempty"`
	TaxGroup                string        `xml:"TAXGROUP,omitempty"`
	PhoneNumber             string        `xml:"PHONE1,omitempty"`
	Secondaryphone          string        `xml:"PHONE2,omitempty"`
	CellularPhoneNumber     string        `xml:"CELLPHONE,omitempty"`
	PagerNumber             string        `xml:"PAGER,omitempty"`
	FaxNumber               string        `xml:"FAX,omitempty"`
	EmailAddress            string        `xml:"EMAIL1,omitempty"`
	SecondaryEmailAddresses string        `xml:"EMAIL2,omitempty"`
	URL                     string        `xml:"URL1,omitempty"`
	SecondaryURL            string        `xml:"URL2,omitempty"`
	Visible                 Bool          `xml:"VISIBLE,omitempty"`
	Status                  string        `xml:"STATUS,omitempty"`
	PriceSchedule           string        `xml:"PRICESCHEDULE,omitempty"`
	Discount                string        `xml:"DISCOUNT,omitempty"`
	PriceList               string        `xml:"PRICELIST,omitempty"`
	PriceListKey            Int           `xml:"PRICELISTKEY,omitempty"`
	TaxID                   string        `xml:"TAXID,omitempty"`
	TaxGroupKey             string        `xml:"TAXGROUPKEY,omitempty"`
	PriceScheduleKey        string        `xml:"PRICESCHEDULEKEY,omitempty"`
	WhenCreated             Datetime      `xml:"WHENCREATED,omitempty"`
	WhenModified            Datetime      `xml:"WHENMODIFIED,omitempty"`
	CreatedBy               string        `xml:"CREATEDBY,omitempty"`
	ModifiedBy              string        `xml:"MODIFIEDBY,omitempty"`
	CreatedatEntityKey      Int           `xml:"MEGAENTITYKEY,omitempty"`  // Read Only
	CreatedatEntityID       string        `xml:"MEGAENTITYID,omitempty"`   // Read Only
	CreatedatEntityName     string        `xml:"MEGAENTITYNAME,omitempty"` // Read Only
	RecordURL               string        `xml:"RECORD_URL,omitempty"`     // Read Only
	Address                 *MailAddress  `xml:"MAILADDRESS,omitempty"`
	CustomFields            []CustomField `xml:",any"`
}

Contact describes the Contact entity

type Control

type Control struct {
	SenderID          string `xml:"senderid,omitempty"`
	Password          string `xml:"password,omitemtpy"`
	ControlID         string `xml:"controlid,omitempty"`
	UniqueID          bool   `xml:"uniqueid"`
	DTDVersion        string `xml:"dtdversion"`
	PolicyID          string `xml:"policyid,omitempty"`
	Debug             bool   `xml:"debug,omitempty"`
	Includewhitespace bool   `xml:"includewhitespace"`
	Status            string `xml:"status,omitempty"`
}

Control provides a header to a request

type ControlConfig

type ControlConfig struct {
	IsTransaction     bool
	IsUnique          bool
	IncludeWhitespace bool
	Debug             bool
	ControlID         string
	PolicyID          string
	DTDVersion        string // will use DefaultDTDVersion if blank

	CompanyPrefs []Preference
	ModulePrefs  []Preference
}

ControlConfig allows developer to specify transactional data for a Request.

type ControlError

type ControlError []ErrorDetail

ControlError contains errors returned from intacct leading to a control failuer https://developer.intacct.com/web-services/error-handling/

func (*ControlError) Error

func (e *ControlError) Error() string

Error fulfill error interface

type ControlIDFunc

type ControlIDFunc func(ctx context.Context) string

ControlIDFunc generates unique Control IDs for requests

func (ControlIDFunc) ID

func (idFunc ControlIDFunc) ID(ctx context.Context) string

ID executes a ControlIDFunc while providing an ID generator based upon time for null instances

type CustomField

type CustomField struct {
	Name  string
	Value string
}

CustomField provides a key/pair structure for marshalling and unmarshalling custom fields for an Intacct object

func (CustomField) MarshalXML

func (c CustomField) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML serializes a custom field into <NAME>VALUE</NAME>

func (*CustomField) UnmarshalXML

func (c *CustomField) UnmarshalXML(d *xml.Decoder, s xml.StartElement) error

UnmarshalXML decodes unreference xml tags into a CustomField Slice

type Date

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

Date used to handle intact read and readQuery date format

func TimeToDate

func TimeToDate(t time.Time) Date

TimeToDate converts a time.Time pointer to an intacct.Date pointer

func (Date) IsNil

func (dx Date) IsNil() bool

IsNil returns whether the underlying time is nil

func (Date) MarshalText added in v0.7.0

func (dx Date) MarshalText() ([]byte, error)

MarshalText formats Date for xml and json

func (Date) String

func (dx Date) String() string

String returns the date in YYYY-MM-DD format

func (*Date) UnmarshalText added in v0.7.0

func (dx *Date) UnmarshalText(text []byte) error

UnmarshalText parses string form Date

func (Date) Val

func (dx Date) Val() *time.Time

Val returns intacct date at *Time.time. Blanks returned as nil

type Datetime

type Datetime Date

Datetime used to handle intact read and readQuery date format

func TimeToDatetime

func TimeToDatetime(t time.Time) Datetime

TimeToDatetime converts a time.Time pointer to an intacct.Datetime pointer

func (Datetime) IsNil

func (dt Datetime) IsNil() bool

IsNil returns whether the underlying time is nil

func (Datetime) MarshalText added in v0.7.0

func (dt Datetime) MarshalText() ([]byte, error)

MarshalText formats Date for xml and json

func (Datetime) String

func (dt Datetime) String() string

String returns an RC3339 output of the date

func (*Datetime) UnmarshalText added in v0.7.0

func (dt *Datetime) UnmarshalText(text []byte) error

UnmarshalText parses string form Date

func (Datetime) Val

func (dt Datetime) Val() *time.Time

Val returns intacct datetime.

type DimensionRelationship

type DimensionRelationship struct {
	Dimension      string `xml:"dimension"`
	ObjectID       string `xml:"object_id"`
	RelationshipID string `xml:"relationship_id"`
}

DimensionRelationship identifies a child relationship

type Endpoint

type Endpoint interface {
	GetEndpoint() string
}

Endpoint returns an endpoint for a request and should always return a valid endpoint.

type ErrorDetail

type ErrorDetail struct {
	ErrorNo      string `xml:"errorno"`
	Description  string `xml:"description"`
	Description2 string `xml:"description2"`
	Correction   string `xml:"correction"`
	Err          error  `xml:"-"`
}

ErrorDetail describes each error

type FieldDetail

type FieldDetail struct {
	Name             string `xml:"Name"`
	GroupName        string `xml:"GroupName"`
	DataName         string `xml:"dataName"`
	ExternalDataName string `xml:"externalDataName"`
	IsRequired       bool   `xml:"isRequired"`
	IsReadOnly       bool   `xml:"isReadOnly"`
	MaxLen           string `xml:"maxLength"`
	DisplayLabel     string `xml:"DisplayLabel"`
	Description      string `xml:"Description"`
	ID               string `xml:"id"`
	Relationship     string `xml:"relationship"`
	RelatedObject    string `xml:"relatedObject"`
}

FieldDetail is the description of each field of an Intacct object

type Filter added in v0.6.0

type Filter struct {
	XMLName xml.Name
	Field   string     `xml:"field,omitempty"`
	Value   FilterVals `xml:"value,omitempty"`
	Filters []Filter
	// contains filtered or unexported fields
}

Filter is a heirarchy of criteria. Use function to add criteria

func NewFilter added in v0.6.0

func NewFilter() *Filter

NewFilter returns an initialized Filter pointer

func (*Filter) And added in v0.6.0

func (f *Filter) And() *Filter

And creates a new And filter and adds it to the method receiver's filter list. The return value is the new And filter not the method receiver.

func (*Filter) Between added in v0.6.0

func (f *Filter) Between(field string, start, end time.Time) *Filter

Between adds a date range filter for the field and begin and end dates to f's list of filters. The receiver value f is returned to allow chaining

func (*Filter) EqualTo added in v0.6.0

func (f *Filter) EqualTo(field string, value string) *Filter

EqualTo adds an equal filter for the field and value to f's list of filters. The receiver value f is returned to allow chaining

func (*Filter) GreaterThan added in v0.6.0

func (f *Filter) GreaterThan(field string, value string) *Filter

GreaterThan adds a greater than filter for the field and value to f's list of filters. The receiver value f is returned to allow chaining

func (*Filter) GreaterThanOrEqualTo added in v0.6.0

func (f *Filter) GreaterThanOrEqualTo(field string, value string) *Filter

GreaterThanOrEqualTo adds a less than or equal to filter for the field and value to f's list of filters. The receiver value f is returned to allow chaining

func (*Filter) In added in v0.6.0

func (f *Filter) In(field string, values ...string) *Filter

In adds a list filter for the field and values to f's list of filters. The receiver value f is returned to allow chaining

func (*Filter) IsNotNull added in v0.6.0

func (f *Filter) IsNotNull(field string) *Filter

IsNotNull adds a null value filter for the field and values to f's list of filters. The receiver value f is returned to allow chaining

func (*Filter) IsNull added in v0.6.0

func (f *Filter) IsNull(field string) *Filter

IsNull adds a null value filter for the field and values to f's list of filters. The receiver value f is returned to allow chaining

func (*Filter) LessThan added in v0.6.0

func (f *Filter) LessThan(field string, value string) *Filter

LessThan adds a less than filter for the field and value to f's list of filters. The receiver value f is returned to allow chaining

func (*Filter) LessThanOrEqualTo added in v0.6.0

func (f *Filter) LessThanOrEqualTo(field string, value string) *Filter

LessThanOrEqualTo adds a less than or equal to filter for the field and value to f's list of filters. The receiver value f is returned to allow chaining

func (*Filter) Like added in v0.6.0

func (f *Filter) Like(field string, value string) *Filter

Like adds a string filter for the field and values to f's list of filters. The receiver value f is returned to allow chaining

func (*Filter) NotEqualTo added in v0.6.0

func (f *Filter) NotEqualTo(field string, value string) *Filter

NotEqualTo adds a not equal filter for the field and value to f's list of filters. The receiver value f is returned to allow chaining

func (*Filter) NotIn added in v0.6.0

func (f *Filter) NotIn(field string, values ...string) *Filter

NotIn adds a list filter for the field and values to f's list of filters. The receiver value f is returned to allow chaining

func (*Filter) NotLike added in v0.6.0

func (f *Filter) NotLike(field string, value string) *Filter

NotLike adds a string filter for the field and values to f's list of filters. The receiver value f is returned to allow chaining

func (*Filter) Or added in v0.6.0

func (f *Filter) Or() *Filter

Or creates a new OR filter and adds it to the method receiver's filter list. The return value is the new Or filter not the method receiver.

func (*Filter) Parent added in v0.7.0

func (f *Filter) Parent() *Filter

Parent returns the filter's parent (nil if no parent assigned) providing a workable chaining process. e.g. f := intacct.NewFilter().And().EqualTo("FLD","Value").EqualTo("FLD2","Value").Parent()

type FilterVals added in v0.6.0

type FilterVals []string

FilterVals handles proper marshaling of empty strings

func (FilterVals) MarshalXML added in v0.6.0

func (fv FilterVals) MarshalXML(e *xml.Encoder, s xml.StartElement) error

MarshalXML output nothing for empty slice, value elements for all others

type Float64

type Float64 float64

Float64 handles intacct xml float values

func (Float64) String

func (f Float64) String() string

Val returns 0 for blank

func (*Float64) UnmarshalXML

func (f *Float64) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML decodes float values and sets value to 0 on any parse errors

func (Float64) Val

func (f Float64) Val() float64

Val returns 0 for blank

type Function

type Function interface {
	GetControlID() string
}

Function defines an action. See https://developer.intacct.com/web-services/functions/

func GetAPISession

func GetAPISession(location string) Function

GetAPISession returns Intacct Function for obtaining a SessionID for for the passed location (blank location is the top-level company). Decode the Response into a SessionResult struct. https://developer.intacct.com/api/company-console/api-sessions/#get-api-session

func GetDimensionAutofillDetails

func GetDimensionAutofillDetails() Function

GetDimensionAutofillDetails provides information about auto-fill settings for to-one relationships between dimensions. (If the relationship is to-many, auto-fill is not available.) https://developer.intacct.com/api/platform-services/dimensions/#list-dimension-auto-fill-details

func GetDimensionRelationships

func GetDimensionRelationships() Function

GetDimensionRelationships Lists all standard dimensions and UDDs and provides information about their to-one and to-many relationships to other dimensions. https://developer.intacct.com/api/platform-services/dimensions/#list-dimension-relationships

func GetDimensionRestrictedData

func GetDimensionRestrictedData(dimension, value string) Function

GetDimensionRestrictedData lists the IDs of related dimensions that are the target(s) of to-many relationships from a single source dimension. https://developer.intacct.com/api/platform-services/dimensions/#list-dimensions-restricted-data

func GetDimensions

func GetDimensions() Function

GetDimensions Lists all standard dimensions and UDDs in a company along with helpful integration information about the object. https://developer.intacct.com/api/platform-services/dimensions/#list-dimensions

func GetFinancialSetup

func GetFinancialSetup() Function

GetFinancialSetup provides basic financial setup information for a company such as its base currency, first fiscal month, multi-currency setting, and so forth. https://developer.intacct.com/api/company-console/financial-setup/#get-financial-setup

func InstallApp

func InstallApp(definition string) Function

InstallApp installs a Platform Services definition https://developer.intacct.com/api/platform-services/applications/#install-application

type InspectDetailResult

type InspectDetailResult struct {
	XMLName      xml.Name      `xml:"Type"`
	Name         string        `xml:"Name,attr"`
	SingularName string        `xml:"Attributes>SingularName"`
	PluralName   string        `xml:"Attributes>PluralName"`
	Description  string        `xml:"Attributes>Description"`
	Fields       []FieldDetail `xml:"Fields>Field"`
}

InspectDetailResult is the full description of an Intactt object via an Inspect function call.

type InspectName

type InspectName struct {
	TypeName string `xml:"typename,attr"`
	Name     string `xml:",chardata"`
}

InspectName is the name listing from a full inspect listing.

type InspectResult

type InspectResult struct {
	XMLName xml.Name `xml:"Type"`
	Name    string   `xml:"Name,attr"`
	Field   []string `xml:"Fields>Field"`
}

InspectResult lists all fields for an object (name only).

type Inspector

type Inspector struct {
	XMLName  xml.Name `xml:"inspect"`
	IsDetail int      `xml:"detail,attr,omitempty"` // set to 1 for detail
	Object   string   `xml:"object"`
	// contains filtered or unexported fields
}

Inspector performs a inspection macro returning the definition of the named Object. For a list of all objects, set Object to "*".

func ObjectFields

func ObjectFields(objectName string, showDetail bool) *Inspector

ObjectFields returns function to list an objects fields. If showDetail, intacct returns an InspectDetailResult else an InspectResult.

func ObjectList

func ObjectList() *Inspector

ObjectList returns an Inspector function that return a []InspectName of all objects.

func (*Inspector) GetControlID

func (i *Inspector) GetControlID() string

GetControlID returns ControlID for function.

func (*Inspector) SetControlID

func (i *Inspector) SetControlID(id string)

SetControlID set the ControlID for function.

type Int

type Int int64

Int handles intacct xml int values

func (Int) String

func (i Int) String() string

func (*Int) UnmarshalXML

func (i *Int) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML decodes int values and sets value to 0 on any parse errors

func (Int) Val

func (i Int) Val() int64

Val returns 0 for blank

type LegacyFunction

type LegacyFunction struct {
	Payload interface{}
	// contains filtered or unexported fields
}

LegacyFunction is used for v2.1 style calls (get_list, get, etc.). See examples in v21 package.

func (LegacyFunction) GetControlID

func (n LegacyFunction) GetControlID() string

GetControlID is needed to fulfill the Function interface

func (LegacyFunction) MarshalXML

func (n LegacyFunction) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML only encodes the Payload field

type ListType

type ListType struct {
	Start int    `xml:"start,attr,omitempty"`
	End   int    `xml:"end,attr,omitempty"`
	Total int    `xml:"total,attr,omityempty"`
	Name  string `xml:",chardata"`
}

ListType describes the start/ending/remaining records from a v2.1 style call.

type Login

type Login struct {
	UserID     string `xml:"login>userid" json:"user_id"`
	Company    string `xml:"login>companyid" json:"company"`
	Password   string `xml:"login>password" json:"password"`
	ClientID   string `xml:"login>clientid,omitempty" json:"client_id,omitempty"`
	LocationID string `xml:"login>locationid,omitempty" json:"location_id,omitempty"`
}

Login provides a username/password authentication mechanism ClientID and LocationID are optional. https://developer.intacct.com/web-services/requests/#authentication-element

func (*Login) GetAuthElement

func (l *Login) GetAuthElement(ctx context.Context) (interface{}, error)

GetAuthElement fulfills the Authenticator interface{}. Returns itself which will marshal into a login element for the request.

func (*Login) SessionRefresher

func (l *Login) SessionRefresher(sv *Service) func(context.Context) (*SessionResult, error)

SessionRefresher returns a function for creating a new SessionID.

type Lookup added in v0.6.0

type Lookup struct {
	XMLName    xml.Name `xml:"lookup"`
	ObjectName string   `xml:"object"`
	ControlID  string   `xml:"-"`
}

Lookup returns an object definition

func (Lookup) GetControlID added in v0.6.0

func (l Lookup) GetControlID() string

GetControlID fulfills intacct.Function so may be used in Service Exec call

type MailAddress

type MailAddress struct {
	Addr1         string        `xml:"ADDRESS1,omitempty"`
	Addr2         string        `xml:"ADDRESS2,omitempty"`
	City          string        `xml:"CITY,omitempty"`
	StateProvince string        `xml:"STATE,omitempty"`
	ZipPostalCode string        `xml:"ZIP,omitempty"`
	Country       string        `xml:"COUNTRY,omitempty"`
	CountryCode   string        `xml:"COUNTRYCODE,omitempty"`
	Latitude      Float64       `xml:"LATITUDE,omitempty"`
	Longitude     Float64       `xml:"LONGITUDE,omitempty"`
	CustomFields  []CustomField `xml:",any"`
}

MailAddress describes the mail address for a contact

type ObjectField added in v0.6.0

type ObjectField struct {
	ID          string   `xml:"ID"`
	Label       string   `xml:"LABEL"`
	Description string   `xml:"DESCRIPTION"`
	Required    bool     `xml:"REQUIRED"`
	ReadOnly    bool     `xml:"READONLY"`
	DataType    string   `xml:"DATATYPE"`
	IsCustom    bool     `xml:"ISCUSTOM"`
	ValidValues []string `xml:"VALIDVALUES>VALIDVALUE"`
}

ObjectField defines parameters of an intacct object (table)

type ObjectRelationship added in v0.6.0

type ObjectRelationship struct {
	Path      string `xml:"OBJECTPATH"`
	Name      string `xml:"OBJECTNAME"`
	Lable     string `xml:"LABEL"`
	Type      string `xml:"RELATIONSHIPTYPE"`
	RelatedBy string `xml:"RELATEDBY"`
}

ObjectRelationship describes relationship between objects

type ObjectType added in v0.6.0

type ObjectType struct {
	XMLName       xml.Name             `xml:"Type"`
	Name          string               `xml:"Name,attr"`
	Type          string               `xml:"DocumentType,attr"`
	Fields        []ObjectField        `xml:"Fields>Field"`
	Relationships []ObjectRelationship `xml:"Relationships>Relationship"`
}

ObjectType is top level response for lookup function

type Operation

type Operation struct {
	Transaction  bool              `xml:"transaction,attr,omitempty"`
	Auth         interface{}       `xml:"authentication"`
	CompanyPrefs []Preference      `xml:"preference/companyprefs/companypref"`
	ModulePrefs  []Preference      `xml:"preference/moduleprefs/modulepref"`
	Content      []RequestFunction `xml:"content>function"`
}

Operation marshals into an intacct request

type OperationError

type OperationError ControlError

OperationError signifies that the error was returned in the operation section rather than the top level ResponseError

func (*OperationError) Error

func (e *OperationError) Error() string

type OrderBy added in v0.6.0

type OrderBy struct {
	XMLName    xml.Name `xml:"order"`
	Field      string   `xml:"field,omitempty"`
	Descending bool     `xml:"descending,omitempty"`
}

OrderBy describes sort conditions

func (OrderBy) MarshalXML added in v0.6.0

func (o OrderBy) MarshalXML(e *xml.Encoder, s xml.StartElement) error

MarshalXML used to create <descending> tag

type Preference

type Preference struct {
	Application string `xml:"application"`
	Name        string `xml:"preference"`
	Value       string `xml:"prefvalue"`
}

Preference add additional data to an operation.

type Query added in v0.6.0

type Query struct {
	XMLName         xml.Name      `xml:"query"`
	Object          string        `xml:"object"`
	Select          Select        `xml:"select"`
	Filter          *Filter       `xml:"filter,omitempty"`
	Sort            *QuerySort    `xml:"orderby,omitempty"`
	Options         *QueryOptions `xml:"options,omitempty"`
	PageSz          int           `xml:"pagesize,omitempty"`
	Offset          int           `xml:"offset,omitempty"`
	TransactionType string        `xml:"docparid,omitempty"`
	// ControlID used for transaction marking. Leave blank for
	// defaul behavior
	ControlID string `xml:"-"`
}

Query implements new intacct query and definition functionality that replaces the readByQuery and inspect functions with query and lookup. Stmt and Lookup structs are intacct functions that may be called by intacct.Service. intacct documentation may be found at: https://developer.intacct.com/web-services/queries/

func (Query) GetAll added in v0.6.0

func (q Query) GetAll(ctx context.Context, sv *Service, resultSlice interface{}) error

GetAll reads all pages and unmarshals them into results. resultSlice must be a pointer to a slice.

Example

ExampleQuery_GetAll demonstrates using an intacct service to query records using the new query function. GetAll reads all pages of the query.

package main

import (
	"bytes"
	"context"
	"fmt"
	"log"

	"github.com/jfcote87/intacct"
)

// Example Config file.
var sessionConfig = `{
    "sender_id": "Your SenderID",
    "sender_pwd": "Your Password",
    "login": {
        "user_id": "xml_gateway",
        "company": "Company Name",
        "password": "User Password",
		"location_id": "XYZ"
	},
	"session": {}
}`

type Project struct {
	RecordNumber      intacct.Int `xml:"RECORDNO,omitempty"`
	ProjectID         string      `xml:"PROJECTID"`
	Projectname       string      `xml:"NAME"`
	Description       string      `xml:"DESCRIPTION,omitempty"`
	ParentProjectKey  intacct.Int `xml:"PARENTKEY,omitempty"`
	ParentProjectID   string      `xml:"PARENTID,omitempty"`
	ParentProjectName string      `xml:"PARENTNAME,omitempty"`
}

func main() {
	var ctx context.Context = context.Background()

	configReader := bytes.NewReader([]byte(sessionConfig))
	sv, err := intacct.ServiceFromConfigJSON(configReader)
	if err != nil {
		log.Fatalf("Configuration error: %v", err)
	}

	var projects []Project

	var filter = intacct.NewFilter()
	filter.And().EqualTo("STATUS", "active").In("PARENTID", "ID01", "ID02")

	var stmt = &intacct.Query{
		Object: "PROJECT",
		Select: intacct.Select{
			Fields: []string{"RECORDNO", "PROJECTID", "NAME", "DESCRIPTION", "PARENTNAME"},
		},
		Sort:   &intacct.QuerySort{Fields: []intacct.OrderBy{{Field: "PROJECTID"}}},
		Filter: filter,
	}

	if err := stmt.GetAll(ctx, sv, &projects); err != nil {
		log.Printf("read error %v", err)
		return
	}
	for _, p := range projects {
		fmt.Printf("%s", p.Projectname)
	}
}
Output:

func (Query) GetControlID added in v0.6.0

func (q Query) GetControlID() string

GetControlID fulfills intacct.Function so may be used in Service Exec call

type QueryOptions added in v0.6.0

type QueryOptions struct {
	CaseInsensitive bool `xml:"caseinsensitive,omitempty"`
	ShowPrivate     bool `xml:"showprivate,omitempty"`
}

QueryOptions set query flags

type QuerySort added in v0.6.1

type QuerySort struct {
	XMLName xml.Name  `xml:"orderby"`
	Fields  []OrderBy `xml:"order"`
}

QuerySort defined fields for sorting,

type Reader

type Reader struct {
	XMLName      xml.Name
	Object       string  `xml:"object,omitempty"`       // Object name
	Keys         *string `xml:"keys,omitempty"`         // comma sep list of keys for read and readByName
	Query        *string `xml:"query,omitempty"`        // query statement for readQuery
	FieldList    string  `xml:"fields,omitempty"`       // field list
	MaxRecs      int     `xml:"pagesize,omitempty"`     // max items returned
	ReturnFormat string  `xml:"returnFormat,omitempty"` // xml for now
	Docparid     string  `xml:"docparid,omitempty"`     // don't know what this is
	Relationship string  `xml:"relationship_id,omitempty"`
	ResultID     string  `xml:"resultId,omitempty"`
	// contains filtered or unexported fields
}

Reader may be a read, readByName, readQuery or readMore function. Use the Read, ReadByName, ReadByQuery or ReadMore functions to create function rather than creating directly.

Example (Readall)

ExampleReader_readall shows how to read all responses to a Reader function

var ctx context.Context = context.Background()

configReader := bytes.NewReader([]byte(sessionConfig))
sv, err := intacct.ServiceFromConfigJSON(configReader)
if err != nil {
	log.Fatalf("Configuration error: %v", err)
}
var results []Vendor
if err = intacct.ReadByQuery("VENDOR", "").
	Fields("RECORDNO", "VENDORID").
	GetAll(ctx, sv, &results); err != nil {
	log.Fatalf("getall error: %v", err)
}
log.Printf("Total Records: %d", len(results))
Output:

func Read

func Read(objectName string, keys ...string) *Reader

Read returns a Reader to read specific keys. If no keys are passed, the first 100 records are returned in an unspecified order.

func ReadByName

func ReadByName(objectName string, keys ...string) *Reader

ReadByName returns a Reader to read specific name keys. If no keys are passed, the first 100 records are returned in an unspecified order.

func ReadByQuery

func ReadByQuery(objectName string, qry string) *Reader

ReadByQuery returns a Reader based upon the passed query string which is an SQL-like query based on fields on the object. Illegal XML characters must be properly encoded. The following SQL operators are supported: <, >, >=, <=, =, like, not like, in, not in. When doing NULL comparisons: IS NOT NULL, IS NULL. Multiple fields may be matched using the AND and OR operators. Joins are not supported. Single quotes in any operands must be escaped with a backslash - For example, the value Erik's Deli would become 'Erik\'s Deli'

func ReadMore

func ReadMore(resultID string) *Reader

ReadMore returns a Reader to retrieve remaining records of a ReadByQuery

func ReadRelated

func ReadRelated(objectName string, relationshipName string, keys ...string) *Reader

ReadRelated retrieves records related to on or more records by a given relationship. Note: this only works on custom objects. see https://developer.intacct.com/api/platform-services/records/#get-related-records

func (*Reader) Fields

func (r *Reader) Fields(fields ...string) *Reader

Fields sets the fields to return. If not set all fields are returned. Do not use with ReadMore type.

func (Reader) GetAll

func (r Reader) GetAll(ctx context.Context, sv *Service, resultSlice interface{}) error

GetAll reads all records for a query. The reader must be a readByQuery or readMore type. resultSlice should be of type *[]<Object>.

func (Reader) GetControlID

func (r Reader) GetControlID() string

GetControlID returns the unique identifier for the call

func (*Reader) PageSize

func (r *Reader) PageSize(numOfRecs int) *Reader

PageSize sets the max number of records returned

if pageSize is not set, 100 is assumed

func (*Reader) SetControlID

func (r *Reader) SetControlID(controlID string) *Reader

SetControlID sets a unique identifier for the call

type Related struct {
	DimensionRelationship
	SourceSide  string `xml:"source_side"`
	RelatedSide string `xml:"related_side"`
}

Related describes relationships between dimensions

type Relationship

type Relationship struct {
	Dimension       string     `xml:"dimension"`
	ObjectID        string     `xml:"object_id"`
	AutoFillRelated Bool       `xml:"autofillrelated"`
	EnableOverride  Bool       `xml:"enableoverride"`
	Related         []Related  `xml:"related"`
	AutoFill        []AutoFill `xml:"autofil"`
}

Relationship describes an Intacct dimension

type Request

type Request struct {
	XMLName xml.Name  `xml:"request"`
	Control Control   `xml:"control"`
	Op      Operation `xml:"operation"`
}

Request is a batch the struct sent to Intacct.

type RequestFunction

type RequestFunction struct {
	ControlID string `xml:"controlid,attr"`
	Payload   interface{}
}

RequestFunction wraps function.

type Response

type Response struct {
	Ack      *Ack            `xml:"acknowledgement"` // used in asyc only
	Control  Control         `xml:"control"`
	Auth     *ResponseAuth   `xml:"operation>authentication"`
	ErrorMsg *ControlError   `xml:"errormessage>error"`
	OpError  *OperationError `xml:"operation>errormessage>error"`
	Results  []Result        `xml:"operation>result"`
}

Response contains function results from a Request

func (*Response) Decode

func (r *Response) Decode(returnValues ...interface{}) error

Decode interrogates the Response returning errors encoded in the top section and Operation section. Each Result is decoded into the corresponding returnValues interface. Errors are tracked within a ResultsError struct. If no errors are found/occur, nil is returned.

returnValues must be a *[]Struct or *Struct type.

func (*Response) Error

func (r *Response) Error() error

Error returns error from a response object.

type ResponseAuth

type ResponseAuth struct {
	Status           string    `xml:"status"`
	UserID           string    `xml:"userid"`
	CompanyID        string    `xml:"companyid"`
	SessionTimestamp time.Time `xml:"sessiontimestamp,omitempty"`
	SessionTimeout   time.Time `xml:"sessiontimeout,omitempty"`
}

ResponseAuth returns the authentication result for a request

type Restriction

type Restriction struct {
	Dimension    string                  `xml:"dimension"`
	ObjectID     string                  `xml:"object_id"`
	Restrictions []DimensionRelationship `xml:"restrictedby"`
}

Restriction lists the to-one restrictions for each dimension

type Result

type Result struct {
	Status    string        `xml:"status"`
	Function  string        `xml:"function"`
	ControlID string        `xml:"controlid"`
	ListType  *ListType     `xml:"listtype"`
	Errors    []ErrorDetail `xml:"errormessage>error"`
	Data      *ResultData   `xml:"data"`
}

Result wraps either an or DataResult for a function call

func (Result) Decode

func (r Result) Decode(dst interface{}) error

Decode unmarshals the results xml into dst. dst must have a type of *[]S or *S. If dst is not a pointer to a slice, only the first object in a list will be unmarshalled.

type ResultData

type ResultData struct {
	ListType     string `xml:"listtype,attr"`
	Count        int    `xml:"count,attr"`
	TotalCount   int    `xml:"totalcount,attr"`
	NumRemaining int    `xml:"numremaining,attr"`
	ResultID     string `xml:"resultId,attr"`
	Payload      []byte `xml:",innerxml"`
}

ResultData of executing a function

type ResultMap

type ResultMap map[string]interface{}

ResultMap represents intacct response xml as a map of interfaces. Repeated xml tags become slices and attributes are encoded as

"@attributeName".  If a tag has attributes and chardata, the

character data may be found as rm[""]. i.e. <VENDOR><NAME type="short">Jim</NAME></VENDOR> becomes "VENDOR":intacct.ResultMap{"NAME":intacct.ResultMap{"@type":"short", "":"Jim"}}} while <VENDOR><NAME>Jim</NAME></VENDOR> becomes "VENDOR":intacct.ResultMap{"NAME":"Jim"}}

func (ResultMap) Bool

func (rm ResultMap) Bool(name string, trueVals ...string) bool

Bool parses true/false fields. If not trueVals are indicated, Bool checks for a values of "true"

func (ResultMap) Date

func (rm ResultMap) Date(name string) *time.Time

Date returns the date (not datetime) from an result map index. It first checks for the Year, Month and Day elements, then checks for a string format of YYYY-MM-DD and finally for MM-DD-YYYY

func (ResultMap) DateTime

func (rm ResultMap) DateTime(name string) *time.Time

DateTime parses a get_list datetime string.

func (ResultMap) Float

func (rm ResultMap) Float(name string) float64

Float parses the named field for a float64

func (ResultMap) Int

func (rm ResultMap) Int(name string) int64

Int parses the named field for an int64

func (ResultMap) ReadArray

func (rm ResultMap) ReadArray(name string) ([]ResultMap, error)

ReadArray returns a slice of elements from an Element index. If the value is nil or a single element, ReadArray returns an empty or a single valued slice. A string value will return an error.

func (ResultMap) String

func (rm ResultMap) String(name string) string

String returns the string value of the Element index when it is a string. Rather than return an error, ReadSlice returns an empty string for types other than a string.

func (ResultMap) StringArray

func (rm ResultMap) StringArray(name string) []string

StringArray returns a string slice

func (ResultMap) Timestamp

func (rm ResultMap) Timestamp(name string) *time.Time

Timestamp parses an RFC3339 formatted date string, Errors are simply returned as nil.

func (ResultMap) UnmarshalXML

func (rm ResultMap) UnmarshalXML(d *xml.Decoder, s xml.StartElement) error

UnmarshalXML turns serialized XML into a map[string]interface{}

type ResultsError

type ResultsError [][]ErrorDetail

ResultsError contains an array of errors corresponding to the functions passed in Exec

func (ResultsError) Error

func (re ResultsError) Error() string

type Select added in v0.6.0

type Select struct {
	Fields []string `xml:"field"`
	Count  string   `xml:"count,omitempty"`
	Avg    string   `xml:"avg,omitempty"`
	Min    string   `xml:"min,omitempty"`
	Max    string   `xml:"max,omitempty"`
	Sum    string   `xml:"sum,omitempty"`
}

Select determines fields to return for query

type Service

type Service struct {
	// see https://developer.intacct.com/web-services/#authentication
	// SenderID and Password are the customer/partner login, not company login
	SenderID string
	Password string
	// must provide interface{} to marshal to a Login or SessionID element
	Authenticator Authenticator
	// ControlIDFunc may be set to create control IDs for the request header.  If
	// nil the control ID for a call will be the current time in nanoseconds.
	ControlIDFunc
	// Set if a unique client is need.
	HTTPClientFunc ctxclient.Func
}

Service stores configuration information and provides functions for sending requests. It is safe for concurrent

func ServiceFromConfig

func ServiceFromConfig(cfg AuthenticationConfig, opts ...ConfigOption) (*Service, error)

ServiceFromConfig creates a service from configuration.

DO NOT make changes to the returned Service. Create new service if necessary.

func ServiceFromConfigJSON

func ServiceFromConfigJSON(r io.Reader, opts ...ConfigOption) (*Service, error)

ServiceFromConfigJSON returns a service from json representation. DO NOT make changes to the returned Service. Create new service if necessary.

func (*Service) Control

func (sv *Service) Control(ctx context.Context, cc *ControlConfig) Control

Control creates a Control struct based on ControlConfig

func (*Service) Exec

func (sv *Service) Exec(ctx context.Context, f ...Function) (*Response, error)

Exec executes the given functions responding with and error if appropriate. Results are contained in the Response.

Example

ExampleService_Exec demonstrates using an intacct service to read a project record. It then creates a new project record as a child of the first record, and finally runs a query reading all projects having orignal project as a parent.

package main

import (
	"bytes"
	"context"
	"fmt"
	"log"

	"github.com/jfcote87/intacct"
)

// Example Config file.
var sessionConfig = `{
    "sender_id": "Your SenderID",
    "sender_pwd": "Your Password",
    "login": {
        "user_id": "xml_gateway",
        "company": "Company Name",
        "password": "User Password",
		"location_id": "XYZ"
	},
	"session": {}
}`

type Project struct {
	RecordNumber      intacct.Int `xml:"RECORDNO,omitempty"`
	ProjectID         string      `xml:"PROJECTID"`
	Projectname       string      `xml:"NAME"`
	Description       string      `xml:"DESCRIPTION,omitempty"`
	ParentProjectKey  intacct.Int `xml:"PARENTKEY,omitempty"`
	ParentProjectID   string      `xml:"PARENTID,omitempty"`
	ParentProjectName string      `xml:"PARENTNAME,omitempty"`
}

func main() {
	var projectName = "EX1732"
	var ctx context.Context = context.Background()

	configReader := bytes.NewReader([]byte(sessionConfig))
	sv, err := intacct.ServiceFromConfigJSON(configReader)
	if err != nil {
		log.Fatalf("Configuration error: %v", err)
	}

	var projectRecord *Project
	resp, err := sv.Exec(ctx, intacct.ReadByName("PROJECT", projectName))
	if err != nil {
		log.Fatalf("Execution error: %v", err)
	}
	if err = resp.Decode(&projectRecord); err != nil {
		log.Fatalf("result error: %v", err)
	}

	// empty result set
	if projectRecord == nil {
		log.Fatalf("No project named %s exists", projectName)
	}

	// Create new projects
	parentNo := projectRecord.RecordNumber

	resp, err = sv.Exec(ctx, intacct.Create("PROJECT", []Project{
		{
			ProjectID:        "X2017",
			Description:      "New sub-project of E1732",
			ParentProjectKey: parentNo,
		},
		{
			ProjectID:        "X2018",
			Description:      "New sub-project of E1732",
			ParentProjectKey: parentNo,
		},
	}))
	if err == nil {
		// pass nil in decode to only check for errors
		err = resp.Decode(nil)
	}
	if err != nil {
		log.Fatalf("createProject execution: %v", err)
	}

	var projectList []Project
	// ReadByQuery to read all projects having parent of p. Using GetAll() to return all pages of results
	if err = intacct.
		ReadByQuery("PROJECT", fmt.Sprintf("PARENTKEY = '%d'", parentNo)).
		PageSize(10).
		GetAll(ctx, sv, &projectList); err != nil {
		log.Fatalf("query full read error: %v", err)
	}
	fmt.Printf("Total children: %d\n", len(projectList))
}
Output:

func (*Service) ExecWithControl

func (sv *Service) ExecWithControl(ctx context.Context, cc *ControlConfig, f ...Function) (*Response, error)

ExecWithControl adds a ControlConfig for transactional data.

type Session

type Session struct {
	ID          SessionID
	Endpoint    string
	LocationID  string
	Expires     time.Time
	ExpiryDelta int64
	RefreshFunc func(ctx context.Context) (*SessionResult, error)
	// contains filtered or unexported fields
}

Session caches and refreshes a sessionid. Best to create via ServiceFrom... funcs.

func (*Session) CheckResponse

func (s *Session) CheckResponse(ctx context.Context, r *Response)

CheckResponse fulfills the AuthResponseChecker functionality and sets the session timeout.

func (*Session) GetAuthElement

func (s *Session) GetAuthElement(ctx context.Context) (interface{}, error)

GetAuthElement returns a new sessionID to authenticate request

func (*Session) GetEndpoint

func (s *Session) GetEndpoint() string

GetEndpoint returns the session's endpoint and fulfills Endpoint interface

func (*Session) Refresh

func (s *Session) Refresh(ctx context.Context) error

Refresh collects a new sessionid from intacct. Must protect this the Session with using s.m.

type SessionID

type SessionID string

SessionID provides an authorization token that may be used in a Request.

func (SessionID) GetAuthElement

func (s SessionID) GetAuthElement(ctx context.Context) (interface{}, error)

GetAuthElement fulfills the Authenticator interface{}. Returns itself which will marshal into a sessionid element for the request.

func (SessionID) MarshalXML

func (s SessionID) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML formats sessionid for a Request.

type SessionResult

type SessionResult struct {
	XMLName    xml.Name  `xml:"api"`
	SessionID  SessionID `xml:"sessionid"`
	Endpoint   string    `xml:"endpoint"`
	LocationID string    `xml:"locationid"`
	Expires    time.Time `xml:"-"`
}

SessionResult is the result of a getSessionID function

type Writer

type Writer struct {
	// Cmd names the top level element.  If empty, Payload is marshalled directly
	Cmd string `xml:"-"`
	// Payload may not be nil if Cmd is empty
	Payload interface{}
	// If not empty, ObjectName will override Payload's XMLName
	ObjectName string `xml:"-"`
	// contains filtered or unexported fields
}

Writer is used to create functions such as create, update, and deleted. For these Intacct functions, use the Create, Update and Delete funcs. See CmdGetApiSession definition for an example of how to use Write to implement other functions.

func Create

func Create(objectName string, payload interface{}) *Writer

Create returns a Writer function to create object(s) in payload

func Delete

func Delete(objectName string, payload interface{}) *Writer

Delete returns a Writer function to delete object(s) in payload. Payload must contain a key for the intacct object

func Update

func Update(objectName string, payload interface{}) *Writer

Update returns a Writer function to update object(s) in payload. Payload must contain a key for the intacct object

func (Writer) GetControlID

func (w Writer) GetControlID() string

GetControlID returns the unique identifier for the call

func (Writer) MarshalXML

func (w Writer) MarshalXML(e *xml.Encoder, s xml.StartElement) error

MarshalXML customizes xml output for Writer

func (*Writer) SetControlID

func (w *Writer) SetControlID(controlID string) *Writer

SetControlID sets a unique identifier for the call

Directories

Path Synopsis
Code generated by intacct v3 schema; DO NOT EDIT.
Code generated by intacct v3 schema; DO NOT EDIT.

Jump to

Keyboard shortcuts

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