flows

package
v0.0.0-...-a2de6b1 Latest Latest
Warning

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

Go to latest
Published: Aug 22, 2024 License: AGPL-3.0 Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const (
	LocationLevelState    = envs.LocationLevel(1)
	LocationLevelDistrict = envs.LocationLevel(2)
	LocationLevelWard     = envs.LocationLevel(3)
)

location levels which can be field types

View Source
const NilMsgID = MsgID(0)

NilMsgID is our constant for nil message ids

View Source
const RedactionMask = "****************"

RedactionMask is the redaction mask for HTTP service logs

Variables

View Source
var EmptyHistory = &SessionHistory{}

EmptyHistory is used for a session which has no history

View Source
var RunContextTopLevels = []string{
	"child",
	"contact",
	"fields",
	"globals",
	"input",
	"legacy_extra",
	"node",
	"parent",
	"results",
	"resume",
	"run",
	"ticket",
	"trigger",
	"urns",
	"webhook",
}

RunContextTopLevels are the allowed top-level variables for expression evaluations

Functions

func ContactQueryEscaping

func ContactQueryEscaping(s string) string

ContactQueryEscaping is the escaping function used for expressions in contact queries

func Context

func Context(env envs.Environment, contextable Contextable) types.XValue

Context generates a lazy object for use in expressions

func ContextFunc

func ContextFunc(env envs.Environment, fn func(envs.Environment) map[string]types.XValue) *types.XObject

ContextFunc generates a lazy object for use in expressions

func NewEnvironment

func NewEnvironment(base envs.Environment, la *LocationAssets) envs.Environment

NewEnvironment creates a new environment

func ValidateURN

func ValidateURN(fl validator.FieldLevel) bool

ValidateURN validates whether the field value is a valid URN

func ValidateURNScheme

func ValidateURNScheme(fl validator.FieldLevel) bool

ValidateURNScheme validates whether the field value is a valid URN scheme

Types

type Action

type Action interface {
	utils.Typed
	Localizable
	FlowTypeRestricted

	UUID() ActionUUID
	Execute(Run, Step, ModifierCallback, EventCallback) error
	Validate() error
}

Action is an action within a flow node

type ActionUUID

type ActionUUID uuids.UUID

ActionUUID is the UUID of an action

type AirtimeService

type AirtimeService interface {
	// Transfer transfers airtime to the given URN
	Transfer(session Session, sender urns.URN, recipient urns.URN, amounts map[string]decimal.Decimal, logHTTP HTTPLogCallback) (*AirtimeTransfer, error)
}

AirtimeService provides airtime functionality to the engine

type AirtimeTransfer

type AirtimeTransfer struct {
	UUID          uuids.UUID
	Sender        urns.URN
	Recipient     urns.URN
	Currency      string
	DesiredAmount decimal.Decimal
	ActualAmount  decimal.Decimal
}

AirtimeTransfer is the result of an attempted airtime transfer

type AirtimeTransferStatus

type AirtimeTransferStatus string

AirtimeTransferStatus is a status of a airtime transfer

const (
	AirtimeTransferStatusSuccess AirtimeTransferStatus = "success"
	AirtimeTransferStatusFailed  AirtimeTransferStatus = "failed"
)

possible values for airtime transfer statuses

type BaseMsg

type BaseMsg struct {
	UUID_        MsgUUID                  `json:"uuid"`
	ID_          MsgID                    `json:"id,omitempty"`
	URN_         urns.URN                 `json:"urn,omitempty" validate:"omitempty,urn"`
	Channel_     *assets.ChannelReference `json:"channel,omitempty"`
	Text_        string                   `json:"text"`
	Attachments_ []utils.Attachment       `json:"attachments,omitempty"`
}

BaseMsg represents a incoming or outgoing message with the session contact

func (*BaseMsg) Attachments

func (m *BaseMsg) Attachments() []utils.Attachment

Attachments returns the attachments of this message

func (*BaseMsg) Channel

func (m *BaseMsg) Channel() *assets.ChannelReference

Channel returns the channel of this message

func (*BaseMsg) ID

func (m *BaseMsg) ID() MsgID

ID returns the internal ID of this message

func (*BaseMsg) SetID

func (m *BaseMsg) SetID(id MsgID)

SetID sets the internal ID of this message

func (*BaseMsg) SetURN

func (m *BaseMsg) SetURN(urn urns.URN)

SetURN returns the URN of this message

func (*BaseMsg) Text

func (m *BaseMsg) Text() string

Text returns the text of this message

func (*BaseMsg) URN

func (m *BaseMsg) URN() urns.URN

URN returns the URN of this message

func (*BaseMsg) UUID

func (m *BaseMsg) UUID() MsgUUID

UUID returns the UUID of this message

type CallStatus

type CallStatus string

CallStatus represents the status of a call to an external service

const (
	// CallStatusSuccess represents that the webhook was successful
	CallStatusSuccess CallStatus = "success"

	// CallStatusConnectionError represents that the webhook had a connection error
	CallStatusConnectionError CallStatus = "connection_error"

	// CallStatusResponseError represents that the webhook response had a non 2xx status code
	CallStatusResponseError CallStatus = "response_error"

	// CallStatusSubscriberGone represents a special state of resthook responses which indicate the caller must remove that subscriber
	CallStatusSubscriberGone CallStatus = "subscriber_gone"
)

func HTTPStatusFromCode

func HTTPStatusFromCode(t *httpx.Trace) CallStatus

HTTPStatusFromCode uses the status code to determine status of an HTTP log

type Category

type Category interface {
	Localizable

	UUID() CategoryUUID
	Name() string
	ExitUUID() ExitUUID
}

Category is how routers map results to exits

type CategoryUUID

type CategoryUUID uuids.UUID

CategoryUUID is the UUID of a node category

type Channel

type Channel struct {
	assets.Channel
}

Channel represents a means for sending and receiving input during a flow run

func NewChannel

func NewChannel(asset assets.Channel) *Channel

NewChannel creates a new channenl

func (*Channel) Asset

func (c *Channel) Asset() assets.Channel

Asset returns the underlying asset

func (*Channel) Context

func (c *Channel) Context(env envs.Environment) map[string]types.XValue

Context returns the properties available in expressions

__default__:text -> the name
uuid:text -> the UUID of the channel
name:text -> the name of the channel
address:text -> the address of the channel

@context channel

func (*Channel) HasParent

func (c *Channel) HasParent() bool

HasParent returns whether this channel has a parent

func (*Channel) HasRole

func (c *Channel) HasRole(role assets.ChannelRole) bool

HasRole returns whether this channel has the given role

func (*Channel) Reference

func (c *Channel) Reference() *assets.ChannelReference

Reference returns a reference to this channel

func (*Channel) String

func (c *Channel) String() string

func (*Channel) SupportsScheme

func (c *Channel) SupportsScheme(scheme string) bool

SupportsScheme returns whether this channel supports the given URN scheme

type ChannelAssets

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

ChannelAssets provides access to all channel assets

func NewChannelAssets

func NewChannelAssets(channels []assets.Channel) *ChannelAssets

NewChannelAssets creates a new set of channel assets

func (*ChannelAssets) Get

func (s *ChannelAssets) Get(uuid assets.ChannelUUID) *Channel

Get returns the channel with the given UUID

func (*ChannelAssets) GetForURN

func (s *ChannelAssets) GetForURN(urn *ContactURN, role assets.ChannelRole) *Channel

GetForURN returns the best channel for the given URN

type Classification

