> For the complete documentation index, see [llms.txt](https://docs.cennso.com/components/tposs/latest/llms.txt) (all documentation: [llms.txt](https://docs.cennso.com/llms.txt)). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.cennso.com/components/tposs/latest/configuration/charging.md).

# Charging configuration

This document describes the settings you can use to configure the charging sub-system in TPOSS. This sub-system is responsible for handling: 

- [Tariffs](#tariffs-configuration)
- [Charging rules](#charging-rules-configuration)
- [Charging Data Records (CDRs)](#charging-data-records-configuration).

## Tariffs configuration

TPOSS provisions a set of [tariffs](#available-tariffs) during the start-up. For each tariff, you have to configure a tenant using this configuration option:

```yaml
tariff:
  # Tenant name for the TPOSS tariffs
  tenant: tposs.cennso.net
```

It is possible to configure tariffs for multiple tenants:

```yaml
tariff:
  tenant: "tposs.cennso.net, additional.tenant.com"
```

With this configuration, a whole set of tariffs is provisioned for every specified tenant. For the example above, two online tariffs will be provisioned: `online@tposs.cennso.net` and `online@additional.tenant.com`.

### Available tariffs

These are the tariffs that TPOSS provisions during the start-up:

| Tariff | Description |
| --- | --- |
| `online@tariff.{TENANT_NAME}` | TPOSS allocates a quota from a valid balance, if such exists. The balance is selected based on the carrier and IMSI. If a valid balance exists, the `Online` rating group is allocated and the user can access the Internet. In the case when multiple balances exist, the one with the earliest expiration time is used. |
| `b2binternet@tariff.{TENANT_NAME}` | The pre-configured quota is allocated at each update request. The quota is taken from the value of the **scg.b2b_internet_quota** configuration option. The `B2BInternet` rating group is allocated and the user can access the Internet. |
| `default@tariff.{TENANT_NAME}` | TPOSS allocates a quota from a valid balance, if such exists. The balance is selected based on the charging account. There can be only one balance. If a valid balance exists, the `Online` rating group is allocated and the user can access the Internet. |
| `home-country-change@tariff.{TENANT_NAME}` | Only the `Portal` and `OnlineRedirection` rating groups are allocated for a user with this tariff. The user cannot access the Internet. |
| `operator-swap@tariff.{TENANT_NAME}` | Only the `Portal` and `OnlineRedirection` rating groups are allocated for a user with this tariff. The user cannot access the Internet. |
| `blocked@tariff.{TENANT_NAME}` | The RADIUS Access-Request request is rejected for a user with this tariff. |

To provision tariffs with a new tenant manually, use the following API:

```elixir
Tposs.init_tariffs(["new-tenant-name"])
```

> [!TIP]
> For more information on how to run TPOSS commands, see the [Troubleshooting guide](https://docs.cennso.com/components/tposs/latest/troubleshooting/diagnosis-ui.md).

## Charging rules configuration

TPOSS specifies the list of charging rules and rating groups to allocate them when creating a user session and execute the charging procedures during the session's lifetime. Each rule has a name and a rating group identifier associated with it. To specify the list of rating groups with respective names to allocate charging rules and handle charging reports, use these configuration options:

```yaml
scg:
  adc_rules:
    # Charging rule name
    online: "Online"

  rating_groups:
    # Rating group identifier for the Online charging rule
    online: 1000

  rating_groups_selectors:
    # Rating group selector definition for the Online charging rule
    online: "handler = online and called_station_id = apn1.*"

  rating_groups_validity_time:
    # Rating group validity time definition for the Online charging rule. The validity time is provided in seconds.
    online: 180

  rating_groups_exclude_rules:
    # The list of charging rules to exclude from the allocation list
    # if the Online charging rule was allocated for the given user session
    online: "RuleName1, RuleName2"
```

In the example above, you may see the definition of the rating group with ID `1000` and with the associated `Online` charging rule. You can use any name instead of `online` in **scg.{OPTION_NAME}.{RULE_NAME}**, however, it must be consistent within the whole configuration for this rating group. Each rating group has a validity time - the period of time in seconds after which TPOSS expects to receive the charging report for the given rating group.

The **scg.rating_groups_exclude_rules.{RULE_NAME}** parameter specifies the list of charging rules that are excluded if the given `RULE_NAME` rule was allocated by TPOSS. The names listed in the **scg.rating_groups_exclude_rules.{RULE_NAME}** must be valid charging rules defined in the **scg.adc_rules** configuration.

Before allocating a charging rule for a user, TPOSS must know what conditions must be met. For this purpose, the **scg.rating_groups_selectors.{RULE_NAME}** configuration option exists. The rule selector is a string that lets you filter rules using one or more key-value pairs. Each condition within the selector follows the `key = value` format. You can combine multiple conditions using `and` or `or`. For example, the following charging rule selector describes the rule that will be applied if the charging rule handler `online` is applicable and the user has [Called-Station-ID](https://datatracker.ietf.org/doc/html/rfc2865#section-5.30) with the `apn.1` prefix:

```
handler = online and called_station_id = apn1.*
```

The possible keys are:

- **handler** - a handler name that checks if it is possible to allocate a given rating group for the given session
- **called_station_id** - a regular expression that is matched against `Called-Station-Id` within a network session

> [!NOTE]
> The `handler` key must be always the first condition in the expression.

The following handlers are supported:

- `b2binternet` - a rule is allocated if a user has the `B2BInternet` tariff
- `online` - a rule is allocated if a user has the `Online` tariff and a valid balance
- `unlimited_streaming` - a rule is allocated if a user has the unlimited streaming [tariff option](https://docs.cennso.com/components/tposs/latest/api-reference/rpc/charging_account_api.md#data-model)
- `whitelist` - a rule is allocated if the session has unknown IMEISV and the [whitelist](https://docs.cennso.com/components/tposs/latest/configuration/imeisv.md) functionality is enabled

The size of quota allocated for a user usually depends on the tariff, balance, and the handler of the rule. If the selector is not specified for the given charging rule, define a pre-allocated quota for such rule:

```yaml
scg:
  rating_groups_quotas:
    portal: 1073741824
```

> [!NOTE]
> Rules without a selector are always allocated to a user, unless they are specified in the **scg.rating_groups_exclude_rules** for rules that are already allocated.

Here is the example of the default TPOSS configuration with the description of all defined charging rules, rating groups, and their behaviour:

```yaml
scg:
  adc_rules:
    # List of charging rules with associated names
    online: "Online"
    portal: "Portal"
    non_whitelisted_imei: "FactoryTest"
    unlimited_streaming: "UnlimitedStreaming"
    unlimited_streaming_pd: "UnlimitedStreamingPD"
    online_redirection: "OnlineRedirection"
    b2binternet: "B2BInternet"

  rating_groups:
    # List of rating groups for the charging rules defined above
    online: 1000
    portal: 2000
    non_whitelisted_imei: 2100
    unlimited_streaming: 3000
    unlimited_streaming_pd: 3100
    b2binternet: 3225
    online_redirection: 4000

  rating_groups_validity_time:
    # List of validity time definitions for each charging rule
    online: 180
    portal: 180
    b2binternet: 180
    non_whitelisted_imei: 180
    unlimited_streaming: 180
    unlimited_streaming_pd: 180
    online_redirection: 180

  rating_groups_selectors:
    # The `Online` rule is allocated if the user is in the `online` tariff and has a valid balance
    online: "handler = online"
    # The `FactoryTest` rule is allocated if the user has unknown IMEISV
    non_whitelisted_imei: "handler = whitelist"
    # The `UnlimitedStreaming` rule is allocated if the user has the `UnlimitedStreaming`
    # tariff option
    unlimited_streaming: "handler = unlimited_streaming"
    # The `UnlimitedStreamingPD` rule is allocated if user has `UnlimitedStreaming`
    # tariff option
    unlimited_streaming_pd: "handler = unlimited_streaming"
    # The `B2BInternet` rule is allocated if the user is in the `b2binternet` tariff
    b2binternet: "handler = b2binternet"

  rating_groups_quotas:
    # List of predefined quotas for some charging rules
    portal: 999999999
    non_whitelisted_imei: 999999999
    unlimited_streaming: 999999999
    unlimited_streaming_pd: 999999999
    online_redirection: 999999999
    b2binternet: 1073741824

  rating_groups_exclude_rules:
    # If the `Online` rule is allocated, the `OnlineRedirection` is not used
    online: "OnlineRedirection"
    # If the `FactoryTest` rule is allocated, the `Portal` is not used
    non_whitelisted_imei: "Portal"
    # If the `B2BInternet` rule is allocated, the `OnlineRedirection` and `Portal` are not used
    b2binternet: "OnlineRedirection, Portal"
```

You can disable the `unlimited_streaming` and `unlimited_streaming_pd` charging rules.

To do so, use this configuration option:

```yaml
scg:
  # Disables UnlimitedStreaming and UnlimitedStreamingPD charging rules
  unlimited_streaming:
    enabled: false
```

To configure the traffic quota that is allocated for the sessions with the `B2BInternet` charging rule, use this configuration option:

```yaml
scg:
  # Specifies the size of quota for the B2BInternet charging rule
  b2b_internet_quota: 1073741824
```

> [!NOTE]
> The **scg.b2b_internet_quota** configuration option is deprecated and will be removed in the next releases. Instead, specify the **scg.rating_groups_quotas.b2binternet = {QUOTA}** option with the `scg.rating_groups_selectors.b2binternet = "handler = b2binternet"` selector.

## Charging Data Records configuration

When the service session is terminated or a balance is exhausted by validity time or by quota, TPOSS creates a Charging Data Record (CDR). TPOSS may write CDRs to multiple backends. The following backends are supported:

- [Database backend](#database-backend)
- [File backend](#file-backend)

Read the sections below to learn how to enable (or disable) and configure these backends.

### Database backend

You can configure TPOSS to generate CDRs to the MySQL database backend using these configuration options:

```yaml
cdr:
  controller:
    database:
      # Enables storing of CDRs in the MySQL database
      enabled: true
      # List of criteria for which CDRs are not generated.
      ignore:
        - "Called-Station-Id:apn1.example-[2-8]\\.com"
        - "Called-Station-Id:apn2.example-[2-8]\\.com"
      # Enables CDR table partitioning.
      partitions_enabled: false
      # Number of CDR table partitions that are initially created.
      initial_partitions_amount: 24
      # Time period during which a partition is considered active.
      # A value of this configuration option consists of two parts separated by a dash: a number and a time unit.
      partitions_duration: 1-day
      # Number of partitions to create when the last partition becomes active.
      new_partitions_amount: 8
      # Time period after which CDRs older than this value are removed from the database during periodic checks.
      # A value of this configuration option consists of two parts separated by a dash: a number and a time unit.
      cdr_cleanup_period: 14-days
      # Specifies the time of day to trigger a once per-day check for outdated CDR partitions that may need to be dropped.
      clean_up_partitions_at: ""
      # A period of time (in milliseconds) after which a special watcher process
      # is triggered to check for CDRs for which the data retention period is over.
      # Applicable only if the **cdr.controller.database.partitions_enabled** is set to `false.`
      watcher_timeout: 300000
      # Specifies how many outdated and closed CDRs can be removed from the database at once.
      # The possible values are `all` or a positive integer number.
      # Applicable only if the **cdr.controller.database.partitions_enabled** is set to `false.`
      cdr_cleanup_limit: all
      # Specifies timeout (in milliseconds) for a database query to clean up outdated CDRs.
      # Applicable only if the **cdr.controller.database.partitions_enabled** is set to `false.`
      cdr_cleanup_query_timeout: 60000
```

The configuration option **cdr.controller.database.enabled** enables storing the generated charging data records in the MySQL database.

The configuration option **cdr.controller.database.ignore** contains a list of selectors that specify criteria for which CDRs should not be generated. If a selector is matched for the given session, the charging data records are not generated. The selectors are in the form of `key:value`. The currently supported key is only `Called-Station-Id`. The value can be any regular expression. In the example above, the CDRs are not created for the sessions from [APNs](https://docs.cennso.com/components/tposs/latest/glossary.md), such as `apn1.example-2.com`, `apn2.example-3.com`, and so on.

> [!TIP]
> Partitioning is an effective way to manage big write-only tables with historic data. That's why it is recommended to enable CDR table partitioning using the **cdr.controller.database.partitions_enabled** option.

If the partitioning is enabled, TPOSS provisions special [stored procedures](https://dev.mysql.com/doc/refman/8.4/en/stored-objects.html) to create, maintain active partitions, and delete the old ones. In a new TPOSS deployment, the configuration option **cdr.controller.database.initial_partitions_amount** specifies the initial number of partitions to create.

The **cdr.controller.database.partitions_duration** configuration option specifies how long the given partition should be considered active and may be used to insert the new charging data records. The **cdr.controller.database.cdr_cleanup_period** configuration option specifies a time unit after which all the partitions which were created earlier than this time are dropped. The definitions of the time periods specified in the **cdr.controller.database.partitions_duration** and **cdr.controller.database.cdr_cleanup_period** options consist of a positive integer and a time unit, for example: `14-days`, `month`, `2-minutes`. The supported time units are:

- second(s)
- minute(s)
- hour(s)
- day(s)
- week(s)
- month(s)
- year(s)

As soon as there is only a single active partition remaining, the database triggers the stored procedure to create new partitions for rotation. The **cdr.controller.database.new_partitions_amount** configuration option specifies the number of new partitions to create.

The **clean_up_partitions_at** parameter is an optional configuration option that may contain a string value in the `"HH:MM"` format. If the configuration value is not empty, TPOSS provisions an event for the deletion of outdated CDR partitions, which should be triggered once a day at the specified time. If this configuration option is set to an empty string (`""`), the event to delete the outdated partitions is triggered every seven minutes. The time zone of the given time depends on the time zone [configured](https://dev.mysql.com/doc/refman/8.4/en/time-zone-support.html) at the database server.

> [!NOTE]
> You should run the partition deletion during a less busy time not to impact other database queries.

If the deletion of partitions that is triggered once per-day failed, or if you want to trigger it during maintenance time, you can do it manually with the MySQL client by calling this procedure:

```sql
CALL drop_partitions(14, 'day');
```

The procedure above drops all the partitions which are older than `14` days. This procedure accepts two arguments:

- The first argument specifies the number of units after which a partition is considered as outdated.
- The second argument specifies the time unit.

> [!TIP]
> If the creation of new partitions failed, check the [Repair partitions in the CDR table](https://docs.cennso.com/components/tposs/latest/troubleshooting/database.md#repair-partitions-in-the-cdr-table) troubleshooting guide.

If partitioning is disabled, the special process watches for a CDR table and deletes CDRs that are outdated. The following options control the behaviour of this process:

- **cdr.controller.database.cdr_cleanup_limit** - limit of CDRs to remove at once. The supported values are any positive integer values or the string `all`.
- **cdr.controller.database.cdr_cleanup_query_timeout** - timeout in milliseconds that specifies the max time of the query to delete outdated CDRs.
- **cdr.controller.database.watcher_timeout** - timeout in milliseconds that specifies how often to check a CDR table for outdated CDRs

### File backend

You can configure TPOSS to generate CDRs to the file backend using these configuration options:

```yaml
cdr:
  controller:
    file:
      # Enables storing CDRs in CSV files.
      enabled: true
      # List of criteria for which CDRs are not generated.
      ignore:
        - "Called-Station-Id:apn1.example-[2-8]\\.com"
        - "Called-Station-Id:apn1.example-[2-8]\\.com"
      # Directory where CDR files are stored
      dir: /srv/data/cdrs
      # Time to rotate a CDR file in seconds.
      time_window: 180
      # Number of closed CDRs that can be written into one file before rotation.
      max_count: 20000
      # Format of a file name where closed CDRs are stored.
      file_name_format: tposs_{start_at:ISO8601:UTC:STRIPPED}_{batch_id}_{sha256}.csv
```

The configuration option **cdr.controller.file.enabled** enables storing the generated charging data records in CSV files.

The **cdr.controller.file.ignore** configuration option contains a list of selectors that specify criteria for which CDRs should not be generated. It works the same as the **cdr.controller.database.ignore** option in the [database controller](#database-backend).

The other configuration options specify where to store CSV files on a disk and how to rotate them. The **cdr.controller.file.dir** configuration option specifies the path to the directory where CDRs are written. The **cdr.controller.file.time_window** specifies time in seconds for the charging data record files rotation. The **cdr.controller.file.max_count** configuration option specifies the maximum number of charging data records in one file.

The **cdr.controller.file.file_name_format** configuration option specifies the format of the CSV file names. The format is a string that may contain placeholders that are replaced in the actual file name on disk. Based on the example above, the resulting file name may look like:

```
tposs_20250620T115411_2_f2ca1bb6c7e907d06dafe4687e579fce76b37e4e93b7605022da52e6ccc26fd2.csv
```

The following placeholders are supported:

- `batch_id` - UUID identifier for the current TPOSS instance. Changed after each TPOSS restart.
- `file_counter` - Number of files created by the given TPOSS instance.
- `file_id` - UUID identifier of the CDR file.
- `start_at` - Time when the CDR file was created.
- `end_at` - Time when the CDR file was closed.
- `first_at` - Time when the first CDR was written to the file.
- `last_at` - Time when the last CDR was written to the file.
- `counter` - Number of CDRs written to the file.
- `sha` - [SHA1 hash](https://datatracker.ietf.org/doc/html/rfc3174) of the CDR file content.
- `sha256` - [SHA256 hash](https://datatracker.ietf.org/doc/html/rfc6234) of the CDR file content.
- `sha512` - [SHA512 hash](https://datatracker.ietf.org/doc/html/rfc6234) of the CDR file content.
- `md5` - [MD5](https://www.ietf.org/rfc/rfc1321.txt) of the CDR file content.

The `start_at`, `end_at`, `first_at`, and `last_at` parameters must provide information about the time format. The format must be passed along with the parameter name, split by the `:` symbol. For example - `start_at:ISO8601:UTC`. The following formats are supported:

- `ISO8601` - UTC date and time in the `ISO8601` format. For example - `2025-06-20T12:11:12`.
- `ISO8601:UTC` - UTC date and time in the `ISO8601` format with suffix `Z`. For example - `2025-06-20T12:11:12Z`.
- `ISO8601:STRIPPED` - UTC date and time in the `ISO8601` format without `-` and `:` symbols. For example - `20250620T121229`.
- `ISO8601:UTC:STRIPPED` - UTC date and time in the `ISO8601` format with suffix `Z` and without `-` and `:` symbols. For example - `20250620T121229Z`.

To write CDRs on a disk, you must specify a [persistent volume](https://kubernetes.io/docs/concepts/storage/persistent-volumes/):

```yaml
persistence:
  enabled: true
  accessMode: ReadWriteOnce
  size: 20Gi
  storageClass: "storage-class"
  existingClaim: ""
```

> [!NOTE]
> To have access to the file-based CDRs, TPOSS provides an SFTP service that you must configure. Read the next section to learn more.

#### SFTP settings

You can enable an SFTP container so that CDRs can be fetched from an external system for further CDR processing:

```yaml
sftp:
  # Enables CDR SFTP exporter.
  enabled: false
  image:
    # Image repository for the SFTP container.
    repository: registry.cennso.com/cennso/tposs-cdr-exporter-sftp
    # SFTP container image tag.
    tag: v1.2.2
    # SFTP container image pull policy.
    pullPolicy: IfNotPresent
  initImage:
    # Image repository for the SFTP init container. Can be any image that contains the `openssl` CLI.
    repository: registry.cennso.com/cennso/nettools
    # SFTP init container image tag.
    tag: v1.16.0
    # SFTP init container image pull policy.
    pullPolicy: IfNotPresent
  sftpConfig:
    # Format of the SFTP user password.
    passwordFormat: "crypt"
    # Password used for authentication against the SFTP server.
    password: "$1$RsBlW1hk$/ISHFEK0yrEX8M7x9.lbB1"
  service:
    # The type of Kubernetes Service used to expose the SFTP container (LoadBalancer, NodePort, or ClusterIP).
    type: LoadBalancer
    # The port exposed by the SFTP Kubernetes Service.
    port: 2287
    # IP address to assign to the LoadBalancer Service.
    loadBalancerIP: ""
    # List of external IP addresses for which the CDR SFTP service will be exposed on.
    externalIPs: []
```

To access an SFTP server, you must first configure credentials for the user. The TPOSS SFTP server provides support only for a single user with the username `sftp`. To specify the password, use the **sftp.sftpConfig.password** configuration option. The format of the password depends on the value of **sftp.sftpConfig.passwordFormat**. The following formats are supported:

- `plain`
- `crypt`

If **sftp.sftpConfig.passwordFormat** is set to `plain`, **sftp.sftpConfig.password** must contain a plaintext password. In this case, the password is hashed by the init container specified in the **sftp.initImage** option.

> [!IMPORTANT]
> You can use any image for the SFTP init container, but it **must** contain the `openssl` CLI.

If **sftp.sftpConfig.passwordFormat** is set to `crypt`, **sftp.sftpConfig.password** must contain a password hashed with a `crypt` algorithm. For example, the value of the key-value pair `sftpConfig.password = "$1$RsBlW1hk$/ISHFEK0yrEX8M7x9.lbB1"` from the example above was obtained by running this command:

```bash
openssl passwd sftp-pass
```

For more information about the SFTP service configuration, see the [Kubernetes service](https://kubernetes.io/docs/concepts/services-networking/service/) documentation.
