Automation

Formulas and calculator in Kommo

The widget automates calculations in Kommo using specified formulas

Features

Automation of calculations
Simple and complex formulas
Working with dates and products
Logical conditions
Margin calculation

Installation and setup guide

Detailed guide for working with widget "Formulas and calculator in Kommo"

Widget setup

When a lead moves to the bot stage, the bot will automatically fill in the field based on the calculation results.

Setting up a bot in a pipeline:

  • Select the stage where the bot will work and click + Add trigger.
  • In the list, select Salesbot → configure the conditions → click + Add new bot.
  • In the bot settings, go to the Widgets section → select Formula.
  • Click on the pencil icon.
  • Select the field in which the result will be written.
  • Enter the formula. Example: lead['Product price'] - lead['Product cost']
  • Add multiple formulas if necessary → repeat steps.

If necessary, add the following steps and terminate the bot. Next, save the bot and pipeline settings.

Realtime formulas

Realtime formulas are configured in the general settings of the “Formulas” widget (not in Salesbot).

  1. Open the general settings of the Formulas widget.
  2. Click on Add.
Click on Add
  1. Enter/select the field where to record the result.
Select a field to record the result
  1. Enter the formula.
Enter the formula
  1. Save your settings.

How it works at the front:

  • After opening a lead card, the formulas are executed automatically.
  • When you change field values ​​in a card, the formulas are recalculated automatically.
  • The result is immediately recorded in the selected fields in the same card.
  • The recalculation is performed with a slight delay to avoid unnecessary recalculations when entering.

Realtime formulas are suitable for online calculations in the lead card: margin, discounts, bonuses, cost, planned profit and other derived indicators.

Mathematical operations

You can use any mathematical operations in formulas:

  • addition (+)
  • subtraction (-)
  • multiplication (*)
  • division (/)

The formula is not limited to two variables. You can use any number of fields and values ​​necessary to calculate the result.

Constant values

If you need to use a constant value in formulas, you can set it using a trigger:

  1. Go to formula bot.
  2. Click Set Variables.

3. Create a new variable, specifying:

  • Name (Latin letters only).
  • Value (number or text).

Important when working with variables:

If the variable is not a number, convert it to a numeric type:

chislo(lead['Название поля с типом текст'])

If the variable is not text, convert it to a text type:

text(lead['Название поля с типом число'])

This is necessary for the formulas to work correctly and to prevent errors in calculations.

After this, the variable can be used in formulas along with Kommo fields.

Hints in formulas

In the formula input field, tooltips are available with the names of fields that can be used in calculations.

To display a tooltip, enter the symbol "[". After this, a drop-down list of available fields will appear.

Correct work with numbers

Sometimes Kommo treats values ​​as text, which results in a “glue” instead of addition (for example: 10+14+5 = 10145).

To avoid this, each value must be wrapped in parseInt().

Example:

parseInt(lead['Сумма в договоре']) - parseInt(lead['Бюджет'])

Logical conditions

Creating logical conditions (if-else in one line)

Example:

lead['поле1'] == 'успех' ? 'да' : 'нет'

Here:

  • if field1 = "success" → result "yes"
  • otherwise → result "no"

Various comparison operators are supported:

  • >= - greater than or equal to
  • <= - less than or equal
  • > - more
  • < - less
  • !== - not equal

Example with conditions:

lead['Расстояние до заказчика (в км)'] <= '50' ? '300р.' : '250р.'

You can check field values ​​and return different results.

Nested conditions

This example shows a nested condition (ternary operator) - when another condition is used inside one condition.

🔹 Analysis of the formula:

lead['Расстояние до заказчика (в км)'] <= '10' ? '300р.' : (lead['Расстояние до заказчика (в км)'] <= '30' ? '1000' : '2000')
  1. The condition is checked: if the distance is ≤ 10 km → the result is “300 rub.”
  2. If the first condition is not met, the second is checked: if the distance is ≤ 30 km → result “1000”.
  3. If both conditions are not met: default result → “2000”.

Essentially, this is an analogue of “if - otherwise if - otherwise”:

  • Up to 10 km → 300 rub.
  • From 11 to 30 km → 1000
  • More than 30 km → 2000

Limitation of decimal places

Sometimes the result of calculations may be a number with a large number of decimal places. To limit their number, use the .toFixed(x) function, where:

x is the number of decimal places that should remain.

Example:

(lead['Сумма'] / lead['Количество']).toFixed(2)

If sum = 105, quantity = 7, then the result will be 15.00 (2 decimal places).

Field keys

Leads (lead):

  • lead['ID'] — lead ID
  • lead['Title'] — Lead name
  • lead['Budget'] — Budget
  • lead['status_id'] — status ID
  • lead['pipeline_id'] — pipeline ID
  • lead['status_name'] — Status name
  • lead['pipeline_name'] — Pipeline name
  • lead['Responsible'] - full name of the responsible person
  • lead['Field'] — Additional lead field

Contact:

  • contact['ID'] — Contact ID
  • contact['Name'] — contact name
  • contact['Name'] — Name
  • contact['Last Name'] — Last name
  • contact['Responsible'] - full name of the responsible person
  • contact['Field'] — Additional contact field