type Classification struct {
	Intents  []ExtractedIntent            `json:"intents,omitempty"`
	Entities map[string][]ExtractedEntity `json:"entities,omitempty"`
}

Classification is the result of an NLU classification

type ClassificationService

type ClassificationService interface {
	Classify(session Session, input string, logHTTP HTTPLogCallback) (*Classification, error)
}

ClassificationService provides NLU functionality to the engine

type Classifier

type Classifier struct {
	assets.Classifier
}

Classifier represents an NLU classifier.

func NewClassifier

func NewClassifier(asset assets.Classifier) *Classifier

NewClassifier returns a new classifier object from the given classifier asset

func (*Classifier) Asset

func (c *Classifier) Asset() assets.Classifier

Asset returns the underlying asset

func (*Classifier) Reference

func (c *Classifier) Reference() *assets.ClassifierReference

Reference returns a reference to this classifier

type ClassifierAssets

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

ClassifierAssets provides access to all classifier assets

func NewClassifierAssets

func NewClassifierAssets(classifiers []assets.Classifier) *ClassifierAssets

NewClassifierAssets creates a new set of classifier assets

func (*ClassifierAssets) Get

Get returns the classifier with the given UUID

type Connection

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

Connection represents a connection to a specific channel using a specific URN

func NewConnection

func NewConnection(channel *assets.ChannelReference, urn urns.URN) *Connection

NewConnection creates a new connection

func (*Connection) Channel

func (c *Connection) Channel() *assets.ChannelReference

Channel returns a reference to the channel

func (*Connection) MarshalJSON

func (c *Connection) MarshalJSON() ([]byte, error)

MarshalJSON marshals this connection into JSON

func (*Connection) URN

func (c *Connection) URN() urns.URN

URN returns the URN

func (*Connection) UnmarshalJSON

func (c *Connection) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarshals a connection from JSON

type Contact

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

Contact represents a person who is interacting with the flow

func NewContact

func NewContact(
	sa SessionAssets,
	uuid ContactUUID,
	id ContactID,
	name string,
	language envs.Language,
	status ContactStatus,
	timezone *time.Location,
	createdOn time.Time,
	lastSeenOn *time.Time,
	urns []urns.URN,
	groups []*assets.GroupReference,
	fields map[string]*Value,
	tickets []*Ticket,
	missing assets.MissingCallback) (*Contact, error)

NewContact creates a new contact with the passed in attributes

func NewEmptyContact

func NewEmptyContact(sa SessionAssets, name string, language envs.Language, timezone *time.Location) *Contact

NewEmptyContact creates a new empy contact with the passed in name, language and location

func ReadContact

func ReadContact(sa SessionAssets, data json.RawMessage, missing assets.MissingCallback) (*Contact, error)

ReadContact decodes a contact from the passed in JSON

func (*Contact) AddURN

func (c *Contact) AddURN(urn urns.URN, channel *Channel) bool

AddURN adds a new URN to this contact

func (*Contact) ClearURNs

func (c *Contact) ClearURNs() bool

ClearURNs clears the URNs on this contact

func (*Contact) Clone

func (c *Contact) Clone() *Contact

Clone creates a copy of this contact

func (*Contact) Context

func (c *Contact) Context(env envs.Environment) map[string]types.XValue

Context returns the properties available in expressions

__default__:text -> the name or URN
uuid:text -> the UUID of the contact
id:text -> the numeric ID of the contact
first_name:text -> the first name of the contact
name:text -> the name of the contact
language:text -> the language of the contact as 3-letter ISO code
created_on:datetime -> the creation date of the contact
last_seen_on:any -> the last seen date of the contact
urns:[]text -> the URNs belonging to the contact
urn:text -> the preferred URN of the contact
groups:[]group -> the groups the contact belongs to
fields:fields -> the custom field values of the contact
channel:channel -> the preferred channel of the contact
tickets:[]ticket -> the open tickets of the contact

@context contact

func (*Contact) Country

func (c *Contact) Country() envs.Country

Country gets the country for this contact..

TODO: currently this is taken from their preferred channel but probably should become an explicit field at some point

func (*Contact) CreatedOn

func (c *Contact) CreatedOn() time.Time

CreatedOn returns the created on time of this contact

func (*Contact) Equal

func (c *Contact) Equal(other *Contact) bool

Equal returns true if this instance is equal to the given instance

func (*Contact) Fields

func (c *Contact) Fields() FieldValues

Fields returns this contact's field values

func (*Contact) Format

func (c *Contact) Format(env envs.Environment) string

Format returns a friendly string version of this contact depending on what fields are set

func (*Contact) Groups

func (c *Contact) Groups() *GroupList

Groups returns the groups that this contact belongs to

func (*Contact) HasURN

func (c *Contact) HasURN(urn urns.URN) bool

HasURN checks whether the contact has the given URN

func (*Contact) ID

func (c *Contact) ID() ContactID

ID returns the numeric ID of this contact

func (*Contact) Language

func (c *Contact) Language() envs.Language

Language gets the language for this contact

func (*Contact) LastSeenOn

func (c *Contact) LastSeenOn() *time.Time

LastSeenOn returns the last seen on time of this contact

func (*Contact) Locale

func (c *Contact) Locale(env envs.Environment) envs.Locale

Locale gets the locale for this contact, using the environment country if contact doesn't have one

func (*Contact) MarshalJSON

func (c *Contact) MarshalJSON() ([]byte, error)

MarshalJSON marshals this contact into JSON

func (*Contact) Name

func (c *Contact) Name() string

Name returns the name of this contact

func (*Contact) PreferredChannel

func (c *Contact) PreferredChannel() *Channel

PreferredChannel gets the preferred channel for this contact, i.e. the channel we would use for sending

func (*Contact) PreferredURN

func (c *Contact) PreferredURN() *ContactURN

PreferredURN gets the preferred URN for this contact, i.e. the URN we would use for sending

func (*Contact) QueryProperty

func (c *Contact) QueryProperty(env envs.Environment, key string, propType contactql.PropertyType) []interface{}

QueryProperty resolves a contact query search key for this contact

Note that this method excludes id, group and flow search attributes as those are disallowed query based groups.

func (*Contact) ReevaluateQueryBasedGroups

func (c *Contact) ReevaluateQueryBasedGroups(env envs.Environment) ([]*Group, []*Group)

ReevaluateQueryBasedGroups reevaluates membership of all query based groups for this contact

func (*Contact) Reference

func (c *Contact) Reference() *ContactReference

Reference returns a reference to this contact

func (*Contact) RemoveURN

func (c *Contact) RemoveURN(urn urns.URN) bool

RemoveURN adds a new URN to this contact

func (*Contact) ResolveDestinations

func (c *Contact) ResolveDestinations(all bool) []Destination

ResolveDestinations resolves possible URN/channel destinations

func (*Contact) SetLanguage

func (c *Contact) SetLanguage(lang envs.Language)

SetLanguage sets the language for this contact

func (*Contact) SetLastSeenOn

func (c *Contact) SetLastSeenOn(t time.Time)

SetLastSeenOn sets the last seen on time of this contact

func (*Contact) SetName

func (c *Contact) SetName(name string)

SetName sets the name of this contact

func (*Contact) SetStatus

func (c *Contact) SetStatus(status ContactStatus)

SetStatus sets the status of this contact (blocked, stopped or active)

func (*Contact) SetTimezone

func (c *Contact) SetTimezone(tz *time.Location)

SetTimezone sets the timezone of this contact

func (*Contact) Status

func (c *Contact) Status() ContactStatus

Status returns the contact status

func (*Contact) Tickets

