Rules: configure how your data is handled
Rules let you change how Clearvo reads and treats your transactions without changing your source system. A rule is a small, declarative statement: when these conditions are true, do this. Rules are saved configuration, not code, and every rule that fires is recorded so you can see exactly what happened.
Where rules run
- Tax Calculations, for both sales and purchases. Rules run on every calculation request, whether it arrives through the API, an integration, a CSV import or the dashboard, before the calculation and at defined points inside it (see Rule types).
- E-Invoicing, when an invoice is sent. Only cleanup, fill-in and check rules run here. Rules never change the amounts or tax outcome of a document you have issued.
Rules only run for an entity that has the matching solution enabled (Tax Calculations or E-Invoicing).
403 with the error code rules_not_included. Reading the trace for a record is never plan-gated.What you can do with rules
- Clean up messy input, for example turn a country name such as "Germany" into the code "DE" before tax is calculated.
- Fill in a value that is missing, for example look up a customer tax code from a product code using your own lookup table.
- Override a value that is present but wrong for your business before tax is calculated, or override the rate once it has been resolved.
- Flag a transaction for review, or block it, when it matches a condition you define.
- Bring your own data with custom fields and reference datasets.
Every rule starts as a draft, can be previewed against your recent real transactions before it goes live, and is versioned.
Anatomy of a rule
A rule has a kind, a flat list of conditions that must all be true (AND), and a list of actions that are applied when they are. An empty conditions list always matches.
{
"ruleKind": "NORMALIZATION",
"code": "CLEAN_CUSTOMER_COUNTRY",
"name": "Turn customer country names into country codes",
"conditions": [
{ "property": "customerCountryFormatInvalid", "operator": "equals", "value": true }
],
"actions": [
{ "property": "customerCountry", "fn": "NORMALIZE_COUNTRY" }
]
}
| Field | Meaning |
|---|---|
| ruleKind | What the rule is for. One of NORMALIZATION, ENRICHMENT, ADJUSTMENT, WARNING, ERROR. |
| code | Your identifier for the rule: letters, numbers, underscore, dot or hyphen, up to 50 characters. Unique within a scope, and the key that precedence works on. |
| name | A readable name, up to 200 characters. Shown in the dashboard and in traces. |
| description | Optional note, up to 2,000 characters. |
| conditions | Up to 50 conditions, each { property, operator, value }, all of which must be true. An entry can also be an OR group, see Condition groups. |
| actions | Up to 50 entries. Each is a literal assignment { property, value } or a named function { property, fn, args }. WARNING and ERROR rules never carry actions. |
| sortOrder | Order within the same kind (0 to 100000). Lower runs first. |
| checkpoint | Where in the calculation an ADJUSTMENT rule runs. Defaults to PRE_CALC. See Rule types. |
| clearanceStatus | What a matching ERROR rule makes of an e-invoicing document: REJECTED (default) refuses it, NEEDS_INFO accepts it and flags it for the sender to complete, EXCLUDED skips it (recorded, nothing submitted; for example a document whose net amount is zero). Only for ERROR rules. An EXCLUDED rule may read only facts that exist once the document is decided, such as documentNetAmount. |
| effectiveFrom / effectiveTo | Optional ISO date-times. A rule applies only to transactions whose tax point date falls in the window (start inclusive, end exclusive, UTC), never to when the rule was saved. |
| legalBasisTag | BUSINESS_POLICY (default) or LEGAL_MANDATE. An ADJUSTMENT rule cannot be tagged LEGAL_MANDATE. |
Conditions on direction and solution are ordinary conditions. To make a rule apply only to purchases, add { "property": "transactionDirection", "operator": "equals", "value": "purchase" } (values are purchase and sale). To limit it to one product, add a solution condition with tax_calculations or einvoicing. With no such condition a rule applies to both.
Rule types
Rules run in a fixed order: by kind (the order below), then by sortOrder, then by code.
| Kind | What it does | Runs on |
|---|---|---|
| NORMALIZATION | Cleans up a raw value into a standard form before anything else runs, for example "Germany" becomes "DE". On e-invoicing documents it can only use the built-in canonicalising functions, never a literal value. | Tax Calculations, E-Invoicing |
| ENRICHMENT | Fills in a value that is missing, for example looking up a customer tax code from a product code. It only fills an empty value; it never overwrites one you or an earlier rule already supplied. | Tax Calculations, E-Invoicing |
| ADJUSTMENT | Overrides a source value that is present but incorrect, before tax is calculated. It can also override resolved values at later checkpoints (below). Never runs on e-invoicing, and an adjustment rule cannot be written to target E-Invoicing. | Tax Calculations only |
| WARNING | Flags a transaction for review and never changes any data. On a calculation, fired warnings are returned in the response warnings array. | Tax Calculations, E-Invoicing |
| ERROR | Stops processing until the flagged issue is fixed. On a calculation a matching error rule rejects the request with HTTP 422 before tax is calculated (RULES_ENGINE_ERROR). On e-invoicing it is folded into the normal rejection of the send. | Tax Calculations (before calculation), E-Invoicing |
A WARNING or ERROR rule must have at least one condition, so that it cannot match every transaction.
Checkpoints (Tax Calculations)
NORMALIZATION, ENRICHMENT, WARNING and ERROR rules always evaluate at PRE_CALC, before jurisdiction, classification and rate resolution. An ADJUSTMENT rule can instead be attached to one of three later checkpoints, each evaluated per line, in this order:
| Checkpoint | When it runs | What it can write |
|---|---|---|
| POST_CLASSIFICATION | Right after a line's tax category is classified | classifiedTaxCategory |
| POST_JURISDICTION_RESOLUTION | Right after the line's jurisdiction is resolved | lineJurisdictionCountry, lineJurisdictionRegion |
| POST_RATE_RESOLUTION | After the rate is resolved, before the tax amount is computed from it | resolvedRate (a fraction, so 0.07 is 7%), the US component rates (resolvedStateRate, resolvedCountyRate, resolvedCityRate, resolvedDistrictRate, resolvedSpecialDistrictRate), and useTaxToleranceAmount |
Properties that only exist at a checkpoint (the resolved*, classifiedTaxCategory and lineJurisdiction* properties) can only be used by a rule attached to that checkpoint. The API rejects anything else with PROPERTY_NOT_AVAILABLE_AT_STAGE.
Conditions
A condition compares a property to a value. Which operators are allowed depends on the property; GET /v1/rules-engine/schema lists the allowed operators for every property.
| Operator | Reads as | Value |
|---|---|---|
| equals | is | A single value |
| not_equals | is not | A single value |
| gt, lt | is greater than, is less than | A number (numeric properties only) |
| between | is between | A two-value array (numeric properties only) |
| in, not_in | is one of, is not one of | An array |
| contains | contains | A string (text properties only) |
| is_null | is not set | Omit, or true |
| in_dataset, not_in_dataset | is in the list, is not in the list | { "dataset": "datasetKey", "keyColumn": "optional" }, see Reference datasets |
Value comparisons for equals treat numbers and numeric strings alike. Dataset key matching is case-insensitive. Some properties, such as source, never match when the value is missing, whichever operator you use.
Rules that change data (NORMALIZATION, ENRICHMENT, ADJUSTMENT) run before tax is calculated, so their conditions can only use facts known at that point: request facts and, for adjustment checkpoints, the values resolved so far. Outputs such as taxCode, rate and taxAmount are available only to WARNING rules, which read them after the fact.
Condition groups (OR)
The top-level conditions list is always ANDed. To say "or", put a group in the list: { "any": [ ... ] } matches when at least one child matches, and { "all": [ ... ] } when every child does. A child is a condition or another group. A rule holds at most 50 conditions in total, groups nest at most 2 levels deep, and a group needs at least one child; a violation is a 422 whose details[].path names the offending condition, such as conditions[1].any[0].operator. A flat list of conditions behaves exactly as before.
"conditions": [
{ "property": "transactionDirection", "operator": "equals", "value": "purchase" },
{ "any": [
{ "property": "supplierCountry", "operator": "equals", "value": "DE" },
{ "property": "companyCode", "operator": "equals", "value": "1000" }
] }
]
The trace entry for a grouped rule carries matchedBranches, naming the branch of each any group that matched.
Actions
An action targets one writable property and either assigns a literal ({ "property": "customerType", "value": "B2B" }) or applies a named function. Functions are a closed list implemented and reviewed by Clearvo; rules cannot contain expressions or code.
| Function | What it does |
|---|---|
| NORMALIZE_COUNTRY, NORMALIZE_CURRENCY, NORMALIZE_REGION, NORMALIZE_CUSTOMER_TYPE | Convert a free-text value to a standard code. They fail safely: an unrecognised or ambiguous value (for example "Georgia" or a bare "$") is left unchanged rather than guessed. |
| NORMALIZE_POSTAL_CODE | Standardise a postal code. args.countryProperty names the property holding the address country, or args.country gives a literal country code. |
| DEFAULT_VALUE | Substitute args.value when the input is empty. |
| LOOKUP | Read a value from a reference dataset. Args: dataset and returnColumn (required); keyProperty (use another property's current value as the lookup key) or keyValue (a literal key). With neither, the target property's own value is the key. |
| LOOKUP_LINKED_RECORD | For a purchase invoice line linked to a purchase order, carry a field from the linked order line, never overwriting a value the invoice line already states. Resolved tax facts (taxCode, rate, taxAmount) cannot be read. |
| ENTITY_COUNTRY, ENTITY_REGION, ENTITY_POSTAL_CODE | Fall back to the connecting entity's own establishment details when a value is missing. |
| UPPERCASE, TRIM, STRIP_SEPARATORS, STRIP_MATCHING_COUNTRY_PREFIX, ADD_COUNTRY_PREFIX, NORMALIZE_COUNTRY_CODE, NORMALIZE_COUNTRY_NAME, NORMALIZE_CURRENCY_NAME, NORMALIZE_US_STATE_NAME | String clean-up helpers. |
| PARSE_DATE | Read a date written in another format and write it as YYYY-MM-DD. Args: example (one example value in your format) or formats (a list of patterns tried in order). See Date formats. |
| PICK_FIRST_BY_TYPE | Used by field mappings to read source-system data. |
GET /v1/rules-engine/schema returns the live list and a JSON Schema of each function's arguments.
Date formats
Dates in a request are written YYYY-MM-DD, for example 2026-06-19. If your data already looks like that you need no rule. If your system writes dates another way (19/06/2026, 19 Jun 2026, a date with a time, an epoch timestamp), add a NORMALIZATION rule for each date field it sends; the date is brought to YYYY-MM-DD before anything else reads it, including the lookup of the original invoice on a credit note. Any other format without a rule is refused with an error that names the field.
Show the rule one example value and it works out the pattern. example understands day, month and year in any order with a separator or month name, an optional time (24-hour or AM/PM, with or without an offset), YYYYMMDD, and an epoch in seconds (10 digits) or milliseconds (13 digits). An example whose day and month cannot be told apart (03/04/2026) is refused when you save the rule: use one whose day is above 12 (19/04/2026), or write the pattern yourself.
{
"ruleKind": "NORMALIZATION",
"code": "ISSUE_DATE_DAY_FIRST",
"name": "Issue date arrives as DD/MM/YYYY HH:mm",
"conditions": [],
"actions": [
{ "property": "issueDate", "fn": "PARSE_DATE", "args": { "example": "19/06/2026 14:32" } }
]
}
To write the pattern yourself, use formats: YYYY, YY, MMMM, MMM, MM, M, DD, D, HH, hh, mm, ss, SSS, A (AM/PM) and Z (offset), with any other character taken literally. EPOCH_SECONDS and EPOCH_MILLIS read an epoch. Put ISO_DATE last in the list to let dates that are already YYYY-MM-DD through.
- The date is the date as written. A time or an offset is read and dropped, never converted:
2026-06-19T23:30:00-05:00is 19 June. - An epoch has no timezone and is read in UTC. Write it in full: 10 digits for seconds, 13 for milliseconds.
- A two-digit year 00 to 69 is 2000 to 2069 and 70 to 99 is 1970 to 1999. Two numbers that vary in width cannot sit side by side (
DMYYYYis refused): put a separator between them. - A date that is not a real calendar date (
31/02/2026) matches nothing and is left as sent, so the date check refuses it. - Rules for
issueDate,taxPointDateanddueDatenormalise the invoice's own dates; a rule fororiginalIssueDatenormalisesoriginalInvoiceRef.issueDateon a credit or debit note.
Where the rules engine draws the line
- Tax outcomes (
taxCode,rate,taxAmount,taxTreatment) are outputs. A rule can never write them directly. To change a rate, use anADJUSTMENTrule atPOST_RATE_RESOLUTIONand writeresolvedRate. - On e-invoicing documents, amount, quantity, price, rate and tax category fields are locked. Rules cannot rewrite them. Date fields can be brought to
YYYY-MM-DDwith PARSE_DATE. - Platform-wide (Global or Tenant) rules may write
customerCountry,supplierCountryandcustomerTaxIdonly through the canonicalising functions. Your own organisation and entity rules can write them freely. - Some default platform checks are legally mandated or structurally required and cannot be disabled or suppressed.
Properties you can use
Conditions and actions name properties from a closed, built-in catalog (plus your own custom fields). The catalog is returned in full, with labels, types, allowed operators and whether each property is writable, by GET /v1/rules-engine/schema (or the get_rules_engine_schema MCP tool; schema version 2.3.0). Call it before writing a rule. This is a guide to the main groups.
| Group | Properties | Notes |
|---|---|---|
| Transaction | transactionDirection (purchase, sale), solution, transactionType, documentType, currency, source | source is the channel the record came from (API, Dashboard, Batch Upload, MCP, or an integration such as Xero, QuickBooks, SAP, Shopify, WooCommerce) and is read-only. currency is writable. |
| Parties | customerCountry, supplierCountry, customerType (B2B, B2C, B2G), customerTaxId, customerName, customerAddressCity, customerRegion, supplierRegion, customerPostalCode, supplierPostalCode, dispatchCountry, dispatchRegion, dispatchPostalCode | Several are writable. Region and postal-code properties apply to e-invoicing records, and dispatch properties to Tax Calculations. |
| Line | amount, productCode, productName, taxCategory, clientTaxCode, quantity, unitPrice, taxRate | taxCategory and clientTaxCode are writable on Tax Calculations. quantity, unitPrice and taxRate are e-invoicing facts. |
| Data quality flags | customerCountryFormatInvalid, supplierCountryFormatInvalid, currencyFormatInvalid, customerTypeFormatInvalid, customerCountryAmbiguous, supplierCountryAmbiguous, currencyAmbiguous | True/false facts computed by the platform. Handy for targeting clean-up rules. |
| Purchase line fields | glAccount, costCenter, intendedUse, accountAssignment, commodityCode, commodityCodeScheme | Built-in properties with flat names, see Purchase line fields. |
| Shipping line facts | shippingCarrier (common, seller_vehicle), chargeAvoidable, actualCostOfShipment | The facts the US shipping rules read for a shipping line. Writable at ENRICHMENT so a default can fill one a line omits; a value on the line is never overwritten. See Default shipping facts. |
| Purchases (verified in the property catalog) | poLink, recoverablePercentOverride, resolvedIsUseTax, resolvedVendorStatedTax, useTaxToleranceAmount | Built-in properties. poLink says whether an invoice line is linked to a purchase order and is read-only; recoverablePercentOverride is writable; the last three are available at the POST_RATE_RESOLUTION checkpoint. |
| Resolved values (adjustment checkpoints) | classifiedTaxCategory, lineJurisdictionCountry, lineJurisdictionRegion, resolvedJurisdictionCountry, resolvedJurisdictionRegion, resolvedTaxCategory, resolvedTaxability, resolvedRate, resolvedTaxCode, resolvedCurrency, resolvedCustomerType, plus US local detail such as resolvedPostalCode and resolvedCityName | Mostly read-only. Only the properties named under Checkpoints are writable. |
| Outputs (read by WARNING and ERROR rules) | country, jurisdictionCountry, taxTreatment, taxCode, taxCategorySlug, rate, taxAmount, totalAmount, totalTax, movement; for e-invoicing also taxability, reverseCharge, mandate, buyerReference, orderReference, customerEndpointId | Read-only. Not usable in conditions of rules that change data. |
Some properties exist only on one of the two products. The schema marks which record shapes (calculation or invoice) populate each property, and a property that does not exist on a given record simply never matches there.
Purchase line fields
Six line facts are built-in properties. They are regular fields on each entry of lineItems[] in POST /v1/tax/calculate, and rules name them directly: glAccount, never customProperties.glAccount. They are accepted on any line but only drive anything on a purchase calculation (transactionDirection: "purchase"). The calculation response echoes the values after rules have run, and a field the line does not carry is omitted.
| Property | Type | Level | Stage | Writable | Affects the tax outcome | Record shape |
|---|---|---|---|---|---|---|
glAccount | string (up to 50) | line | input | yes | no | calculation |
costCenter | string (up to 50) | line | input | yes | no | calculation |
intendedUse | string (up to 100) | line | input | yes | no | calculation |
accountAssignment | enum: stock, expense, asset, project | line | input | yes | no | calculation |
commodityCode | string (up to 40) | line | input | no (read-only) | no | calculation |
commodityCodeScheme | enum: HS6, CN8, TARIC10, UK10, HTS10 | line | input | no (read-only) | no | calculation |
Labels in the schema: "GL account", "Cost center", "Intended use", "Account assignment", "Commodity code" and "Commodity code scheme". glAccount, costCenter, intendedUse and commodityCode take the text operators (equals, not_equals, in, not_in, contains, is_null, in_dataset, not_in_dataset). accountAssignment and commodityCodeScheme take the enum operators (equals, not_equals, in, not_in, is_null, in_dataset, not_in_dataset). The commodity code fields are read-only on purpose: rewriting them would change duty and commodity-rate classification.
intendedUse is free text. It is what matches a line to a buyer-held exemption certificate, using the platform's normalised use classes.
Account assignment and raw ERP codes
accountAssignment is always one of the four values once it is stored or echoed. On input you may send either one of the four, or a raw ERP code such as a SAP account assignment category letter (K, A, P, F, C, Q, E, N, or blank) or a Coupa account type (capital, inventory). A platform default NORMALIZATION rule maps the raw value through the account_assignment_map reference dataset. Your own scope can add mapping rows to that dataset. A raw value with no mapping row (for example SAP U) raises the platform WARNING AP_ACCOUNT_ASSIGNMENT_UNKNOWN and is dropped: the calculation still runs, and the stored and echoed value is absent. This holds even when rules are inactive for the entity. An empty value is not a value and is dropped the same way.
Using them
- In rules, use the flat name in conditions, actions and function arguments, for example
{ "property": "glAccount", "operator": "equals", "value": "6100" }, or{ "field": "glAccount" }inLOOKUP_LINKED_RECORD. - The "Carry through PO facts to linked invoice lines" template fills
glAccount,costCenter,accountAssignment,intendedUse,clientTaxCodeandtaxCategoryon an invoice line from its linked purchase order line when the invoice line does not state them. - Sending any of these names (or any other built-in property name) inside
customPropertiesis a 400 withcode: "BUILT_IN_PROPERTY_AS_CUSTOM"; the message names the flat field to send instead, for examplelineItems[1].glAccount. A rule that namescustomProperties.glAccountis rejected when you save it, with the same code.
Custom fields
A custom field is a fact of your own that you send with a calculation request and then use in rule conditions or actions, for example an internal sales channel or a business unit your ERP tracks. Rules reference it as customProperties.<key>.
- Define it once:
POST /v1/rules-engine/propertieswith apropertyKey(starts with a letter; letters, numbers and underscore), alabel, adataType(string,numberorboolean) andappliesTo(lineorheader, defaultline). ApropertyKeyequal to a built-in property name, such asglAccountorcostCenter, is refused with a 422. - Send values in the
customPropertiesobject, on the request header and/or on each line, ofPOST /v1/tax/calculate. A key that has not been defined is rejected with a 400 (UNKNOWN_CUSTOM_PROPERTY), and so is a key that names a built-in property (BUILT_IN_PROPERTY_AS_CUSTOM; send it as the regular field). - Use
customProperties.<key>in rules. A line rule can read a header-level value; a write always lands on the line's own value.
The key and data type cannot be changed after creation. You can rename the label, or deprecate a field to stop offering it for new rules; deprecating never affects rules or requests that already use it. Conditions on custom fields support the text operators (equals, not_equals, in, not_in, contains, is_null, in_dataset, not_in_dataset).
{
"propertyKey": "businessUnit",
"label": "Business unit",
"dataType": "string",
"appliesTo": "header"
}
Scope and precedence
Every rule lives at one of four scopes, and an Enterprise entity rule can be narrowed further to one company code (see below). A transaction's effective rules are the union of all scopes that apply to it.
| Scope | Applies to | Who authors it |
|---|---|---|
| Global | Every customer. Platform defaults, shown to you as "System default". | Clearvo |
| Tenant | Every customer of one white-label partner. | The partner's administrators |
| Organisation | All entities in your organisation. | You |
| Entity | One entity (one business profile). | You |
Through the API, scope comes from your key and never from the request body. An entity-scoped key creates and lists entity rules. An organisation-scoped key (sent with x-entity-id) is resolved to that entity. Bodies that try to set a scope are refused.
Company-code rules (Enterprise)
A company code is an internal split of one entity's transactions, such as an SAP company code or a Coupa business unit. It is not a separate legal entity: registrations, filings and e-invoicing identity stay on the entity. Send it as companyCode on POST /v1/tax/calculate or POST /v1/send; when you do not, the entity's default company code applies, else none.
- Create the rule with
companyCodeset to one of the entity's active codes (GET /v1/company-codes). It fires only for requests carrying that code, never for a request with a different code or none. - A company-code rule beats the entity-wide rule with the same
code. OmitcompanyCodefor an entity-wide rule. - Any rule can also test the request's code with the read-only
companyCodeproperty, for example to cover several codes in one rule. - Entity-scoped keys only (an organisation-scoped key names the entity with
x-entity-id). Not available on configuration rules. Outside the Enterprise plan the API answers403company_codes_not_included; an unknown or archived code is422company_code_unknown.
Precedence
- The most specific rule with a given
codewins: Entity beats Organisation, Organisation beats Tenant, Tenant beats Global. The less specific rules with the same code are shadowed: their actions do not apply, though the trace records that they were in scope. To override a platform default, create a rule with the same code at your scope. - A company-code rule outranks the entity-wide rule with the same
code, but only for requests carrying that company code. See Company-code rules. - Rules with different codes all apply, in order: by kind (
NORMALIZATION,ENRICHMENT,ADJUSTMENT,WARNING,ERROR), thensortOrder, thencode. If two rules write the same property, the later one writes last. Simulation reports these overlaps as conflicts. - Only active, enabled rules whose effective dates cover the transaction's tax point date take part. Drafts, archived rules and disabled rules never fire.
- Suppression lets you opt your own scope out of a wider platform-default rule (
POST /v1/rules-engine/rules/{id}/suppress, with an optionalreason) without affecting anyone else. Remove it withDELETEon the same path. Legally mandated defaults cannot be suppressed. - Opt-in platform rules are platform defaults that are off until you turn them on.
GET /v1/rules-engine/rules?includeDefaults=1returns them withdefaultEnabled: false,enabledForScope,enabledByAncestorandcanEnable. Turn one on for your scope, and everything beneath it, withPOST /v1/rules-engine/rules/{id}/enable(optionalreason), and off again withDELETEon the same path; a rule enabled from a wider scope is turned off from that scope. A rule that is on by default, a legally mandated rule or a rule the platform has locked is refused with 422RULE_NOT_ENABLEABLE. Available on every plan. - Tax number check at the authority. The opt-in rule
CUSTOMER_TAX_NUMBER_NOT_VALID_AT_AUTHORITYadds a warning to a sent invoice when the tax authority reports the customer's tax number as not valid. The invoice is still sent, and a check the authority cannot answer never produces the warning. Rules on invoices can read this result through the read-only propertycustomerTaxNumberAuthorityStatus(valid,invalid,unconfirmedor empty). The default-on format checkINVALID_CUSTOMER_TAX_ID_GENERALcan be switched off with suppression.
You can see recent changes to platform-level rules that affect your calculations with GET /v1/rules-engine/platform-changes, including ones that have not yet taken effect.
Reference datasets (lookup tables)
A reference dataset is a table of your own data that rules can read, like a spreadsheet lookup. Typical uses: map your product codes to your client tax codes, or keep a list of countries or customers a check should compare against.
- Create the dataset with a
datasetKey, anameand 1 to 10keyColumns. A composite key (for example two columns) is supported. - Add rows one at a time (
POST /v1/rules-engine/datasets/{id}/rowswithrowDatathat includes every key column), or import a CSV. - Use it in a rule with the
LOOKUPfunction (to read a value) or thein_dataset/not_in_datasetoperators (to test membership). Membership is the only way aWARNINGorERRORrule, which has no actions, can use a dataset.
CSV import is two-step: call with dryRun: true (the default) to get the adds, changes and deletes without writing anything, then call again with dryRun: false to apply the same difference. You can export a dataset as CSV. Limits: 50,000 rows per dataset, 8 KB per row and 8 MB per import. Key matching is case-insensitive.
POST /v1/rules-engine/datasets
{ "datasetKey": "product_tax_codes", "name": "Product to client tax code", "keyColumns": ["productCode"] }
POST /v1/rules-engine/datasets/{id}/rows
{ "rowData": { "productCode": "SKU-1001", "clientTaxCode": "STD_SOFTWARE" } }
Templates
A template is a ready-made rule with a few blanks. You supply the parameters and Clearvo builds the rule for you, as a draft owned by your scope. Browse them with GET /v1/rules-engine/templates, read one (including the parameters it expects) with GET /v1/rules-engine/templates/{id}, and create the rule with PUT /v1/rules-engine/templates/{id} and { "params": { ... } }. A missing or mistyped parameter returns a 422 naming the failing params.<key> path. Some templates allow one rule per scope (a setting), others one per row, such as one per supplier.
Purchase (AP) templates:
| Template | Parameters | What it sets |
|---|---|---|
| AP tax-verification tolerance | percent, absoluteAmount | How far a vendor-charged tax amount may differ from the calculated amount before it is flagged. |
| PO-vs-invoice mismatch disposition | disposition: warn, hold or ignore | What happens when a purchase order and its invoice disagree outside tolerance. hold marks the invoice as held for review and does not stop payment in your accounting system. |
| US use tax tolerance | toleranceAmount | Waives self-assessed use tax on a purchase line at or below the amount. Off until you create and activate it. |
| Per-supplier trust and tolerance override | supplierId, trusted, optional percent and absoluteAmount | Marks a supplier as trusted, or replaces the tolerance for that supplier. One per supplier. |
| Carry through PO facts to linked invoice lines | none | Fills missing facts on an invoice line from its linked purchase order line, never overwriting a value the invoice states. |
Purchase (AP) features are part of the Enterprise plan. The list of templates is read from the platform, so use GET /v1/rules-engine/templates for the current set.
In GET /v1/rules-engine/templates and GET /v1/rules-engine/templates/{id}, each parameter can carry optionLabels, a plain-English label for each allowed value (for a boolean, the keys true and false). Each entry in instances carries params, the values that rule was saved with.
Default shipping facts
For US shipping and handling lines, the tax depends on who delivers the goods, whether the customer could avoid the charge, and whether the charge is the actual shipping cost. If a line does not send these, you can set a standing answer once instead of sending it on every line. The US shipping rules still make every decision; a default only supplies a missing fact, and a value sent on the line is never overwritten. With no default, the cautious taxable assumption applies.
| Template | Parameter | Fills |
|---|---|---|
default_shipping_carrier | carrier: common or seller_vehicle | shippingCarrier |
default_shipping_charge_avoidable | chargeAvoidable: boolean | chargeAvoidable |
default_shipping_actual_cost | actualCostOfShipment: boolean | actualCostOfShipment |
Precedence: the value on the line, then your Entity rule, then your Organisation rule, then unset. Each fact resolves independently. These three templates are available on every plan; other rules features remain part of the Enterprise plan. The same three facts can be sent as optional shippingCarrier, chargeAvoidable and actualCostOfShipment columns in a Tax Calculations CSV import.
Testing and reading traces
Simulate before you activate
Simulation runs a rule, read-only, over your most recent records (1 to 500, default 50) and writes nothing. Simulate a saved rule with POST /v1/rules-engine/rules/{id}/simulate, optionally passing a draft to preview an edit, or simulate a rule that does not exist yet with POST /v1/rules-engine/rules/simulate and a draft.
{
"sampleSize": 100,
"draft": {
"domain": "ap",
"ruleKind": "WARNING",
"conditions": [
{ "property": "transactionDirection", "operator": "equals", "value": "purchase" },
{ "property": "amount", "operator": "gt", "value": 10000 }
]
}
}
The response contains matchedCount, sampleSize, up to five sample entries (recordId, before, after) and conflicts, which lists other active rules that also fire on a sampled record and write the same property. A conflict is an ordering warning, not an error. Simulation shows the shape of a rule's effect; it is not a substitute for a real calculation.
A draft sent to the unsaved-rule simulate endpoint must include a domain (ap for purchases, ar for sales), a legacy field that is still required on that one request.
Rules in the response
Every POST /v1/tax/calculate and /v1/send response lists the rules that fired in ruleLog, each with its kind, a label, the property changed, and the before and after values. Only your own organisation and entity rules show their code; platform rules appear without one. At most 100 entries are returned (ruleLogTruncated is set if there were more). Fired WARNING rules appear in warnings.
Full trace for a record
GET /v1/rules-engine/trace?recordType=calculation&recordId=... returns the complete, ordered trace for one already-calculated record, with a plain-English sentence for each step (for example "Tax category changed from not set to Software services"), the rule version that fired, its scope, and whether it ran before the calculation or as a read-only check after it. Use recordType=invoice for a sent invoice. Traces are never plan-gated.
Lifecycle, versions and approval
- Always starts as a draft. A new rule has status
DRAFTand does nothing until activated, whoever creates it and however (dashboard, API, MCP, template). - Activate with
POST /v1/rules-engine/rules/{id}/activate, or send{ "enabled": true }toPATCHa draft, which performs the same transition. After that,enabledis the day-to-day on/off switch for an active rule. - Edit with
PATCH /v1/rules-engine/rules/{id}. You must send the rule's currentversion; a stale version returns 409 so two people cannot silently overwrite each other. Each save creates a new version, andGET /v1/rules-engine/rules/{id}/versionsreturns the history, newest first. Traces record which version fired. - Reorder within a kind with
POST /v1/rules-engine/rules/{id}/moveand a newsortOrder. - Retire a rule with
{ "action": "delete" }onPATCH. Rules are never hard-deleted. A rule that has matched real records is archived and kept for audit; one that never matched is hidden permanently. You do not choose between the two. You can also set"status": "ARCHIVED"directly. - Maker-checker approval. If your organisation turns on rule approval, the person who authored a draft cannot activate it. The attempt returns 403 and a different person must activate it, whether through the activate endpoint or
enabled: true. - Platform defaults are not edited by you. To change one for your scope, override or suppress it.
Ways to author rules
The three routes below create the same rules with the same validation. The same limits and the same draft-first behaviour apply on each.
Dashboard
Rules, reference datasets and custom fields can also be managed from the Clearvo dashboard, which uses the same validation as the API. Rules you create there also start as drafts.
API
Use https://api.clearvo.io/v1/rules-engine/* with your x-api-key. An organisation-scoped key must also send x-entity-id. Start with GET /v1/rules-engine/schema; any property, operator or function not listed there is rejected with a 422 whose details[] names the failing path, such as conditions[1].operator. The full endpoint list is in the API reference under Rules Engine.
MCP and AI agents
Connect your AI tool through Claude Code / MCP and describe the rule in plain English. The agent uses these tools: get_rules_engine_schema, list_rules, get_rule, create_rule, update_rule, simulate_rule, activate_rule, move_rule, suppress_rule and unsuppress_rule, enable_rule and disable_rule, list_rule_versions, get_rules_trace, list_platform_rule_changes, list_rule_property_definitions, create_rule_property_definition and update_rule_property_definition, list_rule_templates, get_rule_template and instantiate_rule_template, the dataset tools (list_rules_engine_datasets, create_rules_engine_dataset, get_rules_engine_dataset, list_rules_engine_dataset_rows, upsert_rules_engine_dataset_row, delete_rules_engine_dataset_row, import_rules_engine_dataset) and the field-mapping tools. An agent should read the schema first, create the rule, simulate it, show you the result, and only then activate it.
Examples
Each example is the body of POST /v1/rules-engine/rules. All of them are created as drafts.
1. Fill in a client tax code from your own table (ENRICHMENT with a lookup)
When a line has no client tax code, look it up from the product_tax_codes dataset using the line's product code. The value you return must be one of your own client tax codes.
{
"ruleKind": "ENRICHMENT",
"code": "FILL_CLIENT_TAX_CODE",
"name": "Fill client tax code from product code",
"conditions": [
{ "property": "solution", "operator": "equals", "value": "tax_calculations" }
],
"actions": [
{
"property": "clientTaxCode",
"fn": "LOOKUP",
"args": {
"dataset": "product_tax_codes",
"keyProperty": "productCode",
"returnColumn": "clientTaxCode"
}
}
]
}
2. Flag large purchase lines for review (WARNING)
{
"ruleKind": "WARNING",
"code": "LARGE_PURCHASE_LINE",
"name": "Review purchase lines over 10,000",
"conditions": [
{ "property": "transactionDirection", "operator": "equals", "value": "purchase" },
{ "property": "amount", "operator": "gt", "value": 10000 }
]
}
3. Block customers outside an approved list (ERROR with a dataset)
{
"ruleKind": "ERROR",
"code": "CUSTOMER_COUNTRY_NOT_APPROVED",
"name": "Customer country is not on the approved list",
"conditions": [
{
"property": "customerCountry",
"operator": "not_in_dataset",
"value": { "dataset": "approved_countries" }
}
]
}
4. Override a resolved rate (ADJUSTMENT at POST_RATE_RESOLUTION)
Illustrative only: if a German line resolves to 19% and you hold a ruling that 7% applies, write the rate after it is resolved. Rates are fractions. Check any rate override with a tax adviser and preview it before activating it.
{
"ruleKind": "ADJUSTMENT",
"checkpoint": "POST_RATE_RESOLUTION",
"code": "DE_REDUCED_RATE_RULING",
"name": "Apply 7% where we hold a ruling",
"conditions": [
{ "property": "resolvedJurisdictionCountry", "operator": "equals", "value": "DE" },
{ "property": "resolvedRate", "operator": "equals", "value": 0.19 }
],
"actions": [
{ "property": "resolvedRate", "value": 0.07 }
],
"effectiveFrom": "2026-11-01T00:00:00Z"
}
5. Use a custom field (ADJUSTMENT)
After defining businessUnit as a custom field and sending it on the request, mark those customers as business customers.
{
"ruleKind": "ADJUSTMENT",
"code": "INTERNAL_UNIT_IS_B2B",
"name": "Treat intercompany business unit as B2B",
"conditions": [
{ "property": "customProperties.businessUnit", "operator": "equals", "value": "INTERCO" }
],
"actions": [
{ "property": "customerType", "value": "B2B" }
]
}
Activate once you are happy
curl -X POST https://api.clearvo.io/v1/rules-engine/rules/RULE_ID/activate \
-H "x-api-key: YOUR_API_KEY"
Field mappings
Field mappings are the engine's other half: per entity and per source system (for example Xero), they define how fields from that system are read into Clearvo, replacing hand-written integration code. A starter mapping is copied to your entity automatically when you connect, so there is no create call. You can list and read them (GET /v1/rules-engine/mappings), change a mapping's source path, transform, order or on/off state (PATCH /v1/rules-engine/mappings/{id}), and restore the defaults for a source system (POST /v1/rules-engine/mappings/reset).