Calculations API reference: the lib library

lib is a library of general-purpose functions available in every calculation (on the Calculations tab and in shared scripts of the Calculations type). Unlike vars/proc/task (see Calculations API reference: variables and case), it handles individual, frequently repeated tasks – working with dates, text, users, the organization structure or roles. This article summarizes the functions available in TAS 5.19.12. Functions for files, DMS and printing are covered in a separate article, Printing and generating files in calculations; dynamic tables are covered in Dynamic Tables in calculations.

All functions are called with the lib. prefix, e.g. lib.format(...). For functions that read or change variables/users/roles, the first argument is usually the name, the ID or the object itself (vars['Supplier'], 'Supplier' and the TVAR_ID number are interchangeable).

Date and time

FunctionReturnsDescription
format(date, phpFormat)stringFormats a date using a PHP format string (yyyy-mm-dd h:MM:ss).
to_date(strDate)DateConverts YYYY-MM-DDThh:mi:ss text to a date.
alterDate(date, strTime)DateModifies a date the same way as PHP strtotime(), e.g. alterDate(vars['Start'], '+4 months').
wmd(date, businessDaysCount)DateAdds/subtracts a number of business days.
wmh(date, hoursAdd, startWork, endWork)DateAdds/subtracts a number of hours, taking working hours and public holidays into account.
whd(startTime, endTime, startWork, endWork)numberNumber of working hours between two dates.
wdd(startTime, endTime)numberNumber of working days between two dates.
wtd(startTime, endTime, unit, startWork, endWork)numberWorking time between two dates in the specified unit (minutes, hours...).
getExchangeRate(currency)*Current currency exchange rate (live from the Czech National Bank).
getHistoricExchangeRate(currency, date)*Currency exchange rate on the given date.
const days = lib.wdd(vars['DepartureDate'].getValue(), vars['ReturnDate'].getValue());
vars['TravelAllowance'].setValue(days * 600);

Text, numbers and arrays

FunctionReturnsDescription
fnRound(number)numberRounds to an integer.
fnNumber(number, decimals, decPoint, thousandsSep)stringFormats a number as text (thousands separator, decimal comma).
fnFloor(number)numberRounds down.
fnSubstr(value, startIndex, endIndex)stringExtracts part of a text by position.
fnStrLength(str)numberLength of a text.
fnStrPad(input, padLength, padString) / fnStrPadRight(...)stringPads a text on the left/right to the given length.
truncate(string, maxLength)stringShortens a text to the given length.
nl2p(text)stringConverts new lines to paragraphs (<p>).
random_text(length)stringRandom text made of the characters A–Z, a–z, 0–9.
gen_passc(length)stringSimple random password.
getChr(asciiCode)stringCharacter for an ASCII code.
fnPregMatch(pattern, subject)booleanTests against a regular expression (without slashes).
fnEq/fnNe/fnLt/fnGt... (and their ...10 variants for 10 values)booleanCompares values (===, !==, <, >...); arguments can also be functions.
fnAnd(v1, v2) / fnOr(v1, v2)booleanLogical AND/OR, also for functions as arguments.
fnEmpty(v1)booleantrue if the value is undefined, null or ''.
fnContain(v1, v2)booleanChecks whether v1 contains v2.
fnToArray(v1)Array<string>Splits a text into an array by the | character.
fnFromArray(glue, arr)stringJoins an array with the glue character.
fnArrayDiff(array1, array2) / fnArrayMerge(...) / fnArrayUnique(array1)arrayDifference, union and duplicate removal in an array.
fnInArray(needle, haystack) / fnDelFromArray(needle, haystack)boolean/arrayFinds and removes an element in an array.
jsonSumArray(json, pathInJson)numberSum of an array in JSON by path, e.g. obj.arr.
csvToArray(file) / csvToJson(data, delimiter, firstLineColNames) / jsonToCsv(data, mapping)–Conversions between CSV, arrays and JSON.
xmlToJson(xml) / jsonToXml(jsonObj) / xmlSanitize(text)–XML ↔ JSON conversions and sanitization of &, <, >.
htmlToText(html)stringStrips HTML tags.
md5/sha1/sha256/sha512(input, digest='hex')stringHash of the input string.
encrypt(input, algorithm, digest) / supportedEncryptAlgorithms()string/string[]Generic hash using the selected Node.js crypto algorithm.
getUUID() / validateUUID(id)string/booleanGenerates or validates a v4 UUID.
createQrCodeBase64(text, options) / createBarcodeBase64(text, options)stringQR code / barcode as a base64 image.
const rate = vars['VatRate'].getValue();
const totalWithVat = lib.fnRound(vars['TotalPrice'].getValue() * (1 + rate));
vars['TotalWithVat'].setValue(lib.fnNumber(totalWithVat, 2, ',', ' '));