func (c *Contact) Tickets() *TicketList

Tickets returns the tickets that this contact has open

func (*Contact) Timezone

func (c *Contact) Timezone() *time.Location

Timezone returns the timezone of this contact

func (*Contact) URNs

func (c *Contact) URNs() URNList

URNs returns the URNs of this contact

func (*Contact) UUID

func (c *Contact) UUID() ContactUUID

UUID returns the UUID of this contact

func (*Contact) UpdatePreferredChannel

func (c *Contact) UpdatePreferredChannel(channel *Channel) bool

UpdatePreferredChannel updates the preferred channel and returns whether any change was made

type ContactID

type ContactID int64

ContactID is the ID of a contact

type ContactReference

type ContactReference struct {
	UUID ContactUUID `json:"uuid" validate:"required,uuid4"`
	Name string      `json:"name"`
}

ContactReference is used to reference a contact

func NewContactReference

func NewContactReference(uuid ContactUUID, name string) *ContactReference

NewContactReference creates a new contact reference with the given UUID and name

func (*ContactReference) Identity

func (r *ContactReference) Identity() string

Identity returns the unique identity of the asset

func (*ContactReference) String

func (r *ContactReference) String() string

func (*ContactReference) Type

func (r *ContactReference) Type() string

Type returns the name of the asset type

func (*ContactReference) Variable

func (r *ContactReference) Variable() bool

Variable returns whether this a variable (vs concrete) reference

type ContactStatus

type ContactStatus string

ContactStatus is status in which a contact is in

const (
	// ContactStatusActive is the contact status of active
	ContactStatusActive ContactStatus = "active"

	// ContactStatusBlocked is the contact status of blocked
	ContactStatusBlocked ContactStatus = "blocked"

	// ContactStatusStopped is the contact status of stopped
	ContactStatusStopped ContactStatus = "stopped"

	// ContactStatusArchived is the contact status of archived
	ContactStatusArchived ContactStatus = "archived"
)

type ContactURN

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

ContactURN represents a destination for an outgoing message or a source of an incoming message. It is string composed of 3 components: scheme, path, and display (optional). For example:

  • _tel:+16303524567_
  • _twitterid:54784326227#nyaruka_
  • _telegram:34642632786#bobby_

func NewContactURN

func NewContactURN(urn urns.URN, channel *Channel) *ContactURN

NewContactURN creates a new contact URN with associated channel

func ParseRawURN

func ParseRawURN(ca *ChannelAssets, rawURN urns.URN, missing assets.MissingCallback) (*ContactURN, error)

ParseRawURN converts a raw URN to a ContactURN by extracting it's channel reference

func (*ContactURN) Channel

func (u *ContactURN) Channel() *Channel

Channel gets the channel associated with this URN

func (*ContactURN) Equal

func (u *ContactURN) Equal(other *ContactURN) bool

Equal determines if this URN is equal to another

func (*ContactURN) SetChannel

func (u *ContactURN) SetChannel(channel *Channel)

SetChannel sets the channel associated with this URN

func (*ContactURN) String

func (u *ContactURN) String() string

func (*ContactURN) ToXValue

func (u *ContactURN) ToXValue(env envs.Environment) types.XValue

ToXValue returns a representation of this object for use in expressions

func (*ContactURN) URN

func (u *ContactURN) URN() urns.URN

URN gets the underlying URN

type ContactUUID

type ContactUUID uuids.UUID

ContactUUID is the UUID of a contact

type Contextable

type Contextable interface {
	Context(env envs.Environment) map[string]types.XValue
}

Contextable is an object that can accessed in expressions as a object with properties

type Dependency

type Dependency interface {
	Reference() assets.Reference
	Type() string
	Missing() bool
}

type Destination

type Destination struct {
	Channel *Channel
	URN     *ContactURN
}

Destination is a sendable channel and URN pair

type Dial

type Dial struct {
	Status   DialStatus `json:"status" validate:"required,dial_status"`
	Duration int        `json:"duration"`
}

Dial represents a dialed call or attempt to dial a phone number

func NewDial

func NewDial(status DialStatus, duration int) *Dial

NewDial creates a new dial

func (*Dial) Context

func (d *Dial) Context(env envs.Environment) map[string]types.XValue

Context for dial resumes additionally exposes the dial object

type DialStatus

type DialStatus string

DialStatus is the type for different dial statuses

const (
	DialStatusAnswered DialStatus = "answered"
	DialStatusNoAnswer DialStatus = "no_answer"
	DialStatusBusy     DialStatus = "busy"
	DialStatusFailed   DialStatus = "failed"
)

possible dial status values

type EmailService

type EmailService interface {
	Send(session Session, addresses []string, subject, body string) error
}

EmailService provides email functionality to the engine

type Engine

type Engine interface {
	NewSession(SessionAssets, Trigger) (Session, Sprint, error)
	ReadSession(SessionAssets, json.RawMessage, assets.MissingCallback) (Session, error)

	Services() Services
	MaxStepsPerSprint() int
	MaxResumesPerSession() int
	MaxTemplateChars() int
}

Engine provides callers with session starting and resuming

type Event

type Event interface {
	utils.Typed

	CreatedOn() time.Time
	StepUUID() StepUUID
	SetStepUUID(StepUUID)
}

Event describes a state change

type EventCallback

type EventCallback func(Event)

EventCallback is a callback invoked when an event has been generated

type Exit

type Exit interface {
	UUID() ExitUUID
	DestinationUUID() NodeUUID
}

Exit is a route out of a node and optionally to another node

type ExitUUID

type ExitUUID uuids.UUID

ExitUUID is the UUID of a node exit

type ExtractedEntity

type ExtractedEntity struct {
	Value      string          `json:"value"`
	Confidence decimal.Decimal `json:"confidence"`
}

ExtractedEntity models an entity match

type ExtractedIntent

type ExtractedIntent struct {
	Name       string          `json:"name"`
	Confidence decimal.Decimal `json:"confidence"`
}

ExtractedIntent models an intent match

type ExtractedReference

type ExtractedReference struct {
	Reference assets.Reference
	// contains filtered or unexported fields
}

ExtractedReference is a reference and its location in a flow

func NewExtractedReference

func NewExtractedReference(n Node, a Action, r Router, l envs.Language, ref assets.Reference) ExtractedReference

NewExtractedReference creates a new extracted reference

type ExtractedResult

type ExtractedResult struct {
	Node   Node
	Action Action
	Router Router
	Info   *ResultInfo
}

type ExtractedTemplate

type ExtractedTemplate struct {
	Template string
	// contains filtered or unexported fields
}

ExtractedTemplate is a template and its location in a flow

func NewExtractedTemplate

func NewExtractedTemplate(n Node, a Action, r Router, l envs.Language, t string) ExtractedTemplate

NewExtractedTemplate creates a new extracted template

type Field

type Field struct {
	assets.Field
}

Field represents a contact field

func NewField

func NewField(asset assets.Field) *Field

NewField creates a new field from the given asset

func (*Field) Asset

func (f *Field) Asset() assets.Field

Asset returns the underlying asset

func (*Field) Reference

func (f *Field) Reference() *assets.FieldReference

Reference returns a reference to this field

type FieldAssets

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

FieldAssets provides access to all field assets

func NewFieldAssets

func NewFieldAssets(fields []assets.Field) *FieldAssets

NewFieldAssets creates a new set of field assets

func (*FieldAssets) All

func (s *FieldAssets) All() []*Field

All returns all the fields in this set

func (*FieldAssets) FirstOfType