Company:

  • company['ID'] — company ID
  • company['Name'] — Company name
  • company['Responsible'] - full name of the responsible person
  • company['Field'] — Additional company field

Last invoice:

  • last_invoice['Status'] — Status
  • last_invoice['Legal. face'] - Jur. face
  • last_invoice['Payer'] — Payer
  • last_invoice['VAT type'] — VAT type
  • last_invoice['Payment date'] — Payment date
  • last_invoice['Invoice items'] — Invoice items
  • last_invoice['Invoice items']?.length — Number of items
  • last_invoice['Comment'] — Comment
  • last_invoice['Cost'] — Cost
  • last_invoice['Payment link'] - Payment link
  • last_invoice['External identifier'] — External identifier
  • last_invoice['Reason for missing VAT'] — Reason for missing VAT
  • last_invoice['Supplier'] — Supplier
  • last_invoice['Taxation system'] — Taxation system
  • last_invoice['Link to lead'] - Link to lead
  • last_invoice['Encrypted payment link'] — Encrypted payment link

Related Lead Formulas

To work with related leads, you can use the arrays lead['contact_leads'] (contact leads) and lead['company_leads'] (company leads).

Formula examples:

Number of successful leads (status 142):

lead['contact_leads'].filter(l => l['status_id'] == 142).length

Sum of successful leads (status 142, sum of budgets):

lead['contact_leads'].filter(l => l['status_id'] == 142).reduce((sum, l) => sum + (parseInt(l['price']) || 0), 0)

Amount of leads by numeric field:

getLeadsFieldSum(lead['contact_leads'], 'Название_числового_поля')

Number of closed leads (status 143):

lead['contact_leads'].filter(l => l['status_id'] == 143).length

Number of leads in a certain status (example status ID: 123123):

lead['contact_leads'].filter(l => l['status_id'] == 123123).length

ℹ️If you need to count by company, replace lead['contact_leads'] with lead['company_leads']. In the example with status 123123, specify the ID of the desired status from your pipeline.

Notes

The variables available in formulas are lead['notes'] (an array of all lead notes) and lead['last_note_text'] (the text of the last note).

Examples:

Text of last note:

lead['last_note_text']

Length of last incoming call (in seconds):

lead['notes'].filter(n => n['note_type'] == 'call_in').length ? parseInt(lead['notes'].filter(n => n['note_type'] == 'call_in').sort((a, b) => a['created_at'] - b['created_at']).pop()['params']['duration']) : 0

Length of last outgoing call (in seconds):

lead['notes'].filter(n => n['note_type'] == 'call_out').length ? parseInt(lead['notes'].filter(n => n['note_type'] == 'call_out').sort((a, b) => a['created_at'] - b['created_at']).pop()['params']['duration']) : 0

Date of last incoming call:

lead['notes'].filter(n => n['note_type'] == 'call_in').length ? new Date(lead['notes'].filter(n => n['note_type'] == 'call_in').sort((a, b) => a['created_at'] - b['created_at']).pop()['created_at'] * 1000).toISOString().replace('T', ' ').slice(0, 16) : ''

Date of last outgoing call:

lead['notes'].filter(n => n['note_type'] == 'call_out').length ? new Date(lead['notes'].filter(n => n['note_type'] == 'call_out').sort((a, b) => a['created_at'] - b['created_at']).pop()['created_at'] * 1000).toISOString().replace('T', ' ').slice(0, 16) : ''

Operations with fields

Numeric:

Adding numbers:

lead['Поле1'] + lead['Поле2']

Subtraction:

lead['Поле1'] - lead['Поле2']

Multiplication:

lead['Поле1'] * lead['Поле2']

Division:

lead['Поле1'] / lead['Поле2']

Converting numbers to words:

numToRuWords(lead['Поле'])

Text:

Concatenating strings:

lead['Поле1'] + lead['Поле2']

Joining with space:

lead['Поле1'] + ' ' + lead['Поле2']

Dividing a line into blocks of 3 characters:

addDivider(lead['Поле'], '.', 3)

Flags:

Value: 'Yes' (if checked) or empty (if unchecked).

Lists:

Read and write as text.

Multilists:

Values ​​are read as text, multiple values ​​are separated by ;

Working with goods

Sum for all lists (Price type):

lead['list_sum']

Amount for a specific list:

lead['list_sums'][ID]

The value of the field with the price by key (example: lead['list_sum_123'], where 123 is the field ID):

lead['list_sum_ID']

Key by field name from the list:

lead['e_IDсписка_1_Название']

Working with dates

Date difference (in days):

(dateToTime(lead['Поле1']) - dateToTime(lead['Поле2']))/3600/24

Difference between the current date and the date from the field:

(Math.floor(Date.now()/1000) - dateToTime(lead['Поле']))/3600/24

Add 7 days:

datePlusSeconds(lead['Поле'], 3600*24*7)

Date update +1 day (d - days, M - months, y - years):

updateDate(lead['Поле'], 1, 'd')

Current date:

new Date(Date.now()).toISOString().split('T')[0]

Current date + 7 days:

