> For the complete documentation index, see [llms.txt](https://docs.cennso.com/components/tposs/6.16/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/6.16/configuration/charging.md).

# Charging configuration

This document describes how you can configure charging in TPOSS, which includes tariffs, charging rules, and Charging Data Records (CDRs) configuration.

## Tariffs configuration

TPOSS provisions a set of tariffs during the start-up. For each tariff, 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 subscriber 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 subscriber with this tariff. The user cannot access the Internet. |
| `blocked@tariff.{TENANT_NAME}` | The RADIUS Access-Request request is rejected for a subscriber 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/6.16/troubleshooting/observer.md).

## Charging rules configuration

TPOSS specifies the list of PCC rules and rating groups to allocate them and execute the charging procedures. Each rule has a name and a number with 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:
    # PCC rule name
    online: "RuleName"

  rating_groups:
    # Rating group definition for the Online PCC rule
    online: 1000

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

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

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

In the example above the rating group with ID `1000` is associated with the `Online` PCC rule. You can use any name instead of `online`, however, it must be consistent within the whole configuration file. Each rating group has 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** specifies the list of PCC rules that are excluded if the given rule was allocated by TPOSS. The names listed in the **scg.rating_groups_exclude_rules** must be valid PCC rules defined in the **scg.adc_rules** configuration.

To allocate a PCC rule for a subscriber, TPOSS must know what conditions must be met. For this purpose, the **scg.rating_groups_selectors** configuration option exists. The rule selector is a string in `key = value [and|or key = value]` format. The possible keys are:

- **handler** - a regular expression that will be matched against `Called-Station-Id` within a network session
- **called_station_id** - a handler name that will check if it is possible to allocate a given rating group for the given 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 is in the B2BInternet tariff
- `online` - a rule is allocated if a user has a valid balance
- `unlimited_streaming` - a rule is allocated if the session has the unlimited streaming tariff option
- `whitelist` - a rule is allocated if the session has unknown IMEISV

If the selector is not specified for the given PCC rule, define a quota for such rule:

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

Rules without a selector are always allocated for a subscriber except it was not specified in the **scg.rating_groups_exclude_rules** for already allocated rules.

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

```yaml
scg:
  adc_rules:
    # List of PCC 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
    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 rating group
    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` rating group is allocated if the subscriber has a valid balance
    online: "handler = online"
    # The `FactoryTest` rating group is allocated if the user has unknown IMEISV
    non_whitelisted_imei: "handler = whitelist"
    # The `UnlimitedStreaming` rating group is allocated if the user has the `UnlimitedStreaming`
    # tariff options
    unlimited_streaming: "handler = unlimited_streaming"
    # The `UnlimitedStreamingPD` rating group is allocated if user has `UnlimitedStreaming`
    # tariff options
    unlimited_streaming_pd: "handler = unlimited_streaming"
    # The `B2BInternet` rating group is allocated if the user is in the `b2binternet` tariff
    b2binternet: "handler = b2binternet"

  rating_groups_quotas:
    # List of predefined quotas for some rating groups
    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:
  # Enables UnlimitedStreaming and UnlimitedStreamingPD PCC 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 PCC 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_selector.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 destinations, usually to the file-based backend and the database backend.

### 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: true
      # Initial number of partitions that are created on the fresh CDR table
      initial_partitions_amount: 8
      # Specifies how long a partition is considered as active
      partitions_duration: 1-hour
      # Specifies how many partitions to create when the currently active partition is the last one
      new_partitions_amount: 8
      # Specifies when to trigger an event to drop the outdated CDR partitions. The supported format is "HH:MM".
      # If set to an empty value, the stored procedure is triggered every 7 minutes.
      clean_up_partitions_at: ""
      # Specifies how long to preserve CDR partitions
      cdr_cleanup_period: 4-days
      # 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
      watcher_timeout: 300000
      # CDRs which were closed before this period are removed from a database.
      # A value of this configuration option consists of two parts separated by dash: a number of units and a time unit.
      # The first part can be omitted. The following time units are supported: second(s), minute(s), hour(s), day(s), week(s), month(s), and year(s).
      cdr_cleanup_limit: 10000
      # If partitions are disabled, this configuration option specifies timeout (in milliseconds) for a database query to clean up the outdated CDRs
      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/6.16/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 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 partitions 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 storage 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 deletion of the outdated CDR partitions that should be triggered once per-day in the given time. You should run the partitions deletion in less busy time to not impact other database queries. If this configuration option is set to an empty string (`""`), the event to delete the outdated partitions is triggered every 7 minutes. The time zone of the given time depends on the time zone configured at the database server.

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 first argument specifies the number of units after which a partition is considered as outdated.
- The second argument specifies the time unit.

If partitioning is disabled, the special process watches for a CDR table and deleted 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

### 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.

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

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

>**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 the sftp container to fetch CSV files with closed CDRs
  enabled: false
  image:
    # Image repository for the sftp container
    repository: registry.cennso.com/tposs/tposs-cdr-exporter-sftp
    # Image tag for the sftp container
    tag: v1.1.0
    # Image pull policy for the sftp container
    pullPolicy: IfNotPresent
  service:
    # Type of service for the sftp pod
    type: LoadBalancer
    # Service port number for the sftp pod
    port: 2287
    # IP address for the load balancer
    loadBalancerIP: ""
  sftpConfig:
    # Password to access CDRs through sftp
    password: "$1$RsBlW1hk$/ISHFEK0yrEX8M7x9.lbB1"
```

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

The **sftpConfig** parameter 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:

```console
openssl passwd sftp-pass
```

>**NOTE:** The username of the SFTP user is `sftp` and it can not be changed.