func (s *FieldAssets) FirstOfType(valueType assets.FieldType) *Field

FirstOfType returns the first field in this set with the given value type

func (*FieldAssets) Get

func (s *FieldAssets) Get(key string) *Field

Get returns the contact field with the given key

func (*FieldAssets) ResolveField

func (s *FieldAssets) ResolveField(key string) assets.Field

func (*FieldAssets) ResolveFlow

func (s *FieldAssets) ResolveFlow(name string) assets.Flow

func (*FieldAssets) ResolveGroup

func (s *FieldAssets) ResolveGroup(name string) assets.Group

type FieldValue

type FieldValue struct {
	*Value
	// contains filtered or unexported fields
}

FieldValue represents a field and a set of values for that field

func NewFieldValue

func NewFieldValue(field *Field, value *Value) *FieldValue

NewFieldValue creates a new field value

func (*FieldValue) QueryValue

func (v *FieldValue) QueryValue() interface{}

QueryValue returns the value for use in contact queries

func (*FieldValue) ToXValue

func (v *FieldValue) ToXValue(env envs.Environment) types.XValue

ToXValue returns a representation of this object for use in expressions

type FieldValues

type FieldValues map[string]*FieldValue

FieldValues is the set of all field values for a contact

func NewFieldValues

func NewFieldValues(a SessionAssets, values map[string]*Value, missing assets.MissingCallback) FieldValues

NewFieldValues creates a new field value map

func (FieldValues) Context

func (f FieldValues) Context(env envs.Environment) map[string]types.XValue

Context returns the properties available in expressions

func (FieldValues) Get

func (f FieldValues) Get(field *Field) *Value

Get gets the value set for the given field

func (FieldValues) Parse

func (f FieldValues) Parse(env envs.Environment, fields *FieldAssets, field *Field, rawValue string) *Value

Parse parses a raw string field value into the different possible types

func (FieldValues) Set

func (f FieldValues) Set(field *Field, value *Value)

Set sets the value for the given field (can be null to clear it)

type Flow

type Flow interface {
	Contextable

	// spec properties
	UUID() assets.FlowUUID
	Name() string
	Revision() int
	Language() envs.Language
	Type() FlowType
	ExpireAfterMinutes() int
	Localization() Localization
	UI() json.RawMessage
	Nodes() []Node
	GetNode(uuid NodeUUID) Node

	Asset() assets.Flow
	Reference() *assets.FlowReference

	Inspect(sa SessionAssets) *Inspection
	ExtractTemplates() []string
	ExtractLocalizables() []string
	ChangeLanguage(envs.Language) (Flow, error)
}

Flow describes the ordered logic of actions and routers

type FlowAssets

type FlowAssets interface {
	Get(assets.FlowUUID) (Flow, error)
	FindByName(string) (Flow, error)
}

FlowAssets provides access to flow assets

type FlowType

type FlowType string

FlowType represents the different types of flows

const (
	// FlowTypeMessaging is a flow that is run over a messaging channel
	FlowTypeMessaging FlowType = "messaging"

	// FlowTypeMessagingBackground is a non-interactive messaging flow (i.e. never waits for input)
	FlowTypeMessagingBackground FlowType = "messaging_background"

	// FlowTypeMessagingOffline is a flow which is run over an offline messaging client like Surveyor
	FlowTypeMessagingOffline FlowType = "messaging_offline"

	// FlowTypeVoice is a flow which is run over IVR
	FlowTypeVoice FlowType = "voice"
)

func (FlowType) Allows

func (t FlowType) Allows(r FlowTypeRestricted) bool

Allows returns whether this flow type allows the given item

type FlowTypeRestricted

type FlowTypeRestricted interface {
	AllowedFlowTypes() []FlowType
}

FlowTypeRestricted is a part of a flow which can be restricted to certain flow types

type Global

type Global struct {
	assets.Global
}

Global represents a constant value available in expressions.

func NewGlobal

func NewGlobal(asset assets.Global) *Global

NewGlobal returns a new global object from the given global asset

func (*Global) Asset

func (g *Global) Asset() assets.Global

Asset returns the underlying asset

func (*Global) Reference

func (g *Global) Reference() *assets.GlobalReference

Reference returns a reference to this global

type GlobalAssets

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

GlobalAssets provides access to all global assets

func NewGlobalAssets

func NewGlobalAssets(globals []assets.Global) *GlobalAssets

NewGlobalAssets creates a new set of global assets

func (*GlobalAssets) Context

func (s *GlobalAssets) Context(env envs.Environment) map[string]types.XValue

Context returns the properties available in expressions

func (*GlobalAssets) Get

func (s *GlobalAssets) Get(key string) *Global

Get returns the global with the given key

type Group

type Group struct {
	assets.Group
	// contains filtered or unexported fields
}

Group adds some functionality to group assets.

func NewGroup

func NewGroup(env envs.Environment, fields *FieldAssets, asset assets.Group) (*Group, error)

NewGroup returns a new group object from the given group asset

func (*Group) Asset

func (g *Group) Asset() assets.Group

Asset returns the underlying asset

func (*Group) CheckQueryBasedMembership

func (g *Group) CheckQueryBasedMembership(env envs.Environment, contact *Contact) bool

CheckQueryBasedMembership returns whether the given contact belongs in a query based group

func (*Group) Reference

func (g *Group) Reference() *assets.GroupReference

Reference returns a reference to this group

func (*Group) ToXValue

func (g *Group) ToXValue(env envs.Environment) types.XValue

ToXValue returns a representation of this object for use in expressions

uuid:text -> the UUID of the group
name:text -> the name of the group

@context group

func (*Group) UsesQuery

func (g *Group) UsesQuery() bool

UsesQuery returns whether this group is query based

type GroupAssets

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

GroupAssets provides access to all group assets

func NewGroupAssets

func NewGroupAssets(env envs.Environment, fields *FieldAssets, groups []assets.Group) (*GroupAssets, []assets.Group)

NewGroupAssets creates a new set of group assets

func (*GroupAssets) All

func (s *GroupAssets) All() []*Group

All returns all the groups

func (*GroupAssets) FindByName

func (s *GroupAssets) FindByName(name string) *Group

FindByName looks for a group with the given name (case-insensitive)

func (*GroupAssets) Get

func (s *GroupAssets) Get(uuid assets.GroupUUID) *Group

Get returns the group with the given UUID

type GroupList

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

GroupList defines a contact's list of groups

func NewGroupList

func NewGroupList(a SessionAssets, refs []*assets.GroupReference, missing assets.MissingCallback) *GroupList

NewGroupList creates a new group list

func (*GroupList) Add

func (l *GroupList) Add(group *Group) bool

Add adds the given group to this group list

func (*GroupList) All

func (l *GroupList) All() []*Group

All returns all groups in this group list

func (*GroupList) Clear

func (l *GroupList) Clear()

Clear clears this group list

func (*GroupList) Count

func (l *GroupList) Count() int

Count returns the number of groups in this group list

func (*GroupList) FindByUUID

func (l *GroupList) FindByUUID(uuid assets.GroupUUID) *Group

FindByUUID returns the group with the passed in UUID or nil if not found

func (*GroupList) Remove

func (l *GroupList) Remove(group *Group) bool

Remove removes the given group from this group list

func (GroupList) ToXValue

func (l GroupList) ToXValue(env envs.Environment) types.XValue

ToXValue returns a representation of this object for use in expressions

type HTTPLog

type HTTPLog struct {
	*HTTPTrace
	CreatedOn time.Time `json:"created_on" validate:"required"`
}

HTTPLog describes an HTTP request/response

