# Rules

> Set cost centers, tags, stages and notices on their own: when an invoice arrives or is issued, or when a purchase order changes, if its conditions hold.

A rule says "when something happens, if these conditions hold, then do this". For example: when an invoice from Aceros del Norte arrives, put it in the Obra Norte cost center. They're the same as **Ajustes › Reglas** in the app: what you create here shows there, with its history, and the other way around. Each rule (`rul_…`) belongs to its issuer's empresa.

| Part | Field | What it holds |
| --- | --- | --- |
| When | `trigger` | `invoice.received` (an invoice from a supplier arrives, from SAT, by email or uploaded), `invoice.issued` (an invoice to a customer is issued or arrives), `invoice.paid` (a PPD invoice is fully paid by its payment complements or credit notes, or is marked paid without a complement; received or issued), `invoice.cancelled` (SAT shows it cancelled; received or issued), `invoice.approved` and `invoice.rejected` (a supplier invoice is approved or rejected in the supplier portal), `payout.submitted` (the payout that carries it is sent for signing), `payout.paid` (the transfer that pays it goes out, in full or in part), `payout.failed` (that transfer doesn't go out or the bank returns it), `invoice.daily` (every morning at 8, Mexico City time, on each invoice with a balance, received or issued, Ingreso and not cancelled: to warn at 30 days unpaid with `age` or `saldo`), `purchase_order.daily` (every morning at 8, on each order not yet fully received, closed or cancelled: to warn when its delivery date passes with `deliveryDays`), `finding.created` (a finding shows up on an invoice from the last 45 days; received or issued; the `findings` condition says which), or a purchase order moment: `purchase_order.saved`, `.approved`, `.rejected`, `.sent`, `.confirmed`, `.received_part`, `.received_all`, `.invoiced_all`, `.price_variance`, `.registered`; or `bank.movement` (a bank movement arrives: a withdrawal when the statement is imported, a deposit when Conciliación classifies it as a loan, transfer, refund or interest); or a SAT notice: `sat.listed` (a supplier, customer or one of your RFCs appears on a SAT list; each morning, once per RFC, list and status), `sat.opinion` (the compliance opinion of one of your RFCs changes, or the first one is not positive), `sat.buzon` (a message arrives in the buzón tributario, a notification is waiting to be opened, or the buzón has no contact details) or `sat.certificate` (each morning at 8, with each CSD and e.firma and its days until expiry). |
| If | `conditions` | `match` (`all` or `any`), its `conditions` and up to 5 `groups`, each with its own `match`. Without conditions it always runs. |
| Then | `actions` | 1 to 8: `cost_center` (invoices, `ccn_…`), `category` (received invoices: the expense category, never changing one a person chose), `account` (invoices: the number of the chart's account its income or expense is booked to instead of its category's, never changing one a person chose; see [The account of each invoice](https://fiscalisto.com/en/docs/api/contabilidad#the-account-of-each-invoice); on `bank.movement`, it books the movement with its income or expense póliza against that account, if it has none and its month isn't closed; another of the company's bank accounts books it as a transfer), `tag` (invoices and orders, `tag_…`, from [Tags](https://fiscalisto.com/en/docs/api/etiquetas)), `stage`, `close` and `ask_approval` (purchase orders; `ask_approval` asks for a draft order's approval through its approval steps, and isn't allowed in `.approved` or `.rejected`) `notify` (invoices, orders and bank movements, `mem_…`) and `lote` (in `invoice.received` and `invoice.approved`: adds the invoice to the open payment batch `lote_name` that pays on `pay_on`, `monday` … `friday`, `in_days` with `days` or `due`, the contrarecibo's date; if there is none, it creates it, prepared as whoever made the rule), `hold_payment` (received invoices: holds its payment, with `note`; it leaves the draft it was in and a signed pago that carries it stops before it goes out, until someone allowed to releases it in the app; `payment_hold` in [What's left to pay](https://fiscalisto.com/en/docs/api/pagos-a-proveedores#whats-left-to-pay); on `sat.listed`, holds every unpaid invoice of that supplier), `email_supplier` (received invoices and purchase orders: emails the supplier at the addresses of its `topic`, with `subject` and `message`, copying the team members in `cc` (`mem_…`); once per invoice or order and topic. The variables fill in on their own with each one's data, and one without that data stays blank: always `{folio}`, `{total}`, `{fecha}`, `{empresa}` and `{rfc_empresa}`, `{proveedor}` and `{rfc_proveedor}`, `{subtotal}`, `{iva}`, `{retenciones}` and `{moneda}`; on invoices, `{uuid}`, `{metodo_pago}`, `{forma_pago}`, `{uso_cfdi}`, `{conceptos}`, `{categoria}`, `{saldo}`, `{orden}`, `{contrarecibo}`, `{fecha_promesa}` and `{hallazgos}`; on orders, `{entrega}`, `{almacen}`, `{credito}`, `{comprador}`, `{nota}` and `{enlace}` (the order for the supplier); in `invoice.rejected` and `purchase_order.rejected`, `{motivo_rechazo}`; on SAT notices (`sat.*`, in `notify` and `hold_payment`), `{aviso}`, `{rfc_aviso}`, `{empresa}` and `{rfc_empresa}`. The message also takes tables: `{tabla_conceptos}` (invoices: `clave`, `descripcion`, `cantidad`, `unidad`, `precio`, `importe`), `{tabla_productos}` (orders: `producto`, `codigo`, `cantidad`, `recibido`, `pendiente`, `precio`, `importe`) and `{tabla_facturas}` (pagos: `folio`, `uuid`, `fecha`, `total`, `retenido`, `pagado`), with the columns you choose in `columns` (per table; without them, the usual ones) and their total below; the subject takes no tables. In `payout.submitted`, `payout.paid` and `payout.failed`, `per` decides: `payout` (the default) sends one email per pago and supplier with all its invoices, where `{folio}` is the list of folios, `{total}` what it pays and `{fecha}` the pago's date (and the one-invoice variables, like `{uuid}`, don't apply); `invoice`, one per invoice. In those events the email also fills `{facturas}` (one line per invoice with what it gets), `{pagado}`, `{fecha_pago}`, `{pago}`, `{cuenta}` (CLABE ending in…), `{banco}` and `{referencia}`; in `payout.paid`, `{rastreo}` (the tracking key) and `{cep}` (the link to the bank's receipt); in `payout.failed`, `{motivo}`. A variable that doesn't exist in that event is refused with `400`. The same variables, without tables, go in the `note` of `notify` and `hold_payment` and in the `reason` of `extra_signature`) and `review_findings` (marks the `findings` as reviewed, except the ones a person reviews: `cancelado`, `efos_definitivo`, `efos_presunto`, `lista_69b_bis` and `lista_69`), and `extra_signature` (in `payout.submitted`: the pago needs `signatures` more signatures, 1 to 3, on top of the ones in Configurar pagos, with `reason` for whoever signs; it never lowers them and doesn't change a pago that already went out), and `webhook` (invoices, orders and bank movements: sends the [`rule.matched`](https://fiscalisto.com/en/docs/api/webhooks#event-types) event to `url`, an https address of Zapier, Make, n8n or your system, with the rule, the record, its link in the app and every field of its conditions; it's signed and retried like the other webhooks. Saving the rule uses the webhook at that address in Desarrolladores › Webhooks or creates one, and the response says which in `webhook_endpoint` (`we_…`); `rule.matched` only reaches its rule's webhook. It needs permission to manage the API), and `flag` (invoices, orders and bank movements: marks the rule's own finding, with its name, `severity` `critical`, `warning` (the default) or `info`, and `detail`, what to check; it stays open until someone reviews it, changing the rule's severity or name changes it on what it marked, and deleting the rule removes them. The response has its `finding_code` (`regla_…`), the `code` it shows with in [`/v1/sat_findings`](https://fiscalisto.com/en/docs/api/hallazgos) for invoices and in [`/v1/findings`](https://fiscalisto.com/en/docs/api/hallazgos) for orders and movements). |
| Else | `else_actions` | 0 to 8 actions, the same as `actions`, that it does when its conditions don't hold (the rule's «No» path). Only with conditions; `[]` removes them. With `once_per_record`, also once per record, apart from `actions`. |
| If it still holds | `follow_ups` | Up to 5 steps days after it acted (`days` and their `actions`), while its conditions still hold. See [If it still holds](#if-it-still-holds). |

## Create a rule

```bash tab="cURL"
curl https://api.fiscalisto.com/v1/rules \
  -H "Authorization: Bearer $FISCALISTO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Aceros del Norte a Obra Norte",
    "trigger": "invoice.received",
    "conditions": {
      "match": "all",
      "conditions": [{ "field": "supplier", "operator": "is", "values": ["ADN0101019Z3"] }]
    },
    "actions": [{ "type": "cost_center", "cost_center": "ccn_OufpKqnrvx9p1" }]
  }'
```

```ts tab="TypeScript"
import { Fiscalisto } from "fiscalisto";

// The key comes from FISCALISTO_API_KEY.
const fiscalisto = new Fiscalisto();

const rule = await fiscalisto.rules.create({
  name: "Aceros del Norte a Obra Norte",
  trigger: "invoice.received",
  conditions: {
    match: "all",
    conditions: [
      {
        field: "supplier",
        operator: "is",
        values: ["ADN0101019Z3"],
      },
    ],
  },
  actions: [
    {
      type: "cost_center",
      cost_center: "ccn_OufpKqnrvx9p1",
    },
  ],
});
```

```python tab="Python"
from fiscalisto import Fiscalisto

# The key comes from FISCALISTO_API_KEY.
fiscalisto = Fiscalisto()

rule = fiscalisto.rules.create({
    "name": "Aceros del Norte a Obra Norte",
    "trigger": "invoice.received",
    "conditions": {
        "match": "all",
        "conditions": [
            {
                "field": "supplier",
                "operator": "is",
                "values": ["ADN0101019Z3"],
            },
        ],
    },
    "actions": [
        {
            "type": "cost_center",
            "cost_center": "ccn_OufpKqnrvx9p1",
        },
    ],
})
```

```php tab="PHP"
<?php

use Fiscalisto\Fiscalisto;

// The key comes from FISCALISTO_API_KEY.
$fiscalisto = new Fiscalisto();

$rule = $fiscalisto->rules->create([
    'name' => 'Aceros del Norte a Obra Norte',
    'trigger' => 'invoice.received',
    'conditions' => [
        'match' => 'all',
        'conditions' => [
            [
                'field' => 'supplier',
                'operator' => 'is',
                'values' => ['ADN0101019Z3'],
            ],
        ],
    ],
    'actions' => [
        [
            'type' => 'cost_center',
            'cost_center' => 'ccn_OufpKqnrvx9p1',
        ],
    ],
]);
```

```go tab="Go"
package main

import (
	"context"
	"fmt"
	"log"

	fiscalisto "fiscalisto.com/go"
)

func main() {
	// The key comes from FISCALISTO_API_KEY.
	client, err := fiscalisto.NewClient("")
	if err != nil {
		log.Fatal(err)
	}
	ctx := context.Background()

	rule, err := client.Rules.Create(ctx, &fiscalisto.CreateRuleParams{
		Name:    fiscalisto.String("Aceros del Norte a Obra Norte"),
		Trigger: "invoice.received",
		Conditions: &fiscalisto.CreateRuleParamsConditions{
			Match: fiscalisto.String("all"),
			Conditions: []fiscalisto.CreateRuleParamsConditionsCondition{
				{
					Field:    "supplier",
					Operator: "is",
					Values:   []string{"ADN0101019Z3"},
				},
			},
		},
		Actions: []fiscalisto.CreateRuleParamsAction{
			{
				Type:       "cost_center",
				CostCenter: fiscalisto.String("ccn_OufpKqnrvx9p1"),
			},
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(rule.ID)
}
```

```java tab="Java"
import com.fiscalisto.FiscalistoClient;
import com.fiscalisto.model.CreateRuleParams;
import com.fiscalisto.model.CreateRuleParamsAction;
import com.fiscalisto.model.CreateRuleParamsConditions;
import com.fiscalisto.model.CreateRuleParamsConditionsCondition;
import java.util.List;

// The key comes from FISCALISTO_API_KEY.
var fiscalisto = new FiscalistoClient();

var rule = fiscalisto.rules().create(new CreateRuleParams()
        .setName("Aceros del Norte a Obra Norte")
        .setTrigger("invoice.received")
        .setConditions(new CreateRuleParamsConditions()
                .setMatch("all")
                .setConditions(List.of(
                        new CreateRuleParamsConditionsCondition()
                                .setField("supplier")
                                .setOperator("is")
                                .setValues(List.of("ADN0101019Z3"))
                )))
        .setActions(List.of(
                new CreateRuleParamsAction()
                        .setType("cost_center")
                        .setCostCenter("ccn_OufpKqnrvx9p1")
        )));
System.out.println(rule.getId());
```

```csharp tab="C#"
using Fiscalisto;

// The key comes from FISCALISTO_API_KEY.
var fiscalisto = new FiscalistoClient();

var rule = await fiscalisto.Rules.CreateAsync(new CreateRuleParams
{
    Name = "Aceros del Norte a Obra Norte",
    Trigger = "invoice.received",
    Conditions = new()
    {
        Match = "all",
        Conditions = new()
        {
            new()
            {
                Field = "supplier",
                Operator = "is",
                Values = new() { "ADN0101019Z3" },
            },
        },
    },
    Actions = new()
    {
        new()
        {
            Type = "cost_center",
            CostCenter = "ccn_OufpKqnrvx9p1",
        },
    },
});
```

It answers the rule, last in its empresa's order. It runs on what arrives from then on; it doesn't change the invoices already there. What can't be saved answers `rule_invalid` with why: an action that doesn't go with its trigger (`cost_center` on a purchase order), a tag or cost center that doesn't exist, or more than 200 rules.

## Conditions

Each condition has `field`, `operator` and its value:

| Field type | Fields | Operators | Value |
| --- | --- | --- | --- |
| List | `supplier`, `customer`, `supplierGroup` (received: the supplier's group), `customerGroup` (issued: the customer's group), `ownRfc`, `tipo`, `metodo`, `forma`, `uso`, `moneda`, `serie`, `clave`, `costCenter`, `direction` (`received` or `issued`, in `invoice.paid` and `invoice.cancelled`), `category`, `tags`, `weekday` (its date's day: `lun` to `dom`), `accountCheck` (in `payout.*`: how the account was verified, `bank`, `hand` or `none`), `opinion` (received: the 32-D compliance opinion the supplier uploaded to the supplier portal: `positive`, `negative`, `expired` or `none`) (invoices); `supplier`, `supplierGroup`, `ownRfc`, `category`, `warehouse`, `stage`, `createdBy`, `moneda`, `project` (orders) | `is`, `not`, `set`, `unset` | `values`: RFCs, SAT codes, categories, `sgr_…`, `cgr_…`, `tag_…`, `ccn_…`, `whs_…`, `mem_…`, the project's id |
| Amount | `total`, `subtotal`, `iva`, `saldo`, `payoutAmount` (what the supplier gets, in `payout.*`), `monthTotal` (what that supplier or customer billed that month, without cancelled ones), `orderTotal` (received: the total of its purchase orders), `lastTotal` (the total of that supplier's or customer's previous invoice), `avgTotal` (the average of their invoices in the 6 months before it) (invoices); `total`, `monthTotal` (what was ordered from that supplier that month, without cancelled ones), `lastTotal` (the total of the previous order to that supplier), `avgTotal` (the average of their orders in the 6 months before it) (orders) | `gte`, `lte`, `between` | `value` (and `to` with `between`), in pesos: invoices in another currency compare at their exchange rate |
| Days and percentages | `age` (days since the invoice's date), `saldoPct` (the balance as a % of the total), `orderDiff` (received: how much it exceeds its purchase orders, in %; negative if less), `dayCount` (that supplier's or customer's invoices that day, this one included); `paymentDays` (credit days), `deliveryDays` (days left until delivery; negative once it passed) (orders) | `gte`, `lte`, `between` | `value` (and `to` with `between`) |
| Text | `partyName`, `concept` (invoices); `note` (orders) | `contains`, `not_contains`, `starts`, `set`, `unset` | `text`, ignoring accents and case |
| Yes or no | `ivaRetenido`, `isrRetenido`, `hasFindings`, `newParty` (the first invoice of that supplier or customer), `hasOrder` (received: linked to a purchase order), `newAccount` (in `payout.*`: the first payment to that account), `satList` (the supplier or customer is on an SAT list: 69-B or 69) (invoices); `advance` (has an advance), `newSupplier` (the first order to that supplier) (orders) | `yes`, `no` | — |

On `bank.movement` the fields are different: `flow` (`out`, a withdrawal, or `in`, a deposit), `bankAccount` (the account's last 4 digits), `ownRfc`, `classification` (of a deposit: `prestamo`, `traspaso`, `devolucion` or `intereses`) and `weekday` are lists; `amount` is an amount; `monthDay` (the day of the month) is a number; `description` (the bank's text) and `reference` are text.

On SAT notices (`sat.*`), `ownRfc` is a list on all of them, plus: on `sat.listed`, `party` (`supplier`, `customer` or `own`, one of your RFCs), `supplier`, `customer`, `supplierGroup`, `customerGroup`, `list` (`69b`, `69b_bis`, `69_no_localizados`, `69_exigibles`, `69_firmes`, `69_sentencias`, `69_cancelados`, `69_csd_sin_efectos`) and `situation` (`presunto`, `definitivo`, `desvirtuado`, `sentencia_favorable`, `listado`) are lists, and `billed12m` (what was invoiced with that RFC in 12 months) and `balance` (its outstanding balance) are amounts, so the rule acts only on the ones that matter to you; on `sat.opinion`, `sentido` and `previous` (`positivo`, `negativo`, `sin_obligaciones`, `suspendido`; `previous` also `ninguno`) are lists and `pending` (pending obligations) is a number; on `sat.buzon`, `kind` (`comunicado`, `notificacion`, `sin_medios`) and `urgency` (`urgente`, `atender`, `informativo`) are lists and `text` (the subject) is text; on `sat.certificate`, `certificate` (`csd` or `efirma`) is a list and `daysLeft` (days until expiry; negative once expired) is a number. The actions are `notify`, `webhook` and, on `sat.listed`, `hold_payment`. Probar looks up today's lists and certificates, so a new rule can be tried before its first morning. They are changed by whoever administers the company.

### Comparing two fields

An amount or a number can also be compared with another field of the same record: put that field in `compare_to`, and `value` (and `to` with `between`) are then a % of that field; 100 is equal. Amounts compare with amounts, and days or percentages with days or percentages. If the record doesn't have the other field (a supplier's first invoice has no `lastTotal`), the condition doesn't hold.

```json
{ "field": "total", "operator": "gte", "value": 150, "compare_to": "lastTotal" }
```

It holds when the total is at least 150% of that supplier's previous invoice. With `"operator": "between", "value": 90, "to": 110, "compare_to": "orderTotal"`, when the total is between 90% and 110% of its purchase order.

A field that isn't of its trigger, or an operator that doesn't go with the field, answers `parameter_invalid` with `param` on the condition; so does a `compare_to` that isn't a number field of the same kind.

## Supplier groups

A rule applies to a whole supplier group with the `supplierGroup` condition (and to a customer group with `customerGroup`, from [Customer groups](https://fiscalisto.com/en/docs/api/listas-de-precios#customer-groups)). `/v1/supplier_groups` creates, lists, changes and removes the groups (`sgr_…`), the same ones as **Proveedores › Grupos** in the app:

```bash tab="cURL"
curl https://api.fiscalisto.com/v1/supplier_groups \
  -H "Authorization: Bearer $FISCALISTO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "name": "Fletes", "suppliers": ["FLE010101AB1", "TRA020202CD3"] }'
```

```ts tab="TypeScript"
import { Fiscalisto } from "fiscalisto";

// The key comes from FISCALISTO_API_KEY.
const fiscalisto = new Fiscalisto();

const supplierGroup = await fiscalisto.supplierGroups.create({
  name: "Fletes",
  suppliers: ["FLE010101AB1", "TRA020202CD3"],
});
```

```python tab="Python"
from fiscalisto import Fiscalisto

# The key comes from FISCALISTO_API_KEY.
fiscalisto = Fiscalisto()

supplier_group = fiscalisto.supplier_groups.create({
    "name": "Fletes",
    "suppliers": ["FLE010101AB1", "TRA020202CD3"],
})
```

```php tab="PHP"
<?php

use Fiscalisto\Fiscalisto;

// The key comes from FISCALISTO_API_KEY.
$fiscalisto = new Fiscalisto();

$supplierGroup = $fiscalisto->supplierGroups->create([
    'name' => 'Fletes',
    'suppliers' => ['FLE010101AB1', 'TRA020202CD3'],
]);
```

```go tab="Go"
package main

import (
	"context"
	"fmt"
	"log"

	fiscalisto "fiscalisto.com/go"
)

func main() {
	// The key comes from FISCALISTO_API_KEY.
	client, err := fiscalisto.NewClient("")
	if err != nil {
		log.Fatal(err)
	}
	ctx := context.Background()

	supplierGroup, err := client.SupplierGroups.Create(ctx, &fiscalisto.CreateSupplierGroupParams{
		Name:      "Fletes",
		Suppliers: []string{"FLE010101AB1", "TRA020202CD3"},
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(supplierGroup.ID)
}
```

```java tab="Java"
import com.fiscalisto.FiscalistoClient;
import com.fiscalisto.model.CreateSupplierGroupParams;
import java.util.List;

// The key comes from FISCALISTO_API_KEY.
var fiscalisto = new FiscalistoClient();

var supplierGroup = fiscalisto.supplierGroups().create(new CreateSupplierGroupParams()
        .setName("Fletes")
        .setSuppliers(List.of("FLE010101AB1", "TRA020202CD3")));
System.out.println(supplierGroup.getId());
```

```csharp tab="C#"
using Fiscalisto;

// The key comes from FISCALISTO_API_KEY.
var fiscalisto = new FiscalistoClient();

var supplierGroup = await fiscalisto.SupplierGroups.CreateAsync(new CreateSupplierGroupParams
{
    Name = "Fletes",
    Suppliers = new() { "FLE010101AB1", "TRA020202CD3" },
});
```

Each supplier is in one group only: those in `suppliers` (or `add_suppliers` in `POST /v1/supplier_groups/{id}`) leave the one they had, and `remove_suppliers` leaves them without a group. `DELETE /v1/supplier_groups/{id}` removes the group: its suppliers are left without one and the rules that use it no longer apply to anyone.

## Test a rule

```bash tab="cURL"
curl https://api.fiscalisto.com/v1/rules/rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6/test \
  -H "Authorization: Bearer $FISCALISTO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "uuid": "5F3B2A10-8C4D-4E6F-9A1B-2C3D4E5F6A7B" }'
```

```ts tab="TypeScript"
import { Fiscalisto } from "fiscalisto";

// The key comes from FISCALISTO_API_KEY.
const fiscalisto = new Fiscalisto();

const { data } = await fiscalisto.rules.test("rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6", { uuid: "5F3B2A10-8C4D-4E6F-9A1B-2C3D4E5F6A7B" });
```

```python tab="Python"
from fiscalisto import Fiscalisto

# The key comes from FISCALISTO_API_KEY.
fiscalisto = Fiscalisto()

data = fiscalisto.rules.test("rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6", {"uuid": "5F3B2A10-8C4D-4E6F-9A1B-2C3D4E5F6A7B"})["data"]
```

```php tab="PHP"
<?php

use Fiscalisto\Fiscalisto;

// The key comes from FISCALISTO_API_KEY.
$fiscalisto = new Fiscalisto();

$data = $fiscalisto->rules->test('rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6', [
    'uuid' => '5F3B2A10-8C4D-4E6F-9A1B-2C3D4E5F6A7B',
])['data'];
```

```go tab="Go"
package main

import (
	"context"
	"fmt"
	"log"

	fiscalisto "fiscalisto.com/go"
)

func main() {
	// The key comes from FISCALISTO_API_KEY.
	client, err := fiscalisto.NewClient("")
	if err != nil {
		log.Fatal(err)
	}
	ctx := context.Background()

	ruleTestList, err := client.Rules.Test(ctx, "rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6", &fiscalisto.TestRuleParams{
		UUID: fiscalisto.String("5F3B2A10-8C4D-4E6F-9A1B-2C3D4E5F6A7B"),
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%+v\n", *ruleTestList)
}
```

```java tab="Java"
import com.fiscalisto.FiscalistoClient;
import com.fiscalisto.model.TestRuleParams;

// The key comes from FISCALISTO_API_KEY.
var fiscalisto = new FiscalistoClient();

var ruleTestList = fiscalisto.rules().test("rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6", new TestRuleParams().setUuid("5F3B2A10-8C4D-4E6F-9A1B-2C3D4E5F6A7B"));
System.out.println(ruleTestList);
```

```csharp tab="C#"
using Fiscalisto;

// The key comes from FISCALISTO_API_KEY.
var fiscalisto = new FiscalistoClient();

var ruleTestList = await fiscalisto.Rules.TestAsync("rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6", new TestRuleParams
{
    Uuid = "5F3B2A10-8C4D-4E6F-9A1B-2C3D4E5F6A7B",
});
```

It changes nothing. It answers, for that invoice (or, without `uuid`, for the 10 latest of its trigger; on `bank.movement`, the 10 latest movements, with `bank_movement`, its id in [Bank movements without an invoice](https://fiscalisto.com/en/docs/api/contabilidad#bank-movements-without-an-invoice): `bwd_…` a withdrawal, `btx_…` a deposit), whether it holds (`matches`), each condition with what the record has (`actual`) and what it would do (`would_do`). `already_ran` says it already ran on it and won't again.

### On the last 90 days

```bash tab="cURL"
curl https://api.fiscalisto.com/v1/rules/rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6/backtest \
  -H "Authorization: Bearer $FISCALISTO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "days": 90 }'
```

```ts tab="TypeScript"
import { Fiscalisto } from "fiscalisto";

// The key comes from FISCALISTO_API_KEY.
const fiscalisto = new Fiscalisto();

const ruleBacktest = await fiscalisto.rules.backtest("rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6", { days: 90 });
```

```python tab="Python"
from fiscalisto import Fiscalisto

# The key comes from FISCALISTO_API_KEY.
fiscalisto = Fiscalisto()

rule_backtest = fiscalisto.rules.backtest("rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6", {"days": 90})
```

```php tab="PHP"
<?php

use Fiscalisto\Fiscalisto;

// The key comes from FISCALISTO_API_KEY.
$fiscalisto = new Fiscalisto();

$ruleBacktest = $fiscalisto->rules->backtest('rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6', ['days' => 90]);
```

```go tab="Go"
package main

import (
	"context"
	"fmt"
	"log"

	fiscalisto "fiscalisto.com/go"
)

func main() {
	// The key comes from FISCALISTO_API_KEY.
	client, err := fiscalisto.NewClient("")
	if err != nil {
		log.Fatal(err)
	}
	ctx := context.Background()

	ruleBacktest, err := client.Rules.Backtest(ctx, "rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6", &fiscalisto.BacktestRuleParams{Days: fiscalisto.Int64(90)})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%+v\n", *ruleBacktest)
}
```

```java tab="Java"
import com.fiscalisto.FiscalistoClient;
import com.fiscalisto.model.BacktestRuleParams;

// The key comes from FISCALISTO_API_KEY.
var fiscalisto = new FiscalistoClient();

var ruleBacktest = fiscalisto.rules().backtest("rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6", new BacktestRuleParams().setDays(90));
System.out.println(ruleBacktest);
```

```csharp tab="C#"
using Fiscalisto;

// The key comes from FISCALISTO_API_KEY.
var fiscalisto = new FiscalistoClient();

var ruleBacktest = await fiscalisto.Rules.BacktestAsync("rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6", new BacktestRuleParams { Days = 90 });
```

It looks at every record of its trigger from the last `days` days (90 by default, 1 to 90; up to the 2,000 most recent, and `capped` says whether it reached that limit) and answers a `rule_backtest`: how many it looked at (`records`), on how many it would have held (`matches`), what they add up to in pesos (`amount`; `null` for SAT notices), what it would have done with each (`would_do`) and with the rest (`else_would_do`, its «Si no se cumple»). It's what **Probar** shows in the app. It changes nothing.

## Change, pause and order

`POST /v1/rules/{id}` changes only what you send; `conditions` and `actions` are replaced whole. `enabled: false` pauses it. With `once_per_record` (`true` by default, except on `purchase_order.saved`) it runs once per invoice, order or bank movement. On `invoice.daily` and `purchase_order.daily`, without `once_per_record` it acts every morning while it holds. With `wait_days` (1 to 90; `0` by default) it doesn't act when it holds: it waits those days and checks the record again as it is then, and acts only if it still holds (one wait per rule and record; pausing or deleting the rule cancels it). Rules run top to bottom, and one with `stop_after` that holds stops the ones after it for that record; `POST /v1/rules/order` changes the order:

```bash tab="cURL"
curl https://api.fiscalisto.com/v1/rules/order \
  -H "Authorization: Bearer $FISCALISTO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "rules": ["rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6"] }'
```

```ts tab="TypeScript"
import { Fiscalisto } from "fiscalisto";

// The key comes from FISCALISTO_API_KEY.
const fiscalisto = new Fiscalisto();

const { data } = await fiscalisto.rules.order({
  rules: ["rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6"],
});
```

```python tab="Python"
from fiscalisto import Fiscalisto

# The key comes from FISCALISTO_API_KEY.
fiscalisto = Fiscalisto()

data = fiscalisto.rules.order({
    "rules": ["rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6"],
})["data"]
```

```php tab="PHP"
<?php

use Fiscalisto\Fiscalisto;

// The key comes from FISCALISTO_API_KEY.
$fiscalisto = new Fiscalisto();

$data = $fiscalisto->rules->order([
    'rules' => ['rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6'],
])['data'];
```

```go tab="Go"
package main

import (
	"context"
	"fmt"
	"log"

	fiscalisto "fiscalisto.com/go"
)

func main() {
	// The key comes from FISCALISTO_API_KEY.
	client, err := fiscalisto.NewClient("")
	if err != nil {
		log.Fatal(err)
	}
	ctx := context.Background()

	ruleList, err := client.Rules.Order(ctx, &fiscalisto.OrderRulesParams{
		Rules: []string{"rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6"},
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%+v\n", *ruleList)
}
```

```java tab="Java"
import com.fiscalisto.FiscalistoClient;
import com.fiscalisto.model.OrderRulesParams;
import java.util.List;

// The key comes from FISCALISTO_API_KEY.
var fiscalisto = new FiscalistoClient();

var ruleList = fiscalisto.rules().order(new OrderRulesParams()
        .setRules(List.of("rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6")));
System.out.println(ruleList);
```

```csharp tab="C#"
using Fiscalisto;

// The key comes from FISCALISTO_API_KEY.
var fiscalisto = new FiscalistoClient();

var ruleList = await fiscalisto.Rules.OrderAsync(new OrderRulesParams
{
    Rules = new() { "rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6" },
});
```

`DELETE /v1/rules/{id}` deletes it: it stops running, and what it already set stays. A cost center a person set is never changed by a rule.

### If it still holds

With `follow_ups` the rule does more on the same record days later, to remind or escalate: up to 5 steps, each with `days` (counted from when it did its `actions`, each step more than the one before, up to 180) and its `actions` (the same ones as above, 1 to 8). On each step's day it checks its conditions again on the record as it is then: once they no longer hold, that step and the ones after it don't run. `[]` removes them, and pausing or deleting the rule cancels the ones left. In its [history](#history), `did` starts with «a los N días, seguía así». For example, notify at once about an unpaid invoice, again after 3 days and management after 7:

```bash tab="cURL"
curl https://api.fiscalisto.com/v1/rules/rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6 \
  -H "Authorization: Bearer $FISCALISTO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "follow_ups": [
      { "days": 3, "actions": [{ "type": "notify", "members": ["mem_OufpKqnrvx9p3fT0aW9CxR2YhJ8kLmNqP4"] }] },
      { "days": 7, "actions": [{ "type": "notify", "members": ["mem_OufpKqnrvx9p3fT0aW9CxR2YhJ8kLmNqP4"], "note": "Sigue sin pagarse {folio}" }] }
    ]
  }'
```

```ts tab="TypeScript"
import { Fiscalisto } from "fiscalisto";

// The key comes from FISCALISTO_API_KEY.
const fiscalisto = new Fiscalisto();

const rule = await fiscalisto.rules.update("rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6", {
  follow_ups: [
    {
      days: 3,
      actions: [
        {
          type: "notify",
          members: [
            "mem_OufpKqnrvx9p3fT0aW9CxR2YhJ8kLmNqP4",
          ],
        },
      ],
    },
    {
      days: 7,
      actions: [
        {
          type: "notify",
          members: [
            "mem_OufpKqnrvx9p3fT0aW9CxR2YhJ8kLmNqP4",
          ],
          note: "Sigue sin pagarse {folio}",
        },
      ],
    },
  ],
});
```

```python tab="Python"
from fiscalisto import Fiscalisto

# The key comes from FISCALISTO_API_KEY.
fiscalisto = Fiscalisto()

rule = fiscalisto.rules.update("rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6", {
    "follow_ups": [
        {
            "days": 3,
            "actions": [
                {
                    "type": "notify",
                    "members": [
                        "mem_OufpKqnrvx9p3fT0aW9CxR2YhJ8kLmNqP4",
                    ],
                },
            ],
        },
        {
            "days": 7,
            "actions": [
                {
                    "type": "notify",
                    "members": [
                        "mem_OufpKqnrvx9p3fT0aW9CxR2YhJ8kLmNqP4",
                    ],
                    "note": "Sigue sin pagarse {folio}",
                },
            ],
        },
    ],
})
```

```php tab="PHP"
<?php

use Fiscalisto\Fiscalisto;

// The key comes from FISCALISTO_API_KEY.
$fiscalisto = new Fiscalisto();

$rule = $fiscalisto->rules->update('rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6', [
    'follow_ups' => [
        [
            'days' => 3,
            'actions' => [
                [
                    'type' => 'notify',
                    'members' => [
                        'mem_OufpKqnrvx9p3fT0aW9CxR2YhJ8kLmNqP4',
                    ],
                ],
            ],
        ],
        [
            'days' => 7,
            'actions' => [
                [
                    'type' => 'notify',
                    'members' => [
                        'mem_OufpKqnrvx9p3fT0aW9CxR2YhJ8kLmNqP4',
                    ],
                    'note' => 'Sigue sin pagarse {folio}',
                ],
            ],
        ],
    ],
]);
```

```go tab="Go"
package main

import (
	"context"
	"fmt"
	"log"

	fiscalisto "fiscalisto.com/go"
)

func main() {
	// The key comes from FISCALISTO_API_KEY.
	client, err := fiscalisto.NewClient("")
	if err != nil {
		log.Fatal(err)
	}
	ctx := context.Background()

	rule, err := client.Rules.Update(ctx, "rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6", &fiscalisto.UpdateRuleParams{
		FollowUps: []fiscalisto.UpdateRuleParamsFollowUp{
			{
				Days: 3,
				Actions: []fiscalisto.UpdateRuleParamsFollowUpAction{
					{
						Type:    "notify",
						Members: []string{"mem_OufpKqnrvx9p3fT0aW9CxR2YhJ8kLmNqP4"},
					},
				},
			},
			{
				Days: 7,
				Actions: []fiscalisto.UpdateRuleParamsFollowUpAction{
					{
						Type:    "notify",
						Members: []string{"mem_OufpKqnrvx9p3fT0aW9CxR2YhJ8kLmNqP4"},
						Note:    fiscalisto.String("Sigue sin pagarse {folio}"),
					},
				},
			},
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(rule.ID)
}
```

```java tab="Java"
import com.fiscalisto.FiscalistoClient;
import com.fiscalisto.model.UpdateRuleParams;
import com.fiscalisto.model.UpdateRuleParamsFollowUp;
import com.fiscalisto.model.UpdateRuleParamsFollowUpAction;
import java.util.List;

// The key comes from FISCALISTO_API_KEY.
var fiscalisto = new FiscalistoClient();

var rule = fiscalisto.rules().update("rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6", new UpdateRuleParams()
        .setFollowUps(List.of(
                new UpdateRuleParamsFollowUp()
                        .setDays(3)
                        .setActions(List.of(
                                new UpdateRuleParamsFollowUpAction()
                                        .setType("notify")
                                        .setMembers(List.of(
                                                "mem_OufpKqnrvx9p3fT0aW9CxR2YhJ8kLmNqP4"
                                        ))
                        )),
                new UpdateRuleParamsFollowUp()
                        .setDays(7)
                        .setActions(List.of(
                                new UpdateRuleParamsFollowUpAction()
                                        .setType("notify")
                                        .setMembers(List.of(
                                                "mem_OufpKqnrvx9p3fT0aW9CxR2YhJ8kLmNqP4"
                                        ))
                                        .setNote("Sigue sin pagarse {folio}")
                        ))
        )));
System.out.println(rule.getId());
```

```csharp tab="C#"
using Fiscalisto;

// The key comes from FISCALISTO_API_KEY.
var fiscalisto = new FiscalistoClient();

var rule = await fiscalisto.Rules.UpdateAsync("rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6", new UpdateRuleParams
{
    FollowUps = new()
    {
        new()
        {
            Days = 3,
            Actions = new()
            {
                new()
                {
                    Type = "notify",
                    Members = new()
                    {
                        "mem_OufpKqnrvx9p3fT0aW9CxR2YhJ8kLmNqP4",
                    },
                },
            },
        },
        new()
        {
            Days = 7,
            Actions = new()
            {
                new()
                {
                    Type = "notify",
                    Members = new()
                    {
                        "mem_OufpKqnrvx9p3fT0aW9CxR2YhJ8kLmNqP4",
                    },
                    Note = "Sigue sin pagarse {folio}",
                },
            },
        },
    },
});
```

## History

```bash tab="cURL"
curl https://api.fiscalisto.com/v1/rules/rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6/runs \
  -H "Authorization: Bearer $FISCALISTO_API_KEY"
```

```ts tab="TypeScript"
import { Fiscalisto } from "fiscalisto";

// The key comes from FISCALISTO_API_KEY.
const fiscalisto = new Fiscalisto();

for await (const item of fiscalisto.rules.listRuns("rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6")) {
  console.log(item.id);
}
```

```python tab="Python"
from fiscalisto import Fiscalisto

# The key comes from FISCALISTO_API_KEY.
fiscalisto = Fiscalisto()

for item in fiscalisto.rules.list_runs("rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6"):
    print(item["id"])
```

```php tab="PHP"
<?php

use Fiscalisto\Fiscalisto;

// The key comes from FISCALISTO_API_KEY.
$fiscalisto = new Fiscalisto();

foreach ($fiscalisto->rules->listRuns('rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6') as $item) {
    echo $item['id'], "\n";
}
```

```go tab="Go"
package main

import (
	"context"
	"fmt"
	"log"

	fiscalisto "fiscalisto.com/go"
)

func main() {
	// The key comes from FISCALISTO_API_KEY.
	client, err := fiscalisto.NewClient("")
	if err != nil {
		log.Fatal(err)
	}
	ctx := context.Background()

	for item, err := range client.Rules.ListRunsAutoPaging(ctx, "rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6", nil) {
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(item.ID)
	}
}
```

```java tab="Java"
import com.fiscalisto.FiscalistoClient;

// The key comes from FISCALISTO_API_KEY.
var fiscalisto = new FiscalistoClient();

for (var item : fiscalisto.rules().listRunsAutoPaging("rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6")) {
    System.out.println(item.getId());
}
```

```csharp tab="C#"
using Fiscalisto;

// The key comes from FISCALISTO_API_KEY.
var fiscalisto = new FiscalistoClient();

await foreach (var item in fiscalisto.Rules.ListRunsAutoPagingAsync("rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6"))
    Console.WriteLine(item.Id);
```

Each time it ran, newest first: on which record (`record`), what it did (`did`), and `outcome` `done` (made changes), `nothing` (already that way) or `failed` (with `error`). Kept for 180 days.

## Changes and undo

```bash tab="cURL"
curl https://api.fiscalisto.com/v1/rules/rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6/versions \
  -H "Authorization: Bearer $FISCALISTO_API_KEY"
```

```ts tab="TypeScript"
import { Fiscalisto } from "fiscalisto";

// The key comes from FISCALISTO_API_KEY.
const fiscalisto = new Fiscalisto();

const { data } = await fiscalisto.rules.listVersions("rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6");
```

```python tab="Python"
from fiscalisto import Fiscalisto

# The key comes from FISCALISTO_API_KEY.
fiscalisto = Fiscalisto()

data = fiscalisto.rules.list_versions("rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6")["data"]
```

```php tab="PHP"
<?php

use Fiscalisto\Fiscalisto;

// The key comes from FISCALISTO_API_KEY.
$fiscalisto = new Fiscalisto();

$data = $fiscalisto->rules->listVersions('rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6')['data'];
```

```go tab="Go"
package main

import (
	"context"
	"fmt"
	"log"

	fiscalisto "fiscalisto.com/go"
)

func main() {
	// The key comes from FISCALISTO_API_KEY.
	client, err := fiscalisto.NewClient("")
	if err != nil {
		log.Fatal(err)
	}
	ctx := context.Background()

	ruleVersionList, err := client.Rules.ListVersions(ctx, "rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%+v\n", *ruleVersionList)
}
```

```java tab="Java"
import com.fiscalisto.FiscalistoClient;

// The key comes from FISCALISTO_API_KEY.
var fiscalisto = new FiscalistoClient();

var ruleVersionList = fiscalisto.rules().listVersions("rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6");
System.out.println(ruleVersionList);
```

```csharp tab="C#"
using Fiscalisto;

// The key comes from FISCALISTO_API_KEY.
var fiscalisto = new FiscalistoClient();

var ruleVersionList = await fiscalisto.Rules.ListVersionsAsync("rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6");
```

Each change to the rule, newest first: a `rule_version` with what it was (`change`: `created`, `edited`, `paused`, `resumed`, `deleted` or `restored`), who (`changed_by`, the `mem_…`; `null` if it was the API or Fiscalisto) and the rule as it was left (`rule`). The last 50 of each rule are kept, from the app, the API and the MCP. To put it back to a version:

```bash tab="cURL"
curl -X POST https://api.fiscalisto.com/v1/rules/rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6/versions/1204/restore \
  -H "Authorization: Bearer $FISCALISTO_API_KEY"
```

```ts tab="TypeScript"
import { Fiscalisto } from "fiscalisto";

// The key comes from FISCALISTO_API_KEY.
const fiscalisto = new Fiscalisto();

const rule = await fiscalisto.rules.restoreVersion("rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6", "1204");
```

```python tab="Python"
from fiscalisto import Fiscalisto

# The key comes from FISCALISTO_API_KEY.
fiscalisto = Fiscalisto()

rule = fiscalisto.rules.restore_version("rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6", "1204")
```

```php tab="PHP"
<?php

use Fiscalisto\Fiscalisto;

// The key comes from FISCALISTO_API_KEY.
$fiscalisto = new Fiscalisto();

$rule = $fiscalisto->rules->restoreVersion('rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6', '1204');
```

```go tab="Go"
package main

import (
	"context"
	"fmt"
	"log"

	fiscalisto "fiscalisto.com/go"
)

func main() {
	// The key comes from FISCALISTO_API_KEY.
	client, err := fiscalisto.NewClient("")
	if err != nil {
		log.Fatal(err)
	}
	ctx := context.Background()

	rule, err := client.Rules.RestoreVersion(ctx, "rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6", "1204")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(rule.ID)
}
```

```java tab="Java"
import com.fiscalisto.FiscalistoClient;

// The key comes from FISCALISTO_API_KEY.
var fiscalisto = new FiscalistoClient();

var rule = fiscalisto.rules().restoreVersion("rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6", "1204");
System.out.println(rule.getId());
```

```csharp tab="C#"
using Fiscalisto;

// The key comes from FISCALISTO_API_KEY.
var fiscalisto = new FiscalistoClient();

var rule = await fiscalisto.Rules.RestoreVersionAsync("rul_OufpKqnrvx9p2Hq8vR4nXk7LmT3wYc9pB6", "1204");
```

The rule goes back to that version and is checked like any change (a cost center or tag that no longer exists gives `rule_invalid`). Restoring is one more version, so it can be undone too. A deleted rule keeps its changes for 90 days: its `rul_…` lists them and, with the `deleted` version, it comes back as it was.
