Microbizz script - functions

Microbizz script - functions

 

Notice that the availability of some functions depends on the context in which the script is run. F.ex. scripts that are run as a custom field do not support the API functions as that would make the whole system slow and unusable.

Maths

The maths functions are available through the Math object.

number = Math.acos(number)

Returns acos of number

number = Math.asin(number)

Returns asin of number

number = Math.atan(number)

Returns atan of number

number = Math.ceil(number)

Returns the smallest integer that is larger or equal to the number

number = Math.cos(number)

Returns cos of number

number = Math.exp(number)

Returns "e" raises to the power of number

number = Math. floor(number)

Returns the largest integer that is smaller or equal to the number

number = Math.ln(number)

Returns the natural log of number

number = Math.log(number)

Returns the log base10 of number

number = Math.max(number[,number[,number…]])

Returns the largest of the arguments

number = Math.min(number[,number[,number…]])

Returns the smallest of the arguments

number = Math.pow(number,exponent)

Returns the number raised to the power of exponent

number = Math.random(min,max)

Returns a value between min and max

number =Math.random(max)

Returns a value between 0 and max

number = Math.random()

Returns a value between 0 and 1

number = Math.round(number)

Returns the nearest integer

number = Math.sin(number)

Returns sin of number

number = Math.sqrt(number)

Returns the square root of the number

number = Math.sum(number[,number[,number…]])

Returns the sum of the arguments

number = Math.tan(number)

Returns tan of number

The Math object also provides two constants Math.PI and Math.e .

Date

The date and time functions are available through the Date object.

string = Date.date(format[,timestamp])

Similar to PHPs date() function

string = Date.dateadjust(date, adjustment)

See below

timestamp = Date.strtotime(string)

Similar to PHPs strtotime() function

timestamp = Date.time()

Seconds since 1970-01-01 00:00:00

timestamp = Date.timeadjust(timestamp, adjustment)

See below

For Date.timeadjust() and Date.dateadjust() the adjustment argument is a string containing a SPACE seperated list of adjustments, the adjustments are applied one by one:

Adjustment syntax

Result

Examples

+NUU

Add N days/weeks/months/years/hours/minutes/seconds, UU=da/wk/mo/yr/hr/mi/se

+3wk

-NUU

See above

 

NUU

Set the day/month/year/hour/minutes/seconds

2018yr

firstDD

Go to the first weekday in the month, DD is a 2-char weekday

firstmo firsttu firstwe

lastDD

Go to the last weekday in the month, DD is a 2-char weekday

lastmo

nextDD

Go to the next weekday/month, DD is either a 2-char weekday or a 3-char month

nexttu nextjan nextfeb

prevDD

Go to the previous weekday/month, DD is either a 2-char weekday or a 3-char month

prevtu prevdec prevnov

Text

The following functions/methods may be called on strings, e.g.  newstring = todo.title.lower()  . 

string = string.base64decode()

Return a base64 decoded version of the string

string = string.base64encode()

Return a base64 encoded version of the string

number = string.bytes_length()

Return number of bytes (not chars!) in the string

string = string.bytes_substr(offset[,length])

Return a string containing part of the original string; notice that the result may not be valid UTF-8, f.ex.  bad = "Æ".bytes_substr(0, 1)

number = string.find(needle)

Find the offset of first occurence of the string needle in the string; returns -1 if not found; offset starts at 0

string = string.format(arglist)

Similar to Pythons format(), replace {name} with a value from the args

res = "{name} is {height} meters tall and {age}".format({height:1.78, age: 42, name: "Peter"})

res = "{0} is {1} meters tall and {2} years old".format(["Peter",1.78,24])

res = "{0} is {1} meters tall and {2} years old".format("Peter",1.78,24)

number = string.length()

Count the number of characters in the string

string = string.lower()

Return a lowercase version of the string

string = string.replace(from,to)

Similar to PHPs str_replace() function, replaces all occurences of from with to

number = string.rfind(needle)

Find the offset of the last occurence of the string needle in the string; returns -1 if not found

array = string.sscanf(format)

Similar to PHPs sscanf() function

array = string.split(seperatorstring)

Split the string at every occurence of the seperator string and return the parts in an array

string = string.sprintf([,arg1[,arg2…]])

Similar to PHPs sprintf() function, replace %s and %d etc with the args

res = "%s is %.2f meters tall".sprintf("Peter", 178/100)

string = string.substr(offset[,length])

Similar to PHPs mb_substr() function

string = string.urldecode()

Return a URL decoded version of the string

string = string.urlencode()

Return a URL encoded version of the string, so that it can be used as part of a URL

string = string.upper()

Return an uppercase version of the string

Array

The following functions/methods may be called on arrays, e.g.   numtodos = todoids.length()  . 

number = array.length()

Counts the number of elements in the array

string = array.join(seperatorstring)

Join the elements of an array, similar to PHPs implode() function

microbizz = ["m","crob","zz"].join("i")

array.sort()

Sorts the elements in the array. e.g colors = colors.sort(). This will modify the original array.

array.rsort()

Sorts the elements in the array reverse order  e.g numbers.rsort(). This will modify the original array

array.reverse()

Reverse the order of the content. e.g [8,3,4,9] into [9,4,3,8]. This will modify the original array.

array.append(value, [value, ...])

Appends values to an existing array. This will modify the original array. It is possible to append other arrays as well.

array.merge(array)