func NewHTTPLog

func NewHTTPLog(trace *httpx.Trace, statusFn HTTPLogStatusResolver, redact utils.Redactor) *HTTPLog

NewHTTPLog creates a new HTTP log from a trace

type HTTPLogCallback

type HTTPLogCallback func(*HTTPLog)

HTTPLogCallback is a function that handles an HTTP log

type HTTPLogStatusResolver

type HTTPLogStatusResolver func(t *httpx.Trace) CallStatus

HTTPLogStatusResolver is a function that determines the status of an HTTP log from the response

type HTTPLogger

type HTTPLogger struct {
	Logs []*HTTPLog
}

HTTPLogger logs HTTP logs

func (*HTTPLogger) Log

func (l *HTTPLogger) Log(h *HTTPLog)

Log logs the given HTTP log

type HTTPTrace

type HTTPTrace struct {
	URL        string     `json:"url" validate:"required"`
	StatusCode int        `json:"status_code,omitempty"`
	Status     CallStatus `json:"status" validate:"required"`
	Request    string     `json:"request" validate:"required"`
	Response   string     `json:"response,omitempty"`
	ElapsedMS  int        `json:"elapsed_ms"`
	Retries    int        `json:"retries"`
}

HTTPTrace describes an HTTP request/response

func NewHTTPTrace

func NewHTTPTrace(trace *httpx.Trace, status CallStatus) *HTTPTrace

NewHTTPTrace creates a new HTTP log from a trace

type Hint

type Hint interface {
	utils.Typed
}

Hint tells the caller what type of input the flow is expecting

type Input

type Input interface {
	utils.Typed
	Contextable

	UUID() InputUUID
	CreatedOn() time.Time
	Channel() *Channel
}

Input describes input from the contact and currently we only support one type of input: `msg`

type InputUUID

type InputUUID uuids.UUID

InputUUID is the UUID of an input

type Inspection

type Inspection struct {
	Dependencies []Dependency  `json:"dependencies"`
	Issues       []Issue       `json:"issues"`
	Results      []*ResultSpec `json:"results"`
	WaitingExits []ExitUUID    `json:"waiting_exits"`
	ParentRefs   []string      `json:"parent_refs"`
}

Inspection contains the results of flow inspection

type Issue

type Issue interface {
	utils.Typed

	NodeUUID() NodeUUID
	ActionUUID() ActionUUID
	Language() envs.Language
	Description() string
}

Issue is a problem found during flow inspection

type Label

type Label struct {
	assets.Label
}

Label represents a message label

func NewLabel

func NewLabel(asset assets.Label) *Label

NewLabel creates a new label from the given asset

func (*Label) Asset

func (l *Label) Asset() assets.Label

Asset returns the underlying asset

func (*Label) Reference

func (l *Label) Reference() *assets.LabelReference

Reference returns a reference to this label

type LabelAssets

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

LabelAssets provides access to all label assets

func NewLabelAssets

func NewLabelAssets(labels []assets.Label) *LabelAssets

NewLabelAssets creates a new set of label assets

func (*LabelAssets) All

func (s *LabelAssets) All() []*Label

All returns all the labels

func (*LabelAssets) FindByName

func (s *LabelAssets) FindByName(name string) *Label

FindByName looks for a label with the given name (case-insensitive)

func (*LabelAssets) Get

func (s *LabelAssets) Get(uuid assets.LabelUUID) *Label

Get returns the label with the given UUID

type LegacyExtraContributor

type LegacyExtraContributor interface {
	LegacyExtra() Results
}

LegacyExtraContributor is something which contributes results for constructing @legacy_extra

type Localizable

type Localizable interface {
	LocalizationUUID() uuids.UUID
}

Localizable is anything in the flow definition which can be localized and therefore needs a UUID

type Localization

type Localization interface {
	GetItemTranslation(envs.Language, uuids.UUID, string) []string
	SetItemTranslation(envs.Language, uuids.UUID, string, []string)
	Languages() []envs.Language
}

Localization provide a way to get the translations for a specific language

type LocationAssets

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

LocationAssets provides access to location assets

func NewLocationAssets

func NewLocationAssets(hierarchies []assets.LocationHierarchy) *LocationAssets

NewLocationAssets creates a new set of location assets

func (*LocationAssets) Hierarchies

func (s *LocationAssets) Hierarchies() []assets.LocationHierarchy

Hierarchies returns all hierarchies

type Modifier

type Modifier interface {
	utils.Typed

	Apply(envs.Environment, SessionAssets, *Contact, EventCallback)
}

Modifier is something which can modify a contact

type ModifierCallback

type ModifierCallback func(Modifier)

ModifierCallback is a callback invoked when a modifier has been generated

type MsgID

type MsgID int64

MsgID is the ID of a message

type MsgIn

type MsgIn struct {
	BaseMsg

	ExternalID_ string `json:"external_id,omitempty"`
}

MsgIn represents a incoming message from the session contact

func NewMsgIn

func NewMsgIn(uuid MsgUUID, urn urns.URN, channel *assets.ChannelReference, text string, attachments []utils.Attachment) *MsgIn

NewMsgIn creates a new incoming message

func (*MsgIn) ExternalID

func (m *MsgIn) ExternalID() string

ExternalID returns the optional external ID of this incoming message

func (*MsgIn) SetExternalID

func (m *MsgIn) SetExternalID(id string)

SetExternalID sets the external ID of this message

type MsgOut

type MsgOut struct {
	BaseMsg

	QuickReplies_ []string       `json:"quick_replies,omitempty"`
	Templating_   *MsgTemplating `json:"templating,omitempty"`
	Topic_        MsgTopic       `json:"topic,omitempty"`
	TextLanguage  envs.Language  `json:"text_language,omitempty"`
}

MsgOut represents a outgoing message to the session contact

func NewIVRMsgOut

func NewIVRMsgOut(urn urns.URN, channel *assets.ChannelReference, text string, textLanguage envs.Language, audioURL string) *MsgOut

NewIVRMsgOut creates a new outgoing message for IVR

func NewMsgOut

func NewMsgOut(urn urns.URN, channel *assets.ChannelReference, text string, attachments []utils.Attachment, quickReplies []string, templating *MsgTemplating, topic MsgTopic) *MsgOut

NewMsgOut creates a new outgoing message

func (*MsgOut) QuickReplies

func (m *MsgOut) QuickReplies() []string

QuickReplies returns the quick replies of this outgoing message

func (*MsgOut) Templating

func (m *MsgOut) Templating() *MsgTemplating

Templating returns the templating to use to send this message (if any)

func (*MsgOut) Topic

func (m *MsgOut) Topic() MsgTopic

Topic returns the topic to use to send this message (if any)

type MsgTemplating

type MsgTemplating struct {
	Template_  *assets.TemplateReference `json:"template"`
	Language_  envs.Language             `json:"language"`
	Country_   envs.Country              `json:"country"`
	Variables_ []string                  `json:"variables,omitempty"`
	Namespace_ string                    `json:"namespace"`
	MediaIds_  []string                  `json:"media_ids,omitempty"`
	Category_  string                    `json:"category"`
}

MsgTemplating represents any substituted message template that should be applied when sending this message

func NewMsgTemplating

func NewMsgTemplating(template *assets.TemplateReference, language envs.Language, country envs.Country, variables []string, namespace string, mediaIds []string, category string) *MsgTemplating

NewMsgTemplating creates and returns a new msg template

func (MsgTemplating) Country

func (t MsgTemplating) Country() envs.Country

Country returns the country that should be used for the template

