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
| Function | Returns | Description |
|---|
format(date, phpFormat) | string | Formats a date using a PHP format string (yyyy-mm-dd h:MM:ss). |
to_date(strDate) | Date | Converts YYYY-MM-DDThh:mi:ss text to a date. |
alterDate(date, strTime) | Date | Modifies a date the same way as PHP strtotime(), e.g. alterDate(vars['Start'], '+4 months'). |
wmd(date, businessDaysCount) | Date | Adds/subtracts a number of business days. |
wmh(date, hoursAdd, startWork, endWork) | Date | Adds/subtracts a number of hours, taking working hours and public holidays into account. |
whd(startTime, endTime, startWork, endWork) | number | Number of working hours between two dates. |
wdd(startTime, endTime) | number | Number of working days between two dates. |
wtd(startTime, endTime, unit, startWork, endWork) | number | Working 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
| Function | Returns | Description |
|---|
fnRound(number) | number | Rounds to an integer. |
fnNumber(number, decimals, decPoint, thousandsSep) | string | Formats a number as text (thousands separator, decimal comma). |
fnFloor(number) | number | Rounds down. |
fnSubstr(value, startIndex, endIndex) | string | Extracts part of a text by position. |
fnStrLength(str) | number | Length of a text. |
fnStrPad(input, padLength, padString) / fnStrPadRight(...) | string | Pads a text on the left/right to the given length. |
truncate(string, maxLength) | string | Shortens a text to the given length. |
nl2p(text) | string | Converts new lines to paragraphs (<p>). |
random_text(length) | string | Random text made of the characters A–Z, a–z, 0–9. |
gen_passc(length) | string | Simple random password. |
getChr(asciiCode) | string | Character for an ASCII code. |
fnPregMatch(pattern, subject) | boolean | Tests against a regular expression (without slashes). |
fnEq/fnNe/fnLt/fnGt... (and their ...10 variants for 10 values) | boolean | Compares values (===, !==, <, >...); arguments can also be functions. |
fnAnd(v1, v2) / fnOr(v1, v2) | boolean | Logical AND/OR, also for functions as arguments. |
fnEmpty(v1) | boolean | true if the value is undefined, null or ''. |
fnContain(v1, v2) | boolean | Checks whether v1 contains v2. |
fnToArray(v1) | Array<string> | Splits a text into an array by the | character. |
fnFromArray(glue, arr) | string | Joins an array with the glue character. |
fnArrayDiff(array1, array2) / fnArrayMerge(...) / fnArrayUnique(array1) | array | Difference, union and duplicate removal in an array. |
fnInArray(needle, haystack) / fnDelFromArray(needle, haystack) | boolean/array | Finds and removes an element in an array. |
jsonSumArray(json, pathInJson) | number | Sum 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) | string | Strips HTML tags. |
md5/sha1/sha256/sha512(input, digest='hex') | string | Hash of the input string. |
encrypt(input, algorithm, digest) / supportedEncryptAlgorithms() | string/string[] | Generic hash using the selected Node.js crypto algorithm. |
getUUID() / validateUUID(id) | string/boolean | Generates or validates a v4 UUID. |
createQrCodeBase64(text, options) / createBarcodeBase64(text, options) | string | QR 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
| Function | Returns | Description |
|---|
initiator() | UserApi | Owner (initiator) of the current case. |
solver() | UserApi | Solver of the current task. |
supervisor() | UserApi | Supervisor of the current case. |
lastSolverOf(task) | UserApi | Last solver of the specified task. |
getCurrentUser() | UserApi | User under whom the calculation runs. |
manager(orgstr) / orgManager(org) | UserApi | Manager of an organization unit (the unit's manager or the manager of its subordinate unit, respectively). |
user(login) | string | The user's "Last name First name". |
userToFirstName(login) / userToLastName(login) / usersToFullName(login) / usersToDisplayName(login) | string | Individual forms of the user's name. |
getUserNameById(login) | string | The 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?) | array | Finds users by column and value. |
getOrgByAttr(attributeName, attributeValue, singleResult=true) | OrgStrApi | Organization unit by column (ORGSTR_NAME, PARENT_ORGSTR_ID...). |
orgUnitOfUser(login) | number | ID of the user's organization unit. |
orgStrNameToId(orgstr) | number | ID of an organization unit by name. |
userInOrg(login, org) / userInOrgTree(login, org) | boolean | Is the user in the given unit / its tree? |
userIsManager(login, org) / userIsManagerTree(login, org) | boolean | Is the user a manager of the given unit / its tree? |
isUserInLevel(userName, level) / isManagerInLevel(userName, level) | boolean | Is the user (manager) at the given level of the organization structure? |
hasOrgChild(orgstr) | boolean | Does the unit have subordinate units? |
roleToId(roleName) / idToRole(roleId) | number/string | Converts between a role name and ID. |
userHasRole(login, role) | boolean | Does 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) | string | Finds 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) | object | Paginated 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
| Function | Returns | Description |
|---|
iprocId() / itaskId(itaskName?) | number | ID of the current case / of a task by name (case-sensitive). |
getSequenceNumber(name) / getSequenceNumberCond(name, cond) | number | Next 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() | string | Header code of the current case. |
getParentProcessStatus() | string | Status 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}) | object | Variables 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?) | string | Changes the recipient/attribute of the e-mail notification linked to this task. |
generalApprover(dtLimit, limitRowId, dtSchval, schvalRowId, actual, totalValue) | number | Returns 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:
| Function | Returns | Description |
|---|
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) | string | Joins the list values with the specified character. |
changeVariableDLName(varName, newDLName) | string | Changes 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(...) | string | Finds, or creates and returns, a row index. |
dynamicTableGetRowCounts(dt) | number | Number 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) | string | Dynamic 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) | string | Replaces @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:
| Object | What 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);