Merge the values of an array into another and insert them at the end of the original. Merging will modify the original array

array = array.slice(offset[, length[,preservekeys]])

Extract a slice of the array. Works similar to PHP's array_slice(). offset and length allows negative values; preservekeys accepts true or false.

array = array.splice(offset[,length[,replacement]])

Remove a slice of this array and possibly replace it with something else; returns the removed slice; the replacement may be a single value (a scalar) or an array

badstuff = ["good","good","bad","bad"].splice(2,2,"moregood")

array.clear()

Remove all elements from the array

number = array.index(value)

Return the index of a value, return -1 if the value is not found in the array

array = array.distinct()

Find distinct values and return them in a new array; only strings and numbers are considered.

res = [1,2,2,2,3,3,3].distinct()

string = array.json()

JSON encodes an array and returns it as a string

array = array.push(value)

Appends a value to the end of the array, returns the same array

value = array_pop()

Returns the last value in the array, removes the value from the array

array = array.unshift(value)

Inserts a value at the beginning of an array, returns the same array

value = array.shift()

Reads the value at the beginning of the array, removes the value from the array

These functions will probably first appear in spring 2022

Dict

dict.clear()

Remove all elements from the dict

dict = dict.copy()

Return a copy of the dict;

string = dict.json()

JSON encodes a dict and returns it as a string

array = dict.keys()

Return an array holding all the keys from the dict

dict.merge(dict)

NOT YET IMPLEMENTED

array = dict.values()

Return an array holding all the values from the dict

Misc

data = bar(valuesarray[,labelsarray])

Return an object which the frontend should display as a bar chart, see table() below

data = pie(valuesarray[,labelsarray])

Return an object which the frontend should display as a pie chart, see table() below

data  = table(rowarray[,rowarray[,rowarray ...]])

Return an object which the frontend should display a a table; the way pie(), bar() and table() work depend on the context

number = isnumber(value)

Returns 1 if the value is a number

number = isdict(value)

Returns 1 if the value is a dict

number = isobject(value)

Returns 1 if the value is an object

number = isstring(value)

Returns 1 if the value is a string

number = isarray(value)

Returns 1 if the value is an array

number = isNaN(value)

Returns 1 if the value is the value NaN (Not a Number)

number = isINFINITY(value)

Returns 1 if the value is the value infinity

number = isfunction(value)

Check if a function exists

ok = isfunction("Math.floor")

ok  = isfunction("get_class")

bad = isfunction("this_function_doesnt_exist")

string = get_class(object)

Returns the class of an object, eg "Todo" or "Tool" ; returns "" for non-objects

classname = get_class(this)

string = typeof(value)

Returns the type of a value, eg. "string", "number", "object" etc.

echo(value, ...)

Outputs the values; usually the result will not be displayed anywhere, this is for debugging only

exit(value)

Exit the script and return the value; may be called from within a function or loop

API

The API object provides a few functions for accessing APIs. Notice that the API object is only available for plugin scripts and update filter scripts.

result = API.post(url, postdata [, options])

Post data to a remote server, and read the result, see API.get for details.

postdata will be sent in the body of the request. See API.get() for details about the result.

result = API.get(url, getparameters [, options])

Read data from a remote server

getparameters is a dict with name:value pairs that will be appended to the URL; options are described below.

Result is a dict containing the following:

name

type

meaning

status

number

1 if all went well, 0 on error

http

dict

details about the HTTP request, some of these fields may be included: code, milliseconds, responseheaders 

error

string

error message

data

string

the data retrieved from the server

 

result = API.microbizz(command, parameters[, options])

Communicate with Microbizz via the Microbizz API; quite low level.

Result is a dict containing the following:

name

type

meaning

status

number

1 if all went well, 0 on error

http

dict



result

dict

The reply from Microbizz, depends on the command, f.ex. GetTodoByID may return the fields status and todos. 

 

get/post/microbizz options

Name

Type

Meaning

headers

dict

List of headers to to include

 

responseheaders

number

Set to 1 to include the response headers in the result

timeout

number

Max seconds this request may take

only20x

number

If set to 1 then anything but a HTTP 20x return status will be considered an error

username

string

User name for basic authentication, password must also be set

password

string

Password for basic authentication, username must also be set

Examples

This examples shows how to read a task via the API

todo = readtodo(432) // the variable todo now holds a dict the task with id=432, or false if the task was not found def readtodo(id) todo = API.microbizz("GetTodoByID", { todoid:id }) // check that the result is valid, be careful to validate the result if !isdict(todo) || !isdict(todo.result) || !isarray(todo.result.todos) || !isdict(todo.result.todos[0])   return false return todo.result.todos[0]

Example 1 - read a task from the API

This example shows how to read a text file from a server, using http

res = API.get("http://system42.microbizz.dk/global.css", {}) // check that the result is valid if (isdict(res) && res.status == 1)   css = res.data

Example 2 - read a file from a remote server

Microbizz

Notice that most of the functions in the Microbizz object are not available from custom fields and update filters. The function Microbizz.Log() is available for update filters.

object = Microbizz.GetTodoByID(id)

Read a task

object = Microbizz.GetCustomerByID(id)

Read a customer

object = Microbizz.GetUserByID(id)

Read a user

object = Microbizz.GetToolByID(id)

Read an equipment/tool

object = Microbizz.GetProjectByID(id)

Read a project

object = Microbizz.GetSupportTicketByID(id)

Read a ticket