func (MsgTemplating) Language

func (t MsgTemplating) Language() envs.Language

Language returns the language that should be used for the template

func (MsgTemplating) Namespace

func (t MsgTemplating) Namespace() string

Namespace returns the namespace that should be for the template

func (MsgTemplating) Template

func (t MsgTemplating) Template() *assets.TemplateReference

Template returns the template this msg template is for

func (MsgTemplating) Variables

func (t MsgTemplating) Variables() []string

Variables returns the variables that should be substituted in the template

type MsgTopic

type MsgTopic string

MsgTopic is the topic, as required by some channel types

const (
	NilMsgTopic      MsgTopic = ""
	MsgTopicEvent    MsgTopic = "event"
	MsgTopicAccount  MsgTopic = "account"
	MsgTopicPurchase MsgTopic = "purchase"
	MsgTopicAgent    MsgTopic = "agent"
)

possible msg topic values

type MsgUUID

type MsgUUID uuids.UUID

MsgUUID is the UUID of a message

type Node

type Node interface {
	UUID() NodeUUID
	Actions() []Action
	Router() Router
	Exits() []Exit

	Validate(Flow, map[uuids.UUID]bool) error

	EnumerateTemplates(Localization, func(Action, Router, envs.Language, string))
	EnumerateDependencies(Localization, func(Action, Router, envs.Language, assets.Reference))
	EnumerateResults(func(Action, Router, *ResultInfo))
	EnumerateLocalizables(func(uuids.UUID, string, []string, func([]string)))
}

Node is a single node in a flow

type NodeUUID

type NodeUUID uuids.UUID

NodeUUID is a UUID of a flow node

type Resthook

type Resthook struct {
	assets.Resthook
}

Resthook represents a named event and a set of subscribers

func NewResthook

func NewResthook(asset assets.Resthook) *Resthook

NewResthook returns a new resthook object

func (*Resthook) Asset

func (r *Resthook) Asset() assets.Resthook

Asset returns the underlying asset

type ResthookAssets

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

ResthookAssets provides access to all resthook assets

func NewResthookAssets

func NewResthookAssets(resthooks []assets.Resthook) *ResthookAssets

NewResthookAssets creates a new set of resthook assets

func (*ResthookAssets) FindBySlug

func (s *ResthookAssets) FindBySlug(slug string) *Resthook

FindBySlug finds the group with the given UUID

type Result

type Result struct {
	Name              string          `json:"name" validate:"required"`
	Value             string          `json:"value"`
	Category          string          `json:"category,omitempty"`
	CategoryLocalized string          `json:"category_localized,omitempty"`
	NodeUUID          NodeUUID        `json:"node_uuid"`
	Input             string          `json:"input,omitempty"` // should be called operand but too late now
	Extra             json.RawMessage `json:"extra,omitempty"`
	CreatedOn         time.Time       `json:"created_on" validate:"required"`
}

Result describes a value captured during a run's execution. It might have been implicitly created by a router, or explicitly created by a [set_run_result](#action:set_run_result) action.

func NewResult

func NewResult(name string, value string, category string, categoryLocalized string, nodeUUID NodeUUID, input string, extra json.RawMessage, createdOn time.Time) *Result

NewResult creates a new result

func (*Result) Context

func (r *Result) Context(env envs.Environment) map[string]types.XValue

Context returns the properties available in expressions

__default__:text -> the value
name:text -> the name of the result
value:text -> the value of the result
category:text -> the category of the result
category_localized:text -> the localized category of the result
input:text -> the input of the result
extra:any -> the extra data of the result such as a webhook response
node_uuid:text -> the UUID of the node in the flow that generated the result
created_on:datetime -> the creation date of the result

@context result

type ResultInfo

type ResultInfo struct {
	Key        string   `json:"key"`
	Name       string   `json:"name"`
	Categories []string `json:"categories"`
}

ResultInfo is possible result that a flow might generate

func NewResultInfo

func NewResultInfo(name string, categories []string) *ResultInfo

NewResultInfo creates a new result spec

func (*ResultInfo) String

func (r *ResultInfo) String() string

type ResultSpec

type ResultSpec struct {
	ResultInfo
	NodeUUIDs []string `json:"node_uuids"`
}

func NewResultSpecs

func NewResultSpecs(results []ExtractedResult) []*ResultSpec

NewResultSpecs merges extracted results based on key

type Results

type Results map[string]*Result

Results is our wrapper around a map of snakified result names to result objects

func NewResults

func NewResults() Results

NewResults creates a new empty set of results

func (Results) Clone

func (r Results) Clone() Results

Clone returns a clone of this results set

func (Results) Context

func (r Results) Context(env envs.Environment) map[string]types.XValue

Context returns the properties available in expressions

func (Results) Get

func (r Results) Get(key string) *Result

Get returns the result with the given key

func (Results) Save

func (r Results) Save(result *Result)

Save saves a new result in our map. The key is saved in a snakified format

type Resume

type Resume interface {
	utils.Typed
	Contextable

	Apply(Run, EventCallback)

	Environment() envs.Environment
	Contact() *Contact
	ResumedOn() time.Time
}

Resume represents something which can resume a session with the flow engine

type Router

type Router interface {
	utils.Typed

	Wait() Wait
	Categories() []Category
	ResultName() string

	Validate(Flow, []Exit) error
	AllowTimeout() bool
	Route(Run, Step, EventCallback) (ExitUUID, string, error)
	RouteTimeout(Run, Step, EventCallback) (ExitUUID, error)

	EnumerateTemplates(Localization, func(envs.Language, string))
	EnumerateDependencies(Localization, func(envs.Language, assets.Reference))
	EnumerateResults(func(*ResultInfo))
	EnumerateLocalizables(func(uuids.UUID, string, []string, func([]string)))
}

Router is a router on a note which can pick an exit

type Run

type Run interface {
	Contextable
	RunSummary
	FlowReference() *assets.FlowReference

	Environment() envs.Environment
	Session() Session
	SaveResult(*Result)
	SetStatus(RunStatus)
	Webhook() types.XValue
	SetWebhook(types.XValue)

	CreateStep(Node) Step
	Path() []Step
	PathLocation() (Step, Node, error)

	LogEvent(Step, Event)
	LogError(Step, error)
	Events() []Event
	ReceivedInput() bool

	EvaluateTemplateValue(string) (types.XValue, error)
	EvaluateTemplateText(string, excellent.Escaping, bool) (string, error)
	EvaluateTemplate(string) (string, error)
	RootContext(envs.Environment) map[string]types.XValue

	GetText(uuids.UUID, string, string) string
	GetTextArray(uuids.UUID, string, []string) ([]string, envs.Language)
	GetTranslatedTextArray(uuids.UUID, string, []string, []envs.Language) []string

	Snapshot() RunSummary
	Parent() RunSummary
	ParentInSession() Run
	Ancestors() []Run

	CreatedOn() time.Time
	ModifiedOn() time.Time
	ExitedOn() *time.Time
	Exit(RunStatus)
}

Run is a single contact's journey through a flow. It records the path they have taken, and the results that have been collected.

type RunStatus

type RunStatus string

RunStatus represents the current status of the flow run

const (
	// RunStatusActive represents a run that is still active
	RunStatusActive RunStatus = "active"

	// RunStatusCompleted represents a run that has run to completion
	RunStatusCompleted RunStatus = "completed"

	// RunStatusWaiting represents a run which is waiting for something from the caller
	RunStatusWaiting RunStatus = "waiting"

	// RunStatusFailed represents a run that encountered an unrecoverable error
	RunStatusFailed RunStatus = "failed"

	// RunStatusExpired represents a run that expired due to inactivity
	RunStatusExpired RunStatus = "expired"
)

