# Konstrukt documentation
> Technical documentation of the Konstrukt planning platform — its data model, calculation engine, apps, security, integration and APIs — plus a separate best-practice section on the ready-made templates.
Konstrukt is a low-code platform for financial planning, forecasting, reporting and other FP&A and finance-operations processes. You model your business as **plans** containing **dimensions**, **value types** and **calculations**, and build spreadsheet-like **apps** on top of them for the people who plan and report.
This site has these parts:
- **Platform documentation** describes the platform itself: its concepts, how data is stored and versioned, how calculations are written and run, how apps are configured, and how you secure, integrate and administer a tenant. It uses neutral examples and describes no particular model.
- **Best practice** collects working rules and known pitfalls for building models, including a guide for AI agents.
## Platform
Overview What the platform is for and how its parts fit together.
Core concepts Tenant, plan, dimension, property, value type, reference, calculation, app.
Architecture Plans as building blocks, the engine, history and interfaces.
Data model Dimensions, properties, value types, precision, limits and line states.
References and history Snapshots, point-in-time references and the full change history.
Calculations Guided and script calculations, dependency graph, run order.
Kex The query and scripting language: clauses, joins, writes, variables, windowing.
Apps Datasets, workspaces, components, actions and the configuration format.
Security and access Roles, groups, access lists, row-level access and SSO.
Hosting and operations Swedish hosting, tenant isolation, encryption, backup, release tracks.
Data integration Import configurations, file transports, REST and the import wizard.
APIs and SQL access REST API, the Kex endpoint and external SQL views.
AI agents and MCP The built-in MCP server, its tools and resources.
## Best practice
## Auto-generated references
Some reference material is generated from the product and kept up to date automatically. This site links to it instead of duplicating it — see [Reference documentation](reference-docs.html).
| Reference | Covers |
|---|---|
| [REST API](https://acme.konstrukt.app/api/documentation/index.html) | Endpoints, request and response schemas |
| [Kex reference](https://acme.konstrukt.app/api/documentation/kex) | Full Kex language reference and function list |
| [Kex Lite reference](https://acme.konstrukt.app/api/documentation/kex-lite) | The expression language used in app datasets |
## For AI agents
!!! agent "Reading this site as an agent"
- [`llms.txt`](llms.txt) lists every page with a one-line summary. [`llms-full.txt`](llms-full.txt) contains the whole site as one Markdown document.
- Every page has a Markdown source under `md/.md`, linked from the page header.
- Read the [Agent guide: pitfalls and learnings](agent-pitfalls.html) before writing Kex, app configuration or data.
- To work in a live tenant, connect to its MCP server; see [AI agents and MCP](ai-agents.html). The server's own resources (`konstrukt://resources/kex/*`, `konstrukt://TenantInstructions.md`) and the app-config schema from `get_app_config_schema` take precedence over this site for tenant-specific conventions.
Back to [www.konstrukt.se](https://www.konstrukt.se) ↗
---
# Platform overview
> What the Konstrukt platform is intended for, its main building blocks and how data flows from source systems through models and calculations to apps, reports and integrations.
Konstrukt is a multi-tenant, browser-based platform for building planning and finance-operations solutions without writing application code. A solution is built from configuration: a data model, calculation scripts and app definitions. The platform provides storage, versioning, calculation scheduling, access control, the end-user interface and the integration surfaces.
## Intended use
The platform is built for processes where people and systems enter, adjust, calculate and report numbers over several dimensions. Typical examples:
- budgeting, forecasting and scenario planning;
- personnel and payroll-cost planning;
- revenue, agreement and recurring-revenue planning;
- project and investment planning;
- consolidation, eliminations, KPI reporting and month-end close support;
- operational registers that feed financial calculations, such as agreements, projects or units.
The same building blocks serve all of these. What differs between solutions is the model — the dimensions, value types, calculations and apps configured in each tenant. Konstrukt delivers ready-made models as templates.
## Building blocks
| Building block | Role | Documented in |
|---|---|---|
| Tenant | An isolated customer environment with its own host name, users and plans | [Concepts](concepts.html#tenant) |
| Plan | A complete data model: dimensions, value types, calculations, apps | [Concepts](concepts.html#plan) |
| Dimension and property | Categorical axes (account, department, month) and their attributes | [Data model](data-model.html) |
| Value type | A measure stored over a set of dimensions | [Data model](data-model.html#value-types) |
| Reference | A stored or point-in-time version of plan data | [References and history](references-history.html) |
| Calculation | A Kex script that derives and writes data automatically | [Calculations](calculations.html) |
| Kex | The query and scripting language | [Kex](kex.html) |
| App | The end-user interface: datasets, workspaces, components, actions | [Apps](apps.html) |
| Access control | Roles, groups, access lists, row-level access | [Security](security.html) |
| Integration and APIs | Imports, REST API, SQL views, MCP server | [Integration](integration.html), [APIs](apis.html), [AI agents](ai-agents.html) |
## How data flows
```flow
Source systems | ERP, payroll, CRM, files -> Import | configurations, API, MCP -> Plan data | value types over dimensions -> Calculations | Kex, run on change -> Apps | tables, charts, actions
Users | entry, spreading, actions -> Plan data | edits are versioned -> Calculations | dependants recalculated -> References | snapshots for comparison
Plan data -> External access | SQL views, REST, MCP -> BI and downstream systems
```
1. **Data enters** through configured imports (files, REST, storage), from users typing in apps, from actions, or from agents through the MCP server.
2. **Every change is versioned.** The platform keeps the full history of value-type data, so any earlier state can be queried. See [References and history](references-history.html).
3. **Calculations run automatically.** When data a calculation reads changes, the calculation and everything that depends on it is recalculated in dependency order. See [Calculations](calculations.html).
4. **Apps present and collect data.** Apps show datasets through tables, charts and metrics, let users enter and spread values, and run actions that execute Kex scripts. See [Apps](apps.html).
5. **Data leaves** through SQL views, the REST API, exports from apps and the MCP server. See [APIs and SQL access](apis.html).
## Configuration, not code
Everything in a solution is configuration held in the tenant:
- The data model is defined in the admin interface or through the MCP server.
- Calculation logic is written in [Kex](kex.html), either directly or through the guided calculation editor, which generates Kex.
- Apps are defined through the app editor. Underneath, each app is an XML configuration, which can also be read and written as JSON through the MCP server. See [App configuration](app-config.html).
Because the whole solution is data, it can be copied between plans, inspected by agents and changed without deploying software.
## Interfaces at a glance
| Interface | Audience | Purpose |
|---|---|---|
| End-user app interface | Planners, managers, controllers | Enter, review and report data |
| Admin interface | Solution builders | Model, calculations, apps, security, integrations |
| Kex console | Solution builders | Run ad-hoc Kex queries and scripts |
| REST API | Integrations | Import, execute Kex, manage entities |
| External SQL views | BI tools, data warehouses | Read plan and reference data with SQL |
| MCP server | AI agents | Read and change the model and data with tools |
### Interface language
The interface is available in **Swedish and English**, and more languages can be added. Each user chooses a language under **Settings** (the gear icon), see [Using apps](end-user.html#user-settings). All system texts follow the chosen language. Names defined in the model — dimensions, dimension values, value types, apps, workspaces, actions and so on — are stored as entered and are not translated.
This documentation uses the English interface labels and concept names, and gives the Swedish label in parentheses where it helps users of the Swedish interface, for example **Initial values** (*Initialvärden*). The [glossary](glossary.html) lists both.
## Related
- [Core concepts](concepts.html)
- [Architecture](architecture.html)
- [Glossary](glossary.html)
---
# Core concepts
> Definitions of the platform's core objects — tenant, plan, dimension, dimension value, property, value type, reference, history, calculation, Kex, dataset, app, workspace, component, action and access list — and how they relate.
This page defines the objects the rest of the documentation builds on. Each definition links to the page that covers the object in detail.
```flow
Tenant -> Plan | model container -> Dimensions | + properties -> Value types | measures over dimensions
Plan -> Calculations | Kex scripts -> Value types | written data
Plan -> Apps -> Datasets | value types + dimensions -> Workspaces -> Components | tables, charts, metrics, actions
```
## Tenant
A tenant is one customer environment. It has its own host name (`https://{tenant}.konstrukt.app`), users, plans, integrations and settings, and its data is isolated from other tenants. Each tenant serves its own REST API, SQL views and MCP server.
## Plan
A plan is the top-level container for a complete data model: dimensions, value types, calculations and apps. A plan is **active** or **archived**; only archived plans can be deleted. A plan can be created as a copy of another active plan.
One plan in each tenant is the **default plan**. Scripts run outside a plan context — from the console, the REST API or the MCP server — are resolved in the default plan, and this includes the target of `write` statements. A calculation runs in the context of the plan it belongs to. Data from other plans is read with `from plan `; this changes where data is read from, not where it is written. `use plan ` switches the context for the rest of a script, including write targets.
Solutions usually consist of several plans with distinct roles — for example one for shared master data, one for planning and one for reporting — that read from each other. See [Architecture](architecture.html#plans-as-building-blocks).
!!! note "Plan versions"
Plans are either **v2** (current) or **v1** (legacy). v1 plans exist only on some older tenants. This documentation describes v2.
## Dimension
A dimension is a categorical axis, such as `Account`, `Department`, `Employee` or `Month`. Its members are **dimension values**, each with a **code** and a **name**. A dimension belongs to a plan and can be used by any number of value types in that plan. Time is modelled as ordinary dimensions, such as `Month` with codes like `202601`.
## Property
A property (*egenskap*) is an extra column on each value of a dimension: `Department.Region`, `Employee.StartDate`, `Account.Type`. A dimension can have any number of properties. A property can be **bound to another dimension**, so that its values are values of that dimension. This creates hierarchies and mappings, such as `Account → AccountGroup`. Properties can hold several values, separated by `;`. See [Data model](data-model.html#properties).
## Value type
A value type (*värdetyp*) is a measure: one value column — number, date or text — stored over zero or more dimensions. `Amount` over `Account × Department × Month` is a three-dimensional cube; `Price` over `Product` is one-dimensional; a value type with no dimensions holds a single value. Think of it as a fact table with exactly one value column. See [Data model](data-model.html#value-types).
Each stored row records who or what wrote it: a user, an import or a calculation. This is its line state (see [Line states](data-model.html#line-states)).
## Reference
A reference (*referens*) is a named version of plan data kept for comparison, such as "Budget 2026 approved" or "Forecast March". It is either:
- a **data reference**, which stores its own copy of the data; or
- a **point-in-time reference**, which stores only a timestamp and reads the plan's history as of that moment.
See [References and history](references-history.html).
## History
Every change to value-type data is kept. Any earlier state of the data can be queried with `from history `. History underlies point-in-time references, auditing and traceability. See [References and history](references-history.html#history).
## Calculation
A calculation (*beräkning*) is a saved Kex script that reads dimensions and value types and writes to one or more value types. Calculations run automatically when the data they read changes. The platform orders them by a dependency graph derived from what each one reads and writes. Calculations can be authored in a guided editor or as free script. See [Calculations](calculations.html).
## Kex
Kex is Konstrukt's query and scripting language, for reading, filtering, joining, aggregating and writing data. It is used in calculations, actions, the Kex console, the REST API and the MCP server. App datasets use a lighter expression dialect, Kex Lite. See [Kex](kex.html).
## App
An app is an access-controlled end-user interface that belongs to one plan. It consists of:
- **Datasets**: selections of value types and dimensions with expressions, initial values, locked values and row-level access. See [Datasets](datasets.html).
- **Workspaces**: pages with filters, data-type selection and a layout of components. See [Workspaces and components](components.html).
- **Components**: tables (grids), text, metrics, charts and actions placed in a workspace.
- **Actions**: forms that collect input and run a Kex script, for example "add employee" or "close month". See [Actions](actions.html).
## Access control
- Users belong to **groups** and hold **roles**.
- **Access lists** restrict which dimension values a user may see or edit.
- Apps and datasets can be restricted to specific users and groups.
- A value type can be marked sensitive, which hides its values from users who lack access to it.
See [Security and access](security.html).
## How the objects relate
| Object | Belongs to | Identified by |
|---|---|---|
| Plan | Tenant | Integer ID |
| Dimension | Plan | String ID, e.g. `Account` |
| Property | Dimension | Integer ID, plus code and name |
| Value type | Plan | String ID, e.g. `Amount` |
| Reference | Plan | Integer ID and name |
| Calculation | Plan | Integer ID |
| App | Plan | GUID |
| Dataset, workspace, component | App | ID within the app configuration |
## Related
- [Platform overview](overview.html)
- [Data model](data-model.html)
- [Calculations](calculations.html)
- [Glossary](glossary.html)
---
# Architecture
> How a Konstrukt solution is structured — plans as building blocks, the calculation engine, change history, the interfaces and the hosting model — at a technical, implementation-neutral level.
This page describes the platform's architecture at the level needed to design solutions and integrations. It deliberately avoids implementation details that may change between releases.
## Tenant and interfaces
Each tenant is served on its own host, `https://{tenant}.konstrukt.app`. The following interfaces all work against the same model and data, and all enforce the same access control:
```flow
Browser | end-user & admin UI -> Tenant API -> Plans | model + data
Integrations | REST, files, storage -> Tenant API
AI agents | MCP at /api/mcp -> Tenant API
BI tools | SQL views -> Plans
```
- **Web interface.** The end-user app interface and the admin interface.
- **REST API.** Imports, Kex execution and management endpoints, authenticated with OAuth client credentials. See [APIs](apis.html).
- **MCP server.** Embedded in the tenant API at `/api/mcp`. Tools are filtered by the caller's privileges. See [AI agents and MCP](ai-agents.html).
- **External SQL views.** A read-only SQL surface for BI and data-warehouse tools. See [APIs](apis.html#external-sql-views).
- **Integration platform.** Import configurations reachable through files, storage and REST. See [Data integration](integration.html).
## Plans as building blocks
A plan is a complete, self-contained model, but it can read data from other plans with `from plan `. Solutions are therefore usually split into plans with distinct responsibilities:
```flow
Master data plan | shared dimensions, registers, actuals -> Planning plan | input, drivers, calculations -> Reporting plan | consolidation, KPIs, snapshots
```
| Role | Typical content |
|---|---|
| Master data | Shared dimensions (accounts, organisation, calendar), registers, imported actuals |
| Planning | Input apps, driver value types, planning calculations |
| Reporting | Aggregation, consolidation, KPIs, comparisons against references |
| Process plans | Separate processes such as close checklists or invoicing, each isolated from the others |
This hub-and-spoke structure keeps each plan small and focused. Master data is maintained once. Access and life cycle (copy, archive) can be managed per plan. Calculations in a reading plan re-run when the data they read in another plan changes.
!!! note "Cross-plan reads"
`from plan ` reads another plan's data using that plan's dimensions. The reading plan must have the dimensions the data uses. See the [agent guide](agent-pitfalls.html#kex) for related pitfalls.
## The calculation engine
Kex scripts are compiled to set-based database queries. They are not evaluated cell by cell:
- Each value type is stored as its own table, keyed by its dimensions.
- A Kex query is translated into SQL over those tables. Joins are resolved from shared dimensions and bound properties.
- Results are streamed to their destination: a value type, an API response or an app.
- Writes are applied as set operations — insert, update, upsert or replace — scoped to the rows the writing calculation owns.
The binding constraint on performance is usually **recalculation propagation**, not the size of a single query. A change to one input value type triggers every calculation that reads it, then every calculation that reads their output, and so on down the dependency graph. The depth and fan-out of that graph, and the grain of the value types it passes through, determine how long a change takes to settle. Solution design should therefore:
- aggregate to the grain needed as early as possible;
- avoid calculations that read broadly but change little;
- keep high-frequency input value types from feeding large parts of the graph unnecessarily.
The [dependency graph](calculations.html#dependency-graph) and [run order](calculations.html#run-order-and-status) are visible in the admin interface and through the MCP server.
!!! tip "Rule of thumb"
Size is best measured in rows per value type and in the number of rows touched per change. Large value types are fine; what matters is how many rows a typical change forces the engine to recalculate.
## History and versioning
Value-type data is stored with system-versioned history: every change keeps the previous version with its validity period. This gives:
- `from history ` in Kex — the data as it was at any moment;
- **point-in-time references**, which are simply named timestamps;
- the audit columns on every row: last edited, edited by, and writing calculation;
- temporal queries (`for system_time as of`) in the external SQL views.
History is **change-based**. Writing a value identical to the stored value creates no new history row. Deleting data removes it from the current state but not from history. See [References and history](references-history.html#history).
## Calculation scheduling
Calculations run asynchronously after the change that triggered them. The platform queues affected calculations in dependency order. The admin interface and the MCP tools `get_running_calculations` and `get_all_running_calculations` show calculations that are running or waiting in the queue. Cycles are detected when a calculation is activated. See [Calculations](calculations.html#dependency-graph).
## App runtime
An app's configuration is stored as XML. Name and description are held outside the configuration. At runtime the interface does the following:
1. It evaluates a dataset's value types, expressions, initial values and access filters on the server.
2. It sends the resulting rows to the browser.
3. Component-level filters, grouping and pivoting are applied in the browser.
Edits are written back to value types through dataset writeback rules and then trigger calculations like any other change. See [Apps](apps.html).
## Hosting and operations
The service is hosted in Sweden, and all platform processing takes place there. Each tenant has its own database. Backend services are shared and stateless apart from caching. Data is encrypted in transit and at rest. New versions are rolled out in release tracks (alpha, beta, feature, stable).
See [Hosting and operations](operations.html) for sub-processors, backup, availability and releases.
## Related
- [Core concepts](concepts.html)
- [Calculations](calculations.html)
- [References and history](references-history.html)
- [APIs and SQL access](apis.html)
---
# Data model
> Dimensions, dimension values, properties and bindings, value types with format, precision, limits and sensitivity, internal columns, line states, and how data is loaded and traced across the model.
A plan's data model consists of **dimensions**, their **properties**, and the **value types** that store measures over dimensions. All three are defined in the admin interface under *Datamodell* (Data model) or through the MCP server, and are visible in the external SQL views.
## Dimensions
A dimension (*dimension*) is a list of members — **dimension values** — each with a **code** and a **name**. Codes are the stable identifiers used in data, imports and Kex; names are for display.
| Example dimension | Example codes |
|---|---|
| `Account` | `3010`, `5010`, `7210` |
| `Department` | `D100`, `D200` |
| `Month` | `202601`, `202602` |
| `Scenario` | `Base`, `Upside` |
### Time as dimensions
The platform has no special time axis. Periods are ordinary dimensions such as `Month`, `Quarter` or `Year`, whose properties link them together (`Month.Quarter`, `Month.Year`) and carry calendar attributes. Properties such as a start or end month on a register entry are typically **bound to the period dimension** rather than stored as free dates. Period logic — "months from start to end", "open for planning" — is then expressed as joins and filters on dimension values.
### Dimension editor
The dimension editor has these side panels:
| Panel | Swedish label | Content |
|---|---|---|
| Properties | *Egenskaper* | The dimension's properties with IDs; bound properties are badged *Bunden till dimension* |
| Connections | *Kopplingar* | Which value types use selected dimension values, with clean-up operations — see [Tracing dimension values](#tracing-dimension-values) |
| Integration | *Integration* | Import configurations feeding the dimension; SQL export toggle and query |
| Details | *Detaljer* | ID, size (rows), display format (*Visa som*), value types using the dimension, history, description |
### Display formats
How a dimension value is shown — code, name or both — is set by a display format. The standard formats are:
| ID | Pattern | Example |
|---|---|---|
| 1 | `{Code} - {Name}` | `3010 - Sales` |
| 2 | `{Name} - {Code}` | `Sales - 3010` |
| 3 | `{Code}` | `3010` |
| 4 | `{Name}` | `Sales` |
The display format can be set on the dimension, overridden per dataset in an app (*Visa som*), and chosen per variable in actions. In Kex, `$formatted` returns the formatted text.
## Properties
A property (*egenskap*) adds a column to every value of a dimension. Properties are referenced in Kex as `Dimension.Property`, for example `Department.Region`.
- **Unbound properties** hold free values: text, numbers or dates.
- **Bound properties** hold values of another dimension. `Account.AccountGroup` bound to the dimension `AccountGroup` makes every account point to a member of that dimension. Bindings are how hierarchies, mappings and reporting structures are built. They are also how Kex joins value types that do not share a dimension directly (`include … on Account.AccountGroup`).
- **Multi-valued properties** hold several values separated by `;`. In Kex they are aggregated as a string by default and expanded to one row per value with `expand Dim.Prop`.
!!! warning "Bindings must not be circular"
A property cannot be bound in a way that forms a cycle between dimensions. The same rule applies to calculations: the platform allows no cycles, either in model structure or in logic.
## Value types
A value type (*värdetyp*) stores one value column over a fixed set of dimensions. Each combination of dimension values holds at most one value.
| Setting | Meaning |
|---|---|
| ID and name | String ID used in Kex, e.g. `Amount`; display name |
| Dimensions | The value type's grain, e.g. `Account × Department × Month` |
| Format (*Format*) | Number, percentage, date, date-time or text |
| Display precision (*Decimalpresentation*) | Decimals shown, optionally hiding decimals when the value is zero |
| Entry precision (*Decimalinmatning*) | Decimals accepted and stored on entry |
| Value limits (*Värdegränser*) | Hard minimum and maximum: entries outside are rejected |
| Value warnings (*Värdevarningar*) | Soft lower and upper bounds: entries outside are warned about but accepted |
| Sensitive (`isSensitive`) | Hides the value, but not the row, from users without access to sensitive data |
| Description | Free text, also exposed to agents |
!!! note "What is shown is not what is stored"
Display precision and entry precision are separate. A value type can accept five decimals and display none. Tables, exports and Kex always work with the stored value.
### Sensitive value types
A sensitive value type hides the **measure**, not the **row**. A user without access to sensitive data still sees which dimension combinations exist — for example, which employees have a salary row — but not the values. This allows roles such as a data administrator who maintains dimensions and runs imports without seeing salaries. See [Security](security.html).
### Changing a value type's dimensions
Dimensions can be added to or removed from a value type only when it is **empty of both plan data and reference data**. Emptying a value type also removes its **history**, and with it the basis for every point-in-time reference that reads that value type.
!!! warning "Irreversible"
Emptying a value type to change its dimensions permanently removes its history. Point-in-time references to the value type will no longer return data for the period before the change. If the history matters, create a data reference first, or model the new grain as a new value type.
The order of a value type's dimensions can be changed at any time (*Ändra dimensions-sortering*). The order affects default presentation only.
### Value type panels
| Panel | Swedish label | Content |
|---|---|---|
| Dimensions | *Dimensioner* | The value type's grain and the change operation |
| Value columns | *Värdekolumner* | Format, precision, limits, warnings, sensitivity |
| Integration | *Integration* | Import configurations, SQL export toggle and query |
| Details | *Detaljer* | Lineage upstream (calculations writing the value type) and downstream (calculations and apps reading it) — see [Traceability](traceability.html) |
A view selector at the top of the value type switches between **plan data** and each **reference** of the plan. In reference view the data is read-only and the summary statistics are recalculated for the reference.
## Internal columns
Every row carries system columns, readable in Kex with `X.**` and in the SQL views.
| Column | On | Meaning |
|---|---|---|
| `$name`, `$formatted` | Dimension values | Name, and text formatted by the display format |
| `$edittime`, `$editby` | Both | Time of last change and who made it |
| `$edittype`, `$editid`, `$rowid` | Both | Change type, change ID and internal row ID |
| `$calcid` | Value types | ID of the calculation that wrote the row; empty for user-entered or imported rows. See [Parallel values](#parallel-values) |
| `$editstate` | Value types | Line state, see below |
### Parallel values
`$calcid` is a hidden system dimension on every value type. For one combination of dimension values, a value type can therefore hold several values side by side: one entered or imported value without a calculation ID, and one value per calculation that writes to it.
Every read sums them away: in apps, in exports, in Kex queries and when a calculation reads its sources. Use `expand X.$calcid` to see the parts, or `exclude calculated` to read only the non-calculated part.
## Line states
Each value-type row records how it came to exist. The app interface uses this to decide styling and editability.
| Code | State | Meaning |
|---|---|---|
| 0 | Suggested | Imported, or written by a suggestion calculation; a user may overwrite it |
| 5 | Zero placeholder | Created when a user edits a cell generated from initial values but the value remains empty or zero |
| 10 | Edited | Entered or changed by a user |
| 30 | Calculated | Written by a calculation |
| 40 | Initial value | Generated placeholder from a dataset's [initial values](datasets.html#initial-values) |
Rows written through import tools, the REST API or MCP get line state 0. Line state 10 is set by edits in the app interface.
Default [presentation rules](components.html) style suggested, read-only and calculated cells differently, so users can see where each number comes from.
## Loading data
Data reaches value types and dimensions through several routes. All of them follow the same import semantics.
| Route | Use | See |
|---|---|---|
| Import wizard on a value type or dimension | Ad-hoc file loads (CSV, TXT, xlsx) | below |
| Import configurations | Repeatable loads over files, storage or REST | [Data integration](integration.html) |
| App entry and actions | User input | [Apps](apps.html) |
| Calculations | Derived data | [Calculations](calculations.html) |
| MCP tools | Agent-driven loads and changes | [AI agents](ai-agents.html) |
### Import wizard
The wizard on a value type (*Importera*) has three steps:
1. **Import type.** *Full import* adds new rows and updates existing ones. *Endast ny data* (only new) adds rows but updates none. *Endast uppdatering* (only update) updates existing rows but adds none.
2. **Column mapping.** Map file columns to dimensions and the value column, with a preview. The writing calculation (`$calcid`) cannot be mapped: lineage can be read but not imported.
3. **Settings.**
- Choose how duplicate rows with the same dimension values are handled: sum, average, min, max, or fail.
- Choose whether unknown codes create new dimension values (*Skapa nya dimensionsvärden*).
An export from a value type can be imported again as-is.
## Tracing dimension values
The **Connections** panel (*Kopplingar*) on a dimension shows, for selected dimension values, every value type in which they occur. From there you can remove the selected values' data from one value type, from a chosen subset in the advanced view, or from all value types.
!!! warning "History is retained"
Removing data through *Kopplingar* removes it from the current state of the value types. Earlier versions remain in [history](references-history.html#history) and can still be read through point-in-time references and `from history`.
!!! agent "Pitfalls for agents"
Pitfalls around identifiers, changing dimensions, creating dimension values on import and sensitive value types are in the [Agent guide](agent-pitfalls.html#data-model).
## Related
- [Core concepts](concepts.html)
- [References and history](references-history.html)
- [Traceability](traceability.html)
- [Data integration](integration.html)
- [Datasets](datasets.html)
---
# References and history
> How Konstrukt keeps a full change history of value-type data, the two kinds of reference (stored data and point-in-time), how they are queried in Kex and used in apps, and what deleting data does and does not remove.
Konstrukt keeps every earlier version of value-type data. **References** give names to versions you want to compare against, such as an approved budget, last month's forecast or the state before a reorganisation. There are two kinds of reference, and the difference between them follows from how history works.
## History
All changes to value-type data are kept in system-versioned history. Each version of a row keeps its value and the period during which it was current.
- **History is change-based, not write-based.** If a calculation or import writes the same value that is already stored, the row counts as unchanged and no history row is created. A recalculation that produces the same result leaves history untouched. This keeps point-in-time views stable across repeated recalculations, and makes history record *what changed* rather than *what was recomputed*.
- History covers user entries, imports, actions and calculations alike. Each version carries its edit time, who made the edit and the writing calculation.
### Querying history
In Kex, `from history` reads data as it was at a given moment:
```kex
Amount from history '2026-03-31 23:59'
Amount from history now() - days(7)
Amount from history startofmonth() - milliseconds(1) values only
```
| Form | Behaviour |
|---|---|
| `from history ` | Value-type data and dimensions as they were at that moment |
| `from history values only` | Historical value-type data, but **current** dimensions; historical rows that refer to dimension values since removed are filtered out |
`from history` can be combined with `from plan` and `from reference`.
The external SQL views support the same idea with `for system_time as of`. See [APIs and SQL access](apis.html#external-sql-views).
## Two kinds of reference
| | Data reference | Point-in-time reference |
|---|---|---|
| Swedish GUI | *Referens* | *Tidpunkts-referens* (clock icon) |
| Stores | Its own copy of data | Only a timestamp |
| Content | Whatever is written to it: imported, copied or calculated | The plan's data as it was at the timestamp, read from history |
| Creation cost | Proportional to the data written | Instant, whatever the data volume |
| Can be changed after creation | Its data can be rewritten | The timestamp can be edited, which changes the whole content |
| Typical use | Actuals from another system, approved budgets, external benchmarks | "As of month-end close", "last week", "before the reorganisation" |
The type is fixed when the reference is created. A data reference cannot be converted into a point-in-time reference, or the other way round.
### Point-in-time references
A point-in-time reference is a named query against history. Because it stores only the timestamp:
- it is **retroactive**: you can create a reference for a moment that has already passed, with no preparation done at that moment;
- editing its timestamp immediately changes its entire content, and nothing needs to be rebuilt;
- it costs no storage.
The timestamp is entered in local time. The interface shows the time zone explicitly, for example *(lokal tid GMT+02:00)*.
In Kex, reading a point-in-time reference with `from reference` is rewritten automatically to `from history values only`. The query diagnostics show this step as *Rewrite point-in-time references*.
### Data references
A data reference holds its own rows for any value type in the plan. You can write to it in the following ways:
- with Kex: `write to Amount reference "Budget approved" <- …`;
- with an import configuration or MCP import tool that targets the reference;
- with a calculation that writes reference data.
Deleting a data reference deletes its data.
## Creating and managing references
References belong to a plan. You create them from the view selector on a value type (*Ny referens*) or from the reference panel on the value-type list:
1. Give the reference a name.
2. Optionally tick *Skapa tidpunkts-referens* (create point-in-time reference) and choose a date and time.
The reference is available immediately. The reference panel shows each reference's ID, its timestamp (for point-in-time references), and the value types and apps that use it. Deleting a reference cannot be undone.
## References in Kex
Compare plan data with a named reference:
```kex
var Budget = Amount from reference "Budget approved"
Diff = sum(Amount) - sum(Budget)
```
Write reference data:
```kex
write to Amount reference "Budget approved" <- Amount
```
A reference can be addressed by ID or by name. See [Kex](kex.html).
## References in apps
In apps, plan data and references are combined in a virtual **data type** dimension. For each workspace you choose which data types are shown:
- **Plan data** can be selected, hidden, required or allowed.
- **Each reference** can be the default, available or unavailable.
This lets a user switch a table between plan data and, for example, last month's forecast, or show them side by side. Initial values can also be generated from reference data. See [Workspaces and components](components.html) and [Datasets](datasets.html#initial-values).
Data type codes in the app configuration are `Plan`, `Reference_`, or a custom code.
## What deleting data does to history
| Operation | Current data | History |
|---|---|---|
| Change a value | Updated | Previous version kept |
| Delete value-type rows (user, import, Kex, MCP) | Removed | Previous versions kept |
| Remove a dimension value's data via *Kopplingar* | Removed from the chosen value types | Previous versions kept |
| Delete a dimension value | Removed from the dimension | Previous versions kept; historical rows referring to it are filtered out of `values only` reads |
| Empty a value type to change its dimensions | Removed | **Removed** |
| Delete a data reference | Its data removed | — |
!!! note "Data removal and history"
Deleting data does not remove it from history. Earlier versions stay readable through `from history` and point-in-time references for as long as the value type keeps its history.
### Retention
History is currently kept until further notice. No specific retention period is guaranteed. Limits may be introduced for storage reasons, and may in future depend on the licence. History can be removed:
- for one value type, by emptying it and changing its dimensions, which rebuilds its table; or
- for a whole plan, by copying the plan (history tables are not copied), then archiving and deleting the original. Point-in-time references in the copy are then empty.
See [Hosting and operations](operations.html#data-retention-in-the-platform).
!!! agent "Pitfalls for agents"
See the [Agent guide](agent-pitfalls.html#history) for what deletion does and does not remove, and how point-in-time references are rewritten.
## Related
- [Data model](data-model.html)
- [Kex](kex.html)
- [Traceability](traceability.html)
- [Workspaces and components](components.html)
---
# Calculations
> How calculations derive data in Konstrukt — guided and script calculations, sources and joins, destination mapping, the working-set and output previews, diagnostics, write modes including suggestions, the dependency graph, run order, status and cycle detection.
A calculation (*beräkning*) is a saved [Kex](kex.html) script that reads value types and dimensions and writes to one or more value types. Calculations are **triggered by data changes**: when any source a calculation reads changes, the calculation runs again, and so does everything downstream of it. You do not schedule calculations or wire triggers; the platform works out the order from what each calculation reads and writes.
```flow
Source data | value types, dimensions -> Working set | joined rows -> Formula | per row -> Output | destination grain -> Destination value type
```
## Two editing modes, one execution model
A calculation is always a Kex script. The admin interface offers two ways to edit one:
| Mode | Calculation type label | Editing |
|---|---|---|
| Guided | *Beräkning* | A form: sources, joins, property defaults, formula, destination |
| Script | *Skript* | Free Kex in a syntax-highlighted editor |
A guided calculation is a Kex script with a model annotation that tells the editor to render it as a form:
```kex
@@model: "Formula", version: "1.0"
@("Planned salaries")
var PlannedSalaries =
Salary
main Salary
check includes
…
write to SalaryCost <- $result = …
```
`@@model` marks the script as a guided calculation, and `@("Alias")` gives a variable its display name in the form. **Edit in script mode** (*Redigera i skriptläge*) shows the underlying script.
!!! warning "Converting to script mode is one-way"
If you remove the `@@model` annotation and save, the calculation is permanently a script calculation. It can no longer be opened in the guided editor.
Edits in either mode are held locally until you save. While there are unsaved changes, a bar offers **Reset** (*Återställ*) and **Save** (*Spara*).
## The guided editor
The guided editor is laid out from top to bottom in this order:
1. **Source data** (*Källdata*). Choose the value types to read. Each source has an alias and a list of included dimensions. For each source you also choose whether it *requires all values in the working set* or *allows missing values*.
2. **Derived join**, stated in plain text, for example *"The system will assume 'Planned salaries' as the main source — a full outer join on 'Month'"*. **Configure** opens the join settings.
3. **Formula** (*Formel*). An expression editor with live validation.
4. **Working-set table** (*Arbetssettabell*). A preview of the rows the formula iterates over.
5. **Destination value type** (*Destinationsvärdetyp*), with dimension mapping, aggregation and write mode.
6. **Output** (*Utdata*). A preview of the result at the destination's grain.
Side panels: **Sources** (*Källor*), **Advanced** (*Avancerat*, the join configuration), **Property defaults** (*Standardvärden för egenskaper*) and **Details** (*Detaljer*).
### Joins
The Advanced panel sets how each source joins the main source. The GUI terms map to Kex include options:
| GUI | Swedish | Kex |
|---|---|---|
| Main | *Main* | `main` |
| Inner | *Inre* | `include` |
| Full outer | *Fullständig yttre* | `include all` |
| Left | *Vänster* | `include optional` |
| Join on bound property | *Lägg till bunden egenskap* | `on Dimension.Property` |
The main source contributes all its dimensions automatically. For other sources, you tick dimensions per source. A dimension that does not exist on the main source is flagged *(Dimension finns ej i Main)*.
### Aggregation of sources
This is a two-stage process that is easy to confuse:
- **Implicit aggregation, always applied.** Each source is summed (`sum()`) to its own dimensions before the join. A source may hold both user-entered and calculated rows for the same combination, and these are added together first.
- **Pre-aggregation, optional.** In the Advanced panel you can explicitly remove dimensions from a source before the join. The source is then aggregated with a chosen function: sum, min, max, average or count. This lowers the source's grain.
### Property defaults
A property default (*Standardvärden för egenskaper*) sets a value to use when a property used in the formula is missing, so that the expression does not fail. It corresponds to Kex `default Dimension.Property to `.
### Destination
For each dimension of the destination value type you choose where its value comes from (*Från*, "From"):
| From | Meaning |
|---|---|
| *Källa* (Source) | Taken from a source dimension, e.g. `Planned salaries.Month` |
| *Kex* | A dynamic Kex expression |
| *Fixed* | A constant dimension value |
Every dimension of the destination must receive a value. You also set:
- **Aggregation** (*Aggregering*): how rows are combined to the destination grain.
- **Write mode**: write all values (*Skriv alla värden*) or only non-zero values (*Skriv endast icke-nollvärden*). Writing only non-zero values keeps the destination sparse, which reduces storage and downstream recalculation.
### Working set and output
The working-set table and the output are a pair. Together they show how a formula turns input into results:
| Table | Grain | Columns |
|---|---|---|
| Working set | The join grain, before the formula | Dimensions annotated with their source, one value column per source, and the formula result per row |
| Output | The destination grain, after formula and aggregation | Destination dimensions and the value, with summary statistics (rows, sum, mean, max, min) |
The previews show the first 1,000 rows and report the total count. Both tables support search, per-column filters, sorting, export and full screen. The difference in row count between the two — for example 6,396 working-set rows aggregating to 647 output rows — makes the calculation's grain visible.
### Diagnostics
The info icon in the working-set table opens **Diagnostics**. It has two tabs:
- **Transformation line**: every step the Kex compiler applies, with the query text before and after each step.
- **Script**: the final script.
Steps include:
- *Initial global query*
- *Create semantic query*
- *Correct identifier names*
- *Check includes*
- *Determine product dimensions*
- *Rewrite point-in-time references*
- *Expand wildcards*
- *Exclude calculated data*
- *Resolve spreads*
- *Resolve includes*
- *Rewrite special functions*
- *Aggregate scalars*
- *Suggest select dimensions*
Steps that change nothing are shown as *(No change)*.
Diagnostics make Kex's implicit resolution inspectable. They are the main tool for answering "why did this join or aggregation happen?".
## Script calculations
A script calculation is a Kex script with at least one `write` statement. The script panel is a line-numbered editor that can be opened in a modal. The output panel shows the last run, or the validation error with the identifier at fault, together with **Diagnostics** and **Retry** (*Försök igen*).
Rules for calculation scripts:
- A saved calculation must contain a valid `write`.
- A calculation can write to several value types. Each `write` is a separate output in the dependency graph.
- Inside a calculation, writes affect only the rows that calculation owns: rows whose `$calcid` is the calculation's ID. The first write to a target replaces the calculation's previous rows there, and later writes to the same target in the same run upsert. See [Kex write variants](kex.html#write-variants).
- A calculation's own rows are separate from user-entered, imported and other calculations' rows for the same combination. Readers sum them together.
### Suggestions
`write suggestion to` writes **suggested values** (line state 0). The user can overwrite a suggestion, and once edited the value belongs to the user: the calculation does not overwrite it again. Suggestions are styled separately in apps (presentation rule key `Suggested`, **Suggested value**, *Föreslaget värde*). Use them for defaults that users are expected to confirm or adjust, such as a start date derived from other data or a proposed budget line.
| Variant | Effect |
|---|---|
| `write suggestion to` | Replace earlier suggestions in the target with the result |
| `write insert suggestion to` | Suggest only where no data exists |
| `write upsert suggestion to` | Update existing suggestions and add new ones |
`suggestion` is valid only in calculations.
## Dependency graph
The platform derives a directed graph from what each calculation **reads** (value types and dimensions) and **writes** (value types). A calculation depends on every calculation that writes something it reads. Cross-plan reads are part of the graph.
**Show diagram** (*Visa diagram*) draws the graph for the whole plan or for selected calculations. Select rows in the calculation list, or use the row menu on a single calculation.
| Element | Meaning |
|---|---|
| Coloured circles | Calculations, shaded by depth (level) |
| Small grey nodes | Value types |
| Layout *None* | Force-directed: shows clusters and isolated islands |
| Layout *Radial* | Radial arrangement |
| Layout *Top-down* | Dependency layers, i.e. the order in which calculations actually run |
Hovering over a calculation shows its full contract without opening it: ID and level, name, every source with its condition, and the write target with its dimension mapping.
!!! agent "Dependency graph via MCP"
`get_calculation_graph` returns per calculation `planId`, `id`, `name`, `isEnabled`, `level`, `references[]` (value types and dimensions read, with plan IDs), `outputs[]` and `dependsOn[]`. Filter with `planIds`, `referencedEntityIds` or `outputEntityIds`. Use it to find everything affected by a change before editing a calculation.
## Run order and status
| Status | Swedish | Meaning |
|---|---|---|
| Ok | *Ok* | Valid and enabled; runs on change and can be run manually |
| Invalid | *Ogiltig* | Script validation fails; the calculation cannot run and has no place in the run order |
| Inactive | *Inaktiv* | Disabled without being deleted |
Validation errors are shown at two levels: a structured list, for example *"The formula expression is not valid"*, and the raw engine message naming the identifier at fault.
Graph validation is separate from script validation. A calculation can be valid on its own but, when activated, form a **cycle** with other calculations. The list then shows a cycle marker with a tooltip naming both edges, for example *"Creates a cycle with other calculations: reads from 32 / writes to 82"*. Cycles are not allowed.
The Details panel shows:
- name, ID and type;
- **run time** (*Körtid*) and **run order** (*Körordning*), meaning the level in the graph;
- status, last run, last changed by;
- tags and description.
The row menu offers: go to calculation, activate or deactivate, copy, export, delete.
## Precalculations
A precalculation (*förberäkning*) is an intermediate calculation that writes to no value type and is used only as a source in another calculation. It is referenced in scripts as `Calc`. Precalculations remain supported. For new work, prefer Kex variables inside the calculation, or an explicit value type where the intermediate result is useful in its own right.
## Flows
Flows (*Flöden*) are saved, parameterised Kex scripts run **on demand**, not on data change — for example "start a new forecast round" with parameters for the previous forecast and the start period.
- **Running a flow.** The *Flows* side tab on a plan lists the plan's flows. Choosing one opens a run form with its parameters, **Run** (*Kör*) and the flow's status.
- **Editing flows.** **Flow editor** opens the plan's flow list (name, status, last run) with **New flow** (*Nytt Flow*). A flow has a name, ID, description, parameters and a script, plus panels for parameters and details.
- **Parameters.** Each parameter has a name, an ID used in the script (for example `@startperiod`), a type and a description.
| Parameter type | Swedish label |
|---|---|
| Decimal | *Decimal* |
| Integer | *Heltal* |
| Text | *Text* |
| Date | *Datum* |
| Date and time | *Datum och tid* |
| Boolean | *Booleansk* |
| Dimension value (of a chosen dimension) | *Dimensionsvärde* |
| Plan | *Plan* |
| Reference | *Referens* |
**Who uses flows.** Flows are for planners and other administrators, to automate larger operations that should run at a chosen moment rather than on every change. Examples:
- re-flagging many properties at once;
- moving or copying data between references and value types;
- starting a forecast round: data is fetched from the master data plan once, when the round starts, and then stays locked, instead of following master data continuously.
## Designing calculations
- **Aggregate early.** Read sources at the grain you need, and use pre-aggregation or a `var` to drop unneeded dimensions before windowing or joining.
- **Write sparsely.** Use *write only non-zero values*, or `having $result != 0`, where zeros carry no meaning.
- **Keep the graph shallow and narrow.** Every level adds recalculation latency to changes that pass through it. See [Architecture](architecture.html#the-calculation-engine).
- **Name for the graph.** Names that state the source and target make the graph and lineage panels readable.
- **Validate before saving.** Use the output preview, the working-set table and Diagnostics. Agents should call `validate_script` first.
!!! agent "Pitfalls for agents"
Known pitfalls when changing calculations — the one-way script conversion, cycles detected on activation, invalid calculations and recalculation load — are in the [Agent guide](agent-pitfalls.html#calculations).
## Related
- [Kex](kex.html)
- [Traceability](traceability.html)
- [Architecture](architecture.html)
- [Data model](data-model.html#line-states)
---
# Kex language
> A structured introduction to Kex, Konstrukt's query and scripting language — statements and variables, clause order, implicit resolution, joins, write variants, dimension operators, windowing, Kex Lite — with links to the auto-generated full reference.
Kex is Konstrukt's language for reading, filtering, joining, aggregating and writing data. The same language is used in calculations, actions, flows, the Kex console, the REST endpoint `/api/v1/kex` and the MCP tools. You state *what* you want in terms of value types, dimensions and properties, and the engine works out the joins and grouping. Kex compiles to set-based SQL, one table per value type (see [Architecture](architecture.html#the-calculation-engine)).
This page is an orientation. The complete language reference, with every function and option, is generated from the product: **[Kex reference ↗](https://acme.konstrukt.app/api/documentation/kex)**.
!!! agent "Authoritative sources for agents"
The MCP server exposes the reference as resources: `KexOverview`, `KexDocumentation` (full reference), `KexGuidelines` (rules for generated scripts), `KexKnowledge` (pitfalls) and `KexScriptExamples`, under `konstrukt://resources/kex/`. Load the overview first and the full reference when needed. Always run `validate_script` before `execute_write_script`, and never retry a failed write script automatically.
## A first query
```kex
Amount where Month.Year == "2026"
```
This returns `Amount` for 2026 with all of its dimensions projected automatically. Aggregation to fewer dimensions is expressed by naming the dimensions you want:
```kex
Total = sum(Amount), Department where Month.Year == "2026"
```
Keywords are lowercase and case-sensitive. Whitespace is not significant.
## Statements and variables
A script is one or more statements.
| Statement | Purpose |
|---|---|
| `var X = ` | A table variable: dimensions plus one or more value columns. Later columns are addressed by alias. |
| `scalar X = ` | A single value (the first row); extra columns as `X.Alias` |
| `dim X = ` | A custom dimension from unique first-column values, or `dim X = X from plan 10` to import one |
| `evaluate [Name] = ` | A named result set; bare expressions are also evaluated |
| `write … <- ` | Write to a value type, see [Write variants](#write-variants) |
Static data can be written inline:
```kex
var Rates = (Currency, Rate) { ("EUR", 11.2), ("USD", 10.4) }
dim Months = {202601, 202602, 202603}
dim Weeks = range('2026-01-05', '2026-03-30', days(7))
```
`range(start, stop, step?)` generates numeric, date and time, or single-character sequences. The start and stop values are inclusive.
A variable can shadow a value type of the same name. Dimensions cannot be shadowed. Start variable names with a capital letter to avoid clashing with future keywords.
## Clause order
Clauses must appear in this order:
| # | Clause | Examples |
|---|---|---|
| 1 | Select expressions | `Total = sum(Amount), Department` · `only` suppresses automatic dimension projection |
| 2 | Include options | `main X`, `include X`, `include optional X`, `include all X`, `include cross X`, `on D.Prop`, `default D.Prop to C`, `expand D.Prop`, `exclude calculated` |
| 3 | Filter | `where …` |
| 4 | Grouping and order | `group by`, `having`, `order by` |
| 5 | Data source | `from plan `, `from reference `, `from history [values only]` |
| 6 | Output options | `limit n`, `check duplication`, `check includes`, `check dim values`, `apply dim formatting`, `apply dim filtering` |
## Implicit resolution
Most scripts need few include options, because Kex infers them:
- **Dimensions** of the main table are projected automatically.
- **The main table** is chosen heuristically: value tables first, then dimensions, then the table sharing the most dimensions, then the first one named.
- **Joins** are resolved from shared dimensions and bound properties.
- **Grouping and ordering** follow from the selected dimensions.
`check includes` turns off much of this inference and requires explicit includes. Guided calculations use it.
The calculation editor's [Diagnostics](calculations.html#diagnostics) shows every resolution step applied to a query.
### Identifier expansion
| Form | Meaning |
|---|---|
| `X.*` | All columns of `X` |
| `X.**` | Including internal columns (`$calcid`, `$edittime`, …), useful for troubleshooting |
| `Amount.*.*` | Multi-step expansion through properties |
| `Region.*.**$name*` | Expansion filtered by name pattern |
## Joins
| Include option | Join | Guided editor term |
|---|---|---|
| `main X` | Driving table | Main |
| `include X` | Inner | *Inre* |
| `include optional X` | Left outer | *Vänster* |
| `include all X` | Full outer | *Fullständig yttre* |
| `include cross X` | Cross product (applied before `all`) | — |
| `… on Dim.Prop` | Join on a bound property | *Bunden egenskap* |
`default Dim.Prop to ` supplies a value where a property is missing.
## Write variants
```kex
write [[insert|upsert] suggestion | insert | update | replacement] [to] Target [reference ] <-
```
| Variant | Outside a calculation | Inside a calculation |
|---|---|---|
| *(no keyword)* | Upsert: update matching rows, insert new ones | Replace the calculation's own rows in the target |
| `insert` | Only rows without data | Same, within the calculation's rows |
| `update` | Only existing rows; no inserts or deletes | Same |
| `replacement` | Replace target contents with the result, deleting non-matching rows. **Calculated rows are not deleted.** | Same as no keyword |
| `suggestion` | Not allowed | Write suggested values the user may overwrite, see [Suggestions](calculations.html#suggestions) |
| `insert suggestion` | Not allowed | Suggest only where no data exists |
| `upsert suggestion` | Not allowed | Update and add suggestions |
| `… reference ` | Write reference data instead of plan data | Same |
Rules that follow from this:
- **Row ownership.** Inside a calculation, writes touch only rows carrying that calculation's `$calcid`. The first write to a target clears the calculation's earlier rows; later writes to the same target in the same run upsert.
- **Write target.** The target is resolved in the plan the script runs in: the calculation's plan, or the [default plan](concepts.html#plan) for console, API and MCP scripts. `from plan` in the query does not move the target; [`use plan`](#use-plan) does.
- **Selected columns.** In a write, the value column is named `$result`, and each dimension of the target must be assigned, either implicitly or with `Dim = …`.
```kex
write to SalaryCost <-
$result = sum(Salary) * (1 + EmployerRate),
Employee, Month
having $result != 0
```
### Excluding calculated rows
`exclude calculated`, in the include-option position, leaves calculated rows out of the query, so that only user-entered and imported rows are read. It is often used together with `write replacement` in actions, which rewrite user data without touching calculated data:
```kex
write replacement to Amount <- Amount.* exclude calculated
where not (Department in @Department && Month in @Month)
```
The documented equivalent is `expand X.$calcid where X.$calcid == null`. Suggested values carry no calculation ID, so `exclude calculated` still returns them.
- The option can stand anywhere among the include options (`main`, `include`, `default`) and directly after the select list, but not after `where`, `check` or `from plan`.
- It applies to every table in the query, not only to `main`.
- It works in plain reads too: `count() only main Amount exclude calculated`.
- It cannot be combined with a reference to `$calcid` in the same query: *The 'exclude calculated' option cannot be used when the '$calcid' column is referenced elsewhere in the query.*
- There is no `exclude suggestions`.
## Dimension operators on variables
| Operator | Effect |
|---|---|
| `dimadd Dim = ` | Add an existing plan dimension to a variable that lacks it, enabling joins across value types that share no dimension. Filters apply to the added dimension. |
| `dimset Dim = ` | Override a dimension already on the variable. The expression affects projection and grouping; **filtering still uses the original dimension**. |
Non-existent dimension codes are filtered lazily, only when the dimension is referenced. `check dim values`, `apply dim filtering` or re-assignment force the check.
## Expressions
- **Constants:**
- text: `"abc"`
- numbers
- dates and times: `'2026-05-17'`, `'12:34:22'`, `'2026-05-17 12:00'`
- interpolated strings: `` `Total {x}` ``
- **Arithmetic and text:** `^ * / + -`, `&` concatenation, `??` coalesce.
- **Comparison:** `==`, `!=` (alias `<>`), `<`, `>`, `<=`, `>=`.
- **Pattern matching:** `=~` and `!~` with `*` and `?`.
- **Membership:** `in {…}` and `not in {…}`, also on multi-valued properties and on tuples `(a, b) in {(…)}`.
- **Logic:** `&&`, `||`, `not`.
- **Null semantics.** `x == null` is true for null. `x == y` is false when both values are null.
- **Multi-valued text.** Values are separated by `;`. Escape a literal `;` as `\;` and a backslash as `\\`.
### Functions
Kex has about 95 functions. See the [reference ↗](https://acme.konstrukt.app/api/documentation/kex) for signatures.
| Category | Examples |
|---|---|
| Conditional | `if`, `case`, `switch` |
| Conversion | `convert(expr, type)` (null on failure), casts `int()`, `string()` (throw on failure) |
| Date and time | `dateadd`, `datediff`, `now`, `today`, `startofmonth`, `endofyear`, `year`, `month`, `week`, `yyyymm`, `days()`, `months()` |
| Aggregate | `sum`, `min`, `max`, `average`, `count`, `distinctcount`, `product`, `concatenatex` |
| Window | `first`, `last`, `lag`, `lead`, and any aggregate with window bounds |
| Text | `concatenate`, `left`, `right`, `substring`, `length`, `upper`, `lower`, `substitute`, `padstart` |
| Math | `mod`, `abs`, `floor`, `ceiling`, `round`, `log`, `exp`, `rangemax`, `rangemin`, `coalesce` |
| Special | `autodim`, `typeof`, `aggregationof` |
### Windowing
```kex
Cumulative = sum(Amount) over all previous rows ordered by (Month) partitioned by (Account)
```
The general form is `FUNC [bound] [ordered by (…)] [partitioned by (…)]`. The bounds are:
- `for previous row`, `for next row`, `for row offset N`;
- `over N previous rows`, `over all previous rows`, `over N next rows`, `over all next rows`;
- `over rows between … and …`;
- `over all rows`.
A bound includes the current row. A trailing `-` excludes it. Windowed functions do not aggregate; nest them in an aggregate to group.
## Control flow and messages
Scripts can branch and stop. This is mostly used in actions, to validate input before writing.
```kex
scalar [Code] = makecode(@Employee.Name) within (Employee)
if any (Employee == [Code]) {
fatal `Employee '{[Code]}' already exists.`
}
write insert to Employee <- Employee = [Code], $name = @Employee.Name
```
| Form | Condition |
|---|---|
| `if (cond) { … }` | A condition on scalars only. A value type or dimension gives *Top-level conditions may only reference scalar values.* |
| `if any (cond) { … }` | True when at least one row satisfies the condition. The condition can read value types, dimensions, properties and variables, and accepts `where` and `from plan`: `if any (Amount > 200 && Month == "202602" from plan 12)`. `main` and `include` are not allowed inside it. |
| `if not any (cond) { … }` | True when no row satisfies the condition |
| `else { … }`, `else if [any] (…) { … }` | Alternative branches. Blocks can be nested. |
A block may contain `if`, `for`, `for row`, `scalar`, `dim`, `var`, `set`, `fatal` and annotations. **Queries and `write` statements are not allowed inside a block**; branch on the condition, then write after the block, or stop with `fatal`.
### fatal
``fatal `message` `` stops the script, and the message is returned as the error: *There was an error executing the Kex script. Employee 'DemoPerson' already exists.* `fatal` is only allowed inside a block, and the message must be a back-quoted string.
`{…}` in the message inserts the value of an expression over scalars: `{[Code]}`, `{Code}`, `{[Code] & "-x"}` or `{1+2}`. A value type or dimension gives *Fatal messages may only reference scalar values.* There are no other message levels; `warning`, `info` and `error` are unknown identifiers.
!!! agent "For agents"
If a result set is evaluated before the `fatal`, `execute_read_script` returns a generic tool error and the `fatal` message is lost. Test guards in scripts that evaluate nothing before them.
### makecode
`makecode(text) within (Dim)` turns a name into a dimension code that is unique in `Dim`. It is used in actions that create dimension values.
| Input | Result |
|---|---|
| `"Account 1"` | `Account1` |
| `"lead and trail"` | `LeadAndTrail` |
| `"åäö ÅÄÖ Émile"` | `aaoAAOEmile` |
| `"a.b-c_d/e & f! (g)"` | `a.b-c_d/e&F!(g)` |
| `"Demo Person"`, when `DemoPerson` … `DemoPerson_4` exist | `DemoPerson_5` |
| `""` in a dimension with numeric codes | the highest numeric code + 1 |
- Whitespace and the characters ``; , ' ? # * ~ { } |`` are removed, and the character after them is upper-cased. Otherwise the case is kept.
- `å ä ö é è ü` are transliterated to ASCII. Other letters are kept as they are.
- The code is at most 100 characters.
- Uniqueness is checked against existing **codes**, ignoring case, not against names. On a clash, `_2`, `_3` … is appended.
- Without `within` there is no uniqueness check, and an empty text gives a GUID.
- The argument must be a constant string or an `@` input: *Only constant string expressions are supported by the 'makecode' keyword.* `within` takes one dimension.
`within (Dim)` looks the dimension up in the plan the script runs in. For a console, API or MCP script in another plan, start with [`use plan`](#use-plan).
### Action inputs
In an action script, `@Identifier` refers to an input of the action, character for character, including dots: `@Employee`, `@Employee.Name`, `@Amount.Value`. The value behaves as a constant, so it can be used in `makecode`. Inputs cannot be declared in the script (`set @X = …` is a syntax error). Outside an action, an input gives *Unknown identifier: '@Employee.Name'.* See [Actions](actions.html#variables).
### Editor annotations
Guided calculations carry metadata for the calculation editor:
- `@@(model: "Formula", version: "1.0")` must be the first statement. `"PreCalcFormula"` marks a precalculation, which ends with a result query and has no `write`. Values must be strings.
- `@("Label")` before a `var` or `scalar` is the display label of a source in the editor.
Neither affects execution. Removing `@@(…)` and saving turns a guided calculation into a script calculation permanently; see [Calculations](calculations.html).
### use plan
`use plan ` or `use plan ""` makes that plan the context for every statement after it: reads without `from plan`, write targets and `makecode … within`. An explicit `from plan` still overrides it for its query. The last `use plan` wins, and statements before it are not affected; a scalar declared earlier keeps its plan.
```kex
use plan 12
write to Forecast <- sum(Actuals) * 1.05, Account, Month
```
`use plan` takes a literal, not a variable, and is not allowed inside blocks. An unknown plan gives *No such plan: 9999*.
### set
`set` changes a variable that is already declared with `var`, `scalar` or `dim`. The operators are `=`, `+=`, `-=`, `*=`, `/=`, `&=` (text), `^=` and `??=` (assign if null).
```kex
scalar Total = 0
for X in sum(Amount), Account {
set Total += sum(X)
}
```
- `set` never declares: *The 'set' keyword cannot be used to assign undeclared variable 'X'.*
- The columns must stay the same: *The 'set' keyword cannot be used to change the columns of variable 'X'.*
- On a table variable, `set V = …` replaces all its rows, and `set V += 1000` applies to every row.
- A scalar is evaluated when it is first used. A scalar defined from another variable, but first read after a `set` of that variable, gets the new value.
### for and for row
`for X in { … }` runs the block once per row of the query; `X` is a one-row table, so read it with aggregates such as `sum(X)` or `min(X.Account)`. `for row in { … }` is the same loop with the variable named `row`. The query can have `where` and `from plan`, and loops can be nested. An empty query runs zero times.
The body follows the block rules: `var`, `scalar`, `dim`, `set`, `if`, `for` and `fatal`, but no queries and no `write`. Variables declared in the body are not visible after the loop; use `set` on an outer variable to carry results out.
### spread
`spread (Source [evenly | proportionally] over Target)` is an expression that distributes a coarser source down to the grain of `Target`. Without a mode it spreads **proportionally** to the target's values:
```kex
var Budget = sum(Qty), Account // 20 for account A1
spread (Budget evenly over Amount) // 10 and 10 over A1's two rows
spread (Budget over Amount) // 5 and 15, weighted by Amount 100 and 300
```
The result has the target's dimensions and can be used in `var`, in a query or as the source of a `write`. Only numeric data can be spread; the source cannot have the same dimensions as the target, or dimensions the target lacks (*Pre-aggregate the source table to exclude any extraneous dimensions.*).
## Pitfalls
!!! agent "Known pitfalls"
There are known pitfalls when writing Kex — windowing over un-aggregated value types, duplicated rows from custom grouping, cross-plan reads and write targets. They are documented for agents in the [Agent guide](agent-pitfalls.html#kex), with write-specific pitfalls under [Writes](agent-pitfalls.html#writes).
## Kex Lite
App dataset expressions use **Kex Lite**, a restricted dialect evaluated per slice of a dataset. The platform generates a context for each expression, for example:
```kex
dim Department = $slice.Department limit 1
var Amount = pivot($slice, "Amount")
```
The expression then refers to the dataset's value types and dimensions by name. Writeback expressions use `$input` for the entered value. See [Datasets](datasets.html#expressions) and the **[Kex Lite reference ↗](https://acme.konstrukt.app/api/documentation/kex-lite)**.
## Where Kex runs
| Context | Reads | Writes | Notes |
|---|---|---|---|
| Calculation | Yes | Yes (own rows) | Triggered on source change |
| Action | Yes | Yes | Run by a user, with `@Variable` inputs |
| Flow | Yes | Yes | Run on demand with parameters |
| Kex console | Yes | Yes | Admin tool, see [Administration](administration.html) |
| REST `/api/v1/kex/script/*` | Yes | Yes, in the default plan | Separate validate, read and write endpoints, see [APIs](apis.html#kex-endpoints) |
| MCP | `execute_read_script` | `execute_write_script` | `validate_script` first, see [AI agents](ai-agents.html) |
| Dataset expressions | Kex Lite | Via writeback | See [Datasets](datasets.html) |
!!! note "Not in the generated reference"
`exclude calculated`, `makecode`, `if` blocks, `fatal`, `@` inputs and the editor annotations are missing from the auto-generated Kex reference. They are described on this page.
## Related
- [Calculations](calculations.html)
- [Actions](actions.html)
- [References and history](references-history.html)
- [Reference documentation](reference-docs.html)
---
# Kex quick card
> The rules and examples an agent needs before writing its first Kex query: clause order, plans, filters, aggregation, joins and windows, with checked examples from the base template.
This card is short on purpose, so it can sit in an agent's context at all times. The full language is described in [Kex](kex.html). The function reference is generated from the product at `/api/documentation/kex` on each tenant host.
## Before the first query
1. **Find the plan and the names.** Plan ids differ between tenants, so call `list_plans`, then `list_value_types` and `list_dimensions` with the plan id. Use the ids (`PnL`, `YearMonth`), not the display names.
2. **Read the tenant's own guide if it has one.** Many tenants describe their model and common questions in MCP resources (`list_mcp_resources`). It says which value type answers which question.
3. **Validate, then run.** Call `validate_script` before `execute_read_script`. Read the error, fix that exact thing and validate again. Do not rewrite the query from scratch.
## The shape of a query
Clauses must come in this order. Every clause except the first is optional.
```text
[only]
[main X | include X ...]
[where ]
[group by ... | having ... | order by ...]
[from plan | from reference ""]
[limit ]
```
**`from plan` comes after `where` and `order by`, not before them.** This is the most common error. Kex is not SQL: there is no `SELECT`, and there is no `FROM` at the top.
## Kex is not SQL
| SQL habit | Kex |
|---|---|
| `SELECT sum(x) FROM t WHERE ...` | `sum(x) where ... from plan 25` |
| `=` for comparison | `==` (and `!=`) |
| `'text'` | `"text"` (single quotes are dates: `'2026-05-17'`) |
| `AND`, `OR`, `NOT` | `&&`, `\|\|`, `not` |
| `GROUP BY Company` | list the dimension: `sum(x), Company`. Grouping is implicit |
| `count(DISTINCT x)` | `distinctcount(x)` |
| `avg(x)` | `average(x)` |
| `LIKE 'A%'` | `=~ "A*"` |
| `IN ('a', 'b')` | `in {"a", "b"}` |
| `x IS NULL` | `x == null` |
| `CASE WHEN c THEN a ELSE b END` | `if(c, a, b)` |
| `TOP 5` / `LIMIT 5` first | `limit 5` last |
Keywords are lowercase. Write dimension codes as text in double quotes, even when they look like numbers: `Company == "2000"`, `YearMonth == "202606"`, `Employee == "2007"`. `YearMonth.Year == "2025"` filters a whole year.
## Plans
- `from plan 25` at the end of a statement reads that statement from plan 25. A value type that is not in the default plan gives *Unknown identifier* until you add it.
- `use plan 25` on the first line sets the plan for the whole script.
- In a script with several statements, each `var` or `scalar` can end with its own `from plan`, so one script can combine plans.
## Aggregation
- The dimensions you list are the grouping: `sum(PnL), Company` gives one row per company.
- **A value type on its own keeps all its dimensions.** `sum(PnL)` without `only` returns one row per combination of every dimension. For a single total, write `sum(PnL) only`.
- `only` turns off automatic projection: `sum(PnL), Company only` gives exactly one column per listed item.
- Filter on an aggregate with `having`, not `where`: `having sum(PnL) < 0`.
## Combining value types
Two value types with different dimensions are joined on the dimensions they share. **Aggregate each one to the dimensions you want first**, in a `var`, then combine the variables. If you skip this, the smaller value type is repeated on every row of the larger one. Costs per consultant get subtracted once per customer, for example.
```kex
var Revenue = sum(PnL), Company where Account.Reportrow == "PL010" && YearMonth.Year == "2025" from plan 25
var Personnel = sum(PnL), Company where Account.Reportrow == "PL080" && YearMonth.Year == "2025" from plan 25
Company, Share = -sum(Personnel) / sum(Revenue)
```
An inner join drops rows that exist on only one side. Use `include optional X` (left join) or `include all X` (full join) when a missing side must still count.
## Windows
Aggregate to the period first in a `var`, then apply the window:
```kex
use plan 25
var R = sum(ConsReported), YearMonth where YearMonth.Year == "2025" && ReportRow == "PL010"
YearMonth, Revenue = R, Cumulative = sum(R) over all previous rows ordered by (YearMonth), Change = R - lag(R, 1) ordered by (YearMonth)
```
- `over all previous rows ordered by (YearMonth)` gives a running total. `over 2 previous rows` gives three months, because the bound includes the current row.
- `lag(R, 12) ordered by (YearMonth)` gives the same month last year, but only if the variable also holds last year's months.
- `partitioned by (Company)` restarts the window per company.
## Checked examples
All examples are from the base template, where Reporting & KPIs is plan 25 and the Financial Plan is plan 30. They are checked against a copy of the Acme demo tenant.
**Total for one year.**
```kex
sum(PnL) only where YearMonth.Year == "2025" && Account.Reportrow == "PL010" from plan 25
```
**Per company, with names, largest first.**
```kex
Revenue = sum(PnL), Company, Company.$name
where YearMonth.Year == "2025" && Account.Reportrow == "PL010"
order by Revenue desc
from plan 25
```
**Top five customers.**
```kex
Revenue = sum(Actuals), Customer, Customer.$name
where Company == "2000" && YearMonth.Year == "2025" && Account.Reportrow == "PL010"
order by sum(Actuals) desc
from plan 25
limit 5
```
**Months with a loss (`having`).**
```kex
Result = sum(PnL), YearMonth
where YearMonth.Year == "2025" && Company == "2000"
having sum(PnL) < 0
from plan 25
```
**A ratio of two parts of the same value type.**
```kex
Company, Company.$name,
PersonnelShare = -sum(if(Account.Reportrow == "PL080", PnL, 0)) / sum(if(Account.Reportrow == "PL010", PnL, 0))
where YearMonth.Year == "2025"
from plan 25
```
**Year over year.**
```kex
use plan 25
var R = sum(ConsReported), YearMonth where YearMonth >= "202501" && YearMonth <= "202608" && ReportRow == "PL010"
YearMonth, Revenue = R, PriorYear = lag(R, 12) ordered by (YearMonth), YoY = R / lag(R, 12) ordered by (YearMonth) - 1
```
**Two plans in one script.**
```kex
var Cost = sum(PnL), Company where YearMonth >= "202601" && YearMonth <= "202606" && Account.Reportrow == "PL080" from plan 25
var Fte = sum(PersonnelEmploymentLevelMonthly) / 6, Company where YearMonth >= "202601" && YearMonth <= "202606" from plan 30
Company, Cost = sum(Cost), AvgFTE = sum(Fte), CostPerFTEMonth = sum(Cost) / sum(Fte) / 6
main Cost include Fte
```
**Count members with a condition.**
```kex
use plan 30
var H = sum(PersonnelEmploymentLevelMonthly), Company, Employee where YearMonth == "202606"
Headcount = count(H), FTE = sum(H), Company, Company.$name where H > 0
```
**Look up one member and a value keyed by it.**
```kex
use plan 30
Employee, Employee.$name, Employee.Company, PersonnelEmploymentEndDate
main Employee
include optional PersonnelEmploymentEndDate on Employee
where Employee == "2007"
```
**Actual against a budget stored as a reference.**
```kex
use plan 25
scalar Actual = sum(PnLMarket) only where YearMonth >= "202601" && YearMonth <= "202608" && ReportRow == "PL010"
scalar Budget = sum(PnLMarket) only where YearMonth >= "202601" && YearMonth <= "202608" && ReportRow == "PL010" from reference "Budget 2026"
evaluate Actual = Actual, Budget = Budget, Diff = Actual - Budget, DiffPct = Actual / Budget - 1
```
## When a query fails
| Error | Usual cause |
|---|---|
| *Syntax error at 'where'* or *at 'order'* | `from plan` is placed before `where` or `order by`. Move it to the end |
| *Syntax error at '='* | `=` instead of `==` |
| *Syntax error at '=='* later in the line | `AND`/`OR` instead of `&&`/`\|\|` |
| *Unexpected input at 'from plan'* | Text in single quotes (`'2000'`), which Kex reads as a date. Use `"2000"` |
| *Unknown identifier: 'SELECT'* | SQL syntax. Start with the select list itself |
| *Unknown identifier: 'X'* | X is in another plan (add `from plan`) or the id is misspelled (check `list_value_types`) |
| *Unresolved dimension 'D'. The dimension is not part of the main scope* | D is not a dimension of the value type you aggregate. Pick a value type that has D, or join one in |
| *Variable 'V' cannot be used as one or more dimensions are…* | The variables have different dimensions. Aggregate both to the same dimensions |
| An empty result | The code does not exist (check the dimension's members) or the period has no data. Say so rather than guessing |
After two failures with the same error, read [Kex](kex.html) or [Agent pitfalls](agent-pitfalls.html) before trying again.
## Related
- [Kex](kex.html) — the full language.
- [Agent pitfalls](agent-pitfalls.html) — mistakes in Kex, writes, apps and calculations.
---
# Kex examples
> Checked Kex read queries ordered by task — totals, filters, top-N, periods, windows, ratios, several value types, plans and references — plus forms that look right but fail.
Every query on this page runs against the base template. Reporting & KPIs is plan 25, the Financial Plan is plan 30 and Masterdata is plan 29. Plan ids differ between tenants, so take them from `list_plans`. Start with the [Kex quick card](kex-card.html) for the rules; this page is for finding a pattern to copy.
## Totals and grouping
**One total.** `only` stops Kex from returning a row per dimension combination.
```kex
sum(PnL) only where YearMonth.Year == "2025" && Account.Reportrow == "PL010" from plan 25
```
**Per month.**
```kex
sum(PnL), YearMonth only where YearMonth.Year == "2025" && Account.Reportrow == "PL010" from plan 25
```
**Per company, with names.**
```kex
Revenue = sum(PnL), Company, Company.$name
where YearMonth.Year == "2025" && Account.Reportrow == "PL010"
order by Revenue desc
from plan 25
```
**Per report row, with the row names.** A property of a property is reached with another dot.
```kex
sum(PnL), Account.Reportrow, Account.Reportrow.$name only
where YearMonth.Year == "2025" && Company == "2000"
order by Account.Reportrow
from plan 25
```
**Per quarter.** Integer division needs `floor`, or the label becomes `Q1.333`.
```kex
Quarter = left(YearMonth, 4) & "-Q" & string(floor((int(right(YearMonth, 2)) - 1) / 3) + 1), sum(PnL) only
where YearMonth.Year == "2025" && Account.Reportrow == "PL010"
from plan 25
```
**Average.**
```kex
average(PersonnelSalary) only from plan 30
```
## Filters
**A period range.** Period codes compare as text, so `"202501"` to `"202512"` works.
```kex
sum(PnL) only where YearMonth >= "202501" && YearMonth <= "202512" && Account.Reportrow == "PL010" from plan 25
```
**A list of members.**
```kex
sum(PnL), Company only where Company in {"2000", "3000"} && YearMonth.Year == "2025" from plan 25
```
**A name pattern.** `*` matches any text.
```kex
sum(PnL), Company only where YearMonth.Year == "2025" && Account.Reportrow == "PL010" && Company.$name =~ "*Norge*" from plan 25
```
**The last three months, counted from today.**
```kex
sum(PnL) only where YearMonth >= yyyymm(today() - months(3)) from plan 25
```
**Dates.** Single quotes are date constants.
```kex
use plan 30
Employee, Employee.$name, PersonnelEmploymentStartDate where PersonnelEmploymentStartDate >= '2026-01-01'
```
**Leave out the "not specified" member.** Most dimensions have a member `"0"` that collects unassigned values.
```kex
sum(PnL), Counterparty only
where YearMonth.Year == "2025" && Account.Reportrow == "PL010" && Counterparty != "0"
from plan 25
```
## Top-N and ranking
**The three largest customers.**
```kex
sum(Actuals), Customer, Customer.$name only
where Company == "2000" && YearMonth.Year == "2025" && Account.Reportrow == "PL010"
order by sum(Actuals) desc
from plan 25
limit 3
```
**The three highest salaries in one company.**
```kex
use plan 30
sum(PersonnelSalary), Employee, Employee.$name only where Employee.Company == "2000" order by sum(PersonnelSalary) desc limit 3
```
**A rank column.**
```kex
use plan 25
var R = sum(PnL), YearMonth where YearMonth.Year == "2025" && Account.Reportrow == "PL010"
YearMonth, R, Rank = count(R) over all previous rows ordered by (R desc)
```
## Conditions on aggregates
**`having` with an alias.** An alias with a space needs brackets.
```kex
[Net sales] = sum(PnL), Company only
where YearMonth.Year == "2025" && Account.Reportrow == "PL010"
having [Net sales] > 20000000
from plan 25
```
**Months with a loss.**
```kex
Result = sum(PnL), YearMonth
where YearMonth.Year == "2025" && Company == "2000"
having sum(PnL) < 0
from plan 25
```
## Counting
**Members with a value.** Aggregate to the members first, then count the rows. `distinctcount(Customer), Company` fails, because the count has no value type to group by.
```kex
use plan 25
var C = sum(Actuals), Company, Customer where YearMonth.Year == "2025" && Account.Reportrow == "PL010"
Customers = count(C), Company where C != 0
```
**Employees with a level above zero in a month.**
```kex
use plan 30
var H = sum(PersonnelEmploymentLevelMonthly), Company, Employee where YearMonth == "202606"
Headcount = count(H), FTE = sum(H), Company, Company.$name where H > 0
```
## Windows
Always aggregate to the period in a `var` first. A window on the raw value type runs once per row of every dimension and gives wrong figures.
**Running total.**
```kex
use plan 25
var R = sum(ConsReported), YearMonth where YearMonth.Year == "2025" && ReportRow == "PL010"
YearMonth, Revenue = R, Cumulative = sum(R) over all previous rows ordered by (YearMonth)
```
**Running total per company.**
```kex
use plan 25
var R = sum(PnL), Company, YearMonth where YearMonth.Year == "2025" && Account.Reportrow == "PL010"
Company, YearMonth, R, Running = sum(R) over all previous rows ordered by (YearMonth) partitioned by (Company)
```
**Rolling three-month average.** The bound includes the current row, so `2 previous rows` is three months.
```kex
use plan 25
var R = sum(PnL), YearMonth where YearMonth.Year == "2025" && Account.Reportrow == "PL010"
YearMonth, R, Avg3m = average(R) over 2 previous rows ordered by (YearMonth)
```
**Change from the previous month.**
```kex
use plan 25
var R = sum(ConsReported), YearMonth where YearMonth.Year == "2025" && ReportRow == "PL010"
YearMonth, Revenue = R, Change = R - lag(R, 1) ordered by (YearMonth)
```
**Year over year.** The variable must also hold last year's months, or `lag(R, 12)` is empty.
```kex
use plan 25
var R = sum(ConsReported), YearMonth where YearMonth >= "202501" && YearMonth <= "202608" && ReportRow == "PL010"
YearMonth, Revenue = R, PriorYear = lag(R, 12) ordered by (YearMonth), YoY = R / lag(R, 12) ordered by (YearMonth) - 1
```
**Share of the total.**
```kex
use plan 25
var R = sum(PnL), YearMonth where YearMonth.Year == "2025" && Account.Reportrow == "PL010"
YearMonth, Share = R / sum(R) over all rows
```
**Total per company on every row.**
```kex
use plan 25
var R = sum(PnL), Company, YearMonth where YearMonth.Year == "2025" && Account.Reportrow == "PL010"
Company, YearMonth, R, CompanyTotal = sum(R) partitioned by (Company)
```
## Ratios and several value types
**Two parts of the same value type.** Use `if` inside the sums.
```kex
Company, Company.$name,
PersonnelShare = -sum(if(Account.Reportrow == "PL080", PnL, 0)) / sum(if(Account.Reportrow == "PL010", PnL, 0))
where YearMonth.Year == "2025"
from plan 25
```
**Two aggregated variables combined.**
```kex
var Revenue = sum(PnL), Company where Account.Reportrow == "PL010" && YearMonth.Year == "2025" from plan 25
var Personnel = sum(PnL), Company where Account.Reportrow == "PL080" && YearMonth.Year == "2025" from plan 25
Company, Share = -sum(Personnel) / sum(Revenue)
```
**Two plans in one script.** Each `var` names its own plan. `main` and `include` decide how the variables are joined.
```kex
var Cost = sum(PnL), Company where YearMonth >= "202601" && YearMonth <= "202606" && Account.Reportrow == "PL080" from plan 25
var Fte = sum(PersonnelEmploymentLevelMonthly) / 6, Company where YearMonth >= "202601" && YearMonth <= "202606" from plan 30
Company, Cost = sum(Cost), AvgFTE = sum(Fte), CostPerFTEMonth = sum(Cost) / sum(Fte) / 6
main Cost include Fte
```
**A constant.**
```kex
scalar TaxRate = 0.206
sum(PnL) * TaxRate only where YearMonth.Year == "2025" from plan 25
```
**Several result sets in one call.** Each `evaluate` gives a named result set, and the last statement is `main`.
```kex
use plan 25
var Revenue = sum(PnL), Company where Account.Reportrow == "PL010" && YearMonth.Year == "2025"
var Cost = sum(PnL), Company where Account.Reportrow == "PL080" && YearMonth.Year == "2025"
evaluate Revenue
evaluate Cost
```
## Members and properties
**Look up one member and a value keyed by it.**
```kex
use plan 30
Employee, Employee.$name, Employee.Company, PersonnelEmploymentEndDate
main Employee
include optional PersonnelEmploymentEndDate on Employee
where Employee == "2007"
```
**All members of a dimension.**
```kex
KPI, KPI.$name from plan 25
```
**All columns of a few rows**, to see what a value type holds. `X.**` also shows internal columns such as `$edittime`.
```kex
PnL.* where Company == "2000" from plan 25 limit 3
```
**Names instead of codes in the result.**
```kex
sum(PnL), Company, Company.$name only
where YearMonth.Year == "2025" && Account.Reportrow == "PL010"
from plan 25
apply dim formatting
```
## References and history
**A stored budget.** A reference is read with `from reference` and the plan set by `use plan`. List the references with the `list_references` tool. They are not a dimension.
```kex
use plan 25
sum(PnLMarket), ReportRow only
where YearMonth.Year == "2026" && ReportRow in {"PL010", "PL080"}
from reference "Budget 2026"
```
**Actual against budget.**
```kex
use plan 25
scalar Actual = sum(PnLMarket) only where YearMonth >= "202601" && YearMonth <= "202608" && ReportRow == "PL010"
scalar Budget = sum(PnLMarket) only where YearMonth >= "202601" && YearMonth <= "202608" && ReportRow == "PL010" from reference "Budget 2026"
evaluate Actual = Actual, Budget = Budget, Diff = Actual - Budget, DiffPct = Actual / Budget - 1
```
**The data as it was a week ago.** `from history` reads the history tables, so it returns nothing in a tenant whose history has been cleared.
```text
sum(PnL) only where YearMonth.Year == "2025" from plan 25 from history today() - days(7)
```
## Checks
**Fail if a row would be counted twice.** Output options come last.
```kex
sum(PnL), YearMonth only where YearMonth.Year == "2025" from plan 25 check duplication
```
## Forms that look right but fail
| Form | What happens | Use instead |
|---|---|---|
| `sum(X) over all previous, YearMonth` | Runs, but the window runs per raw row without order, so the figures are wrong | Aggregate in a `var`, then `sum(R) over all previous rows ordered by (YearMonth)` |
| `lag(sum(X), 12)` | Runtime error: *Column … is invalid in the select list* | `var R = sum(X), YearMonth …` then `lag(R, 12) ordered by (YearMonth)` |
| `sum(R) over all rows ordered by (…) partitioned by (…)` | Syntax error | `sum(R) partitioned by (Company)` |
| `check duplication` before `where` | Syntax error | Put it last |
| `scalar var X = 1` | Runs and does nothing | `scalar X = 1` |
| `distinctcount(Customer), Company` | *Unresolved dimension 'Company'* | Count the rows of an aggregated `var` |
| `from reference "…"` without `use plan` | *Unknown identifier* | Start the script with `use plan` |
| `sum(PnL), Company from plan 25 where …` | *Syntax error at 'where'* | `from plan` after `where` and `order by` |
| `Company == '2000'` | *Unexpected input*: single quotes are dates | `Company == "2000"` |
---
# Tracing a number
> A walkthrough of how to trace any number in Konstrukt back to its origin — from a cell in an app to the value type, the calculation that wrote it, its sources, its history and its import — using the platform's lineage and inspection tools.
Every stored value in Konstrukt records who or what produced it, and every calculation exposes what it reads and writes. You can therefore follow any number upstream to its inputs, or downstream to everything it affects, without having written the logic yourself. This page brings together the tools that make that possible.
```flow
Cell in an app | Inspect cell -> Value type | lineage panel -> Calculation | sources, working set, diagnostics -> Source value types | repeat upstream -> Import or user entry | edited by, edited time
```
## Starting points
| Starting point | What it tells you | Where |
|---|---|---|
| A cell in an app | The value, expression, writeback, presentation rules and why it is read-only | **Inspect cell** (*Inspektera cell*) in the cell context menu, see [Using apps](end-user.html) |
| A value-type row | Last changed, changed by, and the writing calculation's ID as a link | Column chooser in the value-type view: Last changed, Last changed by, Calculation ID (*Senast ändrad*, *Senast ändrad av*, *Beräknings-id*) |
| A value type | Calculations that write to it, calculations that read it, apps that use it, size | **Details** panel on the value type |
| A calculation | Sources with conditions, working set, formula, output, diagnostics, run order, cycle flag | The calculation editor, see [Calculations](calculations.html) |
| The whole logic | Which calculations feed which, in which order | **Show diagram**, see [Dependency graph](calculations.html#dependency-graph) |
| A dimension | Value types that use it, properties and bindings, feeding integrations, SQL view | Dimension editor panels, see [Data model](data-model.html#dimension-editor) |
| A point in time | What the number was then | `from history`, point-in-time references, see [References and history](references-history.html) |
## Walkthrough
1. **Inspect the cell.** In the app, right-click the cell and choose **Inspect cell** (*Inspektera cell*). The panel shows the dataset expression behind the cell, its writeback (if any), the presentation rules that apply, and the reason the cell is read-only if it is. **Show all rows** (*Visa alla rader*) shows the underlying rows that make up the cell.
2. **Open the value type.** In the admin interface, open the value type and switch on the lineage columns. Rows written by a calculation show its ID as a link. Rows with no calculation ID were entered by a user or imported. **Last changed by** says who or which integration wrote them.
3. **Follow the calculation.** Open the calculation. Its **sources** show what it reads and under which conditions. The **working set** shows the joined rows the formula saw, with one value column per source. The **output** shows the result at the destination's grain. Filter both tables to the combination you are tracing.
4. **Check the transformation.** Open **Diagnostics** to see how Kex resolved joins, includes and aggregation for the query.
5. **Repeat upstream.** Each source is a value type. Go back to step 2 for it until you reach user-entered or imported data.
6. **Compare over time.** Switch the value-type view to a reference, or query with `from history `, to see what the number was at an earlier moment and when it changed.
7. **Find the import.** For imported rows, the value type's or dimension's **Integration** panel shows the configurations that feed it. The integration **Jobs** and **Logs** show when they ran. See [Data integration](integration.html).
## Why a cell is read-only
A cell cannot be edited for one of three reasons. The tooltip and the Inspect panel say which one applies.
| Reason | Swedish | Meaning |
|---|---|---|
| Locked values | *Låsta värden* | The dataset's [locked values](datasets.html) cover the cell; it is shown grey |
| Calculated value | *Beräknat värde* | The value is written by a calculation; change its sources instead |
| No writeback | *Uttrycket saknar writeback* | The cell's expression has no writeback rule, so an entry has nowhere to go |
Access restrictions can also make a whole dataset or rows read-only. See [Security](security.html).
## Tracing with Kex
The internal columns make lineage queryable:
```kex
Amount.** where Amount.$calcid == null
```
This lists user-entered and imported rows with their edit time, editor and line state.
```kex
sum(Amount) expand Amount.$calcid
```
This shows how much each calculation contributes to a total. `$calcid` is empty for rows that no calculation wrote.
!!! agent "Tracing via MCP"
- Use `get_calculation_graph` with `outputEntityIds: ["Amount"]` to find the calculations writing a value type.
- Use `referencedEntityIds` to find its readers.
- Then use `execute_read_script` with `X.**` or `expand X.$calcid` to inspect the rows.
## Related
- [Calculations](calculations.html)
- [References and history](references-history.html)
- [Using apps](end-user.html)
- [Data model](data-model.html#internal-columns)
---
# Apps
> What an app is, how it is structured (datasets, workspaces, components), and where its settings and configuration are edited.
An app (*App*) is the user interface of a plan. It is a named, access-controlled set of views through which users read and edit the plan's data. An app belongs to exactly one plan and never holds data of its own: every number it shows is stored in a value type in that plan, and every edit is written back to that value type.
An app is built from three layers:
- **Datasets** say *which data* the app works with: a set of value types, the dimensions to show them by, and the rules that shape the data (initial values, locked values, filters, computed rows).
- **Workspaces** say *how the data is presented*: filters, data-type selection, layout and the components on each page.
- **Components** are the individual building blocks, such as a table, a chart, a metric box or a text block. Every data component reads from one dataset.
Actions (*Handlingar*) are an additional part of a workspace. They are small forms that run a Kex write script, for example to create a new project or remove rows.
## Structure
```flow
Plan | dimensions, value types, calculations -> Dataset | value types × dimensions, rules -> Workspace | filters, data types, layout -> Component | table, chart, metric, text
Workspace | per workspace -> Action component | variables + Kex write script
```
An app has one or more datasets and one or more workspaces. A component points to a dataset by its ID, so several components, in the same workspace or in different ones, can share a dataset. Two tables on the same dataset can, for example, each show a different value type by using component filters (see [Workspaces and components](components.html#component-filters)).
| Layer | Holds | Page |
|---|---|---|
| App | name, description, access, lock state | this page |
| Dataset | value types, dimensions and properties, initial values, locked values, dataset filter, expressions, row-level access | [Datasets](datasets.html) |
| Workspace | filter row, data types and references, value type names and order, layout, action components | [Workspaces and components](components.html) |
| Component | table, text, metric, chart, or a placed action | [Workspaces and components](components.html#component-types) |
| Action component | variables and a Kex script | [Actions](actions.html) |
!!! note "Apps hold no logic of their own"
Business logic lives in the plan: in calculations, which run automatically when their source data changes, and in dataset expressions, which are evaluated when the data is loaded. Removing an app removes the view, not the data it showed. See [Calculations](calculations.html).
## Where apps are managed
In plan administration, apps are listed under **Interaction** (*Interaktion*) together with access lists (*Behörighetslistor*). The breadcrumb for an app reads *Plans / / Apps / * (*Planer / / Appar / *). Apps can also be reached directly from the plan in the side menu.
Each row in the app list has a menu (⋯):
| Menu entry | Swedish label | Effect |
|---|---|---|
| Open app as end user | *Öppna app som slutanvändare* | opens the app in the end-user interface |
| Edit permissions | *Ändra behörigheter* | opens the app's access settings |
| Copy name / Copy ID | *Kopiera namn till urklipp · Kopiera id till urklipp* | copies the app name or GUID to the clipboard |
| Copy app | *Kopiera app* | creates a copy of the app |
| Delete app | *Ta bort app* | deletes the app |
Inside the app editor, the menu (⋯) next to the app name has:
| Menu entry | Swedish label | Effect |
|---|---|---|
| Rename | *Byt namn* | changes the app name |
| Copy | *Kopiera* | asks for a name (default * (Copy)*) and creates a copy in the same plan |
| Delete | *Ta bort* | deletes the app |
| Hide / Show | *Dölj · Visa* | hides the app from end users, or shows it again; saved with **Save** (*Spara*) |
| Edit XML | *Redigera XML* | opens the raw configuration, see [App configuration](app-config.html) |
| Delete comments | *Radera kommentarer* | removes the cell comments made in the app |
A copy gets the configuration, name and description of the original. **Cell comments are not copied**; they belong to the app they were written in.
## App settings
App settings are edited under **Settings** (*Inställningar*) in the app editor.
### Name and description
The name is shown in app lists and breadcrumbs. The **description** (*Beskrivning*) is formatted text edited in a rich-text editor. End users open it with the information icon at the top right inside the app, so it is the natural place for instructions on how to use the app.
Name and description are stored on the app record, not in the app configuration. Copying the configuration from one app to another does not copy them. See [App configuration](app-config.html#what-is-not-in-the-configuration).
### App access
**App access** (*Appåtkomst*) controls who can open the app:
- An **access list** for the app as a whole. Without a list, everyone with access to the plan can open the app.
- **Row-level access per dataset**: read access or read and write access, inherited from the app, full, or limited by a specific list. See [Datasets](datasets.html#row-level-access).
- **Lock app** (*Lås appen*) blocks data entry in the app for all users. It does not block changes to the app's configuration.
Access lists are defined in the plan and apply across apps. For details see [Security](security.html).
### Visibility in app lists
*Hide* sets `Access/@Enabled` to `false` in the configuration. A hidden app:
- is marked with a crossed-out eye in the admin app list and in the editor header;
- disappears from the end-user app lists;
- cannot be opened by URL either: the app shows *Åtkomst nekad* (access denied), also for administrators.
The app still exists and keeps its configuration and comments. *Show* (*Visa*) makes it available again.
## The app editor
Konstrukt has a complete graphical editor for app configuration. Everything described in the app pages can be set in the editor; the raw XML (or JSON through MCP) is an alternative, not a requirement.
The editor has three top-level areas:
| Area | Swedish label | Content |
|---|---|---|
| Settings | *Inställningar* | app access, lock, description |
| Workspace | *Arbetsyta* | one tab per workspace |
| Dataset | *Dataset* | one section per dataset: value type cards and the dimensions matrix |
Each workspace has six tabs:
| Tab | Swedish label | Content |
|---|---|---|
| Components | *Komponenter* | the components and their settings |
| Filters | *Filter* | the workspace filter row |
| Data type / references | *Datatyp / referenser* | plan data and references offered in the workspace |
| Value types | *Värdetyper* | display names and order of value types |
| Actions | *Handlingar* | action components |
| Layout | *Layout* | multi-page or grid layout |
A component has the fields component name (*Komponentnamn*), visibility, dataset, type (*Typ*) and show headers (*Visa rubriker*), and four sub-tabs: **Settings** (*Inställningar*), **Custom aggregations and spreads** (*Egna aggregeringar och spridningar*), **Presentation rules** (*Presentationsregler*) and **Columns** (*Kolumner*).
!!! tip "Test an app as a role"
The top bar has **Act as** (*Agera som*), which switches the session to a role so that an administrator can see an app as that role sees it. Use it to check access lists and read-only settings before handing an app over.
## Configuration format and schema version
Behind the editor, an app configuration is stored as XML with a root element ``. The current schema version is **1.50**. Older configurations are migrated step by step when they are read, followed by migrations that depend on the plan version (v1 or v2). A configuration therefore always reaches the current shape before it is used.
The same configuration is exposed as typed JSON through the MCP server, described by a JSON Schema whose types agents read with the MCP tool `get_app_config_schema`. Agents can read the configuration of any app and write configurations for apps in v2 plans. See [App configuration (XML/JSON)](app-config.html).
!!! warning "Saving is not round-trip"
When a configuration is saved, it is rebuilt from the configuration model. XML that the model does not read, such as comments, unknown attributes and formatting, is not kept. See [App configuration](app-config.html#saving-is-not-round-trip).
!!! tip "Copy before large changes"
Changes to app configurations are recorded like all other changes, but no version history is shown in the interface. Copy the app, or save its XML, before large changes.
## Sub-pages
- [Datasets](datasets.html): value types, dimensions, spreading, initial values, locked values, expressions and row-level access.
- [Workspaces and components](components.html): filters, data types, layouts, tables, presentation rules, metrics and charts.
- [Actions](actions.html): action components, the generator, variables and scripts.
- [Using apps](end-user.html): what end users see, cell inspection, read-only cells, comments and editing.
- [App configuration (XML/JSON)](app-config.html): the underlying configuration and how agents work with it.
## Related
- [Data model](data-model.html)
- [Calculations](calculations.html)
- [Kex](kex.html)
- [Security](security.html)
- [AI agents](ai-agents.html)
---
# Datasets
> How a dataset selects value types and dimensions for an app, and how spreading, initial values, locked values, filters, expressions and row-level access shape that data.
A dataset is a named, dimensioned slice of plan data that app components read from. It contains one or more value types and a dimension set: all, or a subset of, the dimensions that the value types share. A dataset belongs to one app. Every table, chart and metric in the app points to exactly one dataset.
The dataset also holds most of the app's data rules (aggregation and spreading, input rows, locks, computed rows), which apply to every component that uses it.
In the app editor, each dataset has two parts: **value type cards** and a **dimensions matrix**.
## Value types in a dataset
Each value type in the dataset has a card showing its position, ID, aggregation (*Aggregering*) and spread (*Fördelning*). Value types are added with **Add value types to dataset** (*Lägg till värdetyper till dataset*), or created on the spot with **New value type** (*Ny värdetyp*). The card footer lists the dimensions included (*Dimensioner inkluderade*).
A value type can also get a display name for this dataset (`NameOverride`), a condition and default values for excluded dimensions, all described below.
### Aggregation
`Aggregation` is `Sum`, `Min`, `Max`, `Avg` or `Disabled`. `Disabled` means no aggregation at all, which suits dates, comments and text. A component can override the aggregation for its own view, per value type and per dimension. See [Workspaces and components](components.html#value-type-overrides).
### Spreading
When a user edits an aggregated cell, such as a yearly total over twelve months, the new value is spread down to the stored cells below it. The spread type decides how:
| Code | Name | Behaviour |
|---|---|---|
| 0 | `Proportional` | keeps the current proportions between the underlying cells (*Proportionell*) |
| 1 | `Even` | spreads evenly; the sum becomes the entered value |
| 3 | `SetValue` | sets the entered value on **every** affected cell; correct for averages and prices, but changes the total for summed value types |
| 4 | `Locked` | does not spread; the aggregate cannot be changed by spreading |
Code 2 is not used. The same codes are used for writeback expressions (see [below](#writeback)) and for component-level overrides.
!!! tip "Choose spread by what the number means"
Use `Proportional` or `Even` for additive values such as `Amount` or `Headcount`. Use `SetValue` for rates and unit values such as `Price`, where typing 100 on a year should mean 100 in every month, not 100 in total.
### Dimensions removed by aggregation
A value type can have more dimensions than the dataset shows. The card then shows *Dimension removed by aggregation: * (*Dimension borttagen genom aggregering*), and the dataset shows the value type aggregated over that dimension.
**Set default values** (*Sätt standardvärden*) gives a default code for each excluded dimension (`ExcludedDimensionValueDefaults`). The defaults are used when data is spread on updates, so that entered values have a code for the dimensions the dataset does not show.
### Value type condition
A value type can be restricted with a **condition**: a Kex filter that limits which rows of that value type the dataset loads. Open the card menu (⋯) and choose **Set filter** (*Ställ in filter*). A filtered card carries the chip **Filtered** (*Filtrerad*).
The panel has two views of the same condition:
- a **guided form**: field, operator and value;
- a **code view** behind **Show advanced** (*Visa avancerat*), where the condition is written as Kex.
The two views convert both ways. Writing `Amount > 100000` in the code view shows up in the form as *Value · Greater than · 100000*.
The condition is the body of a Kex `where` clause, without the keyword:
```kex
Amount > 100000 && Account in {"4010", "4020"}
```
Rules:
- **No subqueries.**
- **Scoped to the value type.** The condition can reference the value type and its own dimensions only, not other value types.
- **Type-checked at validation.** An invalid condition fails with `InvalidValueTypeCondition` and a path to the failing part of the configuration.
The panel has a **Preview** (*Förhandsgranska*) that runs the query against real data. It only updates once the condition has been applied in the panel.
## The dimensions matrix
The dimensions matrix lists the dataset's dimensions with their properties nested below them, followed by a **Global** section with three rows: **Value types** (*Värdetyper*), **References** (*Referenser*) and **Plan data** (*Plandata*). The Global rows are used as sources for initial values and locked values (see below).
The columns are:
| Column | Swedish label | Purpose |
|---|---|---|
| Initial values | *Initiala värden* | expansion rules, organised in sets |
| Locked values | *Låsta värden* | lock rules, organised in sets |
| Data filter | *Datafilter* | dataset filter |
| Expressions | *Uttryck* | computed dimension values |
| Display as | *Visa som* | display format |
| Sort by | *Sortera efter* | sort key and method |
A cell shows a badge with the number of selected values, or **+** when empty. The checkbox in the left column controls whether a property is exposed as a column in the dataset. It is independent of the rule columns: a property can drive initial values or locks without being visible to the user.
### Display as
**Display as** sets how dimension values are labelled. The default is *Inherited from dimension* (*Ärvd från dimension*) or *Inherited from property* (*Ärvd från egenskap*), that is, the format set on the dimension itself. Display formats are configurable per tenant. The four standard formats are:
| ID | Format |
|---|---|
| 1 | `{Code} - {Name}` |
| 2 | `{Name} - {Code}` |
| 3 | `{Code}` |
| 4 | `{Name}` |
### Sort by
**Sort by** chooses the sort key, **Code** or **Name**, and the method: `Natural` (default; "Month 2" before "Month 10") or `Alpha` (plain character order). The GUI shows, for example, *Name (natural)* (*Namn (naturlig)*). Value types and data types have their own sort settings.
## Initial values
A value type only contains the dimension combinations that have data, sometimes none at all. To plan, users need rows to type into before data exists. **Initial values** (*Initiala värden*) define how data is expanded, cartesian when several dimensions are involved, to create these placeholder rows.
Initial values are a **generating** mechanism, not a filter. Valid dimension combinations are not maintained as a separate register. They are borrowed from data that already exists (the dataset's own value types, a reference or another value type) and expanded against the dimensions you want to plan in.
Placeholder cells are shown with the line state *Initial values* (*Initialvärde*) in the Inspect panel until someone enters a value. Presentation rules can style them separately.
### Sets
Initial values are organised in **sets** (*SET 1*, *SET 2* …; add more with **+**). Each set is a separate rule:
- **Within a set**, the result is expanded as a cartesian product across dimensions. Several selections within the same dimension (for example two properties, or a property and dimension values) give the intersection of those selections. The editor marks this with an `&` badge and the tooltip *"An intersection of the selected values in the dimension will be used"* (*Ett snitt av de valda värdena i dimensionen kommer att användas*).
- **Across sets**, each set is expanded on its own and the result is the union of all sets.
### Value sources per dimension
For each dimension or property in a set, the values can come from three sources. In the panel, choose explicit values, or **All values in** (*Alla värden i*) with the option **Property** (*Egenskap*) or **Dataset**.
| Source | Configuration | Values used |
|---|---|---|
| Specified values | `SpecifiedValues` | exactly the selected codes |
| All values in dimension or property | `AllValuesInDimension` | every value in the dimension or property, whether or not it occurs in the dataset |
| Values in dataset | `ValuesInDataset` | only the values that occur in the dataset's data |
Expanding over *all* values of a large dimension can create many rows.
### Global sources
The three Global rows add sources of dimension combinations to a set:
| Row | Meaning |
|---|---|
| **Value types** | which of the dataset's value types get placeholders; ⚹ means all value types (`ExpandAllValueTypes`) |
| **References** | expand from a reference: *"reference data as a set of initial values based on the reference's own plan data, shown in addition to data from this dataset"* |
| **Plan data** | expand from other value types outside the dataset; each selected value type must contain **all** dimensions of the dataset |
### Example
A dataset has `Amount` on `Account` × `Department` × `Month`. The dimension `Month` has a property `OpenForPlanning`, and there is a reference with last year's actuals.
| Set | Selections | Result |
|---|---|---|
| SET 1 | Value types = `Amount`; References = actuals; `Month.OpenForPlanning` = `1` | one input row for every `Account` × `Department` combination found in the actuals, in every month open for planning |
| SET 2 | Value types = `Amount`; `Account` = `4010`, `4020`; `Department` = all values in dimension; `Month.OpenForPlanning` = `1` | rows for two specific accounts in every department, in every open month |
The app shows the union of both sets, without anyone maintaining a list of valid combinations.
### Dimensions a set does not name
A set expands only the dimensions it names. Every other dimension is taken from the **combinations that already exist in the data**, not from all values of the dimension. For example, a set that names three accounts in a dataset with two existing department-and-month pairs gives 3 × 2 rows. Adding *All values in dimension* for `Month` to the set expands months fully as well.
Rows created by initial values are placeholders: they show 0 and are not stored until a user enters a value.
### Initial values and performance
Initial values do not change how much data is loaded from the server. The expansion runs in the client and is fast, even for very large datasets. What initial values do change is the **size of the dataset the tables are built from**: every placeholder row is a row in the client. Large expansions therefore slow down rendering somewhat and increase memory use considerably.
!!! tip "Keep expansion sets tight"
Expand only the combinations users actually plan in. Scope sets with properties and flags (active employees, open months, projects in planning) rather than *All values in dimension* on large dimensions.
## Locked values
**Locked values** (*Låsta värden*) mark cells that users cannot edit. They use the same set structure as initial values, without the expansion sources: within a set the selections combine (intersection within a dimension), and each set locks its own cells. The result is the union of the cells all sets point to.
Example:
| Set | Selections | Locks |
|---|---|---|
| SET 1 | `Month.Closed` = `1` | all closed months, for every value type |
| SET 2 | Value types = `AmountActual`, `HeadcountActual` | the two actuals value types, in every month |
Locked cells are shown with a grey background, and hovering or right-clicking shows *"This value is read-only (Locked by Locked Values)"*. Reference data is always read-only in apps, so a data-type selection in a lock rule is ignored. See [Using apps](end-user.html#why-a-cell-is-read-only).
## Dataset filter
The **data filter** (*Datafilter*) restricts the dataset to selected dimension values or property values, for example only departments in one region. Data outside the filter is not part of the dataset, so the filter applies to every component that uses it, unlike component filters. See [Workspaces and components](components.html#component-filters).
## Expressions
An **expression** (*Uttryck*) creates a computed dimension value in the dataset. It can be placed on any dataset dimension:
- on the value type dimension, it adds a computed "value type" row or column such as `Amount per head`;
- on `Month`, it adds a computed period such as `Q1` = January + February + March;
- on a property, it adds a computed property value.
The expression returns a value for every combination of the other dimensions. Structurally, expression rows equal stored rows.
### Expression settings
| Setting | Swedish label | Configuration | Values |
|---|---|---|---|
| Code | *Kod* | `DatasetDimensionValueCode` | code of the computed value |
| Name | *Namn* | `DatasetDimensionValueName` | display name |
| Format | *Format* | `Format` | see table below |
| Decimals | *Decimals* | `Precision` | decimals shown |
| Aggregation | *Aggregering* | `Aggregation` | `Sum` · `Min` · `Max` · `Avg` · `Quot` · `Disabled` |
| Omit null rows | *Utelämna null-rader* | `OmitNullRows` | when on, rows or columns where the expression is null are removed from the grid structure |
| Format code | Meaning |
|---|---|
| 1 | Number |
| 2 | Percent |
| 3 | Date |
| 4 | Date and time |
| 6 | Text |
`Quot` exists only for expressions. It is intended for ratios, which cannot be summed up a hierarchy. The GUI shows it as *Weighted average* (*Viktat snitt*). On subtotal and total rows, `Quot` divides the aggregated numerator by the aggregated denominator: for price = amount / quantity, a total is sum(amount) / sum(quantity), not the sum or average of the row ratios.
### Standard and LegacyQuot
| Type | Meaning |
|---|---|
| `Standard` | a Kex Lite expression (v2 plans) |
| `LegacyQuot` | a numerator/denominator pair from v1 plans; in v2 the same thing is written as a `Standard` expression |
### Kex Lite and the generated context
Expressions are written in **Kex Lite**, the expression form of Kex. See the [Kex Lite reference](https://acme.konstrukt.app/api/documentation/kex-lite). The editor shows a collapsed `// Context:` block at the top. Expanded, it shows how the expression is evaluated:
```kex
// Context:
dim DataType = $slice.DataType limit 1
dim Department = $slice.Department limit 1
dim Month = $slice.Month limit 1
var ValueType = pivot($slice, "ValueType")
if (ValueType.Headcount == 0, null, ValueType.Amount / ValueType.Headcount)
```
- `$slice` is the cell's slice of the data.
- Every other dimension is bound to a single value (`limit 1`), including `DataType` (plan data or a reference).
- The dimension the expression sits on is **pivoted**, so its members become named fields (`ValueType.Amount`). On `Month`, the pivot would be over `Month` instead.
You write only the last line. The context is generated.
On a dimension other than the value type, members are referenced the same way, with the code in brackets. A computed quarter on `Month`:
```kex
Month.[202601] + Month.[202602] + Month.[202603]
```
### Writeback
By default, an expression cell is read-only. A **writeback expression** makes it editable by describing how an entered value maps back to a stored value type:
| Setting | Configuration | Meaning |
|---|---|---|
| Expression | `Expression` | Kex Lite expression evaluated on the entered value, `$input` |
| Destination | `DatasetDimensionValueCode` | the stored value type (or dimension value) the result is written to |
| Spread | `SpreadOverride` | spread type for the write, see [Spreading](#spreading) |
| Edit precision | `EditPrecisionOverride` | decimals accepted on input |
Example: the dataset stores `Price` and `Quantity`. An expression `Revenue` is defined as
```kex
ValueType.Price * ValueType.Quantity
```
with the writeback expression
```kex
$input / ValueType.Price
```
and destination `Quantity`, spread `Proportional`. When a user types a revenue figure, the system calculates the corresponding quantity, writes it to `Quantity` and spreads it proportionally. `Revenue` itself is never stored. Other expressions that depend on `Quantity`, and all totals, are recalculated in the view.
If no spread is given, the writeback inherits the spread of the input value type. Expressions on the value type dimension create a virtual value type of their own and should always have an explicit spread.
Writeback is turned off with **Turn off writeback expression** (*Stäng av writeback-uttryck*). A cell from an expression without writeback shows *"This value is read-only (The expression has no writeback)"*.
## Row-level access
Each dataset has its own row-level access, set under **Settings → App access** (*Inställningar → Appåtkomst*):
| Mode | Configuration | Meaning |
|---|---|---|
| Inherit | `Inherit` with `EnableDimensionBasedAccess` | use the app's access list as is; `EnableDimensionBasedAccess` requires the dataset to contain all dimensions configured in the app's access list, when that list uses dimension-based access |
| Limit | `Limit` with `AccessListId` | use a specific access list for this dataset |
Both modes have `ReadOnly`, which makes the whole dataset read-only (*Read access* / *Read and write access*, *Läsåtkomst* / *Läs- och skrivåtkomst*). The GUI offers *Inherit from app*, *Full* and *Choose list* (*Ärv från app* / *Full* / *Välj lista*). Without explicit settings, the dataset inherits with dimension-based access if the app has an access list, and otherwise gives full access.
The GUI choices map to the configuration as follows:
| GUI | Configuration |
|---|---|
| *Läs- och skrivåtkomst* + *Full* | `{"$type": "Inherit", "EnableDimensionBasedAccess": false, "ReadOnly": false}` |
| *Läsåtkomst* | the same, with `"ReadOnly": true` |
| *Ärv från app* | `Inherit` with `EnableDimensionBasedAccess: true`. The choice is disabled when the app has no access list. |
| *Välj lista* | `Limit` with `AccessListId` |
## Related
- [Workspaces and components](components.html)
- [Using apps](end-user.html)
- [App configuration (XML/JSON)](app-config.html)
- [Data model](data-model.html)
- [Kex](kex.html)
---
# Workspaces and components
> How workspaces organise filters, data types and layout, and how tables, text, metrics, charts and presentation rules are configured.
A workspace (*Arbetsyta*) is one screen of an app: a filter row, a choice of data types, and a layout holding components such as tables, text, metrics and charts. End users switch between workspaces with a selector at the top. Every data component reads from one [dataset](datasets.html).
## Workspaces
A workspace has a name, a hidden flag, and six tabs in the editor: **Components** (*Komponenter*), **Filters** (*Filter*), **Data type / references** (*Datatyp / referenser*), **Value types** (*Värdetyper*), **Actions** (*Handlingar*) and **Layout**. Actions are described in [Actions](actions.html).
### Filters
The **Filters** tab defines the workspace filter row. A filter can be on a dimension, a property, the data type or the value type. Each row has a three-state switch:
| State | Swedish label | Configuration |
|---|---|---|
| Unavailable | *Otillgänglig* | the filter is absent from the workspace filter list |
| Available | *Tillgänglig* | the filter is present |
| Required | *Obligatoriskt* | the filter is present and marked as required |
The order in the tab (drag and drop) is the order users see. Only one filter per dimension is kept. Dimension and property filters have their own **Display as** and **Sort by** settings. Selections are carried in the app URL; see [Using apps](end-user.html#the-app-frame).
#### Required filters
A required filter is configured in the side panel **Filter requirement** (*Filterkrav*):
| Setting | Swedish label | Configuration (JSON) |
|---|---|---|
| Message | *Meddelande* | `Message` |
| Maximum number of selected values | *Maxantal valda värden* | `MaxSelections` |
| Make required for all components | *Gör obligatorisk för alla komponenter* | `AllComponents` |
| Components | chips | `Components[]` |
Until a value is selected, the affected components show the message instead of data, for example *"Select a department"* with maximum 1 on a large table. Requirements can also be put on data-type and value-type filters.
### Data types and references
Apps treat plan data and references as members of a virtual dimension, `DataType`. Its codes are:
| Code | Meaning |
|---|---|
| `Plan` | plan data |
| `Reference_` | a reference in the plan, for example `Reference_12`. Metrics and URLs use the bare ID instead, see [Metric](#metric) |
| *(custom string)* | a custom data type created by a dataset expression on the `DataType` dimension |
The **Data type / references** tab decides which data types the workspace offers.
Plan data has four modes:
| Mode | Meaning |
|---|---|
| `Selected` | offered and pre-selected in the filter |
| `Hidden` | not shown |
| `Required` | users must filter to it; the GUI shows *Required* (*Obligatoriskt*) |
| `Allowed` | offered but not pre-selected |
`UsePlanName` shows the plan's name instead of "Plan", and a name override can be set.
References have three states:
| State | Swedish label | Configuration |
|---|---|---|
| Default | *Förvald* | listed and selected |
| Available | *Tillgänglig* | listed, not selected |
| Unavailable | *Otillgänglig* | not listed |
The display order of data types is set by dragging them from *Unsorted* (*Osorterade*) into *Sorted* (*Sorterade*). Reference data is always read-only in apps. See [References and history](references-history.html).
### Value types
The **Value types** tab holds only display-name overrides and the display order of value types in the workspace.
### Layouts
The **Layout** tab chooses one of two layouts:
| Layout | Swedish label | Behaviour |
|---|---|---|
| `MultiPage` | *Flera sidor* | one component per page; users switch pages with a page selector |
| `Matrix` | *Rutnätslayout* | several components placed on a grid |
The `Matrix` layout is a **12-column grid**. Each component has a location (`X`, `Y`, `Width`, `Height`). The editor shows width and height as percentages: a width of 12 columns is *100 %*, and a height of 5 units is *50 %* (10 units = 100 %). Components can be hidden individually.
Layout **Settings** (*Inställningar*) for the grid layout are **Background** (*Bakgrund*) and **Border** (*Kantlinje*), each an on/off switch with a colour for light and dark mode, and **Spacing** (*Avstånd*): `Minimum`, `Small`, `Medium` (default) or `Large`, stored by name. In a multi-page layout, pages can be hidden from the page selector.
## Component types
| Type | GUI (*Typ*) | Purpose |
|---|---|---|
| `Grid` | Table (*Tabell*) | editable table with groupings, pivots, totals and presentation rules |
| `Label` | Text (*Text*) | static text, plain or Markdown |
| `LayoutableAction` | Layoutable action (*Layoutbar åtgärd*) | places an existing action component in the layout instead of the sidebar |
| `Metric` | Metric (*Mätvärde*) | a KPI box with one value and an optional comparison |
| `BarChart` | Chart → Bar (*Diagram → Stapel*) | bar chart |
| `LineChart` | Chart → Line (*Diagram → Linjer*) | line or area chart |
| `PieChart` | Chart → Pie (*Diagram → Cirkel*) | pie chart |
| `WaterfallChart` | Chart → Waterfall (*Diagram → Vattenfall*) | waterfall (bridge) chart |
| `TreeMapChart` | Chart → Treemap (*Diagram → Trädkarta*) | treemap |
Every component has an ID, a name (shown as the title in a grid layout) and **Show headers** (*Visa rubriker*, `HideHeader`).
### Text
A `Label` component shows text from `Content`. `Format` is `Text` (default) or `Markdown`. Raw HTML is never rendered.
### Layoutable action
A `LayoutableAction` has no logic of its own. It points to an action component by `ActionComponentId` and shows it in the layout.
In the app, a layoutable action renders as an inline form titled with the component name: the action's fields, a *Keep values* toggle (*Behåll värden*), the run button and *Clear* (*Rensa*). Unless the action is hidden from the sidebar, it also appears as a vertical tab at the right edge. The tab has a *Keep open* toggle (*Behåll öppen*) instead. The action's script writes to the plan the app belongs to.
## Tables
A table (`Grid`) is the main editing component. Its **Settings** tab has a *Functions* section (*Funktioner*):
| Setting | Swedish label | Values |
|---|---|---|
| Row totals | *Radsummor* | Left · Right · Disabled (`Left`, `Right`, `Disabled`) |
| Auto-size columns | *Automatisk storlek på kolumner* | Disabled · Cell content · Grid width (`Default`, `FitCellContents`, `FitGridWidth`) |
| Column totals | *Kolumnsummor* | Enabled · Disabled (`EnableColumnTotals`) |
Further flags: `EnableUserConfig` lets users change their own column setup with *Edit* in the component menu, and `EnableComments` allows cell comments.
### Groupings, intermediaries and pivots
A table has three axes:
| Axis | Swedish label | Role | Settings |
|---|---|---|---|
| Groupings | *Grupperingar* | row groups with subtotals, shown in a merged group column | `EnableEdit` |
| Intermediaries | *Intermediaries* | row dimensions shown as their own columns between groups and values | `EnableEdit`, `Link` |
| Pivots | *Pivots* | dimensions turned into columns | `SortDirection` (`Ascending`, `Descending`) |
Each axis entry is one of four kinds: a **dimension**, a **property** of a dimension, the **value type** dimension, or the **data type** dimension. A typical budget table has the value type as grouping, `Account` and `Department` as intermediaries, and `Month` as pivot.
`EnableEdit` on an intermediary makes the column editable, so users can change, for example, the account of a row directly in the table.
#### Dimension links
An intermediary can carry a **link**. Clicking a dimension value then navigates to a component (`NavigateToComponentId`), optionally in another workspace or app (`NavigateToWorkspaceId`, `NavigateToAppId`). `FilterToSelectedValue` filters the target to the clicked value, `IncludeGroupingsInFilter` also passes the row's grouping values, and `OpenInNewTab` and `HideIcon` control how the link opens and shows.
### Component filters
Component filters limit what **this component** shows from its dataset. They are evaluated client-side and do not change the dataset. A filter is a list of sets. Each set has a mode:
- `Include`: show only the selected values;
- `Exclude`: show everything except the selected values.
A set can contain several dimension and property filters, and at most one value type filter and one data type filter. All sets in the list apply together.
Component filters let several components share one dataset. Two tables on the same dataset can each show one value type, for example one showing `Amount` and one showing `Headcount`, while initial values, locks and expressions are maintained once.
### Column settings
The **Columns** tab (*Kolumner*) stores per-column settings. There are two kinds:
| Kind | Identified by | Settings |
|---|---|---|
| `Column` | `Id` (XML `Value`) | `Enabled`, `NameOverride`, `Width`, `SortIndex`, `SortDirection`, `Pinned` |
| `ColumnGroup` | `Id` | `Enabled`, `NameOverride`, `Pinned` |
`Pinned` is `Left` or `Right`. Column IDs follow the pattern `[~]`, for example `Month~202601` for one pivoted month or `ValueTypeId~Amount` for a pivoted value type. The full grammar is in [App configuration](app-config.html#column-setting-ids).
A `ColumnGroup` is a pivot group header, for example one month above its value-type columns. Column-group settings are created by end users with edit rights in the app, not in the admin **Columns** tab: **Edit** (the pencil), then the menu on a group header offers *Fästning grupp* (pin group) and *Ändra namn* (rename). Saving writes for example:
```json
{"$type": "ColumnGroup", "Id": "TestMonth~202601", "Enabled": true,
"NameOverride": "Jan 2026", "Pinned": "Left"}
```
### Value type overrides
The tab **Custom aggregations and spreads** (*Egna aggregeringar och spridningar*) overrides aggregation and spread for a value type **in this component only**, optionally per dimension or property. Example: show `Headcount` summed over departments but not aggregated over months, or turn off aggregation for a date value type.
```json
{"ValueTypeId": "Headcount",
"Dimensions": [{"$type": "Dimension", "DimensionId": "Department", "Aggregation": "Sum"}]}
```
### Header template
`HeaderTemplate` defines a dynamic component header. Placeholders: `{planName}`, `{appName}`, `{appStatus}`, and `{currentSelections_Code}` / `{currentSelections_Name}` for the codes or names of the currently selected cells.
### External links
`ExternalLinks` define links to other systems built from the row's dimension values. `Pattern` is a URL template with `{}` placeholders. On a group row, the placeholder expands to the values of the child rows, joined with `Delimiter`:
```json
{"Title": "Open in project system",
"Pattern": "https://projects.example.com/?ids={Project}",
"Delimiter": ","}
```
External links appear in the cell's right-click menu and open in a new browser tab.
!!! warning "Placeholder syntax"
Use `{DimensionId}`. The `{d_DimensionId}` form described in the configuration schema produces no link.
### App links (drill-through)
An **app link** turns the values of an intermediary column into links to another app, workspace or component, for drill-through to a detail view. It is set on the intermediary's settings:
```json
{"$type": "Dimension", "DimensionId": "Month",
"Settings": {"$type": "Intermediary", "EnableEdit": false,
"Link": {"NavigateToAppId": "", "NavigateToWorkspaceId": 3,
"NavigateToComponentId": "6", "FilterToSelectedValue": true,
"IncludeGroupingsInFilter": true, "OpenInNewTab": false, "HideIcon": false}}}
```
| Setting | Effect |
|---|---|
| `NavigateToAppId`, `NavigateToWorkspaceId`, `NavigateToComponentId` | The target. Leave out the app to link within the same app. |
| `FilterToSelectedValue` | Pass the clicked value as a filter |
| `IncludeGroupingsInFilter` | Also pass the values of the grouping levels above the row |
| `OpenInNewTab` | Open the target in a new tab |
| `HideIcon` | Hide the link icon next to the value |
Clicking a value opens the target with the values in the URL, for example `?Month=202602&Account=A1&componentId=6`, and the target shows a back arrow to the source. The values only filter the target where its workspace has a filter for that dimension.
Link values are styled with the presentation-rule target `Link`.
## Presentation rules
Presentation rules (*Presentationsregler*) style table cells based on what they contain and where they come from. The editor's own summary: *"Create custom styles based on conditional statements. When conditions overlap, later entries override earlier ones."* Order matters: rules are dragged into order, and **a later rule overrides an earlier one**.
Each rule has a **name** (*Namn*), an **enabled** switch (*Aktiverad*), the **targets** it applies to (*Applicera på*), optional filters on **line state** (*Applicera på radstatus*) and **access type** (*Applicera på accesstyp*), further **conditions** (*Villkor för applicering*), and **effects** (*Effekter*) such as background and font colour.
The **Example** column (*Exempel*) in the rule list shows a live preview of each rule's style. **Reset default styles** (*Återställ standardstilar*) restores the default rules.
### Targets
| Target | Applies to |
|---|---|
| `Leaf` | value cells at the lowest level (*Löv*) |
| `RowTotal` | row total cells (*Radtotal*) |
| `Group` | cells on group rows (*Grupp*) |
| `GroupRowTotal` | row totals on group rows (*Grupp radtotal*) |
| `ColumnHeader` | the header row, including dimension column headers |
| `Footer` | the column-totals row at the bottom (*Gridfot*) |
| `PivotColumn` | pivoted columns; used with *Visibility* to hide a column, for example one value type or expression, scoped with the rule's value-type selection |
| `RowTotalColumn` | the row-total column; used with *Visibility* to hide it |
| `GridDimensionGrouping` | the grouping column, on group rows and leaf rows |
| `GridDimensionIntermediary` | the intermediary (row-leaf) columns |
| `Row` | whole rows, including group rows; with *Sequence pattern* every row, odd or even rows |
| `Link` | dimension values that are [app links](#app-links-drill-through) |
Verified behaviour:
- Rules are applied in list order, so a later `Row` rule overrides earlier column rules (`GridDimensionGrouping`, `GridDimensionIntermediary`) on the rows it applies to.
- A hidden pivot column is still **included in the row total**. Hiding an expression column does not remove it from the total.
- Style settings on `RowTotalColumn` (such as font colour) have no effect; only *Visibility* does.
- A row total across value types requires the same aggregation for all of them. Mixing, for example, `Quot` and `Sum` gives *Can't aggregate ValueTypes (…) with different aggregations (Quot, Sum)* instead of a table.
Not every setting works on every target:
| Setting | Targets |
|---|---|
| Height | `ColumnHeader`, `Footer`, `Row` |
| Visibility | `PivotColumn`, `RowTotalColumn`, `Row` |
| Sequence pattern | `Row` |
| Value condition, line state, line access | `Leaf`, `RowTotal`, `Group`, `GroupRowTotal`, `Footer` |
| Other styles (colours, font, alignment) | all targets except `PivotColumn` and `RowTotalColumn` |
### Line state and line access
Line state records where a cell's value comes from:
| Code | Line state | Swedish label | Meaning |
|---|---|---|---|
| 0 | `Suggested` | *Föreslagen* | recently imported, or written by a suggestion calculation (`write suggestion to`); users can overwrite it |
| 10 | `Edited` | *Redigerad* | entered by a user |
| 30 | `Calculated` | *Beräknad* | written by a calculation |
| 40 | `InitialValues` | *Initiala värden* | a placeholder from [initial values](datasets.html#initial-values), not yet filled in |
| Code | Line access | Swedish label |
|---|---|---|
| 1 | `Read` | *Läs* |
| 2 | `ReadWrite` | *Läs/Skriv* |
With line state in rules, a cell shows whether its number was entered, suggested, calculated, or is an empty slot. See [Traceability](traceability.html).
### Value conditions
A rule can have a value condition (*Värdevillkor*), decimal or string, with a first comparison and an optional second comparison joined by `And` or `Or`:
| Type | Comparisons |
|---|---|
| Decimal | `Equal` · `NotEqual` · `GreaterThan` · `LowerThan` · `Exists` |
| String | `Equal` · `NotEqual` · `Match` · `Exists` |
Example: highlight values *Greater than 100000* in red to flag outliers.
### Sequence pattern
`SequencePattern` (`Every`, `Odd`, `Even`) applies only to the `Row` target and is used for row banding. Banding takes **two** rules, one `Odd` and one `Even`, each with its own background colour.
### Scoping to specific data
A rule can be limited to specific dimension values, property values, value types or data types. Examples:
- style the value type `AmountActual` in a different colour from the budget rows;
- strike through closed periods: scope to `Month.Closed` = `1` with font decoration `LineThrough`.
### Styles
Available effects: font colour and background colour (each with a light-mode and a dark-mode value), font weight (`Normal`, `Bold`), font style (`Normal`, `Italic`), font decoration (`None`, `Underline`, `LineThrough`), font size, horizontal alignment (`Start`, `Center`, `End`), vertical alignment (`Top`, `Center`, `Bottom`), and, on targets that support them, height and visibility (`Visible`, `Hidden`).
Colours are hex values stored **without** a leading `#`, for example `1F9AAD`.
### Default rules
New apps get three default rules, identified by a default rule key instead of a name:
| Key | Swedish label | Matches | Typical style |
|---|---|---|---|
| `Suggested` | *Föreslaget värde* | line states Suggested and Initial values, access Read/Write | font `1F9AAD`, dark mode `00bcd4` |
| `ReadOnly` | *Skrivskyddat* | access Read | font `595959` (dark `bdbdbd`), grey background |
| `Calculated` | *Beräknat värde* | line state Calculated | font `595959` (dark `bdbdbd`) |
The default rules target `Leaf`, `RowTotal`, `Group`, `GroupRowTotal` and `Footer`. Their exact colours can differ between apps. The `ReadOnly` rule is what makes locked and read-only cells grey. Custom rules placed after the default rules override them.
## Metric
A `Metric` is a KPI box. It shows `ValueTypeId` from `DatasetId` in one data type (`DataType`: `Plan`, or a reference given by its bare ID, for example `"12"`). `Unit` is `Custom` with a free label (for example "FTE") or `Currency` with an ISO 4217 code and optional label. `Compare` adds an optional comparison value.
`Icon` takes a name from a fixed list (see below). An unknown icon name is **silently removed** when the configuration is read.
The comparison is shown next to the main value as a target or reference:
| Compare type | Compares with |
|---|---|
| `ValueType` | another value type |
| `DataType` | the same value type in another data type, for example plan against a budget reference |
| `UserSelectDataType` | the data type the user has currently selected in the workspace's data-type filter |
Each comparison has `Mode` (`Difference` for the absolute difference, `Relative` for the relative difference), an optional name override, and three colour pairs (light/dark): `Color` (equal), `PositiveColor` (greater) and `NegativeColor` (smaller).
In the app, the comparison is shown as a pill next to the value: green with ▲ and a plus sign when greater, red with ▼ when smaller, grey with — when equal. `Relative` is (value − comparison) / comparison.
!!! warning "Reference codes in metrics"
In `Metric.DataType` and `Compare.DataType`, a reference is identified by its bare ID (`"12"`), which is also what the editor saves. `"Reference_12"` is accepted but silently compares against nothing.
The client renders these icon names:
`Search` · `Time` · `Calendar` · `Done` · `Visibility` · `Key` · `Lock` · `Power` · `Construction` · `Carpenter` · `Money` · `CurrencyExchange` · `PriceTag` · `ShoppingCart` · `Savings` · `AccountBalance` · `Balance` · `Business` · `Store` · `Portfolio` · `Calculate` · `CardMembership` · `AutoGraph` · `BubbleChart` · `LineChart` · `WaterfallChart` · `Numbers` · `Person` · `People` · `Handshake` · `Call` · `Mail` · `Comment` · `Campaign` · `ThumbUp` · `ThumbDown` · `SentimentVerySatisfied` · `SentimentSatisfied` · `SentimentNeutral` · `SentimentVeryDissatisfied` · `RocketLaunch` · `Car` · `Restaurant` · `Hotel` · `Dice` · `Camera` · `Computer` · `Rocket`
!!! warning "User-selected comparison"
A `UserSelectDataType` comparison could not be made to work in testing: the metric shows *Obligatoriskt filter är inte uppfyllt* (required filter not satisfied). Use `DataType` with a fixed reference until this is resolved.
## Charts
Charts read from a dataset like tables do. Common settings are tooltips, value labels, a palette (the current theme, or user-defined colours) and a legend (hidden, or at the left, top, right or bottom).
Most charts have a **category axis**, which takes a dimension, a property, the value type or the data type, and a **value axis**, which takes a list of value types with linear or logarithmic scaling. Both axes can be moved to the opposite side, reversed, and given grid lines, tick marks and a label. An optional `Series` splits the data by a further dimension or property. Non-numeric value types can only be plotted through a numeric aggregation such as a count.
| Chart | Specific settings |
|---|---|
| Bar | `Layout` (`Vertical`, `Horizontal`), `Stacking` (`None`, `Stacked`) |
| Line | `Mode` (`Lines`, `Area`, `StackedArea`), `Curve` (`Natural`, `Linear`, `Step`), `ConnectEmptyValues`, `ShowMarkers` |
| Pie | `Values` (value types) and `Series` instead of axes |
| Waterfall | `LockedAtZeroCodes` (bars that start at zero, such as opening and closing balances), `Color`, `IncreaseColor`, `DecreaseColor` |
| Treemap | category axis for the boxes; value axis for box size |
When a chart shows several value types, use the value type dimension as category or series so the values can be told apart.
!!! note "Charts are a tenant feature"
The tenant feature list includes Charts (*Diagram*). If the chart types are missing in the component type list, the feature may not be enabled for the tenant. See [Administration](administration.html).
## Related
- [Datasets](datasets.html)
- [Actions](actions.html)
- [Using apps](end-user.html)
- [App configuration (XML/JSON)](app-config.html)
- [Traceability](traceability.html)
---
# Actions
> How action components collect input from users and run a Kex write script, including the generator templates, variable types and script conventions.
An action component (*Handling*, configured on the workspace tab **Actions**, *Handlingar*) is a small form that runs a Kex script. It consists of **variables**, which the user fills in, and a **script**, which runs with those values when the user presses the run button. Typical actions add a new dimension value together with its first data, remove rows, or move values between dimension values.
Actions are shown to end users in the sidebar of the workspace, as vertical tabs along the right edge. They can also be placed in the layout with a `LayoutableAction` component (see [Workspaces and components](components.html#layoutable-action)).
```flow
User | fills in variables -> Action component | @Variables bound to input -> Kex write script | write insert / replacement / update -> Value types and dimensions | data changed, calculations follow
```
## Action settings
| Setting | Swedish label | Configuration | Meaning |
|---|---|---|---|
| Name | *Namn* | `Name` | title of the action |
| Description | *Beskrivning* | `Description` | help text shown with the form |
| Run button label | *Knappetikett* | `RunButtonLabel` | text on the button; optional |
| Show in sidebar | *Visa i sidofält* | `HideInSidebar` (inverted) | whether the action is listed in the sidebar |
| Variables | *Variabler* | `VariableInputs` | the input fields |
| Script | *Skript* | `Script` | the Kex script |
Action names must be unique within the workspace. Older configurations that contain duplicate names are given unique names when read.
### Groups
Actions can be collected in an **action group** (`ActionComponentGroup`), which shows them under a common heading in the sidebar. A group has only an ID, a name and a description. It has no logic of its own. Actions can also be placed directly on the workspace without a group.
## The generator
Actions are rarely written from scratch. **Create → Component** (*Skapa → Komponent*) opens **Generate action component** (*Generera åtgärdskomponent*) with three templates:
| Template | Swedish label | Generates |
|---|---|---|
| Add | *Lägg till* | creates new dimension values and writes initial data |
| Remove | *Ta bort* | removes rows from selected value types |
| Custom action | *Anpassad åtgärd* | an empty component; you write the script yourself |
For *Add* and *Remove*, the wizard first asks for the **value types** that rows should be added to or removed from. It then shows **one tab per dimension** of the selected value types. For each dimension, choose a type (*TYP*):
| Type | Swedish label | Effect |
|---|---|---|
| New | *Ny* | the action creates a new dimension value |
| Existing | *Befintlig* | the user selects an existing value; becomes a `Dimension` variable |
| Fixed | *Fixed* | a hard-coded value; no input |
A dimension set to **New** opens two further choices:
- which **properties** the user should fill in for the new value, each again as New, Existing or Fixed;
- the toggle **Require code for new dimension value** (*Krav på kod till nytt dimensionsvärde*). When it is off, the code is derived from the name with `makecode`.
The generator produces both the variable list and the script. Both remain **fully editable** afterwards: the script field is a normal Kex editor with a validity indicator. A generated script is a starting point, not a locked template.
### Example: Add
*Add* on the value type `Amount`, with `Project` as New (including the property `Region`) and `Department` as Existing, produces the variables `@Project.Name` (text, format Name), `@Project.Region` (property), `@Department` (dimension) and `@Amount.Value` (numeric), and a script of this shape:
```kex
scalar [Project.Code] = makecode(@Project.Name) within (Project)
if any (Project == [Project.Code]) {
fatal `Project '{[Project.Code]}' already exists.`
}
write insert to Project <- Project = [Project.Code], $name = @Project.Name,
[.Region] = @Project.Region
write insert to Amount <- @Amount.Value, Project = [Project.Code], Department = @Department
```
The script derives a code from the entered name, stops with an error message if a project with that code already exists, then creates the dimension value with its property and writes the first value. The exact generated text depends on the model.
### Example: Remove
*Remove* on the same value type produces:
```kex
write replacement to Amount <-
Amount.*
exclude calculated
where not (Project in @Project && Department in @Department)
```
How to read it:
- **Removal is written as a rewrite.** `write replacement` replaces the contents of `Amount` with the result of the query, and the query is "all of `Amount` except the selected combination" (`where not (…)`). Rows that are not in the result are deleted.
- **`exclude calculated`** leaves calculated rows out of the query, so the replacement only concerns data entered by users or imported. Calculated rows are neither rewritten nor deleted by the action. They are maintained by their calculations.
- **`in` instead of `==`**, because the variables can be multi-select. With `Multiple` on, `@Project` can hold several projects, and the action removes all of them in one run.
See [Kex](kex.html#write-variants) for the write variants and how they behave inside and outside calculations.
The generator uses `exclude calculated`, `makecode(…) within (…)`, `if any (…) { … }` and `` fatal `…` ``. They are described under [Control flow and messages](kex.html#control-flow-and-messages) and [makecode](kex.html#makecode).
## Variables
Variables are the form fields of the action. The script refers to a variable as `@Identifier`.
| Variable type | Swedish label | Configuration | Value |
|---|---|---|---|
| Text | *Textvariabel* | `Text` | a string |
| Numeric | *Numerisk variabel* | `Numeric` | a number |
| Dimension | *Dimensionsvariabel* | `Dimension` | one or more values of a dimension |
| Property | *Egenskapsvariabel* | `Property` | one or more values of a dimension property |
All variables have an **identifier**, a **name** (the field label) and an optional **description**.
### Text variables
| Setting | Swedish label | Values |
|---|---|---|
| `Format` | *Format* | `Code` (*Kod*): validated as a dimension-value code · `Name` (*Namn*): validated as a dimension-value name · `FreeText` (*Fritt text*): any text |
| `MaxLength` | *Max antal tecken* | maximum number of characters |
| `Pattern` | *Mönster* | a regular expression the input must match |
### Numeric variables
| Setting | Values |
|---|---|
| `FormatCode` | `Number` or `Percent` |
| `Min`, `Max` | allowed range; optional |
### Dimension and property variables
| Setting | Swedish label | Meaning |
|---|---|---|
| `DimensionId` | *Dimension* | the dimension to choose from |
| `PropertyId` | *Egenskap* | property variables only: the property to choose from |
| `Multiple` | *Flera* | allow several values; use `in` in the script |
| `SortBy`, `SortingMethod` | | sort order in the picker |
| `DisplayFormatId` | *Visa som* | display format in the picker |
| `AccessListId` | *Behörighetslista* | limits the selectable values to those the user may access under the list |
| `Condition` | *Sätt filter* (funnel icon) | a Kex condition limiting the selectable values, edited in the same guided/Kex panel as the [value type condition](datasets.html#value-type-condition) |
!!! tip "Save before setting a variable filter"
The *Set filter* panel on a variable stays empty until the action has been saved once. Create the variables, save the action, and then configure the filters.
## The script
The script is ordinary Kex, usually with one or more `write` statements. See [Kex](kex.html). A few conventions:
- Refer to inputs with `@Identifier`. Generated identifiers follow the pattern `@` for existing values, `@.Name` for a new value's name, `@.` for properties, and `@.Value` for the numeric input.
- Use `write insert` for "create if not present", `write update` to change existing rows only, and `write replacement` with `where not` to remove.
- Validate with guard clauses (`if any (…) { fatal … }`) so that the user gets a clear message instead of a partial write.
- Calculations that read the changed value types run automatically after the action, like after any other data change. See [Calculations](calculations.html).
In the configuration, the script is stored in an **attribute** (`Script="…"`), not in an element. This is deliberate: it keeps line breaks and indentation intact.
!!! warning "Actions change data directly"
An action runs a write script against the plan when the user presses the button. Test new actions in a copy of the plan or on test dimension values, and prefer `write insert` and guarded scripts over broad `replacement` writes.
An action is **not part of the grid's undo history**: after it has run, no *Ångra* (undo) button appears. To reverse an action, run a counter-action or edit the values.
## Legacy action components
Configurations from older versions can contain `LegacyActionComponents`, a declarative predecessor (add, remove, change property value, move or copy plan data). In v2 plans they are removed when the configuration is read. Their content is not converted. Rebuild such actions with the generator.
!!! agent "Pitfalls for agents"
See the [Agent guide](agent-pitfalls.html#actions) for pitfalls when generating or editing action scripts.
## Related
- [Kex](kex.html)
- [Workspaces and components](components.html)
- [Using apps](end-user.html)
- [App configuration (XML/JSON)](app-config.html)
---
# Using apps
> What end users see and can do in an app: filters and URLs, personal settings (language, text size, theme), component and cell menus, cell inspection, read-only cells, comments and editing.
This page describes apps from the end user's side: how a view is selected and shared, what the menus offer, how a cell explains itself, and what happens when a value is entered. The configuration behind each behaviour is linked where relevant.
## The app frame
At the top of an app:
- the **filter row**, with the filters configured for the workspace in their configured order (see [Workspaces and components](components.html#filters));
- **Clear filters** (*Rensa filter*);
- a **workspace** selector;
- a **page** selector, when the workspace uses a multi-page layout;
- an information icon at the top right that opens the app's **description** (*Beskrivning*), usually written as instructions for users.
Actions are shown as vertical tabs along the right edge (see [Actions](actions.html)).
If a required filter has not been set, the affected components show the configured message, for example *"Select a department"*, instead of data.
### The URL carries the view
Filter selections, the workspace, the page or action and the data-type selection are all part of the URL:
```
/plans/{planId}/apps/{appId}/workspaces/{n}?Department=D100&DataTypes=12,Plan
```
Filters appear as query parameters in the form `?=`, and `DataTypes` lists the selected references by ID together with `Plan`. A view is therefore addressable: copy the URL to share exactly what you are looking at, including filters and data types.
## User settings
The gear icon at the top right opens **Settings** (*Inställningar*). These are personal settings for the signed-in user:
| Setting | Swedish label | Options |
|---|---|---|
| Language | *Språk* | English, Swedish (*Svenska*) |
| Text size | *Textstorlek* | Small (*Liten*), Medium, Large (*Stor*) |
| Theme | *Tema* | Dark mode (*Mörkt läge*), System, Light mode (*Ljust läge*) |
Changes take effect with **Apply** (*Verkställ*). **Logout** (*Logga ut*) is in the same panel.
- **Language** switches all system texts. Names defined in the model — dimensions, value types, apps, workspaces, actions — are shown as they were entered and are not translated.
- **Theme** *System* follows the operating system's light or dark setting. Colours in presentation rules and layouts have separate light and dark values, see [Presentation rules](components.html#presentation-rules).
Next to the gear icon, users with the right privileges see **Act as** (*Agera som*) for viewing the product as another role (see [Security](security.html)), plus notifications, admin tools and the help menu.
## Component menu
Every component has a menu that expands into a row of icon buttons:
| Button | Swedish label | Effect |
|---|---|---|
| Export | *Exportera* | exports the component's data |
| Edit | *Ändra* | the user's own column configuration; only when the component allows user configuration |
| Hide zeros | *Dölj nollor* | hides rows that contain only zeros |
| Reload | *Ladda om* | reloads the component's data |
| Full screen | *Fullskärm* | shows the component in full screen |
## Cell context menu
Right-clicking a table cell opens a context menu. The menu adapts to the cell: *Cut* is missing on read-only cells, and *Evaluate expression* only appears on expression cells.
| Entry | Swedish label | Effect |
|---|---|---|
| Cut, Copy, Paste | *Klipp ut*, *Kopiera*, *Klistra in* | clipboard operations |
| Copy with headers | *Kopiera med rubriker* | copies the selection including row and column headers |
| Copy with grouped headers | *Kopiera med grupperade rubriker* | also includes grouping headers |
| Expand/collapse selected rows | *Expandera/Kollapsa valda rader* | opens or closes groups |
| Auto-size selected columns | *Automatisk storlek på valda kolumner* | fits column widths to content |
| Use as filter | *Använd som filter* | intended to filter on the cell's dimension values, see below |
| Inspect cell | *Inspektera cell* | opens the Inspect panel |
| Write comment | *Skriv kommentar* | opens the comments panel for the cell |
| Evaluate expression | *Utvärdera uttryck* | shows an expression cell's formula and result |
!!! warning "Use as filter (known issue)"
*Use as filter* is intended to set a filter on the combination of dimension values that forms the cell. It currently has no effect when used on a value cell, and only works when chosen on a dimension value. This is a known issue. The intended behaviour will be documented once it is fixed.
### Evaluate expression
**Evaluate expression** opens the **Evaluate** panel (*Utvärdera*), showing:
- the dimension and code of the expression;
- a link **Edit in app editor** (*Redigera i appeditor*) for administrators;
- the expression in a read-only editor, including the generated `// Context:` block (see [Datasets](datasets.html#kex-lite-and-the-generated-context));
- **Evaluations** (*Utvärderingar*): the actual result for this cell.
End users can thus see the formula behind a number, and its value for the selected cell, without administrator rights.
## Inspect panel
**Inspect cell** opens the side panel **Inspect** (*Inspektera*). It shows, for the selected cell, the configuration concepts that produced it.
### Cell information
| Field | Swedish label | Shows |
|---|---|---|
| Value | *Värde* | the unrounded value, full precision |
| Format | *Format* | the format code |
| Line access | *Linjeåtkomst* | Read or Read/Write (*Läs* / *Läs-Skriva*) |
| Line state | *Linjestatus* | Suggested, Edited, Calculated or Initial values |
| Reference | *Referens* | the data type: `Plan` or a reference |
| Aggregation | *Aggregering* | the value type's aggregation |
| Spread | *Fördelning* | the spread type |
| Display / edit precision | *Visa precision* / *Redigera precision* | decimals shown and decimals accepted |
| Dimension codes | *Dimensionskoder* | the cell's dimension values, each linking to the dimension value |
A placeholder created by [initial values](datasets.html#initial-values) shows line state *Initial values* until someone enters a value.
### Expression or value types
For a cell produced by a dataset expression, the panel shows the **expression**: code, the dimension it creates a value on, the expression text, name, aggregation, format and precision, and, if present, the **writeback expression** with its expression, destination code and spread code. A user can see from this where a typed value will be written.
For a stored cell, the panel shows the **value types** section instead.
### Presentation rules
The panel lists the presentation rules that **matched** the cell:
- the rule's name, with a link to the rule in the app editor;
- **why** it matched, for example *Access type: Read* or a scoped value type;
- the **targets** (*MÅL*) the rule applies to, in plain words, with the matching target highlighted;
- the resulting **CSS**, in one block for light mode and one for dark mode, for example `color: #595959; background-color: #eeeeee;`.
**Show all rows (n)** (*Visa alla rader*) expands the full list of candidate rules. Since later rules override earlier ones, this list explains why a cell looks the way it does. See [Presentation rules](components.html#presentation-rules).
## Why a cell is read-only
A cell that cannot be edited explains why. Hovering or right-clicking shows a tooltip with one of three reasons:
| Tooltip | Reason | What to do |
|---|---|---|
| *This value is read-only (Locked by Locked Values)* (*Låst av Locked Values*) | the cell is covered by the dataset's [locked values](datasets.html#locked-values) | ask the app administrator if the lock should change |
| *This value is read-only (Calculated value)* (*Beräknat värde*) | the value was written by a calculation | change the calculation's source data instead |
| *This value is read-only (The expression has no writeback)* (*Uttrycket saknar writeback*) | the cell comes from an expression without a [writeback](datasets.html#writeback) | enter the value on the underlying value type instead |
Read-only cells have a **grey** background, and cells open for input are **white**. The grey comes from the default presentation rule *Read-only* (*Skrivskyddat*), which matches cells with read access. Apps can restyle this.
Reference data is always read-only in apps.
## Comments
When a table allows comments, **Write comment** opens the **Comments** panel (*Kommentarer*) with the comment list, an input field and the checkbox **All comments** (*Alla kommentarer*).
A posted comment shows the author, the time and a **Cell** chip. Hovering the chip shows the full dimensional address the comment is bound to, for example:
> Department: D100 · Data type: Plan · Value type: Amount · Account: 4010 · Month: Mar 2026
A comment is bound to the **full dimension coordinate**, not to a position in the view. It stays with the data when the view is filtered, pivoted or regrouped. Cells with comments have a small marker in the corner.
Administrators can remove an app's comments with *Delete comments* (*Radera kommentarer*) in the app menu.
## Editing and spreading
Double-click an editable cell to enter a value.
- **Leaf cells** store the value directly on the value type.
- **Aggregated cells** (group rows, totals, pivoted periods above the stored level) spread the entered value to the cells below according to the value type's spread type: proportional, even, set value, or locked. See [Spreading](datasets.html#spreading).
- **Expression cells with writeback** convert the entered value with the writeback expression and write the result to the destination value type.
Dependent expression rows and all totals are recalculated in the view immediately. Calculations that read the changed value type run automatically in the plan; their results are available in the app once they have run. See [Calculations](calculations.html).
Edited cells get line state *Edited*. Display precision and edit precision are separate: a value type can accept more decimals on input than it shows.
### Saving
In v2 plans, an entered value is written to the plan directly, and dependent calculations run as with any other change. There is no separate apply or publish step. That step existed only in legacy (v1) plans.
### Undo
After an edit, **Undo** and **Redo** buttons (*Ångra* / *Gör om*) appear, and Cmd/Ctrl + Z works too. Undo is not in the context menu, and the undo history is lost when the page is reloaded. Each undo or redo is itself written as an edit, so an undone value ends with line state 10 (edited), not its original state.
## Keyboard shortcuts
The Help menu lists the shortcuts under *Kortkommandon*:
| Action | Swedish label | Mac | Windows |
|---|---|---|---|
| New | *Ny…* | Option + Cmd + N | Ctrl + Alt + N |
| Save | *Spara* | Option + Cmd + S | Ctrl + Alt + S |
| Select all rows | *Markera alla rader* | Option + Cmd + A | Ctrl + Alt + A |
| Leave cell | *Avsluta cell* | Esc | Esc |
| Export | *Exportera* | Option + Cmd + E | Ctrl + Alt + E |
| Import | *Importera* | Option + Cmd + I | Ctrl + Alt + I |
| Open the Konstrukt search field | *Öppna konstrukt sökfält* | Option + Cmd + F | Ctrl + Alt + F |
| Open column filter in the grid | *Öppna kolumnfilter i gridden* | Option + Cmd + U | Ctrl + Alt + U |
The Windows combinations follow from the client's shortcut definitions (Ctrl on Windows where Mac uses Cmd, Alt where Mac uses Option). They have not been tested on a Windows machine.
## Related
- [Datasets](datasets.html)
- [Workspaces and components](components.html)
- [Actions](actions.html)
- [Traceability](traceability.html)
- [Apps](apps.html)
---
# App configuration (XML/JSON)
> Reference for the configuration behind an app: the XML structure and schema version, what saving preserves, the JSON representation and schema exposed through MCP, and an element reference.
Everything configured in the app editor is stored as one configuration document per app. It is stored as XML and exposed as typed JSON through the MCP server. This page is a reference for people and agents who read or write that configuration directly. For what the settings mean, follow the links to the conceptual pages: [Datasets](datasets.html), [Workspaces and components](components.html) and [Actions](actions.html).
## Ways to access the configuration
| Route | Read | Write | Format |
|---|---|---|---|
| App editor | yes | yes | graphical |
| *Edit XML* (*Redigera XML*) in the app menu (⋯) | yes | yes | XML |
| MCP: `load_complete_app_config`, `search_app_config` | yes (v1 and v2 plans) | | JSON |
| MCP: `patch_app_config`, `overwrite_complete_app_config`, `create_app_with_config` | | yes (**v2 plans only**) | JSON |
The admin editor reads and writes the XML through these endpoints:
| Operation | Endpoint |
|---|---|
| Read | `GET /api/admin/plans/{planId}/apps/{appId}/xml` |
| Save | `POST /api/admin/plans/{planId}/apps/{appId}/xml` |
| Validate | `POST /api/admin/appconfig/validate/xml` and `…/xml/configvalidated` |
!!! warning "Internal endpoints"
The admin endpoints above belong to the internal API used by the editor. They are not part of the public, supported REST API and may change without notice. To read and write app configuration programmatically, use the [MCP server](ai-agents.html) (see [JSON representation via MCP](#json-representation-via-mcp)).
## Before editing by hand
### Saving is not round-trip
When a configuration is saved, the server does not store the submitted XML as it is. It parses it into the configuration model, serialises the model to new XML, and then patches the new XML with selected parts of the old one. That patch list contains exactly one path today:
```
/App/Config/Datasets/DataSet/Styles
```
(`Styles` is a legacy dataset styling block with no editor. The model only reports that it exists.)
Consequences:
- Anything the model does not read is **dropped on the next save**: XML comments, custom or unknown attributes, formatting and element order that the model does not preserve.
- Attributes that are only read by the legacy app engine, such as `AllowPartialUserFlow` and `AggregationExpression`, and the old `Konstrukt_Std_*` component types, are not read by the current model and do not survive.
- A hand edit is kept only if it is expressed in elements and attributes that the model reads. Check the result by reading the configuration back after saving.
### Component errors are found late
The XML validation schema is deliberately open around ``, because it cannot vary the allowed content by the `Type` attribute. An error inside a component is therefore only found when the configuration is deserialised, and the message has no line or column number. Change one component at a time.
### What is not in the configuration
The app's **name**, **description**, status and some access flags are stored on the app record, not in the configuration. The `Name` and `Description` attributes on `` that appear in the XML validation schema are not read. They would only be stale copies.
In practice:
- copying the XML from one app to another does not copy the name or description;
- through MCP, name and description are parameters of `create_app_with_config`, not part of the JSON.
### Schema version and migrations
The root element carries `SchemaVersion`. The current version is **1.50**. When a configuration is read it is migrated step by step (`1.39 → 1.42 → 1.45 → 1.452 → 1.48 → 1.50`), followed by migrations that depend on the plan version. These migrations convert dataset expressions and remove legacy action components in v2 plans. Always write the current version.
## XML structure
```xml
…
…
…
…
…
…
…
…
…
```
`Access` holds app access (see [Apps](apps.html#app-access)). Without it, default access applies.
### Recurring idiom: absence, presence, presence with a flag
Several three-state settings in the editor are encoded by whether an element exists and whether it carries a flag:
| Setting | Absent | Present | Present with flag |
|---|---|---|---|
| Workspace filter | Unavailable | Available | Required (`IsRequired="true"`) |
| Workspace reference | Unavailable | Available (`Selected="false"`) | Default (`Selected="true"`) |
### Dimension and property rows
A dataset dimension and a dataset property are both `` elements:
```xml
```
`Value="DimTagNo"` marks the row as a property. The property is identified by `DimTagGroupId` together with `DimensionId`.
### Initial values sources
The expansion source is not written explicitly. It is derived:
| XML | Source |
|---|---|
| `TakeFromDataSet="true"` | `ValuesInDataset` |
| `` present | `SpecifiedValues` |
| no `` | `AllValuesInDimension` |
Further rules:
- `DimensionId="ValueTypeId"` is the virtual dimension used to select value types.
- `` expands from a reference; only the first `` element is used.
- `` expands from other value types.
- `ExpandAllValueTypes` defaults to `true` when no value types are listed, otherwise `false`.
- `Enabled="false"` on `` or `` makes the whole block ignored.
- `DimensionId="DataType"` is ignored in both blocks. An empty ` ` is harmless.
### Expressions
- `` says which dimension the expression creates a value on.
- `DimValueNo` is the code and `DimValueName` the display name. An empty name is read as a single space, which is how blank spacer rows are made.
- `Language` is `Kex` (v2 plans) or `JavaScript` (v1). A missing attribute means `JavaScript`. On save, the language is set from the plan version.
- `Numerator` + `Denominator` (with an empty `Value`) marks a `LegacyQuot` expression. Otherwise `Value` holds a `Standard` expression.
- Writeback attributes: `WritebackExpression`, `WritebackDimValueNo`, `WritebackSpread`, `EditPrecision`. Older files without `WritebackSpread` on value-type-dimension expressions are backfilled to `Proportional`.
### Column setting IDs
`` identifies the column with `Value`, while `` uses `Id`. The attribute names differ and are easy to mix up. (In JSON both use `Id`.) Column IDs follow the grammar `[~]`:
| Pattern | Example | Column |
|---|---|---|
| `GROUP_COL_ID` | | the merged grouping column |
| `` | `Department` | the dimension's column (or its total column when pivoted) |
| `~` | `Month~202601` | a pivoted column for one dimension value |
| `_` | `Account_101` | a property column |
| `_~` | `Month_102~01` | a pivoted property column |
| `ValueTypeId~` | `ValueTypeId~Amount` | a pivoted value type column |
See [Workspaces and components](components.html#column-settings) for what the settings do.
### Scripts in attributes
An action's script is stored in the `Script` attribute, so that whitespace and line breaks are preserved. Escape `"`, `<`, `>` and `&` as XML entities when editing by hand.
## XML and JSON names
The JSON model uses different names for some XML attributes:
| XML | JSON | GUI |
|---|---|---|
| `Grouping` rows | `DatasetDimensions[]` | dimensions matrix |
| `DimTagGroupId` | `DimensionPropertyId` | property |
| `SortByDimValueNo="true"` / `"false"` | `SortBy: "Code"` / `"Name"` | Sort by |
| `DisplayFormatId` | `DisplayFormatId` | Display as |
| `IncludeDimValueNo` (legacy) | `DisplayFormatOverride` | not supported in the current end-user interface |
| `ValueType/@Name` | `NameOverride` | name override |
| `SpreadValue` | `SpreadOverride` | Spread |
| `DimValueNo` / `DimValueName` | `DatasetDimensionValueCode` / `DatasetDimensionValueName` | Code / Name |
| `WritebackDimValueNo` | `WritebackExpression.DatasetDimensionValueCode` | destination |
| `MultiSelect` | `Multiple` | Multiple |
| `SortById` | `SortBy` | |
| `Layout/@Type` | `Layout.$type` (`MultiPage`, `Matrix`) | Layout |
| `Component/@Type` | `$type` | Type |
| `` | `VariableInputs` | Variables |
Enumerations are stored by name except where a numeric code is shown in the tables on the conceptual pages (spread, format code, line state, line access, display format).
## JSON representation via MCP
The MCP server exposes the configuration as JSON:
| Tool | Purpose |
|---|---|
| `get_app_config_schema` | describe the configuration types: without `types` the root and every type name; with `types` (`["WorkspacePage", "MatrixLayout"]`) each type's properties, which are required, the `$type` of each variant and the types they refer to |
| `search_app_config` | find parts of a configuration with a JSONPath (`$..MainComponent`) or JSON Pointer; each match returns its pointer |
| `load_complete_app_config` | read a whole configuration (v1 and v2 plans) |
| `patch_app_config` | change parts of a configuration with a JSON Patch (**v2 plans only**) |
| `overwrite_complete_app_config` | replace a whole configuration (**v2 plans only**) |
| `validate_complete_app_config` | validate a configuration without saving (v1 and v2 plans) |
| `create_app_with_config` | create an app with name, description and configuration in one call (**v2 plans only**) |
| `delete_app` | permanently delete an app |
| `list_apps` | list apps in a plan (`id` is a GUID, plus `name` and `description`) |
Reads return the configuration together with an **etag**. Pass it as `ifMatch` to `patch_app_config` or `overwrite_complete_app_config`, and the write is rejected if someone changed the configuration in the meantime.
`patch_app_config` takes an RFC 6902 JSON Patch array (`add`, `remove`, `replace`, `move`, `copy`, `test`) plus `merge`, which applies a JSON Merge Patch at a position and leaves unnamed properties alone. Positions are JSON Pointers from `search_app_config`, or a JSONPath that matches exactly one position. The whole patch is applied together: if one edit fails, nothing is saved. `dryRun: true` validates and reports the changes without saving.
```json
[{"op": "test", "path": "/Workspaces/0/Name", "value": "Budget entry"},
{"op": "merge", "path": "/Workspaces/0", "value": {"Name": "Budget input"}}]
```
Prefer `search_app_config` and `patch_app_config` to reading and rewriting the whole configuration; configurations can be large. Use `replace`, not `merge`, when changing the `$type` of a node, so that properties of the old type do not survive.
The JSON is described by a JSON Schema (draft 2020-12) with 153 definitions. Its root is `AppConfigModel` with the required members `Id`, `PlanId`, `Datasets`, `Workspaces` and `Access`. Read the types you need with **`get_app_config_schema`**: the full schema is about 123,000 characters, too large for most agents to use. It is also published as the MCP resource `konstrukt://schema/app-config`, for clients that can attach resources.
When a configuration does not match the format, `validate_complete_app_config`, `patch_app_config`, `overwrite_complete_app_config` and `create_app_with_config` show the expected shape of the type in the error: its properties, which are required, and the valid `$type` values.
Points to know:
- **Polymorphism uses `$type`** (layouts, components, grid axes, settings, filters, expressions, row-level access, action components, variables). Component filter items and presentation-rule value conditions use **`Type`** instead.
- Several fields are polymorphic (chart axes, action targets). Guessing their shape can produce a configuration that parses but silently omits data.
- The model may contain implementation-specific details, and its structure is not guaranteed to be stable across versions. Always read the schema from the server rather than relying on a copy.
- **Colours** are serialised without a leading `#` (`"Light": "1F9AAD"`), although the schema text describes them as hex with `#`. Follow what `load_complete_app_config` returns.
- Output can contain `LegacyActionComponents: []` on workspaces, which the schema does not define.
- **Dataset IDs are integers** (`"Id": 1` on a dataset, `"DatasetId": 1` on a component). Component IDs are strings. Earlier versions of the format used strings for dataset IDs as well; a string now fails with *The JSON value could not be converted to System.Int32*.
- The root `Id` (the app's GUID) is required, also when creating an app.
- Reads return empty collections explicitly (`"Expressions": []`, `"ColumnSettings": []` …).
- MCP has no tool for renaming an app, changing its description or copying it.
A minimal configuration, for orientation only (validate against the schema before use):
```json
{
"Id": "…", "PlanId": 30,
"Datasets": [{
"Id": 1, "Name": "Budget",
"DatasetDimensions": [
{"DimensionId": "Account", "SortBy": "Code", "SortingMethod": "Natural"},
{"DimensionId": "Month", "SortBy": "Code", "SortingMethod": "Natural"}
],
"ValueTypes": {"SortBy": "Name", "SortingMethod": "Natural",
"Items": [{"ValueTypeId": "Amount", "Aggregation": "Sum", "SpreadOverride": 0}]},
"RowLevelAccess": {"$type": "Inherit", "EnableDimensionBasedAccess": false, "ReadOnly": false}
}],
"Workspaces": [{
"Id": 1, "Name": "Budget entry", "Hidden": false,
"Filters": [{"$type": "ValueType"}, {"$type": "DataType"}],
"ActionComponents": [],
"DataTypes": {"PlanData": {"Value": "Selected", "UsePlanName": false}},
"ValueTypes": {},
"Layout": {"$type": "MultiPage", "Pages": [{
"HideInPageSelector": false,
"MainComponent": {
"$type": "Grid", "Id": "1", "Name": "Budget", "DatasetId": 1,
"RowTotal": "Left", "AutoSizeStrategy": "Default", "HideHeader": false,
"EnableColumnTotals": true, "EnableUserConfig": true, "EnableComments": true,
"Groupings": [],
"Intermediaries": [{"$type": "Dimension", "DimensionId": "Account",
"Settings": {"$type": "Intermediary", "EnableEdit": false}}],
"Pivots": [{"$type": "Dimension", "DimensionId": "Month",
"Settings": {"$type": "Pivot", "SortDirection": "Ascending"}}]
}}]}
}],
"Access": {"Locked": false, "Enabled": true}
}
```
!!! agent "For agents"
The safe editing order (`get_app_config_schema` → get → modify → validate → set → read back) and the known pitfalls — enum codes, `$type` versus `Type`, colours without `#`, silently removed icons — are in the [Agent guide](agent-pitfalls.html#app-configuration).
## Element reference
| Element (XML) | JSON | Purpose | Key attributes | See |
|---|---|---|---|---|
| `App` | `AppConfigModel` | root | `SchemaVersion` | [Apps](apps.html) |
| `Access` | `Access` | app access | `Locked`, `Enabled`, `AccessListId` | [Apps](apps.html#app-access) |
| `DataSet` | `Datasets[]` | dataset | `Id`, `Name` | [Datasets](datasets.html) |
| `Grouping` | `DatasetDimensions[]` | dimension or property in the dataset | `Value`, `DimTagGroupId`, `DimensionId`, `SortByDimValueNo`, `SortingMethod`, `DisplayFormatId` | [Datasets](datasets.html#the-dimensions-matrix) |
| `ValueTypes/ValueType` | `ValueTypes.Items[]` | value type in the dataset | `Value`, `Name`, `Aggregation`, `Condition`, `SpreadValue` | [Datasets](datasets.html#value-types-in-a-dataset) |
| `ExcludedDimensionValueDefaults/Code` | `ExcludedDimensionValueDefaults` | defaults for excluded dimensions | `DimensionId`, `Value` | [Datasets](datasets.html#dimensions-removed-by-aggregation) |
| `InitialValues/Set` | `InitialValues[]` | expansion rule | `Enabled`, `ExpandAllValueTypes`, `TakeFromDataSet` | [Datasets](datasets.html#initial-values) |
| `LockedValues/Set` | `LockedValues[]` | lock rule | `Enabled` | [Datasets](datasets.html#locked-values) |
| `Filters/Filter` | `DatasetFilter` | dataset filter | `DimensionId`, `DimTagGroupId`, codes | [Datasets](datasets.html#dataset-filter) |
| `Expressions/Dimensions/Expression` | `Expressions[]` | computed dimension value | `DimValueNo`, `DimValueName`, `Aggregation`, `Format`, `Precision`, `Language`, `OmitNullRows`, `Value`, `Writeback*` | [Datasets](datasets.html#expressions) |
| `InheritRowLevelAccess` / `LimitRowLevelAccess` | `RowLevelAccess` | row-level access | `EnableDimensionBasedAccess`, `AccessListId`, `ReadOnly` | [Datasets](datasets.html#row-level-access) |
| `Styles` | (`HasStyling`) | legacy dataset styling; preserved, not editable | | this page |
| `Workspace` | `Workspaces[]` | workspace | `Id`, `Name`, `Hidden` | [Components](components.html#workspaces) |
| `Workspace/Filter` | `Filters[]` | filter row | `IsRequired`, `Message`, `Max`, `AllRequired`, `RequiredComponent` | [Components](components.html#filters) |
| `PlanData`, `References/Reference`, `DataTypeSortOrder` | `DataTypes` | data types offered | `Value`, `UsePlanName`, `Id`, `Selected` | [Components](components.html#data-types-and-references) |
| `Workspace/ValueTypes`, `ValueTypeSortOrder` | `ValueTypes` | value type names and order | `Id`, `Name` | [Components](components.html#value-types) |
| `Layout` | `Layout` | layout | `Type` | [Components](components.html#layouts) |
| `Page` | `Pages[]` | page in a multi-page layout | `Hidden` | [Components](components.html#layouts) |
| `MatrixComponent`, `Location` | `Components[]`, `Location` | component placement | `X`, `Y`, `Width`, `Height`, `Hidden` | [Components](components.html#layouts) |
| `LayoutSettings` | `Settings` | grid layout styling | `Spacing`, `BackgroundColor(DarkMode)`, `BorderColor(DarkMode)` | [Components](components.html#layouts) |
| `Component` | `AppComponent` | component | `Id`, `Name`, `Type`, `HideHeader` | [Components](components.html#component-types) |
| Grid `Filters/Set` | `Filters[]` | component filter | `Mode`, `Filter/@Type` | [Components](components.html#component-filters) |
| Grid column `Setting` | `ColumnSettings[]` | column settings | `Type`, `Value` / `Id`, `Width`, `Pinned` | [Components](components.html#column-settings) |
| `Rule` | `PresentationRules[]` | presentation rule | `Enabled`, `NameIndex`, `DefaultRuleKey`, `Name`, style attributes | [Components](components.html#presentation-rules) |
| `MetricComparison` | `Compare` | metric comparison | `Type`, `Mode`, colours | [Components](components.html#metric) |
| `ActionComponentGroup` | `ActionComponentGroup` | group of actions | `Id`, `Name`, `Description` | [Actions](actions.html#groups) |
| `ActionComponent` | `ActionComponent` | action | `Id`, `Name`, `RunButtonLabel`, `HideInSidebar`, `Script` | [Actions](actions.html) |
| `Variables/Text`, `Numeric`, `Dimension`, `Property` | `VariableInputs[]` | action variables | `Identifier`, `Name`, type-specific attributes | [Actions](actions.html#variables) |
| `LegacyActionComponents` | | legacy actions; removed in v2 plans | | [Actions](actions.html#legacy-action-components) |
### Presentation rule attributes
`NameIndex` is a random number from 0 to 19, set when a rule is created or copied. It only picks a placeholder name for the rule's preview in the editor. It has no other meaning. Default rules have `NameIndex="-1"` and a `DefaultRuleKey`. The name shown is `Name` if set, otherwise the label of the default rule key, otherwise the placeholder name.
Colour attributes come in pairs, `FontColor` / `FontColorDarkMode` and `BackgroundColor` / `BackgroundColorDarkMode`. In JSON they are grouped as `Styles.FontColor.{Light,Dark}`.
!!! note "Schema enum values not covered here"
The JSON Schema defines some enum values (for example additional line states and line access `0`) that are internal or legacy and are deliberately not described in these docs. Do not use values that are not listed on the conceptual pages.
## Related
- [Apps](apps.html)
- [Datasets](datasets.html)
- [Workspaces and components](components.html)
- [Actions](actions.html)
- [AI agents](ai-agents.html)
---
# Security and access
> How Konstrukt controls who can see and change what — users, roles and groups, access lists, app and dataset access, sensitive value types, single sign-on and machine credentials.
Access in Konstrukt is layered. Authentication decides who a user is (single sign-on or a Konstrukt login). Authorization then works from the outside in: which **plans** a user can open, which **apps** inside a plan, which **rows** of each dataset they can read or write, and — for sensitive measures — whether they can see the **value** at all. Machine access (APIs, SQL, file transports, MCP) uses separate credentials that are described at the end of this page.
## Access model at a glance
| Layer | Controls | Configured in |
|---|---|---|
| Users, roles, groups | Who exists and which roles they hold | Users (*Användare*) |
| Plan access | Which plans a user sees at all | User administration |
| Access lists (*Behörighetslistor*) | Rules that grant read or read/write per role or group, optionally limited by dimension values | Plan admin → Interaction (*Interaktion*) |
| App access (*Appåtkomst*) | Whether an app is enabled, locked, and which access list governs it | App settings (*Inställningar*) |
| Dataset access | Read or read/write per dataset, inherited from the app or from a chosen list | App settings, per dataset |
| Sensitive value types | Hides the value of a measure while the row stays visible | Value type settings |
| Locked values, calculated data | Not access control, but they also make cells read-only | Dataset configuration, calculations |
A user's effective permission on a cell is the most restrictive result of these layers.
## Users, roles and groups
The Users area (*Användare*) in the left rail has three views: Users, Roles and Groups (*Användare · Roller · Grupper*).
- **Users** carry roles, plan access and a user type.
- **Roles** are the unit that access lists grant permissions to. A role can be linked to groups.
- **Groups** bundle roles. Access list rules can target either a role or a group.
Users only see plans they have access to; everything below the plan level (apps, datasets, rows) is filtered further by access lists.
Through MCP, `get_users` returns each user's login ID, UPN (e-mail), display name, user type (for example `Konstrukt.SysAdmin`) and role names. `get_roles` returns each role with its linked groups. Neither shows individual permissions.
### Act as
Administrators can switch to another role with **Act as** (*Agera som*) in the top bar and see apps exactly as that role would. Use it to verify an access list or a dataset restriction before publishing an app to end users.
## Access lists
Access lists (*Behörighetslistor*) belong to a plan and are found in the plan admin under Interaction (*Interaktion*), described in the product as "control which data each group can see".
An access list has:
| Field | Meaning |
|---|---|
| Description (*Beskrivning*) | Free text |
| Limit permission based on dimension (*Begränsa behörighet baserat på dimension*) | When on, rules restrict access to specific dimension values (for example a user sees only their own `Department` values) |
| Rules | A grid of role or group × permission type, for example Read & write (*Läsa & Skriva*) |
The same list can be reused by several apps, datasets and action-component inputs. In app configuration a list is referenced by `AccessListId` on `AppAccess`, on a dataset's `RowLevelAccess`, and on dimension or property variables of action components (so a form only offers values the user may use).
Through MCP, a rule without dimension restriction is returned as a role name and an access level, for example `{"roleName": "CFO", "accessLevel": "ReadWrite"}`. Rules have no priority or ordering field.
!!! agent "For agents"
Read rules with `get_access_rules(planId, accessListId)` and write them with `import_access_rules`. Import modes are `Insert`, `Update`, `Upsert` (default) and `Replace`. `Replace` removes rules not in the payload — confirm with the user first. The `accessListId` has to be taken from an existing app config (`AppAccess.AccessListId`, `RowLevelAccess.AccessListId`) because no tool lists access lists.
## App access
Each app has an access section in its settings (**Settings** → **App access**, *Inställningar* → *Appåtkomst*):
| Setting | Effect | JSON (`Access`) |
|---|---|---|
| Enabled | Whether the app is available | `Enabled` |
| Lock app (*Lås appen*) | Locks the app for editing | `Locked` |
| Access list | Which list controls who can open the app | `AccessListId` — `null` grants full access for everyone |
## Dataset access
Every dataset in an app has its own access setting, so one app can combine a dataset everyone may edit with a read-only dataset that only some roles see.
| GUI choice | Meaning |
|---|---|
| Read (*Läsåtkomst*) | Rows can be read, not edited |
| Read and write (*Läs- och skrivåtkomst*) | Rows can be read and edited |
| Inherit from app (*Ärv från app*) | Uses the app's access list |
| Full | Full access; no access list applied to the dataset |
| Choose list (*Välj lista*) | Uses a specific access list for this dataset |
In the configuration JSON this is `RowLevelAccess`, discriminated by `$type`:
| `$type` | Fields | Meaning |
|---|---|---|
| `Inherit` | `ReadOnly`, `EnableDimensionBasedAccess` | Inherit from the app; optionally apply dimension-based rules |
| `Limit` | `ReadOnly`, `AccessListId` | Restrict to a specific access list |
```json
"RowLevelAccess": { "$type": "Limit", "ReadOnly": true, "AccessListId": 12 }
```
How the GUI choice *Full* maps to the JSON types, and exactly what a locked app prevents, are tracked as open questions on [Datasets](datasets.html#row-level-access) and [Apps](apps.html). See [Datasets](datasets.html) for the rest of the dataset configuration.
## Sensitive value types
A value type can be marked sensitive (`isSensitive`, **Sensitive data**, *Känslig data*). For affected users the rows stay visible — the dimension combination is shown — but the **value itself is hidden**. It hides the measure, not the row.
Typical use: a user who administers dimensions and imports data into a value type holding salaries, but must not see the salary amounts.
Seeing sensitive values is a specific permission that is assigned to roles. By default a tenant has three roles with some form of admin access:
| Role | Sensitive values |
|---|---|
| Admin | Visible |
| Builder | Visible |
| Limited Builder | Hidden |
Where sensitive values are hidden:
| Surface | Sensitive values |
|---|---|
| Apps and the admin interface | Hidden for users without the permission |
| Exports from the interface | Hidden for users without the permission |
| External SQL views | **Not hidden.** A tenant has a single SQL integration account, which sees all data |
Grant SQL access only to consumers that are allowed to see all data, including sensitive value types.
## Read-only cells that are not access control
Some cells are read-only for reasons unrelated to permissions. The grid shows the reason on hover:
| Tooltip reason | Cause | What the user can do |
|---|---|---|
| Locked by Locked Values | The dataset's Locked values (`LockedValues`) cover the cell | Ask an administrator |
| Calculated value | A calculation wrote the value | Change the calculation's sources |
| Expression has no writeback | An expression column without a writeback expression | Enter the value on the underlying value type |
See [Datasets](datasets.html) and [Calculations](calculations.html).
## Sign-in
A tenant can allow several sign-in methods in parallel. Each method is switched on or off per tenant.
| Method | Description |
|---|---|
| Microsoft account | Sign-in with a Microsoft work account |
| Google account | Sign-in with a Google account |
| Internal account | User name and password, managed in Konstrukt. No multi-factor authentication. |
| Custom single sign-on | The customer's own identity provider over **OpenID Connect** (OAuth 2.0) or **SAML** |
Authentication is being rebuilt as part of the move to the new hosting environment in 2026. After the move, sign-in with Microsoft and Google accounts is available to all users by default.
!!! tip "Requiring MFA"
Internal accounts have no multi-factor authentication. To require MFA, use Microsoft, Google or custom single sign-on with an identity provider that enforces it, and switch off internal accounts for the tenant.
### Custom single sign-on with OpenID Connect
Konstrukt enables custom SSO for the tenant once the provider details have been registered. Current requirements:
| Item | Value |
|---|---|
| Redirect URI | `https://oauth.konstrukt.app/api/signin/{tenant}` — `{tenant}` is the tenant's subdomain (the `{tenant}` in `{tenant}.konstrukt.app`) |
| User identifier | A `upn` claim in the ID token; each Konstrukt user must have the matching UPN |
| Flow | Implicit grant for ID and access tokens |
Example with Microsoft Entra ID as the customer's own provider:
1. Create an **App registration**; set a **Web** redirect URI (above).
2. Under **Authentication**, allow implicit grant for access tokens and ID tokens.
3. Under **Certificates & secrets**, create a client secret and store it — it is shown once.
4. Under **Token configuration**, add the optional claim `upn` to the ID token. The UPN must already exist on the users in the directory.
5. Send Konstrukt, over a secure channel, the **Directory (tenant) ID**, **Application (client) ID** and the **client secret**.
6. Add each user's UPN to the corresponding Konstrukt user (the directory's user export helps).
7. Konstrukt enables SSO for the tenant.
### Passwords and sessions
- When a password is set for an internal account, Konstrukt generates a long random password (at least 10 characters).
- Sessions are long-lived: a sign-in lasts at least about 30 days.
!!! agent "For agents"
`import_users` creates users but **no logins**; it is only practical on tenants that use SSO, where the login comes from the identity provider and is matched on UPN. `import_users` defaults to mode `Insert`; `import_groups` and `import_roles` default to `Upsert`. `get_users` returns active users with roles, plan access and user type.
## Machine credentials
Non-interactive access uses dedicated credentials, each scoped to one surface:
| Credential | Used for | Created in |
|---|---|---|
| API key (Key ID + API key) | REST API via OAuth 2.0 client credentials; KDI command-line importer | Integration → API keys (*API-nycklar*) |
| SAS token | Uploading import files to the Azure storage container | Integration → Accounts (*Konton*) |
| SFTP account | Uploading import files over SFTP | Integration → Accounts |
| SQL integration account | Reading external SQL views; user ID, generated password and IP allow-list | Integration → Accounts |
| MCP client | AI agents; tools are filtered by the caller's privileges | See [AI agents and MCP](ai-agents.html) |
An **API key** is issued by an administrator for a chosen user, and carries that user's permissions in the API. It does not grant anything the user cannot do. A key is valid for **one year** by default. Create a new key before the old one expires, and update the integrations that use it.
The key list shows purpose (*Ändamål*), user name, expiry date (*Giltig till*) and the **Master key** flag (*Huvudnyckel*). A master key can emulate other users, which applies only to legacy (v1) plans. In v2 plans, users switch between their roles instead (see [Act as](#act-as)), and no master key is needed. Leave *Huvudnyckel* unticked.
The SQL integration account is one account per tenant and only accepts connections from allow-listed IP addresses.
## Traceability
Every value and dimension value carries edit metadata (who and when, `$editby`, `$edittime`), and changes are kept in history. Deleting data does not delete its history. See [References and history](references-history.html) and [Traceability](traceability.html).
## Hosting, encryption and backup
The service is hosted in Sweden. Each tenant has its own database, and data is encrypted in transit and at rest. See [Hosting and operations](operations.html) for sub-processors, backup and restore, and releases.
## Related
- [Datasets](datasets.html)
- [Data integration](integration.html)
- [APIs and SQL access](apis.html)
- [AI agents and MCP](ai-agents.html)
- [Tenant administration](administration.html)
---
# Hosting and operations
> Where and how Konstrukt is hosted and operated — Swedish hosting and sub-processors, tenant isolation, encryption, backup and restore, availability, release tracks and how releases are announced.
This page describes how the Konstrukt service is hosted and operated. The legal commitments are in the [general terms](https://www.konstrukt.se/allmanna-villkor) and the [sub-processor list](https://www.konstrukt.se/underbitraden) on konstrukt.se. Those pages take precedence over this one.
## Hosting and data location
Konstrukt runs in its own hosting environment, operated with Swedish partners in data centres in Sweden. All processing within the platform takes place in Sweden.
| Sub-processor | Role |
|---|---|
| Nordlo Elevate AB | Operations and hosting: the established hosting environment (through 2026) and the SQL cluster (from 2026) |
| Safespring AB | Operations and hosting infrastructure: the new hosting environment (from 2026) |
| Berget AI AB | AI functionality in the service (from 2026) |
The [sub-processor list ↗](https://www.konstrukt.se/underbitraden) is the authoritative and current list. It also covers the tools used when Konstrukt delivers consulting and support. How AI features and the MCP server handle customer data is described on [AI and your data ↗](https://www.konstrukt.se/ai-och-kunddata); see also [AI agents and MCP](ai-agents.html).
## Tenant isolation
- **Each tenant has its own database.** Plan data, model, history, users and configuration are stored per tenant.
- **Backend services are shared** between tenants. They are stateless apart from caching, and every request runs against the calling tenant's database.
- Each tenant has its own host name (`https://{tenant}.konstrukt.app`), and its APIs, SQL views and MCP server serve only that tenant.
## Encryption
In the current hosting environment, all data is encrypted **in transit and at rest**.
## Backup and restore
Backups are stored both on site and off site.
| Backup | Frequency | Retention |
|---|---|---|
| Transaction log backup | Every hour | — |
| Full backup | Every hour | 2 days |
| Daily backup | Every day | 7 days |
| Weekly backup | Every week | 4 weeks |
A customer can ask Konstrukt to restore a tenant from a full backup.
Backups are separate from the platform's own [history](references-history.html#history). History lets users read any earlier state of the data inside the product, without a restore.
## Availability
The availability commitment, how it is measured and the service credits are set out in the [general terms ↗](https://www.konstrukt.se/allmanna-villkor).
## Releases
New versions are rolled out in **release tracks**. Each tenant follows one track.
| Track | Used for |
|---|---|
| Alpha | Development, demo and internal environments; part of quality assurance |
| Beta | Further internal environments, and customers who want early access to new functionality |
| Feature | Most customers |
| Stable | Customers who are particularly sensitive to defects |
- Releases are deployed without advance notice. Maintenance windows can occur, but are not scheduled on a regular basis. The general terms set the limits for planned maintenance.
- After a release, administrators are notified in the interface. The release notes are available from the Help menu, see [Tenant administration](administration.html#help-menu).
- The version a tenant runs is shown in the Help menu.
## Data retention in the platform
- **Plan data** is kept until it is deleted.
- **History** is currently kept until further notice. No specific retention period is guaranteed. Limits on history may be introduced for storage reasons, and may in future depend on the licence.
- **Removing history** is possible in two ways:
1. Empty a value type and change its dimensions. The value type's table is rebuilt without history. See [Changing a value type's dimensions](data-model.html#changing-a-value-types-dimensions).
2. Copy the plan, which copies everything except the history tables, then archive and delete the old plan. This removes the history of the whole plan, and point-in-time references in the copy become empty. See [Tenant administration](administration.html#lifecycle).
- **Import logs and archived import files** are currently kept without automatic purging.
- **Backups** follow the retention periods above. The general terms state how long personal data may remain in backups after deletion.
## Related
- [Architecture](architecture.html)
- [Security and access](security.html)
- [References and history](references-history.html)
- [Tenant administration](administration.html)
---
# Data integration
> How data gets into Konstrukt — import configurations, the three transports that share one configuration key (KDI, REST, storage/SFTP), file formats, the GUI import wizard, import semantics, jobs and the integration platform.
Data enters a Konstrukt model through **import configurations**. A configuration defines *what* is imported and *how* (target object, import mode, whether new dimension values are created, who is notified on error). The *transport* — a command-line importer, a REST call or a file drop — is a free choice, because every transport routes the file by the same configuration key. For outbound data (SQL views, the Kex endpoint) see [APIs and SQL access](apis.html).
```flow
Source system | ERP, HR, CRM, files -> Transport | KDI.exe, REST, Azure storage, SFTP -> Import configuration | key (GUID), mode, options -> Target | value type, reference, dimension, property
```
## The Integration area
Integration (*Integration*) is a top-level entry in the left rail. Its panels:
| Panel | Swedish label | Content |
|---|---|---|
| Jobs | *Jobb* | [Managed integration](#managed-integrations) jobs, which can be run from here |
| Logs | *Loggar* | One entry per import, from every transport |
| Configurations | *Konfigurationer* | All import configurations, grouped by target type |
| Accounts | *Konton* | Transport credentials: SQL integration, Storage Account integration, SFTP integration |
| API keys | *API-nycklar* | Keys for the REST API, KDI and MCP |
### Logs
Each import writes one log entry, whatever the transport. The list shows:
- date and time (*Datum och tid*);
- the target's name and ID (*Namn*);
- the entity type (*Entitet*): value type or dimension;
- the event type (*Händelsetyp*), that is, the import mode, for example Add (*Lägg till*), Update (*Uppdatera*) or Replace (*Ersätt*);
- the configuration (*Konfiguration*);
- the result (*Resultat*), for example *Lyckades* (succeeded) or *Varning* (succeeded with warnings).
Expanding an entry shows the full report:
- the outcome and duration;
- the source, meaning the transport or integration and the user it ran as;
- the affected plan and value type or dimension;
- row counts: added, updated and deleted, plus how many duplicate rows were aggregated;
- warnings, with line numbers, for example *No such code … in dimension Project* for rows whose codes do not exist.
The panel *Skicka rapporter till (e-post)* sets default recipients for import reports. Files received over SFTP or Azure storage can be downloaded from the log to check what was imported. This is not possible for files that arrived by other routes.
Log entries and archived import files are currently kept without automatic purging.
### Jobs
The job list shows name, status, start time, next run (for example *Manuellt*, manual) and last run. Expanding a job shows its ID, run time, next run, status and a description written for the customer. **Run job** (*Kör jobb*) starts it immediately.
## Import configurations
The Configurations panel has one tab per target type: Value types, References, Dimensions, Properties (*Värdetyper · Referenser · Dimensioner · Egenskaper*). References are valid import targets in their own right — reference data is imported like plan data.
| Column | Meaning |
|---|---|
| Name | Target object name |
| Plan | Plan the target belongs to |
| Configuration (*Konfiguration*) | Configuration number |
| Configuration type (*Konfigurationstyp*) | Import mode, see below |
| Create new values (*Skapa nya värden*) | Yes/No — create dimension values that appear in the file but not in the dimension |
| Send e-mail to (*Skicka e-post till*) | Recipients of import reports |
The row menu has **Edit configuration** and **Delete configuration** (*Ändra konfiguration · Ta bort konfiguration*).
### Configuration settings
| Setting | Swedish label | Options |
|---|---|---|
| Configuration type | *Konfigurationstyp* | Add (*Lägg till*): add new rows only · Add & update (*Lägg till & Uppdatera*) · Update (*Uppdatera*): existing rows only · Replace (*Ersätt*): empty the value type, then write the file · Delete (*Ta bort*): the file is a [delete filter](#delete-filter-files) |
| Write to reference data | *Skriv till referensdata* | Import into a reference instead of plan data |
| Missing values | *Hantering av saknade värden* | Create new values (*Skapa nya värden*) |
| Report recipients | *Skicka rapporter till* | None (default) or a custom e-mail address, and which imports trigger an e-mail, for example imports with warnings |
| Aggregation of duplicates | *Aggregering* | Default, Sum, Average, Min, Max, or Fail on duplicates (*Misslyckas om dubbletter*) |
Recipients and aggregation are under **Show advanced** (*Visa avancerat*).
### Per-object Integration panel
Dimensions and value types have an Integration side panel (*Integration*) with two parts:
- **Import** (*Importera*) — one card per configuration feeding the object, with its mode (e.g. Add, Add & update) and a status marker. Row menu: Edit configuration, Delete configuration (*Ändra konfiguration · Ta bort konfiguration*). Button: Add configuration (*Lägg till konfiguration*).
- **Export** (*Exportera*) — the Enable export (*Aktivera export*) switch and a generated SQL statement; see [APIs and SQL access](apis.html#active-export).
For each configuration the panel generates ready-to-use instructions for every transport, with the tenant name and configuration key filled in. The generated instruction is the authoritative form of the call; the sections below describe the mechanism.
The configuration types on offer depend on the target:
| Target | Add | Add & update | Update | Replace | Delete |
|---|---|---|---|---|---|
| Value type (plan data) | ✓ | ✓ | ✓ | ✓ | ✓ |
| Reference | ✓ | ✓ | ✓ | ✓ | ✓ |
| Dimension | ✓ | ✓ | ✓ | – | – |
| Property | ✓ | ✓ | ✓ | – | – |
Configurations for references and properties are created from the object's own Integration panel. A value-type configuration asks whether to write to plan data (*Plandata*) or to a reference (*Referens*); a dimension configuration asks whether to write to the dimension or to one of its properties (*Egenskap*). A dimension configuration can also allow new property values to be created (*Tillåt skapande av nya egenskapsvärden*).
## Transports
| Transport | Best for | Authentication | Processing |
|---|---|---|---|
| KDI command-line importer | On-premises Windows servers, scheduled tasks | API key | Not documented |
| REST API | Real-time integration with immediate feedback | OAuth 2.0 client credentials (API key) | Synchronous; result returned in the call |
| Azure storage container | Bulk and parallel uploads from tools with blob support | SAS token in the URL | Asynchronous; result e-mailed and logged |
| SFTP | Systems that can only deliver files | SFTP account | Asynchronous |
### KDI — command-line importer
KonstruktDataImporter (KDI) is a Windows command-line program for on-premises sources that cannot reach a cloud API directly. It sends data over HTTPS, so it also works behind a proxy. Schedule it with Windows Task Scheduler, an SSIS job or any other local tool that can run an `.exe` on a schedule.
The Integration panel offers **Download KDI.exe** (*Ladda ner KDI.exe*) and a generated command line for each configuration:
```
KonstruktDataImporter.exe {tenant} {api-key} {configuration-key}.csv
```
```
KonstruktDataImporter.exe [arguments] [options]
```
| Argument | Meaning |
|---|---|
| `Tenant` | Tenant domain: `mycompany` for `https://mycompany.konstrukt.app` |
| `ApiKey` | API key used to authenticate the calls |
| `FileName` | Path to the input file |
| Option | Meaning |
|---|---|
| `-p ` | Plan to import into. Default: the current default plan |
| `-r ` / `-rn ` | Import value-type data into a reference instead of plan data. The name is not case-sensitive. No effect on dimension data |
| `-d` | Delete all existing value-type data before inserting. Without it, new rows are added and existing rows updated |
| `-dff` | The file is a [delete filter](#delete-filter-files) |
| `-a` | Add only: existing values are not updated. Cannot be combined with `-d` |
| `-c` | Create values. For value-type data: create missing dimension values. For dimension data: create missing properties and property values, which are otherwise ignored without error |
| `-e ` | Send an e-mail to this address if the import fails |
| `-nocfg` | Do not create an import configuration. By default, an import of value-type or dimension data creates one in the tenant if none exists |
| `-retry ` | Retry a failed import up to *n* times, for example to ride out network errors |
| `-origin ` | Short name for the data source, used in the log. Default: `KonstruktDataImporter.exe` |
| `-v` | Verbose logging |
| `-t users` / `-t accesses` | The file contains [users or access rules](#users-and-access-rules) instead of model data |
| `-app ` | App to import access rules into. Required with `-t accesses` |
#### Choosing the target
- **Configured import:** if the file is named after an import configuration's key (`abc123….csv`), the configuration's stored settings are used.
- **By name:** otherwise the file name, up to the first `_`, must be an existing dimension ID or value-type ID, for example `Amount_20260322_142203.csv`. A file for a dimension property is named `DimensionId_PropertyName`, for example `Account_AccountGroup.csv`.
- **Dimension or value-type data:** a header with `DimValueNo` and `DimValueName` is read as dimension data. Anything else is read as value-type data, and the header must then contain the IDs of all the value type's dimensions. Missing value fields get default values (`DecimalValue` 0, `StringValue` null, `DateTimeValue` 0).
- **Property files** have the header fields `DimTagNo` and `DimTagName`.
#### Reading from a database
Instead of a data file, KDI can take a `.json` file that describes a query against Microsoft SQL Server or MySQL. The result is imported as if it were a delimited file named `Id`, with `Headers` as its header row:
```json
{
"Type": "mssql",
"Server": "sql-server-name",
"Database": "database-name",
"User": "myuser",
"Password": "mypassword",
"Integrated": false,
"Id": "Amount",
"Headers": ["Account", "Department", "Month", "DecimalValue", "StringValue"],
"Query": "select account, department, month, amount, comment from mytable where filter = 1"
}
```
`Type` is `mssql` (default) or `mysql`. `Integrated: true` uses Windows authentication instead of a user and password.
#### Delete filter files
With `-dff`, the file lists which value-type data to delete, in plan data or in a reference.
- **Header:** one column for each dimension (`DimensionId`) or property (`DimensionId.PropertyName`) to filter on.
- **Rows:** each row is one set of data to delete, and data must match every value in the row. Empty cells ignore that column for the row. Rows with invalid values are ignored completely.
```
Department;Account;Month.Year
D100;3010;2026
;5010;2026
D100;;
```
A typical use is clearing all data for a period through an integration before new data is loaded.
#### Users and access rules
- **Users** (`-t users`):
- `ID`
- `UPN` (optional; used with single sign-on)
- `Name`
- `Type` (optional; the user type, for example `Konstrukt.SysAdmin` or `Konstrukt.BaseAdmin`; it depends on the tenant configuration)
- `Plans` (optional; plan IDs separated by `|`, or `*` for all plans)
- **Access rules** (`-t accesses -app `, optionally `-p ` and `-d` to replace existing rules):
- `User`
- `Pattern1` and `Pattern2` (used when dimension-based access is enabled)
- `AccessLevel` (`Read` or `ReadWrite`; default `ReadWrite`)
### REST
Files can be posted to `/api/v1/import/{key}` on the tenant host. The request is authorized with a bearer token obtained from `/api/v1/token` using the client-credentials grant; see [APIs and SQL access](apis.html#authentication). The Integration panel generates a complete Bash and PowerShell script for each configuration in three steps: request a token, extract `access_token`, post the import file (with `TODO` markers where the key goes).
The endpoint processes the file immediately and returns the outcome in the same call. The request format is described in the auto-generated [REST API reference](https://acme.konstrukt.app/api/documentation/index.html) (each tenant serves it at `/api/documentation/index.html` on its own host).
### Azure storage container
Upload the file to the Konstrukt blob container, named after the configuration key:
```
https://konstruktdataimporter.blob.core.windows.net/konstruktdataimporter/{configuration-key}.{extension}?{sas-token}
```
| Part | Value |
|---|---|
| Storage account and container | Both `konstruktdataimporter` |
| `{configuration-key}` | Key of the import configuration, copied from the object's Integration panel |
| `{extension}` | `.csv`, `.txt`, `.tsv` or `.xlsx` |
| `{sas-token}` | Access key (SAS token) created under Integration → Accounts → Storage Account integration (*Skapa ny accessnyckel*). The key has an expiry date, shown under the key. |
Any tool with blob-storage support can upload. Without one, an `HTTP PUT` with header `x-ms-blob-type: BlockBlob` and the file as body is enough:
```bash
curl -H "x-ms-blob-type: BlockBlob" \
--upload-file path/to/file.csv \
--url "https://konstruktdataimporter.blob.core.windows.net/konstruktdataimporter/{configuration-key}.csv?{sas-token}"
```
Microsoft's storage SDKs (Python, JavaScript, C# and others) work the same way: container `konstruktdataimporter`, blob name `{configuration-key}.{extension}`, SAS token as credential.
Files uploaded to storage are processed in the background and can be uploaded in parallel. Results are e-mailed to the configured recipients and logged. Uploaded files are archived and can be downloaded from the log afterwards.
!!! note "Older importer setups"
Earlier setups authenticated to the storage account with separate directory credentials and configured files outside the tenant. Current setups create the SAS token and configurations inside the tenant.
### SFTP
The SFTP server is `sftp.konstrukt.app`, port `22`. Files are named the same way as in the storage container, `{configuration-key}.{extension}`, and the configuration key decides which import runs. Files uploaded to the root (`/`) are imported automatically. `/inbox` is also read, for clients that cannot write to the root. The SFTP account under Integration → Accounts shows the server, port, host-key fingerprint (*Fingeravtryck*), user ID and password. Files received over SFTP or Azure storage can be downloaded afterwards, to check what was imported.
## File formats
| Format | Extension | Separator |
|---|---|---|
| CSV | `.csv` | Semicolon `;` |
| Text / TSV | `.txt`, `.tsv` | Tab |
| Excel | `.xlsx` | Sheet (select the sheet in the GUI or with `sheetName`) |
Files are flat tables with column headers in the first row. Encoding is detected in most cases; UTF-8 is the safe choice. Use `.` as decimal separator and no thousands separator.
### Value type files
One column per dimension (identified by dimension ID or name) and one column for the value:
```
Month;Amount
202401;10.0
202402;12.2
202403;12.9
```
### Dimension files
One column `Code`, optionally `Name`, and any number of property columns (identified by property ID, code or name). A property **omitted** from the file is not updated; a property column with an **empty cell** clears the value.
```
Code;Name;Active
202401;Jan 2024;0
202402;Feb 2024;0
202403;Mar 2024;1
```
### Dimension property files
Columns `Code` and `Name` only.
## Import in the GUI
Value types have an import wizard in their toolbar. It uses the same mechanism as the import APIs.
| Step | Content |
|---|---|
| 1. Import type | Full import (*Full import*): add new rows and update existing · Only new data (*Endast ny data*): add new rows only · Only update (*Endast uppdatering*): update existing rows only |
| 2. Column mapping | The file's columns with a target selector under each, and a numbered preview of the rows |
| 3. Settings | Duplicate handling — Sum, Average, Min, Max, or Fail on duplicates (*Summa · Genomsnitt · Min · Max · Misslyckas om dubbletter*) — and Create new dimension values (*Skapa nya dimensionsvärden*) |
The calculation ID cannot be mapped: provenance can be read out, not imported. A file exported from a value type can be imported back unchanged.
## Import semantics
All import surfaces share the same operations:
| Operation | Effect | GUI | MCP tool |
|---|---|---|---|
| Insert | Add new rows only | Only new data | `insert_*_data` |
| Update | Update existing rows only | Only update | `update_*_data` |
| Upsert | Add new and update existing; never delete | Full import | `upsert_*_data` |
| Replace | **Empty the value type**, then write the rows in the file (value types only) | Replace (*Ersätt*) | `replace_value_type_data` |
| Delete | Delete the rows matching a [delete filter](#delete-filter-files), for example all data for a period | Delete (*Ta bort*) | `delete_value_type_data` |
| Configured import | Run a pre-defined import configuration | — | `import_data(key)` |
Duplicate rows (same dimension values) are aggregated with `Sum`, `Min`, `Max`, `Avg`, `Concatenate`, or rejected (`Disabled`). Missing dimension values and property values can be created automatically. Notification e-mails can go to the default recipients, to none, or to a list.
Imported values are stored with edit state *suggested* and their origin is logged; see [Traceability](traceability.html). Import writes are kept in history like any other change.
!!! agent "For agents"
Prefer `import_data(key)` when an import configuration exists — it applies the administrator's mode and options. Use `replace_value_type_data` only with explicit user confirmation, since rows missing from the payload are deleted. `fieldMappings` are index-based and comma-separated (empty entry = skip column); value type files map `Value` plus dimension IDs, dimension files `Code`, `Name` and property names. Set `dataOrigin` to a label that identifies your integration in the log. Details in [AI agents and MCP](ai-agents.html#data-import-parameters).
## Managed integrations
Besides the self-service transports above, Konstrukt offers **managed integrations**, which Konstrukt builds and operates. A managed integration runs as a job with three steps:
```flow
Extract | connectors fetch data from source systems -> Transform | shape the data for the model -> Load | through import configurations
```
- **Extract.** One or more connectors fetch data from the source systems. One job can combine several sources, and several companies or accounts in the same source system.
- **Transform.** The data is reshaped to match the model's dimensions and value types.
- **Load.** Each resulting table is loaded through an import configuration, which decides the target and import mode, as for the other transports. One job can write any number of tables.
Jobs appear under Integration → [Jobs](#jobs), where customers can run them. Their imports appear in the [Logs](#logs).
### Available connectors
The catalogue grows continuously. New source systems, and new endpoints in existing ones, can be added.
| Connector | Type | Data sets |
|---|---|---|
| Microsoft SQL Server | Database | Any table or query |
| MySQL | Database | Any table or query, including source systems that offer a MySQL analytics database, such as Kleer |
| Google BigQuery | Data warehouse | Complete tables |
| Fortnox | Accounting | Accounts, vouchers, customers, suppliers, invoices, supplier invoices, invoice and supplier payments, contracts, cost centres, employees, expenses, salary transactions, financial years |
| Microsoft Dynamics 365 Business Central | ERP | Companies, customers, vendors, accounts, dimensions and dimension values, general ledger entries with dimensions. Custom APIs are supported |
| Oracle NetSuite | ERP | Journal entries, transactions, accounts, departments, classes, locations, subsidiaries, customers, vendors, employees, budgets, currencies, accounting periods, consolidated exchange rates, items, custom segments; any SuiteQL query |
| Xero | Accounting | Accounts, budgets, contacts, currencies, invoices, organisation, payments, prepayments, purchase orders; profit and loss and balance sheet reports |
| QuickBooks Online | Accounting | Accounts, classes, locations, invoices, bills, journal entries; profit and loss and balance sheet reports |
| 24SevenOffice | Accounting | Accounts, customers, transaction lines, account balances, currencies, organisations, products and categories, bank accounts and transactions, taxes, transaction types, sales orders and types |
| Procountor | Accounting | Companies, currencies, dimensions, fiscal years, persons, invoices, ledger receipts, journals, ledger accounts, payments, products, general ledger |
| Tripletex | Accounting | Companies, contacts, currencies, departments, employees, accounts, accounting periods, projects, customers, suppliers, invoices, ledger, postings, vouchers, supplier invoices |
| Fennoa | Accounting | Customers, dimensions and dimension types, sales invoices, accounts, VAT codes, periods, locking periods, budgets, ledger, opening balances |
| Fiken | Accounting | Companies, accounts, account balances, contacts, products, invoices, sales, purchases, journal entries, transactions, bank accounts and balances, offers, inbox documents, projects |
| Kleer | Accounting | Vouchers with details, and an expanded general ledger with every transaction reference and the instance-specific code parts; dimensions, clients, client projects, activities, events, users, company information; a derived forecast of future supplier payments based on payment history. Data can also be read from Kleer's analytics database (*Analytics SQL*) through the MySQL connector, which is faster than the API for large volumes |
| Björn Lundén | Accounting | Accounts, articles, cost bearers, cost centres, financial years, projects, journals |
| RamBase | ERP | General ledger, ledger accounts and account groups, report account groups, dimension definitions, finance projects, departments, companies, customers, sales invoices, suppliers, supplier invoices, employees |
| Rillion One | AP automation | Supplier invoices, filtered by status and change date |
| HubSpot | CRM | Deals, companies, contacts, products, line items, owners, deal pipelines; search and associations |
| Pipedrive | CRM | Deals with products, organisations with custom fields, persons, stages, users |
| Upsales | CRM | Subscriptions, products, companies, orders |
| Younium | Subscription billing | Invoices, measurements, sales orders, units of measurement, products, accounts, subscriptions, usage, reports, insights metrics |
| Revny | Subscription billing | Customers, subscriptions, products, invoices |
| Plock.io | Subscription billing | Accounts, subscriptions, invoices |
| Blikk | Time and project | Time reports, projects, contacts, time codes, payment plans, time articles, activities, cost centres, users |
| Hailey HR | HR | Employees, employments, casual employments, salaries, salary types, departments, legal entities, cost centres, business areas, locations, titles, teams, custom fields, absence per employee and day |
| Zendesk | Customer support | Tickets, organisations, ticket fields |
!!! agent "Pitfalls for agents"
Destructive import semantics (`replace` deletes missing rows, `Replace` mode on access imports) are summarised in the [Agent guide](agent-pitfalls.html#destructive-operations).
## Related
- [APIs and SQL access](apis.html)
- [Security and access](security.html)
- [Data model](data-model.html)
- [Traceability](traceability.html)
- [AI agents and MCP](ai-agents.html)
---
# APIs and SQL access
> Programmatic access to a Konstrukt tenant — the REST API and its OAuth client-credentials authentication, the Kex query endpoint, and the external SQL views with point-in-time queries.
A Konstrukt tenant can be read and written by other systems through three machine interfaces: the **REST API**, the **Kex endpoint** of that API (run a Kex script, get JSON back), and **external SQL views** for BI and data-warehouse tools. AI agents use a fourth interface, the MCP server, described in [AI agents and MCP](ai-agents.html). Inbound file imports are covered in [Data integration](integration.html).
| Interface | Direction | Protocol | Typical consumer |
|---|---|---|---|
| REST API | Read and write | HTTPS, JSON, OAuth 2.0 | Integration services, scripts |
| Kex endpoints (`/api/v1/kex…`) | Validate, read and write Kex scripts (results as JSON) | HTTPS, OAuth 2.0 | Applications that need model-aware queries |
| Import endpoint (`/api/v1/import/{key}`) | Write | HTTPS, OAuth 2.0 | See [Data integration](integration.html#rest) |
| External SQL views | Read | T-SQL over TCP 1433 | BI tools, data warehouses |
| MCP server (`/api/mcp`) | Read and write | Model Context Protocol | AI agents |
## REST API
Each tenant serves its API on its own host: `https://{tenant}.konstrukt.app/api/...`.
The endpoint reference is generated from the running service and is always current. Every tenant serves it at `/api/documentation/index.html`, for example [https://acme.konstrukt.app/api/documentation/index.html](https://acme.konstrukt.app/api/documentation/index.html). This page does not duplicate it.
| Resource | Path |
|---|---|
| Interactive reference (Swagger UI) | `/api/documentation/index.html` |
| OpenAPI 3.0 specification | `/api/v1/openapi.json` (no sign-in required) |
| OAuth 2.0 server metadata | `/.well-known/oauth-authorization-server` |
All operations are under `/api/v1`. There is currently one API version.
### Authentication
The API uses **OAuth 2.0**. The token endpoint supports two grant types:
| Grant | Used by |
|---|---|
| `client_credentials` | Integrations and scripts, with an API key |
| `authorization_code` (with PKCE) | Interactive clients that sign in through the browser, such as MCP clients |
For integrations:
1. **Create an API key** in the tenant under Integration → API keys (*API-nycklar*). Only administrators can create keys. The key is created for a chosen user and carries that user's permissions. The **Key ID** and **API key** are shown **once**, when the key is created. Store them then, because an existing key cannot be displayed again. Keys are valid for one year by default.
2. **Request an access token.**
| Property | Value |
|---|---|
| Endpoint | `POST https://{tenant}.konstrukt.app/api/v1/token` |
| Content type | `application/x-www-form-urlencoded` |
| `grant_type` | `client_credentials` |
| `client_id` | Key ID |
| `client_secret` | API key |
```bash
curl -X POST https://{tenant}.konstrukt.app/api/v1/token \
-d "grant_type=client_credentials" \
-d "client_id={key-id}" \
-d "client_secret={api-key}"
```
3. **Call the API** with the returned `access_token` as a bearer token:
```
Authorization: Bearer {access_token}
```
A minimal Python client:
```python
import requests
BASE_URL = "https://{tenant}.konstrukt.app"
token = requests.post(f"{BASE_URL}/api/v1/token", data={
"grant_type": "client_credentials",
"client_id": "{key-id}",
"client_secret": "{api-key}",
}).json()["access_token"]
headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
# Call any endpoint listed in /api/documentation/index.html with these headers.
```
An access token from `client_credentials` is valid for about **six hours**. The specification defines no refresh grant, so when a token expires, request a new one with the same credentials. Interactive clients that sign in with `authorization_code`, such as MCP clients, can choose a longer token lifetime, up to 30 days.
The API has no rate limits, and no rate-limit headers are returned. Batch work rather than sending many small calls, since every write triggers dependent calculations.
### Kex endpoints
The Kex endpoints run a [Kex](kex.html) script against the tenant and return the result as JSON. They give external systems the same query semantics as calculations and apps: implicit joins over shared dimensions, plan and reference selection (`from plan`, `from reference`), and point-in-time reads (`from history`).
| Method and path | Body | Returns |
|---|---|---|
| `POST /api/v1/kex/script/validate` | `{ "Script": "…" }` | Validation result |
| `POST /api/v1/kex/script/read` | `{ "Script": "…" }` | `{ "resultSets": [ { "name", "rows" } ] }` |
| `POST /api/v1/kex/script/write` | `{ "Script": "…" }` | Result sets, including insert, update and delete counts for each write |
| `GET /api/v1/kex?script=…` | — | A flat array of rows |
```json
POST /api/v1/kex/script/read
{ "Script": "Total = sum(Amount), Department where Month >= \"202401\" from plan 3" }
```
A script can return several result sets, one per `evaluate` or bare expression.
!!! warning "Writes go to the default plan"
The Kex endpoints take no plan parameter. A script runs in the tenant's [default plan](concepts.html#plan): `from plan` changes where data is read from, not where a `write` goes. To work in another plan, start the script with [`use plan`](kex.html#use-plan). Test write scripts with `/validate` first.
### Import endpoint
`/api/v1/import/{key}` imports a file using an import configuration. It is one of three transports for the same configuration; see [Data integration](integration.html).
## External SQL views
For BI tools and data warehouses, Konstrukt exposes read-only **external views** in the `externalViews` schema of the tenant's SQL database.
### Connecting
Create an SQL integration account (*SQL-integration*) under Integration → Accounts (*Konton*):
| Setting | Value |
|---|---|
| Host | `sql.konstrukt.app` |
| Port | `1433` |
| User | Account-specific user ID |
| Password | Generated when the account is created |
| Network | Connections only from IP addresses on the account's allow-list |
The views are queried with T-SQL.
### Enable export {#active-export}
A dimension or value type only gets a view when **Enable export** (*Aktivera export*) is ticked for it. The switch is in the object's Integration side panel (*Integration* → *Exportera*), together with a ready-made statement with a copy button and a link to the SQL integration settings (*Gå till SQL-integration*):
```sql
select * from externalViews.d_Department where PlanId = 3
```
### View catalogue
| View | Content |
|---|---|
| `externalViews.Plan` | All plans: `PlanId`, `Name`, `IsActive`, `IsDefault` |
| `externalViews.Reference` | All references usable for value type data: `ReferencedId`, `PlanId`, `Name`, `Description` |
| `externalViews.vt_{ValueType}` | Plan data of one value type |
| `externalViews.vtr_{ValueType}` | Reference data of one value type (adds `ReferenceId`) |
| `externalViews.d_{Dimension}` | Dimension values of one dimension with their properties |
| `externalViews.Metadata` | Lists available views — for troubleshooting only; content may change |
By default the value type and dimension views contain data from **all active plans**, with a union of the dimensions (or properties) used across those plans. Konstrukt can configure the views per plan — for example only the default plan, a range of plans, or including archived plans.
### Value type views
`externalViews.vt_{ValueType}` has one column per dimension plus:
| Column | Meaning |
|---|---|
| `PlanId` | Plan of the row |
| `ValueTypeId` | Value type ID |
| `DecimalValue` | Value for numeric value types |
| `StringValue` | Value for text value types (instead of `DecimalValue`) |
| `DateValue` | Value for date/time value types, in UTC |
| `CalculationId` | ID of the calculation that wrote the row; empty for non-calculated rows |
| `EditTime` | Last time the value changed |
| `EditState` | Type of the last change (below) |
| `EditState` | Meaning |
|---|---|
| `0` | Suggested — created in the admin interface or imported through an integration |
| `10` | Set by a user in an app |
| `30` | Set by a calculation |
```
PlanId ValueTypeId Year Month DecimalValue
3 Amount 2024 10 99500.00
3 Amount 2024 11 99500.00
4 Amount 2025 1 100250.00
```
### Dimension views
`externalViews.d_{Dimension}` has `PlanId`, `DimensionId`, `Code`, `Name`, `EditTime`, and two columns per property: `{Property}_Code` and `{Property}_Name`.
```
PlanId DimensionId Code Name Region_Code Region_Name
3 Department 100 Sales N North
3 Department 200 Marketing S South
```
### Point-in-time queries
The views are temporal: the state of the data at any earlier moment can be queried with `for system_time as of` (UTC).
```sql
-- Amount as it stood on 1 June 2025, 00:00 UTC
select * from externalViews.vt_Amount for system_time as of '2025-06-01 00:00:00'
```
Point-in-time references do not appear in the `vtr_` views — they store a moment, not data. Query the `vt_` view with `for system_time as of` at the reference's timestamp instead. See [References and history](references-history.html).
### Compatibility and other views
- Older databases expose an earlier version of the views in the `dbo` schema with the prefix `vw_external_`. Differences: `PlanLineId` is removed from value type views, `DimValueId`/`Id` from dimension views, and property names are always included.
- Additional views (for example apps, app statuses or access groups) can be created for specific needs. They are not guaranteed to be as stable as the views listed above.
!!! warning "Sensitive value types are visible in SQL views"
The SQL integration account is one account per tenant and sees all data. Values of sensitive value types (`isSensitive`) are **not** hidden in the `vt_` views. See [Security](security.html#sensitive-value-types).
## Choosing an interface
| Need | Use |
|---|---|
| Nightly load of actuals from an ERP | Import configuration + storage, SFTP or KDI ([Data integration](integration.html)) |
| Immediate feedback on each import | `/api/v1/import/{key}` |
| BI dashboards on plan data, including history | External SQL views |
| An application that needs aggregated, model-aware answers | Kex endpoint |
| Building or changing the model itself | MCP server ([AI agents and MCP](ai-agents.html)) or the admin GUI |
!!! agent "For agents"
MCP clients do not need the REST API: `execute_read_script` runs the same Kex as `/api/v1/kex`, and the import tools cover the import endpoint. Use the REST API only when generating code for a customer's own integration. Always point to `https://{tenant}.konstrukt.app/api/documentation/index.html` for endpoint details instead of guessing request shapes.
## Related
- [Data integration](integration.html)
- [Kex](kex.html)
- [References and history](references-history.html)
- [Security and access](security.html)
- [AI agents and MCP](ai-agents.html)
---
# AI agents and MCP
> How AI agents work with a Konstrukt tenant — the embedded MCP server, its knowledge resources and tenant documents, the full tool catalogue, safe working rules, the in-product assistant Kai, and the agent-readable sources of this documentation.
Every Konstrukt tenant embeds a **Model Context Protocol (MCP) server** in its API. An MCP-capable agent connected to it can read and build the whole model — plans, dimensions, value types, calculations, references, apps and access rules — import data, and validate and run Kex scripts, within the privileges of the user it acts as. The server also ships the knowledge an agent needs to write correct Kex and app configuration. Inside the product, the assistant **Kai** uses the same authoring rules.
## The MCP server
| Property | Value |
|---|---|
| Endpoint | `https://{tenant}.konstrukt.app/api/mcp` |
| Scope | One tenant per server; the caller's own user |
| Tool filtering | Tools are filtered by the caller's privileges |
| Plan access | Plan-scoped operations check the caller's access to that plan |
| Server instructions | Sent on connect: core concepts, where the knowledge resources are, working rules |
### Identifiers
| Object | ID type | Example |
|---|---|---|
| Value type | String | `"Amount"` |
| Dimension | String | `"Department"` |
| Plan | Integer | `3` |
| Calculation | Integer | `101` |
| Dimension property | Integer (also has `code` and `name`) | `9905` |
| App | GUID string | `"7c1e…"` |
| Import configuration | Key (GUID) | — |
`isLegacy` appears on plans only when the tenant still has legacy (v1) plans; most tenants have only v2 plans. App-config writing is supported for v2 plans only.
### Authentication and access
- An MCP client signs in through the browser with an **API key**: the Key ID and API key are entered as client ID and client secret in a web sign-in. The key belongs to a user account, and the MCP session carries that user's permissions.
- After the move to the new hosting environment (autumn 2026), MCP clients will instead authenticate with the tenant's ordinary sign-in methods, such as Microsoft and Google accounts. See [Sign-in](security.html#sign-in).
- MCP access is currently available to **administrators**.
Tested clients: Claude, ChatGPT, Microsoft Copilot, Google Gemini and OpenCode, including OpenCode with models hosted by Berget AI.
### Connecting a client
1. In the MCP client, add a remote MCP server (connector) with the URL `https://{tenant}.konstrukt.app/api/mcp`.
2. Connect. The client opens a Konstrukt sign-in page in the browser.
3. Sign in with an API key: enter the **Key ID** as client ID and the **API key** as client secret. See [Machine credentials](security.html#machine-credentials).
4. The client lists the tools and resources the account has access to. Start with `konstrukt://TenantInstructions.md`, see [Working rules](agent-pitfalls.html#working-rules).
Integrations that call the REST API directly use the same key pair as client ID and client secret in the `client_credentials` grant. See [REST API](apis.html).
## Knowledge resources
Platform knowledge is exposed as **MCP protocol resources** (`resources/list`, `resources/read`):
| URI | Content | When to load |
|---|---|---|
| `konstrukt://resources/kex/KexOverview.md` | Short structural overview of Kex: clause skeleton, implicit resolution, identifiers, expansion | First, for most syntax questions |
| `konstrukt://resources/kex/KexDocumentation.md` | Complete Kex language reference | Only when the overview is not enough |
| `konstrukt://resources/kex/KexGuidelines.md` | Authoring rules: clause order, minimal scripts, validate before returning, disambiguation | Before writing scripts |
| `konstrukt://resources/kex/KexKnowledge.md` | Known pitfalls (custom grouping duplication, windowing over un-aggregated value types) | Before windowed or grouped scripts |
| `konstrukt://resources/kex/KexScriptExamples.md` | A few minimal examples | Optional |
| `konstrukt://resources/kex/GeneralInstructions.md` | Concept definitions: plan, dimension, property, value type, dataset, calculation, app | When unsure of a concept |
| `konstrukt://schema/app-config` | JSON Schema (draft 2020-12) for app configuration, about 123,000 characters | For clients that can attach resources; agents should read the types they need with `get_app_config_schema` instead |
| `konstrukt://TenantInstructions.md` | Tenant-specific instructions and links to tenant documents | **At the start of any work** on a tenant |
| `konstrukt://tenant/{name}` | Tenant-authored documents | As linked from `TenantInstructions.md` |
The human-readable equivalents are [Kex](kex.html), the Kex reference at [https://acme.konstrukt.app/api/documentation/kex](https://acme.konstrukt.app/api/documentation/kex) (served by every tenant at the same path) and [App configuration](app-config.html).
### Tenant knowledge base
A tenant can publish its own conventions for agents: naming rules, which plan holds what, how a recurring refresh is done.
- `save_mcp_resource(name, content, description)` creates or replaces a document. Names may contain `/` for folders (`plans/sales.md`); allowed characters are `a-z A-Z 0-9 . - _ ~` and `/`. Documents appear as `konstrukt://tenant/{name}`.
- Saving `TenantInstructions.md` rewrites the tenant instructions sent to clients. It **cannot be deleted**; save empty content to stop sending instructions.
- `delete_mcp_resource` deletes a document permanently.
- A proven pattern: one document per plan under `plans/`, each linked from `TenantInstructions.md`, stating the plan's dimensions, code conventions, known data quirks and the exact refresh procedure.
!!! note "Two resource surfaces"
The tools `list_mcp_resources` and `get_mcp_resource` only see **tenant documents** (`TenantInstructions.md` and documents saved with `save_mcp_resource`). The platform resources under `konstrukt://resources/kex/` and the schema are read through the MCP protocol's `resources/read`, not through `get_mcp_resource`.
## Tool catalogue
A caller with full privileges currently sees 61 tools.
### Plans
| Tool | Purpose |
|---|---|
| `list_plans` | All accessible plans, active and archived: `id`, `name`, `isActive`, `isDefault` (and `isLegacy` if applicable) |
| `get_data_model` | Metadata for one or more plans; `include` = `*`, `(none)` or entity names `ValueTypes`, `Dimensions`, `DimensionProperties`, `Calculations` |
| `create_plan` | New plan, optionally a copy of an active plan (`copyFromPlanId`) |
| `update_plan` | Rename a plan (only provided fields change) |
| `archive_plan` | Set a plan inactive; required before deletion |
| `delete_plan` | Permanently delete an archived plan |
### Dimensions and properties
| Tool | Purpose |
|---|---|
| `list_dimensions` | Dimensions of a plan |
| `create_dimension` · `update_dimension` · `delete_dimension` | Dimension CRUD (`id`, `name`, `description`) |
| `list_dimension_properties` | Properties of a dimension: `id`, `code`, `name`, `description` |
| `create_dimension_property` | New property; `bindToDimensionId` binds it to another dimension |
| `update_dimension_property` · `delete_dimension_property` | Property CRUD |
| `insert_dimension_data` · `update_dimension_data` · `upsert_dimension_data` | Import dimension values (insert-only, update-only, upsert); `autoCreatePropertyValues` |
| `insert_dimension_property_data` · `update_dimension_property_data` · `upsert_dimension_property_data` | Import property values; property identified by `propertyIdentifier` (name, then code, then ID) |
### Value types and data
| Tool | Purpose |
|---|---|
| `list_value_types` | Value types of a plan |
| `create_value_type` · `update_value_type` · `delete_value_type` | Value type CRUD: `id`, `name`, `dimensionIds[]`, `formatCode`, `viewPrecision`, `editPrecision`, `isSensitive`, `description` |
| `insert_value_type_data` · `update_value_type_data` · `upsert_value_type_data` | Import plan or reference data |
| `replace_value_type_data` | Insert, update and **delete rows not in the payload** |
| `delete_value_type_data` | Delete rows matching an uploaded filter file |
| `import_data` | Run a pre-defined import configuration by key |
### References
| Tool | Purpose |
|---|---|
| `list_references` | References of a plan: `id`, `name` |
| `create_reference` | Data reference, or point-in-time reference when `pointInTime` is given |
| `update_reference` | Update a reference; a data reference cannot become point-in-time or vice versa |
| `delete_reference` | Delete a reference and its reference data |
### Calculations
| Tool | Purpose |
|---|---|
| `list_calculations` | Calculations with `script`, `isEnabled`, `isValid`, `validationMessages[]` |
| `create_calculation` · `update_calculation` · `delete_calculation` | CRUD with server-side validation; `update_calculation` also takes `enabled` |
| `get_calculation_graph` | Dependency graph: per calculation `level`, `references[]`, `outputs[]`, `dependsOn[]`; filter by `planIds`, `referencedEntityIds`, `outputEntityIds` |
| `get_running_calculations` | Running or enqueued calculations in one plan |
| `get_all_running_calculations` | Running or enqueued calculations across plans (plan ID → calculation IDs) |
### Scripts
| Tool | Purpose |
|---|---|
| `validate_script` | Validate a Kex script without executing it |
| `execute_read_script` | Run a read-only script; returns one or more named result sets |
| `execute_write_script` | Run a script that may modify data; write result sets report `Inserted`, `Updated`, `Deleted` |
### Apps
| Tool | Purpose |
|---|---|
| `list_apps` | Apps in a plan: `id` (GUID), `name`, `description` |
| `search_app_config` | Find parts of an app's configuration by JSONPath or JSON Pointer, with the pointer of each match |
| `load_complete_app_config` | Read an app's whole configuration as JSON, with an etag (v1 and v2) |
| `patch_app_config` | Change parts of a configuration with a JSON Patch; `dryRun` and `ifMatch` supported (v2 only) |
| `overwrite_complete_app_config` | Replace a whole configuration (v2 only) |
| `validate_complete_app_config` | Validate a configuration without saving (v1 and v2) |
| `create_app_with_config` | Create an app and write its configuration in one call (v2 only); name and description are parameters, not part of the JSON |
| `delete_app` | Permanently delete an app and all its data |
### Access
| Tool | Purpose |
|---|---|
| `get_users` | Active users with roles, plan access and user type |
| `get_groups` · `get_roles` | Groups with their roles; roles with their groups |
| `get_access_rules` | Rules of one access list (`planId`, `accessListId`) |
| `import_users` | Import users (default mode `Insert`); creates **no logins** — for SSO tenants |
| `import_groups` · `import_roles` · `import_access_rules` | Import with mode `Insert`, `Update`, `Upsert` (default) or `Replace` |
### MCP resources
| Tool | Purpose |
|---|---|
| `list_mcp_resources` | List tenant documents |
| `get_mcp_resource` | Read a tenant document by name |
| `save_mcp_resource` | Create or replace a tenant document (including `TenantInstructions.md`) |
| `delete_mcp_resource` | Delete a tenant document (not `TenantInstructions.md`) |
### Documentation and schema
| Tool | Purpose |
|---|---|
| `list_documentation` | List the platform documentation pages |
| `read_documentation` | Read a page by uri, `konstrukt://resources/docs/.md` |
| `get_app_config_schema` | Describe app-config types. Without `types`, the root (`AppConfigModel`) and every type name; with `types`, each type's properties, which are required, the `$type` of each variant and the types they refer to. Use it **before** building any app-config payload |
### Not available through MCP
Flows, precalculation configuration, creating or listing access lists, integration configurations and jobs, cell comments, app rename or copy, API keys, themes and feature flags. Use the admin GUI for these.
!!! note "Tools follow privileges"
The tool list is filtered by the signed-in user's privileges. An agent should treat a missing tool as a permission boundary, not as an error to work around.
## Data import parameters
The `insert_*`, `update_*`, `upsert_*`, `replace_*` and `delete_*` data tools share these parameters:
| Parameter | Meaning |
|---|---|
| `contentType` | `text/csv` (semicolon-separated), `text/tab-separated-values`, or `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet` (shorthand `application/vnd.ms-excel`) for xlsx |
| `data` | File content as a string (or request body) |
| `fieldMappings` | Comma-separated, **index-based** target per column; empty entry skips the column. Value type files: `Value` and dimension IDs. Dimension files: `Code`, `Name`, property names |
| `sheetName` | Sheet for xlsx |
| `planId` | Target plan; `null` = default plan |
| `referenceId` / `referenceName` | Write reference data instead of plan data |
| `aggregation` | Duplicate rows: `Sum`, `Min`, `Max`, `Avg`, `Concatenate`, `Disabled` |
| `autoCreateDimensionValues` · `autoCreatePropertyValues` · `autoCreateConfig` | Create missing values or configuration automatically |
| `notifyEmail` | `default`, `none`, or a list of addresses |
| `dataOrigin` | Label written to the import log |
```json
{
"planId": 3,
"contentType": "text/csv",
"fieldMappings": "Department,Month,Value",
"aggregation": "Sum",
"autoCreateDimensionValues": false,
"dataOrigin": "agent: monthly refresh",
"data": "Department;Month;Amount\n100;202401;1200\n200;202401;800"
}
```
Semantics are the same as in the GUI and the other transports; see [Data integration](integration.html#import-semantics).
## Script validation contract
`validate_script` returns a typed result without touching data:
```json
{
"$type": "Valid",
"isReadOnly": false,
"resultSets": [
{
"name": "Result",
"type": "WriteResult",
"columnNames": ["Inserted", "Updated", "Deleted"],
"columnTypes": ["…"],
"writeTarget": { "$type": "…", "valueTypeId": "Amount" }
}
]
}
```
| Field | Meaning |
|---|---|
| `$type` | `Valid` or `Invalid` (then `error` holds the message) |
| `isReadOnly` | `true` if the script contains no write statement — safe for `execute_read_script` |
| `resultSets[].type` | `Query` for evaluated expressions, `WriteResult` for `write` statements |
| `resultSets[].columnNames` · `columnTypes` | Columns of the result set; write results report `Inserted`, `Updated`, `Deleted` |
| `resultSets[].writeTarget` | Target of a write statement (e.g. `valueTypeId`) |
The write target of a script resolves in the **default plan**; `from plan N` in the source query does not change it. `use plan N` at the start of the script does: see [`use plan`](kex.html#use-plan).
## Working rules
The server's own guidance gives agents a small set of working rules: read the tenant instructions first, validate before running, never retry write scripts automatically, read the app-config schema before writing configuration, and respect destructive semantics. They are collected, with known pitfalls per area, in the [Agent guide: pitfalls and learnings](agent-pitfalls.html#working-rules).
!!! agent "Before any change"
Read the [Agent guide](agent-pitfalls.html) once. Show the user the validated script or payload and wait for confirmation before calling a write tool.
## Kai
Kai is Konstrukt's in-product assistant, opened from the top bar. It is enabled per tenant with the Kai feature flag and has its own settings page under System (*System* → *Kai*); see [Tenant administration](administration.html). The Kex authoring guidelines served to MCP clients are extracted from the practices Kai uses, so scripts written by Kai and by external agents follow the same rules.
AI functionality in the platform is provided through Berget AI, with processing in Sweden. Customer data is not used to train models. See [AI and your data ↗](https://www.konstrukt.se/ai-och-kunddata) and [Hosting and operations](operations.html).
!!! note "Beta"
Kai is a beta feature under development, so its capabilities are not documented here yet. Usage is shown under System → Kai.
## This documentation for agents
Every page of this site is available as Markdown, and the site publishes an index for language models:
| Resource | Content |
|---|---|
| `llms.txt` | Index of all pages with one-line descriptions ([llmstxt.org](https://llmstxt.org) format) |
| `llms-full.txt` | All pages concatenated as Markdown |
| `md/{slug}.md` | Markdown source of one page, e.g. `md/ai-agents.md` |
Pages mark agent-specific guidance in **For agents** callouts.
## Related
- [Kex](kex.html)
- [App configuration](app-config.html)
- [Data integration](integration.html)
- [Security and access](security.html)
- [Architecture](architecture.html)
---
# Tenant administration
> Administering a Konstrukt tenant — navigation, plan lifecycle and the default plan, the plan admin landing, plan documentation, System settings (features, themes, maintenance, console, Kai, advanced) and the help menu.
A tenant is one customer environment at `https://{tenant}.konstrukt.app`, holding any number of plans, their apps and users. Administration happens at two levels: **tenant level** (System, Users, Integration) and **plan level** (the admin landing of each plan). This page covers both, except security and integration, which have their own pages.
## Navigation
| Element | Swedish label | Purpose |
|---|---|---|
| Plans | *Planer* | Plan list and the structure tree of each plan |
| Integration | *Integration* | Import configurations, jobs, transport accounts, API keys — see [Data integration](integration.html) |
| Users | *Användare* | Users, roles and groups — see [Security and access](security.html) |
| System | *System* | Tenant-wide settings (below) |
The left rail holds these four entries; its panel can be pinned. The top bar holds Notifications, **Act as** (*Agera som*, switch to another role), Go to admin (*Gå till admin*), Settings (*Inställningar*), Help (*Hjälp*) and Kai.
Under a plan, the structure tree lists the plan's apps directly, followed by Apps (*Appar*), Access lists (*Behörighetslistor*), **Data model & logic** (*Datamodell & logik*: Dimensions, Value types, Calculations, Flows — *Dimensioner · Värdetyper · Beräkningar · Flows*) and Archived plans (*Arkiverade planer*).
In lists, the chevron at the start of a row expands a summary panel; clicking the **name** opens the object.
## Plans
A plan is the top-level container of a data model: dimensions, value types, calculations, references and apps. Users only see plans they have access to.
### Plan list
The plan list offers grid and list views, search and sorting. One plan carries the **DEFAULT** badge.
The **default plan** (`isDefault`) is the implicit context for Kex: a script without `from plan` reads from — and a `write` statement writes to — the default plan. Scripts that work on another plan state it explicitly, per query with `from plan`, or for the rest of the script with [`use plan`](kex.html#use-plan):
```kex
sum(Amount) group by Department from plan 3
```
### Plan overview
Opening a plan shows Recent apps, All apps and Notes (*Senaste appar · Alla appar · Anteckningar*). Notes show the plan documentation.
### Lifecycle
| Step | MCP tool | Notes |
|---|---|---|
| Create | `create_plan` | Empty, or a copy of an existing **active** plan (`copyFromPlanId`) |
| Rename | `update_plan` | Only provided fields change |
| Archive | `archive_plan` | Sets the plan inactive; it moves to Archived plans (*Arkiverade planer*) |
| Delete | `delete_plan` | Only possible for an archived plan; permanent |
Archiving is the normal way to retire a plan: archived plans remain listed (`list_plans` returns them with `isActive: false`) and can be included in SQL views on request.
!!! warning "Delete is permanent"
Deleting a plan cannot be undone. Archive first, verify that nothing depends on the plan (cross-plan calculations, SQL consumers, integrations), then delete.
A copy includes **the whole plan**: model, current plan data, references and everything else in the plan. Only the **history tables** are left out. Two consequences:
- **Point-in-time references are empty in the copy**, because they read from history. Data references keep their stored data.
- Copying a plan, then archiving and deleting the original, is a way to clear a plan's history (see [Data retention](operations.html#data-retention-in-the-platform)).
### Plan versions: v1 and v2
Plans are either **v2** (current) or **v1** (legacy). Legacy plans exist only on some tenants and are flagged `isLegacy`. Dataset expressions in Kex and writing app configuration through MCP are v2 features; v1 apps can be read but not written as JSON. New plans are v2.
## Plan admin landing
The admin landing of a plan groups its configuration in four areas, using the product's own descriptions:
| Group | Swedish label | Items | Description |
|---|---|---|---|
| Data model | *Datamodell* | Dimensions (*Dimensioner*), Value types (*Värdetyper*) | Connect dimensions with value types to create a data model. Dimensions are the categories of the plan (products, employees, markets, periods); value types structure the numbers and values stored in the plan, including imported reference data. |
| Interaction | *Interaktion* | Apps (*Appar*), Access lists (*Behörighetslistor*) | Set up the visual environment for users. Apps are the views through which users see and edit plan data; access lists control which data each group can see. |
| Data logic | *Datalogik* | Calculations (*Beräkningar*) | Calculate new values automatically when plan data changes. |
| Other | *Övrigt* | Plan documentation (*Plandokumentation*) | Describe how the plan is used, for end users and for administrators. |
See [Data model](data-model.html), [Apps](apps.html), [Security and access](security.html) and [Calculations](calculations.html).
### Plan documentation
Plan documentation (*Plandokumentation*) has two separate variants:
| Variant | Audience | Path |
|---|---|---|
| User (*Slutanvändare Konstrukt*) | End users of the plan's apps | `/admin/plans/{planId}/description` |
| Admin (*Admin*) | Administrators maintaining the plan | `/admin/plans/{planId}/description/Admin` |
For agent-facing documentation of a plan, use tenant MCP documents instead; see [AI agents and MCP](ai-agents.html#tenant-knowledge-base).
Both variants are edited in a rich-text editor (font, size, bold, lists, alignment, text colour, links, images, uploaded images and clear formatting) and saved with **Save** (*Spara*). The user variant is shown on the end user's landing page for the plan; the admin variant only on this page.
## System
System (*System*) holds tenant-wide settings.
| Section | Swedish label | Purpose |
|---|---|---|
| Features | *Funktioner* | Feature flags for the tenant |
| Themes | *Teman* | Accent colours and logo (white-labelling) |
| Maintenance | *Underhåll* | Maintenance operations |
| Console | *Konsol* | Kex console |
| Kai | *Kai* | Usage of the in-product assistant |
| MCP | *MCP* | Instructions and resource files for AI agents |
| Advanced | *Avancerad* | Low-level system settings |
### Features
| Feature | Swedish label | Area |
|---|---|---|
| API keys | *API-nycklar* | Integrations with API keys: create keys and build your own integrations |
| Charts | *Diagram* | Chart components in apps |
| Dark mode | *Mörkt läge* | Lets users switch between light and dark theme |
| Kai | *Kai* | Enables the Kai assistant |
| New initial-value logic | *Ny initialvärdeslogik* | The improved client-side expansion algorithm for initial values; an old flag that is normally on |
| Themes | *Teman* | Custom accent colours and logo |
Changes take effect with **Save settings** (*Spara inställningar*).
The page is available to tenant administrators, who can switch the flags themselves. In the English interface the initial-value flag is labelled *New Initial Values (beta)*.
See [Initial values and performance](datasets.html#initial-values-and-performance) for how initial values affect the client.
### Themes
Themes (*Teman*) let a tenant carry the customer's own brand. The editor has:
- a logo for light mode and a logo for dark mode (upload or remove);
- four accent colours (*Accentfärg 1–4*);
- fonts for normal, bold and italic text (default Roboto);
- a live preview of switches, checkboxes, progress bars, buttons, navigation tabs, headings, text and form fields.
**Reset to Konstrukt theme** (*Återställ till Konstrukt-Tema*) restores the original logo, fonts and accent colours. The feature is enabled with the *Teman* feature flag.
### Maintenance
Maintenance (*Underhåll*) has:
| Setting | Swedish label | Purpose |
|---|---|---|
| Clear cache | *Rensa cache* | Clears the tenant's server cache |
| Server status | *Serverstatus* | Online, or offline for maintenance |
| Users with access in offline mode | *Användare som har access i offline läge* | Users who can still sign in while the tenant is offline |
When the tenant is offline, ordinary users cannot sign in. Only the users listed under *Users with access in offline mode* can.
### Console
The Kex console (*Konsol*) runs Kex scripts directly against a plan: a plan selector, an editor with line numbers, live parse errors, and Apply (*Verkställ*) to execute.
!!! warning "The console can write"
A script with a `write` statement changes data when applied. Validate and test read-only first; outside calculations, a plain `write` upserts into the target value type. See [Kex](kex.html).
### Kai
System → Kai shows Kai usage per month: the credit limit, credits used and remaining, and usage per user. See [AI agents and MCP](ai-agents.html#kai).
!!! note "Beta"
Kai is a beta feature under development. The credit limit is a technical usage limit.
### MCP
System → MCP holds the documents that AI agents connected over MCP can read. **Server instructions** (*Serverinstruktioner*) are read by all agents at `konstrukt://TenantInstructions.md`, which Konstrukt's own MCP instructions point them to. Use them to describe the tenant: what the plans are for, naming conventions, and anything agents should always keep in mind. Further resource files can be added here, and can also be written by agents with administrator rights. See [Tenant knowledge base](ai-agents.html#tenant-knowledge-base).
### Advanced
Advanced (*Avancerad*) is a list of low-level system settings as key–value pairs: for example date formats, cache timeouts, the default plan, the tenant's current data-migration version and whether calculations run when dimension values or properties change.
!!! warning "Change only with support"
As the interface warns, changing system settings can cause unexpected behaviour or make the tenant unavailable. Contact Konstrukt support before changing anything here.
## Help menu
The Help menu (*Hjälp*) in the top bar is also the in-product entry point to documentation and support.
| Item | Swedish label | Purpose |
|---|---|---|
| Release notes | *Release Notes* | Changes per version |
| User guide | *Användarguide* | End-user documentation |
| Administrator guide | *Administratörsguide* | Administrator documentation |
| Admin tasks | *Adminuppgifter* | Task-oriented administrator help |
| FAQ | *FAQ* | Frequently asked questions |
| Kex | *Kex* | Reference documentation for the Kex expression language ([Kex reference](https://acme.konstrukt.app/api/documentation/kex), served by each tenant at the same path) |
| Keyboard shortcuts | *Kortkommandon* | Shortcut overview |
| Take a screenshot for support | *Ta en skärmbild för supporten* | Captures the current view for a support case |
| Copy debug information | *Kopiera Debug-information* | Copies debug information to include in a support case |
When reporting an issue, include the debug information and a screenshot, plus the URL: app URLs carry the plan, app, workspace and data-type selection, so a link reproduces the view.
New versions are rolled out in release tracks. Administrators are notified in the interface after a release, and the release notes are in the Help menu. See [Releases](operations.html#releases).
!!! agent "For agents"
There are no MCP tools for feature flags, themes, maintenance, advanced settings, API keys or plan documentation. Plan lifecycle is available through `list_plans`, `create_plan`, `update_plan`, `archive_plan` and `delete_plan`; always check `isDefault` before writing scripts, because `write` targets resolve in the default plan. Never call `delete_plan` without explicit user confirmation.
## Related
- [Security and access](security.html)
- [Data integration](integration.html)
- [AI agents and MCP](ai-agents.html)
- [Data model](data-model.html)
- [Concepts](concepts.html)
---
# Reference documentation
> Links to the reference documentation that Konstrukt generates from the product and keeps up to date automatically — the REST API, the Kex language and Kex Lite — and how it relates to this site and to the MCP resources.
Some documentation is generated from the product itself and is always current for the version a tenant runs. This site links to it rather than duplicating it.
| Reference | Covers | Link |
|---|---|---|
| REST API | All endpoints with request and response schemas, and an interactive explorer | [api/documentation/index.html ↗](https://acme.konstrukt.app/api/documentation/index.html) |
| Kex | The full Kex language: statements, clauses, options, operators and every function | [api/documentation/kex ↗](https://acme.konstrukt.app/api/documentation/kex) |
| Kex Lite | The expression dialect used in app datasets | [api/documentation/kex-lite ↗](https://acme.konstrukt.app/api/documentation/kex-lite) |
Every tenant serves the same paths on its own host:
```
https://{tenant}.konstrukt.app/api/documentation/index.html
https://{tenant}.konstrukt.app/api/documentation/kex
https://{tenant}.konstrukt.app/api/documentation/kex-lite
```
Use your own tenant's address to see the reference for the exact version you run.
## Other sources
| Source | Content | Access |
|---|---|---|
| In-product help menu | Release notes, guides, Kex reference link, keyboard shortcuts | Help menu in the product, see [Administration](administration.html) |
| Plan documentation | Model-specific documentation in user and admin variants | Per plan, in the product |
| MCP resources | `konstrukt://resources/kex/*`, `konstrukt://schema/app-config`, `konstrukt://TenantInstructions.md`, `konstrukt://tenant/*`; app-config types through the tool `get_app_config_schema` | Through the MCP server, see [AI agents and MCP](ai-agents.html) |
| Integration instructions | Generated command lines and scripts per import configuration | Integration panel on each value type and dimension, see [Data integration](integration.html) |
## How the sources divide the work
- **This site** explains concepts, behaviour and how the parts fit together. It is the starting point for learning the platform.
- **Auto-generated references** are authoritative for syntax, function signatures and API contracts.
- **MCP resources** are authoritative for agents working in a specific tenant, including that tenant's own conventions.
If this site and a generated reference disagree about syntax, the generated reference is correct for the tenant's version.
The links on this site point to the generated references on `acme.konstrukt.app`. Every tenant serves the same references for its own version at `https://{tenant}.konstrukt.app/api/documentation/…`.
## Related
- [Kex](kex.html)
- [APIs and SQL access](apis.html)
- [AI agents and MCP](ai-agents.html)
---
# Glossary
> English terms used in this documentation with their labels in the English and Swedish Konstrukt interface, and short definitions.
The Konstrukt interface is available in Swedish and English; see [Interface language](overview.html#interface-language). This glossary maps the English terms used in this documentation to the labels in the English and Swedish interface. A dash means the term has no fixed label in the interface; an empty English cell means the English label has not been verified yet. Names defined in the model, such as dimension and app names, are not translated and appear as entered in both languages.
## Model and data
| English | English (GUI) | Swedish (GUI) | Definition |
|---|---|---|---|
| Tenant | — | — | A customer environment with its own host, users and plans |
| Plan | Plan | *Plan* | Container for a complete data model |
| Default plan | — | — | The plan scripts outside a calculation run against |
| Dimension | Dimension | *Dimension* | Categorical axis, e.g. account or month |
| Dimension value | | *Dimensionsvärde* | A member of a dimension, with code and name |
| Property | Property | *Egenskap* | An extra column on a dimension's values |
| Bound property | | *Bunden till dimension* | A property whose values are values of another dimension |
| Value type | Valuetype | *Värdetyp* | A measure stored over a set of dimensions |
| Plan data | Plan data | *Plandata* | The current data of a plan |
| Reference | Reference | *Referens* | A named version of data for comparison |
| Point-in-time reference | | *Tidpunkts-referens* | A reference that stores only a timestamp and reads history |
| History | History | *Historik* | All earlier versions of value-type data |
| Sensitive data | Sensitive data | *Känslig data* | Value-type setting that hides values from unauthorised users |
| Display format | Display as | *Visa som* | How dimension values are shown: code, name or both |
| Display precision | Decimal presentation | *Decimalpresentation* | Decimals shown |
| Entry precision | Decimal input | *Decimalinmatning* | Decimals accepted on entry |
| Value limits | Value limits | *Värdegränser* | Hard minimum and maximum |
| Value warnings | Value warnings | *Värdevarningar* | Soft lower and upper bounds |
| Connections | Connections | *Kopplingar* | Panel for tracing dimension values across value types |
## Logic
| English | English (GUI) | Swedish (GUI) | Definition |
|---|---|---|---|
| Calculation | Calculation | *Beräkning* | A Kex script run automatically on source change |
| Guided calculation | Calculation (type) | *Beräkning* (type) | A calculation edited as a form |
| Script calculation | Script (type) | *Skript* (type) | A calculation edited as free Kex |
| Source data | Source data / Sources | *Källdata* / *Källor* | Value types a calculation reads |
| Destination value type | Destination valuetype | *Destinationsvärdetyp* | Where a calculation writes |
| Working-set table | Workset table | *Arbetssettabell* | Preview of the joined rows a formula iterates over |
| Output | Output | *Utdata* | Preview of the result at destination grain |
| Diagnostics | | *Diagnostik* | The Kex transformation steps for a query |
| Property defaults | Property defaults | *Standardvärden för egenskaper* | Fallback values for missing properties |
| Run order | Run order | *Körordning* | A calculation's level in the dependency graph |
| Run time | | *Körtid* | Duration of the last run |
| Invalid | Invalid | *Ogiltig* | Status of a calculation whose script fails validation |
| Inactive | Inactive | *Inaktiv* | Status of a disabled calculation |
| Suggested value | | *Föreslaget värde* | A value written with `write suggestion`, which the user may overwrite |
| Precalculation | | *Förberäkning* | An intermediate calculation used only as a source |
| Flow | Flow | *Flöde* | A saved, parameterised script run on demand |
## Apps
| English | English (GUI) | Swedish (GUI) | Definition |
|---|---|---|---|
| App | App / Application | *App* | End-user interface over one plan |
| Dataset | Dataset | *Dataset* | Value types and dimensions with expressions and rules |
| Workspace | Workspace | *Arbetsyta* | A page in an app with filters, data types and layout |
| Component | Component | *Komponent* | An element in a workspace |
| Layoutable action | Layoutable Action | *Layoutbar åtgärd* | An action placed in the layout |
| Table (grid) | Grid | *Tabell* | Grid component |
| Text (label) | Text | *Text* | Text component with Markdown |
| Metric | Metric | *Mätvärde* | Single-number component |
| Chart | Charts (Bar, Lines, Pie, Waterfall, Treemap) | *Diagram* | Bar, line, pie, waterfall or treemap |
| Actions | Actions | *Handlingar* | Action components: forms that run Kex |
| Initial values | Initial values | *Initialvärden* | Generated placeholder rows |
| Locked values | Locked values | *Låsta värden* | Rows that cannot be edited |
| Spread | Spread | *Fördelning* | How an entry on an aggregate is distributed to its rows |
| Aggregation | Aggregation | *Aggregering* | How rows are combined |
| Presentation rules | Presentation Rules | *Presentationsregler* | Conditional styling |
| Filter requirement | | *Filterkrav* | Rules for required filter selections |
| Multiple pages | Multi page | *Flera sidor* | Workspace layout with one component per page |
| Grid layout | Grid layout | *Rutnätslayout* | Workspace layout with a 12-column grid |
| Inspect cell | Inspect cell | *Inspektera cell* | Cell inspection panel |
| Evaluate expression | | *Utvärdera uttryck* | Run an expression in a cell's context |
## Security and operations
| English | English (GUI) | Swedish (GUI) | Definition |
|---|---|---|---|
| Role | Roles | *Roll* | A set of privileges |
| Group | Groups | *Grupp* | A set of users |
| Access list | Access List | *Behörighetslista* | Rules restricting which dimension values a user may see or edit |
| Act as | Act as | *Agera som* | Admin function to view the product as another role |
| Integrations | Integration | *Integrationer* | The integration area: jobs, logs, configurations, accounts, API keys |
| Configuration | Config | *Konfiguration* | An import definition, routed by its GUID |
| Configuration types | | *Lägg till · Lägg till & Uppdatera · Uppdatera · Ersätt · Ta bort* | Import configuration types, see [Configuration types](integration.html#configuration-settings) |
| Create new values | | *Skapa nya dimensionsvärden* | Create unknown dimension codes on import |
| Enable export | Enable export | *Aktivera export* | Enables an object's external SQL view |
| Features | Features | *Funktioner* | Tenant feature flags |
| Themes | Theme | *Teman* | Tenant white-labelling |
| Maintenance | Maintenance | *Underhåll* | Tenant maintenance area |
| Console | Console | *Konsol* | Kex console |
## Related
- [Core concepts](concepts.html)
- [Platform overview](overview.html)
---
# Agent guide: pitfalls and learnings
> Best practice for AI agents working in a Konstrukt tenant — working rules, and known pitfalls in Kex, writes, the data model, calculations, app configuration, actions and history, with links back to the platform pages they concern.
This page collects what agents most often get wrong when they work in a Konstrukt tenant through the MCP server, the REST API or the Kex console. The platform pages describe how things work. This page describes the traps.
Each section has a stable anchor, and the platform pages link here from the part they concern. Read the whole page once before making changes in a tenant. Then return to the relevant section before each kind of task.
!!! agent "Where authoritative guidance lives"
The MCP server serves its own guidance as resources: `KexGuidelines.md` (rules for generated scripts), `KexKnowledge.md` (known pitfalls) and `GeneralInstructions.md`. Tenant-specific conventions are in `konstrukt://TenantInstructions.md`. When these resources and this page disagree, the server's resources win for that tenant and version.
## Working rules {#working-rules}
These rules come from the server's own guidance and apply to any agent, including the in-product assistant Kai.
1. **Read `konstrukt://TenantInstructions.md` first** when you start work on a tenant, then the tenant documents it links to.
2. **Load knowledge on demand.** Start with `KexOverview.md`. Open the full reference only when you need it.
3. **Validate before returning or running a script.** Use `validate_script`. On errors, fix and retry a limited number of times (about five), using the error messages.
4. **Never validate or run write scripts in an automated retry loop.** A write is a destructive operation and needs explicit confirmation from the user.
5. **Resolve names from the model and ask only when it is ambiguous.** Syntax questions get a generic example without a model lookup. For data questions, fuzzy-match names against the model. Ask only when two candidates are equally plausible or the data exists in several plans. Never ask the same question twice.
6. **Read the app-config schema before writing configuration.** See [App configuration](#app-configuration).
7. **A calculation must write.** A saved calculation needs a valid `write to`. Create and update both validate on the server.
8. **Respect destructive semantics.** See [Destructive operations](#destructive-operations).
A safe opening sequence on an unknown tenant:
1. `resources/read konstrukt://TenantInstructions.md`
2. The `konstrukt://tenant/…` documents it links to
3. `list_plans` (note `isDefault`)
4. `get_data_model(planId, include="*")`
5. `KexOverview.md`
For any change, show the user the validated script or payload and wait for confirmation before calling a write tool.
## Identifiers {#identifiers}
- Value type and dimension IDs are **strings** (`"Amount"`, `"Department"`).
- Plan, calculation, property and reference IDs are **integers**.
- App IDs are **GUIDs**.
- Display names and IDs often differ. A value type named *Other forecast.Account* may have the ID `OtherForecastAccount`. Always resolve IDs with `get_data_model` or `list_value_types` rather than deriving them from names.
- Dimension codes are strings, even when they look numeric: `Month in {"202601"}`.
## Kex {#kex}
Pitfalls in queries. The language itself is described on the [Kex](kex.html) page.
- **Aggregate before windowing.** A value type often has more dimensions than a query shows, so a window applied to it directly partitions over all of them. Aggregate into a `var` with only the dimensions you need, then apply the window.
```kex
var A = sum(Amount), Account, Month
Cumulative = sum(A) over all previous rows ordered by (Month) partitioned by (Account)
```
- **Custom grouping can duplicate rows.** Group by dimensions, not by free-text properties, and aggregate variable queries.
- **Variables need a value column and unique rows.** `var x = Month` is invalid; `var x = Month, 1` is valid.
- **Cross-plan reads use the other plan's dimensions.** Custom `dim` variables are ignored inside `from plan`. The current plan must have every dimension the foreign data uses.
- **`from` clauses come after grouping.** `from plan`, `from reference` and `from history` must follow `group by`, `having` and `order by`.
- **`apply dim formatting`** works in evaluation results only, not in variables.
- **Clause order is strict.** It runs select → include options → `where` → grouping → `from …` → `limit`/`check`/`apply`. See [Clause order](kex.html#clause-order).
- **Do not invent syntax.** Some valid constructs are missing from the generated reference; they are described under [Control flow and messages](kex.html#control-flow-and-messages). Use a construct only when `validate_script` accepts it.
- **No queries or writes inside `if` blocks.** Blocks hold `var`, `scalar`, `dim`, `set`, nested `if` and `fatal`. Write after the block. Never assume that a keyword from SQL or DAX exists.
- **Each variable needs its own `from plan N`.** A `from plan` clause applies to one query, not to the whole script. Without it, a variable reading another plan fails with *Unknown identifier*.
- **`dimset` works only in table-valued variables** (`var X = …`), not directly in a `write` query.
- **Keep scripts short.** Separate select expressions with commas, leave out redundant `group by`, and add comments sparingly. This makes scripts easier for users to review.
## Writes {#writes}
The semantics are on the [Kex](kex.html#write-variants) page. These are the consequences that surprise agents:
- **The write target resolves in the default plan** for scripts run through MCP, the REST API or the console. `from plan N` in the query changes where data is *read* from, not where it is *written*. Start the script with `use plan N` to make plan N the context for everything after it, including write targets and `makecode … within`. See [`use plan`](kex.html#use-plan).
- **With no keyword, a write is an upsert** outside a calculation, and nothing is deleted. Use `replacement` to remove rows that are not in the result.
- **`replacement` outside a calculation does not delete calculated rows**, and `update` does not modify them. Calculated data is owned by its calculation.
- **Inside a calculation, the first write to a target clears that calculation's earlier rows.** Later writes to the same target in the same run upsert. A calculation never touches other calculations' rows or user-entered rows.
- **`suggestion` is valid only in calculations.** The last suggesting calculation to a target deletes earlier suggestions, unless `insert` or `upsert` is used. Let only one calculation suggest into a given value type.
- **A user value does not replace a calculated value.** Upserting data into a cell a calculation writes creates a separate, non-calculated row, and reads sum the two. To override a calculated number, change its inputs, or write the calculation with `suggestion`.
- **`exclude calculated` still returns suggestions.** Suggested rows carry no calculation ID.
- **Keep write blocks disjoint.** Several `write` blocks to the same target in one calculation should have mutually exclusive conditions, for example on period flags. If they overlap, the result depends on statement order, and the overlapping cells are rewritten on every run, which adds history versions even when the final value is unchanged. See Disjoint writes.
- **Data written through MCP or import tools gets line state 0** (suggested/imported), not 10 (edited in the interface).
- **There is no `write upsert to`.** A plain `write to` already upserts outside calculations; `upsert` is only valid as `write upsert suggestion to`.
- **Every dimension of the target must be assigned**, either implicitly or with `Dim = …`, and the value column is `$result`.
- **Writing an identical value creates no history row.** This is fine, but do not use history to detect whether a script *ran*.
## Data model {#data-model}
- **Changing a value type's dimensions requires emptying it**, and emptying also deletes its history, which removes the basis for point-in-time references. Propose a new value type instead, unless the user explicitly accepts losing history. See [Data model](data-model.html#changing-a-value-types-dimensions).
- **Property bindings must not be circular.**
- **Creating dimension values on import** (*Skapa nya dimensionsvärden*) turns every unknown code into a new member. Check codes against the dimension first, or misspelled codes become new members.
- **Sensitive value types** hide values, not rows, from users without the permission (for example the Limited Builder role). Rows without values can be an access effect rather than missing data. The SQL views do not hide sensitive values.
- **Descriptions are read by other agents.** Put the grain, sign convention, currency and writing calculation in value-type and calculation descriptions.
## Calculations {#calculations}
- **Guided to script is one-way.** Removing the `@@model` annotation and saving permanently turns a guided calculation into a script calculation. Do not strip annotations from guided calculations you edit.
- **Check the graph before changing a calculation.** Call `get_calculation_graph` with `referencedEntityIds` or `outputEntityIds` to see what depends on the value types you touch.
- **Cycles are detected when a calculation is activated**, not when it is saved. A valid script can still be rejected by the graph.
- **An invalid calculation does not run.** Check `isValid` and `validationMessages` in `list_calculations` before trusting numbers downstream of it.
- **Recalculation propagates.** A write to a widely read input value type re-runs every dependent calculation. Batch changes instead of writing row by row, and check `get_running_calculations` before reading results that depend on the change.
- **Write sparsely.** Use `having $result != 0` where zeros carry no meaning.
- **Do not promote precalculations** (`Calc`) in new work. Use variables inside the calculation, or a value type.
## App configuration {#app-configuration}
- **Read the schema first.** Use `get_app_config_schema` with the types you will write. Several fields are polymorphic, discriminated by `$type`. Component filter items and presentation-rule value conditions use `Type` instead. A guessed payload can parse but silently omit data.
- **Do not guess property names one at a time.** Read the types with `get_app_config_schema` before writing, for example `["WorkspacePage", "MatrixLayout", "BarChartComponent"]`. When a write is rejected, use the shape the error shows instead of trying another name. A workspace page holds one `MainComponent`, so a chart beside a table needs a `MatrixLayout`.
- **Patch, do not rewrite.**
1. Find the position with `search_app_config` (JSONPath such as `$..MainComponent`); note the pointer and the etag.
2. Build a JSON Patch that changes only what the task needs. Start with a `test` op on a value you expect, so a stale pointer fails instead of editing the wrong node.
3. Run `patch_app_config` with `dryRun: true` and check the reported changes.
4. Run it for real with `ifMatch` set to the etag.
5. Read the changed part back with `search_app_config`.
- **Use `overwrite_complete_app_config` only for wholesale rewrites**, based on `load_complete_app_config` and with `ifMatch`. Validate with `validate_complete_app_config` first.
- **Dataset IDs are integers.** `"DatasetId": 1`, not `"1"`; component IDs stay strings.
- **Writing works in v2 plans only.**
- **Never guess enum codes.**
- Spread is `0`, `1`, `3` or `4`; there is no `2`.
- Format codes are `1`–`4` or `6`; there is no `5`.
- Take line states, line access and display-format IDs from the schema or from these docs.
- **Colours are written without `#`** (`"1F9AAD"`), although the schema text says otherwise. Follow what `load_complete_app_config` returns.
- **References in metrics use the bare ID.** `Metric.DataType` and `Compare.DataType` take `"12"`, not `"Reference_12"`; the latter silently compares against nothing.
- **External-link placeholders are `{DimensionId}`**, not `{d_DimensionId}` as the schema text says.
- **`create_app_with_config` needs an `Id`** in the JSON (any GUID). Check `list_apps` after an error; earlier versions could leave an empty app behind when validation failed.
- **A grid without a value-type axis sums across value types.** Put value types on a pivot or grouping axis when a dataset has more than one.
- **Unknown metric icons are silently removed.** Use names from the fixed server list.
- **Name and description are not part of the configuration.** They are parameters of `create_app_with_config`. MCP has no tool to rename or copy an app.
- **Saving through the admin editor is not round-trip.** Comments, unknown attributes and legacy attributes are dropped. See [App configuration](app-config.html#saving-is-not-round-trip).
- **Component errors surface late** and without line numbers. Change one component at a time.
- **Initial values grow the client dataset.** Every placeholder row is held in the browser. Broad expansions on large dimensions cost memory and rendering time, not server load. Scope sets with properties and flags.
- **Hiding an app blocks it completely.** `Access.Enabled = false` removes the app from end-user lists, and opening it by URL gives *access denied*, also for administrators.
- **Copying an app does not copy its comments.**
- **Changes are live.** Users see a changed configuration immediately. Confirm before overwriting a production app.
## Actions {#actions}
- **Actions change data directly** when a user runs them. Treat the script as a write script: validate it and show it to the user.
- **The variable filter panel stays empty until the action is saved.** Save the action first, then configure variable filters.
- **Use `exclude calculated`** in remove-style actions (`write replacement … exclude calculated where not (…)`), so that calculated rows are never rewritten.
## Imports and destructive operations {#destructive-operations}
- **`replace_value_type_data` deletes every row missing from the payload.** Use upsert unless a full replacement is intended.
- **`delete_app` deletes the app.** `delete_plan` requires an archived plan.
- **`Replace` mode on the access imports** replaces existing entries.
- **Duplicate rows in an import** are aggregated or rejected depending on the chosen option. Aggregate the payload yourself so that the result is predictable.
- **`import_users` creates no logins.** On SSO tenants, sign-in is handled by the identity provider.
## History and deletion {#history}
- **Deleting data does not delete its history.** Earlier versions stay readable through `from history` and point-in-time references. Never tell a user that a deletion removed data from the system entirely.
- **A point-in-time reference is rewritten to `from history … values only`.** Rows referring to dimension values that have since been deleted are filtered out.
- **Copying a plan empties its point-in-time references.** The copy includes everything except the history tables, so point-in-time references return nothing. Recreate them from new timestamps, or keep reading from the original plan.
- **References cannot change type.** A data reference cannot become a point-in-time reference, or the other way round.
## Known issues {#known-issues}
- **Use as filter** (*Använd som filter*) in the cell context menu has no effect on a value cell. It works only when chosen on a dimension value. Do not instruct users to use it on value cells.
## Related
- [AI agents and MCP](ai-agents.html)
- [Kex](kex.html)
- [App configuration](app-config.html)