Skip to main content
Skip table of contents

Microbizz script - functions

Maths

The maths functions are available through the Math object.

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.sum(number[,number[,number…]])Returns the sum of the arguments
number = Math.min(number[,number[,number…]])Returns the smallest of the arguments
number = Math.max(number[,number[,number…]])Returns the largest of the arguments
number = Math.ceil(number)Returns the smallest integer that is larger or equal to the number
number = Math. floor(number)Returns the largest integer that is smaller or equal to the number
number = Math.round(number)Returns the nearest integer
number = Math.pow(number,exponent)Returns the number raised to the power of exponent
number = Math.sqrt(number)Returns the square root of the number
number = Math.exp(number)Returns "e" raises to the power of number
number = Math.log(number)Returns the log base10 of number
number = Math.ln(number)Returns the natural log of number
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.cos(number)Returns cos of number
number = Math.sin(number)Returns sin of number
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.

timestamp = Date.time()Seconds since 1970-01-01 00:00:00
string = Date.date(format[,timestamp])Similar to PHPs date() function
timestamp = Date.strtotime(string)Similar to PHPs strtotime() function
timestamp = Date.timeadjust(timestamp, adjustment)See below
string = Date.dateadjust(date, 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

+NUUAdd N days/weeks/months/years/hours/minutes/seconds, UU=da/wk/mo/yr/hr/mi/se+3wk
-NUUSee above
NUUSet the day/month/year/hour/minutes/seconds2018yr
firstDDGo to the first weekday in the month, DD is a 2-char weekdayfirstmo firsttu firstwe
lastDDGo to the last weekday in the month, DD is a 2-char weekdaylastmo
nextDDGo to the next weekday/month, DD is either a 2-char weekday or a 3-char monthnexttu nextjan nextfeb
prevDDGo to the previous weekday/month, DD is either a 2-char weekday or a 3-char monthprevtu prevdec prevnov

Text

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

number = string.length()

Count the number of characters in the string
string = string.lower()Return a lowercase version of the string
string = string.upper()Return an uppercase version of the string
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
number = string.rfind(needle)Find the offset of the last occurence of the string needle in the string; returns -1 if not found
string = string.substr(offset[,length])Similar to PHPs mb_substr() function
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.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)

string = string.replace(from,to)Similar to PHPs str_replace() function, replaces all occurences of from with to
string = string.urlencode()Return a URL encoded version of the string, so that it can be used as part of a URL
string = string.urldecode()Return a URL decoded version of the string
string = string.base64encode()Return a base64 encoded version of the string
string = string.base64decode()Return a base64 decoded version of the string
array = string.split(seperatorstring)Split the string at every occurence of the seperator string and return the parts in an array
array = string.sscanf(format)Similar to PHPs sscanf() function
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)

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 (star)
value = array_pop()Returns the last value in the array, removes the value from the array (star)
array = array.unshift(value)Inserts a value at the beginning of an array, returns the same array (star)
value = array.shift()Reads the value at the beginning of the array, removes the value from the array (star)

(star)These functions will probably first appear in spring 2022

Dict

array = dict.keys()Return an array holding all the keys from the dict
array = dict.values()Return an array holding all the values from the dict
dict.merge(dict)NOT YET IMPLEMENTED
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

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

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:

nametypemeaning
statusnumber1 if all went well, 0 on error
httpdictdetails about the HTTP request, some of these fields may be included: code, milliseconds, responseheaders 
errorstringerror message
datastringthe 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:

nametypemeaning
statusnumber1 if all went well, 0 on error
httpdict
resultdictThe reply from Microbizz, depends on the command, f.ex. GetTodoByID may return the fields status and todos. 

get/post/microbizz options

NameTypeMeaning
headersdict

List of headers to to include

responseheadersnumberSet to 1 to include the response headers in the result
timeoutnumberMax seconds this request may take
only20xnumberIf set to 1 then anything but a HTTP 20x return status will be considered an error
usernamestringUser name for basic authentication, password must also be set
passwordstringPassword 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

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
object = Microbizz.GetEdiInvoiceByID(id)Read an EDI
object = Microbizz.GetRegistrationByID(id)Read a registration
object = Microbizz.GetPersonByID(id)Read a person
object = Microbizz.GetInvoiceByID(id)Read an invoice
object = Microbizz.GetInvoiceExportLineByID(id)Read an invoice line
object = Microbizz.GetSalesContractByID(id)Read a quotation
object = Microbizz.GetProductByID(id)Read a product
object = Microbizz.GetEventByID(id)Read an appointment
Microbizz.Log(text, data)Write to the System log; the text should not be longer than 200 chars; the data can be a dict or array or string
Microbizz.SaveProperty(name, value)

Save a property in Microbizz, the name must be a string, the value must be a string, number, array or dict.

Don't use it for storing large amounts of data, the maximum size may be restricted to a few KBytes in the future.

The property may be read by any other script.

value = Microbizz.ReadProperty(string[,defaultvalue])

Read a previously saved property, see Microbizz.saveProperty().

If there is no previously saved value, or if the value is an empty string, then the default value is returned.

Microbizz.contractThis holds the contract number, e.g. 2345
Microbizz.useridThis holds the ID of the active user
Microbizz.languageThis holds the two letter code of the currently selected language, e.g. "en"
Microbizz.thousandseparatorThis holds the thousand separator for the selected language
Microbizz.decimalpointThis holds the decimal point for the selected language

Notice that you cannot have multiple copies of the same task or customer etc. F.ex. if you call

  firsttask = Microbizz.GetTodoByID(1234)

  secondtask = Microbizz.GetTodoByID(1234)

then any changes you make to firsttask will also be made to secondtask.

HTML

The HTML object provides functions for generating HTML. Notice the custom fields only allow simple HTML (like <span>), plugins don't allow HTML generation at all, and scripts that are displayed in a tab allow much more complex HTML to be generated.

This is still experimental and may change at any time.

Custom fields

HTML.span(text [,style[,attributes]]Return an HTML string with a <span> element; style and attributes are dicts 
HTML.div(text [,style[,attributes]]Similar to HTML.SPAN() but returns a <div> element

Tab

string = HTML.encode(string)HTML encodes a string
HTML.html(string)Adds a piece of HTML to the output; you may simply generate all the tags yourself, as a string, and then just call this function once, but the other functions ensures that things are properly escaped/encoded.
HTML.text(string)

HTML encodes a string and adds it to the output, this is the same as

HTML.html(HTML.encode(string))

HTML.starttag(tag[, styles[, attrs[, classes]]])

Starts a tag (eg. <div>), styles and attrs are optional dicts, classes is an optional array

HTML.endtag(string)Ends a tag (eg. </div>)
object = HTML.output()Generate HTML, usually only used at the end of the script, in return

Example

styles = {"color":"red"}
HTML.starttag("div", styles, {"id":"mytag"})
HTML.text("A is < B")
HTML.endtag("div")
return HTML.output()

Example 3 - output HTML in a tab

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.