type RunSummary

type RunSummary interface {
	UUID() RunUUID
	Contact() *Contact
	Flow() Flow
	Status() RunStatus
	Results() Results
}

RunSummary represents the minimum information available about all runs (current or related) and is the representation of runs made accessible to router tests.

type RunUUID

type RunUUID uuids.UUID

RunUUID is the UUID of a flow run

type Segment

type Segment interface {
	Flow() Flow
	Node() Node
	Exit() Exit
	Operand() string
	Destination() Node
	Time() time.Time
}

Segment is a movement on the flow graph from an exit to another node

type Services

type Services interface {
	Email(Session) (EmailService, error)
	Webhook(Session) (WebhookService, error)
	Classification(Session, *Classifier) (ClassificationService, error)
	Ticket(Session, *Ticketer) (TicketService, error)
	Airtime(Session) (AirtimeService, error)
}

Services groups together interfaces for several services whose implementation is provided outside of the flow engine.

type Session

type Session interface {
	Assets() SessionAssets

	UUID() SessionUUID
	Type() FlowType
	SetType(FlowType)

	Environment() envs.Environment
	SetEnvironment(envs.Environment)

	Contact() *Contact
	SetContact(*Contact)

	Input() Input
	SetInput(Input)

	Status() SessionStatus
	Trigger() Trigger
	CurrentResume() Resume
	BatchStart() bool
	PushFlow(Flow, Run, bool)

	Resume(Resume) (Sprint, error)
	Runs() []Run
	GetRun(RunUUID) (Run, error)
	FindStep(uuid StepUUID) (Run, Step)
	GetCurrentChild(Run) Run
	ParentRun() RunSummary
	CurrentContext() *types.XObject
	History() *SessionHistory

	Engine() Engine
}

Session represents the session of a flow run which may contain many runs

type SessionAssets

type SessionAssets interface {
	contactql.Resolver

	Source() assets.Source

	Channels() *ChannelAssets
	Classifiers() *ClassifierAssets
	Fields() *FieldAssets
	Flows() FlowAssets
	Globals() *GlobalAssets
	Groups() *GroupAssets
	Labels() *LabelAssets
	Locations() *LocationAssets
	Resthooks() *ResthookAssets
	Templates() *TemplateAssets
	Ticketers() *TicketerAssets
	Topics() *TopicAssets
	Users() *UserAssets
}

SessionAssets is the assets available to a session

type SessionHistory

type SessionHistory struct {
	ParentUUID          SessionUUID `json:"parent_uuid"`
	Ancestors           int         `json:"ancestors"`
	AncestorsSinceInput int         `json:"ancestors_since_input"`
}

SessionHistory provides information about the sessions that caused this session

func NewChildHistory

func NewChildHistory(parent Session) *SessionHistory

NewChildHistory creates a new history for a child of the given session

func (*SessionHistory) Advance

func (h *SessionHistory) Advance(newParent SessionUUID, receivedInput bool) *SessionHistory

Advance moves history forward to a new parent

type SessionStatus

type SessionStatus string

SessionStatus represents the current status of the engine session

const (
	// SessionStatusActive represents a session that is still active
	SessionStatusActive SessionStatus = "active"

	// SessionStatusCompleted represents a session that has run to completion
	SessionStatusCompleted SessionStatus = "completed"

	// SessionStatusWaiting represents a session which is waiting for something from the caller
	SessionStatusWaiting SessionStatus = "waiting"

	// SessionStatusFailed represents a session that encountered an unrecoverable error
	SessionStatusFailed SessionStatus = "failed"
)

type SessionUUID

type SessionUUID uuids.UUID

SessionUUID is the UUID of a session

type Sprint

type Sprint interface {
	Modifiers() []Modifier
	Events() []Event
	Segments() []Segment
}

Sprint is an interaction with the engine - i.e. a start or resume of a session

type Step

type Step interface {
	Contextable

	UUID() StepUUID
	NodeUUID() NodeUUID
	ExitUUID() ExitUUID
	ArrivedOn() time.Time

	Leave(ExitUUID)
}

Step is a single step in the path thru a flow

type StepUUID

type StepUUID uuids.UUID

StepUUID is the UUID of a run step

type Template

type Template struct {
	assets.Template
}

Template represents messaging templates used by channels types such as WhatsApp

func NewTemplate

func NewTemplate(t assets.Template) *Template

NewTemplate returns a new template objects based on the passed in asset

func (*Template) Asset

func (t *Template) Asset() assets.Template

Asset returns the underlying asset

func (*Template) FindTranslation

func (t *Template) FindTranslation(channel assets.ChannelUUID, locales []envs.Locale) *TemplateTranslation

FindTranslation finds the matching translation for the passed in channel and languages (in priority order)

func (*Template) Reference

func (t *Template) Reference() *assets.TemplateReference

Reference returns the reference for this template

type TemplateAssets

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

TemplateAssets is our type for all the templates in an environment

func NewTemplateAssets

func NewTemplateAssets(ts []assets.Template) *TemplateAssets

NewTemplateAssets creates a new template list

func (*TemplateAssets) FindTranslation

func (a *TemplateAssets) FindTranslation(uuid assets.TemplateUUID, channel *assets.ChannelReference, locales []envs.Locale) *TemplateTranslation

FindTranslation looks through our list of templates to find the template matching the passed in uuid If no template or translation is found then empty string is returned

func (*TemplateAssets) Get

Get returns the template with the passed in UUID if any

type TemplateTranslation

type TemplateTranslation struct {
	assets.TemplateTranslation
}

TemplateTranslation represents a single translation for a template

func NewTemplateTranslation

func NewTemplateTranslation(t assets.TemplateTranslation) *TemplateTranslation

NewTemplateTranslation returns a new TemplateTranslation for the passed in asset

func (*TemplateTranslation) Asset

Asset returns the underlying asset

func (*TemplateTranslation) Locale

func (t *TemplateTranslation) Locale() envs.Locale

Locale returns the locale

func (*TemplateTranslation) Substitute

func (t *TemplateTranslation) Substitute(vars []string) string

Substitute substitutes the passed in variables in our template

type Ticket

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

Ticket is a ticket in a ticketing system

func NewTicket

func NewTicket(uuid TicketUUID, ticketer *Ticketer, topic *Topic, body, externalID string, assignee *User) *Ticket

NewTicket creates a new ticket

func OpenTicket

func OpenTicket(ticketer *Ticketer, topic *Topic, body string, assignee *User) *Ticket

OpenTicket creates a new ticket. Used by ticketing services to open a new ticket.

func ReadTicket

func ReadTicket(sa SessionAssets, data []byte, missing assets.MissingCallback) (*Ticket, error)

ReadTicket decodes a contact from the passed in JSON. If the ticketer or assigned user can't be found in the assets, we report the missing asset and return ticket without those.

func (*Ticket) Assignee

func (t *Ticket) Assignee() *User

func (*Ticket) Body

func (t *Ticket) Body() string

func (*Ticket) Context

func (t *Ticket) Context(env envs.Environment) map[string]types.XValue

Context returns the properties available in expressions

uuid:text -> the UUID of the ticket
subject:text -> the subject of the ticket
body:text -> the body of the ticket

@context ticket

func (*Ticket) ExternalID

func (t *Ticket) ExternalID() string

func (*Ticket) MarshalJSON

func (t *Ticket) MarshalJSON() ([]byte, error)