new Date(Date.now() + 7 * 86400000)

Changing types

Text → number:

chislo(lead['Поле'])

Number → text:

text(lead['Поле'])

Cases for full name

Full name in the required case:

namePad(contact['ФИО'], 'родительный')

Complex formulas

Operations with parentheses:

lead['Поле1'] * (lead['Поле2'] - lead['Поле3'])

Conditions:

If >10, then 1, otherwise 0:

(lead['Поле'] > 10) ? 1 : 0

Equality check:

(lead['Поле'] == 'тип 1') ? 'Если условие выполнено' : 'Если условие не выполнено'

With text:

(lead['Поле'] === 'Текст') ? 'Если условие выполнено' : 'Если условие не выполнено'

With options:

((lead['Поле']=='1') ? 'Вариант1' : '') + ((lead['Поле']=='2') ? 'Вариант2' : '') + ((lead['Поле']=='3') ? 'Вариант3' : '')

Functions

The widget provides functions for automatically linking contacts and companies to leads:

Linking contacts

  • Attach contact by Phone - search for a contact by phone number
  • Attach contact by email - search for a contact by email address
  • Attach a contact by custom field - search for a contact by any custom field (for example, TIN, internal ID, etc.)

Linking companies

  • Attach a company by custom field - search for a company by any custom field (for example, TIN, internal ID, etc.)

Using these functions, you can automatically find and attach contacts/companies to leads, or create new ones if they are not found. You can set this up using Salesbot.

Setting up binding by phone or email

In the field selection, find the Functions section:

Section Functions in field selection

In the formula you need to enter a field from which you need to take phone or email to create a contact:

Entering a field to create a contact

Setting up binding using a custom field

To link a contact or company using a custom field, select the desired field from the list of available fields in the widget interface.

Example 1: Link a contact using the TIN field:

  1. Select "Options" → "Attach a contact using a custom field" → select the "TIN" field from the list
  2. In the formula, indicate the lead field from which to take the TIN value: return lead["TIN"]

Example 2: Link a company using the "Internal ID" field:

  1. Select "Options" → "Attach company by custom field" → select the "Internal ID" field from the list
  2. In the formula, indicate the lead field where to get the ID from: return lead["Internal ID"]

If a contact or company with the specified field value is not found, the system will automatically create a new entity with this value and link it to the lead.

Currency conversion

The convertCurrency() function is available in formulas for automatic currency conversion at official rates of the Central Bank of the Russian Federation.

Function format: await convertCurrency(amount, "source_currency", "target_currency")

Supported currencies (54 currencies)

Major world currencies:

  • USD - US dollar
  • EUR - Euro
  • GBP - Pound sterling
  • CHF – Swiss franc
  • CNY - Chinese Yuan
  • JPY - Japanese yen
  • RUB - Russian ruble

Popular currencies: AUD (Australian Dollar), CAD (Canadian Dollar), NZD (New Zealand Dollar), HKD (Hong Kong Dollar), SGD (Singapore Dollar), TRY (Turkish Lira), INR (Indian Rupee), BRL (Brazilian Real), ZAR (South African Rand), KRW (South Korean Won)

CIS currencies: KZT (Kazakhstani tenge), BYN (Belarusian ruble), UAH (Ukrainian hryvnia), AZN (Azerbaijani manat), AMD (Armenian dram), GEL (Georgian lari), KGS (Kyrgyz som), MDL (Moldavian leu), TJS (Tajik somoni), TMT (Turkmen manat), UZS (Uzbek sum)

European currencies: PLN (Polish Zloty), CZK (Czech Krone), HUF (Hungarian Forint), RON (Romanian Leu), RSD (Serbian Dinar), DKK (Danish Krone), NOK (Norwegian Krone), SEK (Swedish Krona)

Asian currencies: THB (Thai Baht), VND (Vietnamese Dong), IDR (Indonesian Rupiah), MMK (Myanmar Kyat), BDT (Bangladeshi Taka)

Middle East: AED (United Arab Emirates Dirham), SAR (Saudi Riyal), QAR (Qatar Riyal), OMR (Omani Rial), BHD (Bahraini Dinar), EGP (Egyptian Pound), IRR (Iranian Rial)

And others: DZD, MNT, BOB, CUP, NGN, ETB, XDR

Examples of use

Example 1: Convert 100 dollars to rubles

await convertCurrency(100, "USD", "RUB")

Example 2: Convert the lead budget from dollars to euros

await convertCurrency(lead["Бюджет"], "USD", "EUR")

Example 3: Calculate 15% of the budget and convert to dollars

await convertCurrency(lead["price"] * 0.15, "RUB", "USD")

Example 4: Convert between CIS currencies (tenge to rubles)

await convertCurrency(10000, "KZT", "RUB")

Features of work

  • Exchange rates are updated automatically once a day from the API of the Central Bank of the Russian Federation
  • The result is rounded to 2 decimal places
  • Courses are cached for fast execution (repeated requests are completed instantly)
  • Conversion between any currencies (not necessarily through rubles)
  • If there is an error, returns the original amount

The currency conversion function uses the official rates of the Central Bank of the Russian Federation, which are updated daily.