Users, roles and organization structure

FunctionReturnsDescription
initiator()UserApiOwner (initiator) of the current case.
solver()UserApiSolver of the current task.
supervisor()UserApiSupervisor of the current case.
lastSolverOf(task)UserApiLast solver of the specified task.
getCurrentUser()UserApiUser under whom the calculation runs.
manager(orgstr) / orgManager(org)UserApiManager of an organization unit (the unit's manager or the manager of its subordinate unit, respectively).
user(login)stringThe user's "Last name First name".
userToFirstName(login) / userToLastName(login) / usersToFullName(login) / usersToDisplayName(login)stringIndividual forms of the user's name.
getUserNameById(login)stringThe user's login name.
getUserAttr(login, attributeName) / getOrgAttr(input, attributeName)*Value of any user/organization column (e.g. USER_EMAIL, ORGSTR_NAME).
getUserByAttr(attributeName, attributeValue, userStatus?)arrayFinds users by column and value.
getOrgByAttr(attributeName, attributeValue, singleResult=true)OrgStrApiOrganization unit by column (ORGSTR_NAME, PARENT_ORGSTR_ID...).
orgUnitOfUser(login)numberID of the user's organization unit.
orgStrNameToId(orgstr)numberID of an organization unit by name.
userInOrg(login, org) / userInOrgTree(login, org)booleanIs the user in the given unit / its tree?
userIsManager(login, org) / userIsManagerTree(login, org)booleanIs the user a manager of the given unit / its tree?
isUserInLevel(userName, level) / isManagerInLevel(userName, level)booleanIs the user (manager) at the given level of the organization structure?
hasOrgChild(orgstr)booleanDoes the unit have subordinate units?
roleToId(roleName) / idToRole(roleId)number/stringConverts between a role name and ID.
userHasRole(login, role)booleanDoes the user have the given role?
getUserWithRole(role, filterInactive?) / getUsersWithRole(role, filterInactive?, returnOnlyFirst?)UserApi/UserApi[]The first user / all users with the given role.
getUserWithOrganization(org, filterInactive?) / getUsersWithOrganization(...)UserApi/UserApi[]The first user / all users of the given organization unit.
getUserFromOrgWithRole(destVariableName, functionName, roleName, orgstrId)stringFinds a user with the given role in an organization unit and stores them in a variable.
setRoleToUser(user, roleName, roleCategory) / removeRoleFromUser(user, role) / clearRoleFromUsers(role)*Assigns a role to a user, removes it from a user, or removes it from all users.
getUsers(query) / getRoles(query) / getOrgUnits(query)objectPaginated list of users/roles/org. units – same behavior as the GET /users, /roles, /org-units services (filters, sort, page).
// Doplní e-mail manažera nákupu do proměnné jen pro čtení
const buyerManager = lib.getUserWithRole('Purchasing manager');
vars['ApproverEmail'].setValue(lib.getUserAttr(buyerManager, 'USER_EMAIL'));

Case, tasks and sequence numbers

FunctionReturnsDescription
iprocId() / itaskId(itaskName?)numberID of the current case / of a task by name (case-sensitive).
getSequenceNumber(name) / getSequenceNumberCond(name, cond)numberNext number from a number sequence (order numbering etc.), optionally only if a condition is met.
createNote(note) / createNonEmptyNote(note)*Adds a note to the case (the second variant only if the text is not empty).
setCaseOwner(login)*Changes the case owner.
changeCaseStatus(iprocId, status)–Sets IPROC_CASE_STATUS of another case.
setHeaderByName(headerName) / setHeaderByCode(headerCode)*Assigns a header of a multi-header template to the case.
getHeaderCode()stringHeader code of the current case.
getParentProcessStatus()stringStatus of the parent process (for a subprocess).
finishSubProcesses() / finishSubprocessTree()–Finishes first-level subprocesses / the entire subprocess tree.
getListSubProcess(archivedIncluded=false)*List of IDs of the case's subprocesses.
getSharedVariables(iprocId, {tvarIds, tvarNames})objectVariables of another case marked for sharing.
findShareVariables(filter, iprocStatus, tProcId)–Finds cases where a shared variable matches the filter.
setEventFilter(taskName, processVarName, eventVarName)*Sets a filter for waiting for an external event.
addStaticRights(userNames, groupName) / removeStaticRightsGroup(groupName) / removeStaticRightsUser(user)*Adds/removes static case visibility rights.
assignRightsToSubprocesses()*Adds a visibility right to the subprocess.
changeITaskComment(itaskId, comment, lang?)–Changes the comment of another task in the same case.
changeMailRecipient(mails) / changeMailAttribute(attribute, value, language?)stringChanges the recipient/attribute of the e-mail notification linked to this task.
generalApprover(dtLimit, limitRowId, dtSchval, schvalRowId, actual, totalValue)numberReturns the number matching an approval condition in the process graph based on limits in a dynamic table.
customView(cvId, filter, order, sort, offset, limit)*Loads overview data the same way as the cv/:id service.
vars['OrderNumber'].setValue('PO-' + new Date().getFullYear() + '-' + lib.getSequenceNumber('purchaseOrders'));

Dynamic lists and legacy dynamic table functions

Newer code for dynamic tables uses dt.from(...) (see Dynamic Tables in calculations); these lib functions are older equivalents kept for backward compatibility and for working with Dynamic List/Dynamic Rows variables:

FunctionReturnsDescription
fillDLList(listVarName) / fillList(listVarName)*Selects/fills all allowed values of a list variable.
fullList(varName)*List of allowed values of a list variable.
setUserList(listVarName, source, delimiter)*Fills a dynamic list with user names separated by the specified character.
defDynList(dynListName, operation, fnc, param1, param2, onlyActive) / defDynListOrg(...)*Modifies the filter of the dynamic list options.
dynListToString(listVarName, glue)stringJoins the list values with the specified character.
changeVariableDLName(varName, newDLName)stringChanges a variable's DLIST_NAME at runtime (common with headers).
dynamicTableGetCell(dlName, colIndex, rowIndex) / dynamicTableUpdateCell(...) / dynamicTableUpdateCellCond(...)–Reads/updates a dynamic table cell by index.
dynamicTableGetRowId(dlName, colIndex, rowValue) / dynamicTableGetNewRowId(dlName, method) / dynamicTableGetNewRowIdCond(...)stringFinds, or creates and returns, a row index.
dynamicTableGetRowCounts(dt)numberNumber of rows in the table.
updateDTFromCsv(dynTableName, csvContent, firstLineHeaders, delimiter, operation, fileName) / updateDtFromDb(dbTableName, dynTableName, mapping, operation, rowCb)*Fills a dynamic table from CSV or from a database table, respectively.
getDRCell(varName, colName, rowIndex) / getDRCol(varName, drColName) / getCurrentRowOfDRCell(varName, colName)stringDynamic Row values by column/row/current iteration.
addRowsToDR(drName, value) / fnDelFromDR(drName, colName, value)*Adds or deletes Dynamic Row rows, respectively.
extendDR(srcDRName, dstSrcName, map)*Fills the target Dynamic Row with data from the source one according to a column mapping.
translateDynamicRowTemplate(template, drName)stringReplaces @Index and @{ColName} in a text with values from a Dynamic Row.
setDRAsIterator(varName, drColName) / getCurrentIteration() / getIteratorIndex() / iterator(position)–Working with a variable as an iterator (multi-instance).

Other services in calculations

Besides lib, a task calculation also has the following standalone objects available:

ObjectWhat it does
html.parse(input)Parses an HTML string into a tree that can be traversed with querySelector/querySelectorAll – useful for reading data from HTML responses or templates.
sql.execute(query, params?)Runs a raw SQL query against the TAS database and returns an array of rows. Always pass parameters via the second argument, never directly in the string (SQL injection).
jwt.sign/verify/decode(...)Signs, verifies or decodes a JWT token (the jsonwebtoken library). jwt.secureSign/secureVerify additionally sign with a secret from the Vault based on securitySelector.
vault.get(name)Returns a non-serializable reference to a secret from the Vault – it is passed only to trusted APIs, e.g. axios...setVaultHeader().
identity.findUser(userName) / findByExternalId/findByObjectGUID/findByImmutableId / findOrCreateUser(...) / assignManagers(...) / setOrganization(...) / createOrganizationStructure(...)Finding and managing users/the organization structure linked to external identities (Azure AD etc.).
ai.processDocument(fileName, schema?)Sends an attached document to AI and uses it to fill in the task variables (or variables based on a custom JSON schema).
ftp.getFtpClient(config) / getFtpClientWithVaultPassword(config, passwordRef)Returns a client for an FTP/SFTP server with the methods list, upload, download, delete, exists, createDirectory, removeDirectory, rename.
axios.getAxios(config)Returns an HTTP client with the methods get/post/put/patch/delete/request, support for form files (sendFile, sendFormData) and insertion of Vault secrets into headers (setVaultHeader).
// Volání externího API s tokenem z Vaultu
const tokenRef = await vault.get('erp-api-token');
const client = await axios.getAxios({ baseURL: 'https://erp.example.com', timeout: 10000 });
client.setVaultHeader('Authorization', tokenRef, 'Bearer ');
const { data: supplier } = await client.get('/suppliers/' + vars['SupplierId'].getValue());
vars['SupplierName'].setValue(supplier.name);

How and when calculations run

Calculations API reference: variables and case

Syca (opens in a new tab)

Powered by HelpDocs (opens in a new tab)