MarshalJSON marshals this ticket into JSON

func (*Ticket) SetExternalID

func (t *Ticket) SetExternalID(id string)

func (*Ticket) Ticketer

func (t *Ticket) Ticketer() *Ticketer

func (*Ticket) Topic

func (t *Ticket) Topic() *Topic

func (*Ticket) UUID

func (t *Ticket) UUID() TicketUUID

type TicketList

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

TicketList defines a contact's list of tickets

func NewTicketList

func NewTicketList(tickets []*Ticket) *TicketList

NewTicketList creates a new ticket list

func (*TicketList) Add

func (l *TicketList) Add(ticket *Ticket)

Adds adds the given ticket to this ticket list

func (*TicketList) All

func (l *TicketList) All() []*Ticket

All returns all tickets in this ticket list

func (*TicketList) Count

func (l *TicketList) Count() int

Count returns the number of tickets

func (TicketList) ToXValue

func (l TicketList) ToXValue(env envs.Environment) types.XValue

ToXValue returns a representation of this object for use in expressions

type TicketService

type TicketService interface {
	// Open tries to open a new ticket
	Open(session Session, topic *Topic, body string, assignee *User, logHTTP HTTPLogCallback) (*Ticket, error)
}

TicketService provides ticketing functionality to the engine

type TicketUUID

type TicketUUID uuids.UUID

TicketUUID is the UUID of a ticket

type Ticketer

type Ticketer struct {
	assets.Ticketer
}

Ticketer represents a ticket issuing system.

func NewTicketer

func NewTicketer(asset assets.Ticketer) *Ticketer

NewTicketer returns a new classifier object from the given classifier asset

func (*Ticketer) Asset

func (t *Ticketer) Asset() assets.Ticketer

Asset returns the underlying asset

func (*Ticketer) Reference

func (t *Ticketer) Reference() *assets.TicketerReference

Reference returns a reference to this classifier

type TicketerAssets

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

TicketerAssets provides access to all ticketer assets

func NewTicketerAssets

func NewTicketerAssets(ticketers []assets.Ticketer) *TicketerAssets

NewTicketerAssets creates a new set of ticketer assets

func (*TicketerAssets) Get

Get returns the ticketer with the given UUID

type Timeout

type Timeout interface {
	Seconds() int
	CategoryUUID() CategoryUUID
}

Timeout is a way to skip a wait after X amount of time

type Topic

type Topic struct {
	assets.Topic
}

Topic represents a ticket topic

func NewTopic

func NewTopic(asset assets.Topic) *Topic

NewTopic creates a new topic from the given asset

func (*Topic) Asset

func (t *Topic) Asset() assets.Topic

Asset returns the underlying asset

func (*Topic) Context

func (t *Topic) Context(env envs.Environment) map[string]types.XValue

Context returns the properties available in expressions

__default__:text -> the name
uuid:text -> the UUID of the topic
name:text -> the name of the topic

@context topic

func (*Topic) Reference

func (t *Topic) Reference() *assets.TopicReference

Reference returns a reference to this topic

type TopicAssets

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

TopicAssets provides access to all topic assets

func NewTopicAssets

func NewTopicAssets(topics []assets.Topic) *TopicAssets

NewTopicAssets creates a new set of topic assets

func (*TopicAssets) FindByName

func (s *TopicAssets) FindByName(name string) *Topic

FindByName looks for a topic with the given name (case-insensitive)

func (*TopicAssets) Get

func (s *TopicAssets) Get(uuid assets.TopicUUID) *Topic

Get returns the topic with the given UUID

type Trigger

type Trigger interface {
	utils.Typed
	Contextable

	Initialize(Session, EventCallback) error
	InitializeRun(Run, EventCallback) error

	Environment() envs.Environment
	Flow() *assets.FlowReference
	Contact() *Contact
	Connection() *Connection
	Batch() bool
	Params() *types.XObject
	History() *SessionHistory
	TriggeredOn() time.Time
}

Trigger represents something which can initiate a session with the flow engine

type TriggerWithRun

type TriggerWithRun interface {
	Trigger

	RunSummary() json.RawMessage
}

TriggerWithRun is special case of trigger that provides a parent run to the session

type URNList

type URNList []*ContactURN

URNList is the list of a contact's URNs

func ReadURNList

func ReadURNList(a SessionAssets, rawURNs []urns.URN, missing assets.MissingCallback) (URNList, error)

ReadURNList parses contact URN list from the given list of raw URNs

func (URNList) Equal

func (l URNList) Equal(other URNList) bool

Equal returns whether this list of URNs is equal to another

func (URNList) MapContext

func (l URNList) MapContext(env envs.Environment) map[string]types.XValue

MapContext returns a map of the highest priority URN for each scheme - exposed in expressions as @urns

func (URNList) RawURNs

func (l URNList) RawURNs() []urns.URN

RawURNs returns the raw URNs

func (URNList) ToXValue

func (l URNList) ToXValue(env envs.Environment) types.XValue

ToXValue returns a representation of this object for use in expressions

func (URNList) WithScheme

func (l URNList) WithScheme(scheme string) URNList

WithScheme returns a new URN list containing of only URNs of the given scheme

type User

type User struct {
	assets.User
}

User adds some functionality to user assets.

func NewUser

func NewUser(asset assets.User) *User

NewUser returns a new user object from the given user asset

func (*User) Asset

func (u *User) Asset() assets.User

Asset returns the underlying asset

func (*User) Context

func (u *User) Context(env envs.Environment) map[string]types.XValue

Context returns the properties available in expressions

__default__:text -> the name or email
email:text -> the email address of the user
name:text -> the name of the user
first_name:text -> the first name of the user

@context user

func (*User) Format

func (u *User) Format() string

Format returns a friendly string version of this user depending on what fields are set

func (*User) Reference

func (u *User) Reference() *assets.UserReference

Reference returns a reference to this user

type UserAssets

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

UserAssets provides access to all user assets

func NewUserAssets

func NewUserAssets(users []assets.User) *UserAssets

NewUserAssets creates a new set of user assets

func (*UserAssets) Get

func (s *UserAssets) Get(email string) *User

Get returns the user with the given email

type Value

type Value struct {
	Text     types.XText       `json:"text" validate:"required"`
	Datetime *types.XDateTime  `json:"datetime,omitempty"`
	Number   *types.XNumber    `json:"number,omitempty"`
	State    envs.LocationPath `json:"state,omitempty"`
	District envs.LocationPath `json:"district,omitempty"`
	Ward     envs.LocationPath `json:"ward,omitempty"`
}

Value represents a value in each of the field types

func NewValue

func NewValue(text types.XText, datetime *types.XDateTime, number *types.XNumber, state envs.LocationPath, district envs.LocationPath, ward envs.LocationPath) *Value

NewValue creates an empty value

func (*Value) Equals

func (v *Value) Equals(o *Value) bool

Equals determines whether two values are equal

type Wait

type Wait interface {
	utils.Typed
	FlowTypeRestricted

	Timeout() Timeout

	Begin(Run, EventCallback) bool
	Accepts(Resume) bool
}

Wait tells the engine that the session requires input from the user

type WebhookCall

type WebhookCall struct {
	*httpx.Trace
	ResponseJSON    []byte
	ResponseCleaned bool // whether response had to be cleaned to make it valid JSON
}

WebhookCall is the result of a webhook call

type WebhookService

type WebhookService interface {
	Call(session Session, request *http.Request) (*WebhookCall, error)
}

WebhookService provides webhook functionality to the engine

Jump to

Keyboard shortcuts

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