
Core library for fiscal cash register systems — implements business rules, data validation, offline queuing with retries, OFD delivery and configurable HTML receipt rendering with multiple layouts, themes and localization.
superkassa-core is the core multi-project Kotlin Multiplatform (KMP) library for the Superkassa fiscal cash register system. It implements all business rules, data validation, domain entities, and use cases, separated into seven distinct modules:
core-domain: Pure Kotlin Multiplatform domain entities (Receipt, KkmInfo, ShiftInfo) and port definitions (StoragePort, ClockPort, DeliveryPort).core-data: Implementations of storage backing, OFD communication orchestration, retry policies, and lease locking.core-presentation: Presentation layer facade (SuperkassaApi) that exposes the core system functions to client applications.offline-queue: Offline database command queue, handling request caching, retry scheduling with backoff policies, state mapping, and error reporting.core-string: Base localizable string assets, templates, and text resource mappings.delivery: Transportation network delivery layer for sending documents to remote servers.receipt-renderer: Print layout engine for building and formatting receipts in HTML and raw configurations, supporting multiple layouts, sizes (58mm, 80mm, Fullscreen), color themes, and multi-language translations (Russian, Kazakh, English).The core is not published to Maven Central. Every GitHub release carries the compiled library as superkassa-core-maven-<version>.zip: a Maven-layout repository with every module for all targets (JVM, Android, iOS), Gradle module metadata, and the exact builds of ofd-proto-codec, the protocol libraries (ofd-kt-proto, ofd-kt-proto-v204) and ofd-network-client the core was compiled against, none of which is in Maven Central; the remaining dependencies resolve from Maven Central and Google. The core's own build takes those libraries the same way — as compiled builds from their GitHub releases, never from sources.
superkassa-core-maven-<version>.zip from the release and unzip it into a folder, for example libs/superkassa-core.repositories {
maven(uri("libs/superkassa-core"))
// Third-party dependencies of the core (kotlinx, Ktor, Room, …)
mavenCentral()
google()
}
dependencies {
// Embedded core for Android, iOS and desktop applications
implementation("io.github.texport:superkassa-core-embedded:<version>")
// Or a single layer, e.g. the API facade
implementation("io.github.texport:superkassa-core-presentation:<version>")
}The iOS target is packaged as a unified SuperkassaCore binary XCFramework distributed via Swift Package Manager. Add the package reference to your Package.swift:
dependencies: [
.package(url: "https://github.com/texport/superkassa-core", from: "1.1.4")
]superkassa-core — это основная мультипроектная библиотека Kotlin Multiplatform (KMP) для фискальной системы Superkassa. Она реализует все бизнес-правила, валидацию данных, доменные сущности и сценарии использования (Use Cases), разделенные на семь модулей:
core-domain: Чистые сущности предметной области KMP (Receipt, KkmInfo, ShiftInfo) и интерфейсы портов (StoragePort, ClockPort, DeliveryPort).core-data: Реализации портов хранения, отправки документов в ОФД, политик повторных попыток и межпроцессных блокировок.core-presentation: Фасад презентационного слоя (SuperkassaApi), предоставляющий методы интеграции ядра с внешними клиентами.offline-queue: Очередь оффлайн-команд в базе данных, кэширование запросов, политики повторных отправлений (backoff) и статусное логирование.core-string: Базовые локализуемые строковые ресурсы, шаблоны и текстовые маппинги.delivery: Транспортный сетевой уровень для доставки фискальных документов на удаленные серверы.receipt-renderer: Движок генерации печатных форм чеков в формате HTML, поддерживающий различные макеты, размеры ленты (58мм, 80мм, Fullscreen), цветовые схемы и многоязыковую локализацию (русский, казахский, английский).Ядро не публикуется в Maven Central. Каждый выпуск на GitHub несёт собранную библиотеку файлом superkassa-core-maven-<версия>.zip: хранилище в раскладке Maven, в котором каждый модуль со всеми целями (JVM, Android, iOS), метаданные модулей Gradle и ровно те сборки кодека ofd-proto-codec, библиотек протокола (ofd-kt-proto, ofd-kt-proto-v204) и клиента сети ofd-network-client, с которыми собрано ядро, — в Maven Central их нет; остальные зависимости берутся из Maven Central и Google. Сборка самого ядра берёт эти библиотеки так же — готовыми сборками из их выпусков на GitHub, а не из исходников.
superkassa-core-maven-<версия>.zip из выпуска и распакуйте в папку, например libs/superkassa-core.repositories {
maven(uri("libs/superkassa-core"))
// Сторонние зависимости ядра (kotlinx, Ktor, Room, …)
mavenCentral()
google()
}
dependencies {
// Встраиваемое ядро для приложений Android, iOS и компьютеров
implementation("io.github.texport:superkassa-core-embedded:<версия>")
// Или отдельный слой, например фасад API
implementation("io.github.texport:superkassa-core-presentation:<версия>")
}Для iOS-проектов ядро скомпилировано в бинарный фреймворк SuperkassaCore.xcframework и распространяется через Swift Package Manager. Добавьте зависимость в ваш Package.swift:
dependencies: [
.package(url: "https://github.com/texport/superkassa-core", from: "1.1.4")
]superkassa-core provides out-of-the-box zero-config factory methods (SuperkassaCoreEngine) with embedded Room KMP SQLite storage, Ktor HTTP delivery, and ESC/POS receipt rendering for all platforms:
// In your Android Activity, Fragment, or ViewModel:
val api: SuperkassaApi = SuperkassaCoreEngine.createAndroid(dbName = "superkassa.db")// In your Swift App or Manager:
let api = SuperkassaCoreEngine.companion.createIos(dbName: "superkassa.db")// In your Compose for Desktop or Swing application:
val api: SuperkassaApi = SuperkassaCoreEngine.createDesktop(dbPath = "superkassa_desktop.db")// In your Spring Boot, Ktor, or Micronaut Server:
val api: SuperkassaApi = SuperkassaCoreEngine.createProduction(dbPath = "superkassa_server.db")Here is an example of registering a cashier sell receipt once initialized:
// 1. Initialize physical KKM. There is no default PIN: the administrator
// of the new cash register gets the PIN given here (4 to 10 characters).
val kkm = api.initKkm(
request = KkmInitDirectRequest(
ofdId = "kazakhtelecom",
ofdEnvironment = "prod",
ofdSystemId = "sys-12345",
ofdToken = "token-abc-123",
kkmKgdId = "123456789012",
factoryNumber = "SWK-0001",
manufactureYear = 2026,
adminPin = "7391"
)
)
// 2. Register sell receipt
val sellResult = api.createSellReceipt(
kkmId = kkm.id,
pin = "7391",
request = ReceiptSellRequest(
items = listOf(
ReceiptItemRequest(
name = "Фискальный товар",
price = 1500.0,
quantity = 1L,
vatGroup = "VAT_12",
measureUnitCode = "796"
)
),
payments = listOf(
ReceiptPaymentRequest(type = "CASH", sum = 1500.0)
),
idempotencyKey = "unique-receipt-key-1"
)
)
println("Receipt registered successfully with ticket number: ${sellResult.ticketNumber}")superkassa-core-testing is test tooling for applications and the node: the
embedded core on a data directory with an in-process BFD (FakeBfd) and a
movable clock, no external systems. Add it to test dependencies only:
testImplementation("io.github.texport:superkassa-core-testing:<version>")TestBench.open(SuperkassaPlatform(dataDir)).use { bench ->
// Registered the owner's way: BFD number and token, admin PIN, cashier PIN.
val kassa = bench.registerKassa(
KassaSetup(adminPin = "7391", cashierPin = "4826", vat = VatMode.Payer(VatGroup.VAT_16))
)
kassa.openShift()
val sale = kassa.sell()
kassa.refund(sale)
kassa.offlineSale() // the BFD is unreachable once: the document waits in the queue
bench.bfd.reject(CommandTypeEnum.COMMAND_TICKET, 13) // faults: unreachable, lost, held, refused
// Hand bench.superkassa and kassa.kkmId to the screen under test.
}The BFD substitution in the embedded assembly requires an explicit
@OptIn(ReplacedExternals::class), so production code cannot enable it by accident.
The project follows a strict Clean Architecture boundary design across all seven modules:
Receipt, ShiftInfo) are fully decoupled from serialization libraries (no @Serializable annotations) and have no framework dependencies.internal adapters to prevent detail leakage.SuperkassaApi and decoupled structures (like ReceiptSellRequest, UserRole) containing serialization descriptors, preventing leakage of serialization frameworks into the domain layer.To integrate superkassa-core into your host platform (JVM Server, Android App, iOS App), the developer must provide implementation adapters for the following core domain ports:
Для интеграции superkassa-core в целевую платформу (JVM Сервер, Android, iOS) разработчик должен предоставить реализации следующих портов:
StoragePort:
CoreSettingsRepositoryPort:
CoreSettings).CoreSettings).DeliveryPort:
ReceiptRenderPort & DocumentConvertPort:
OfdConnectionPort / OfdManagerPort:
ClockPort / IdGeneratorPort / PinHasherPort:
superkassa-core is the core multi-project Kotlin Multiplatform (KMP) library for the Superkassa fiscal cash register system. It implements all business rules, data validation, domain entities, and use cases, separated into seven distinct modules:
core-domain: Pure Kotlin Multiplatform domain entities (Receipt, KkmInfo, ShiftInfo) and port definitions (StoragePort, ClockPort, DeliveryPort).core-data: Implementations of storage backing, OFD communication orchestration, retry policies, and lease locking.core-presentation: Presentation layer facade (SuperkassaApi) that exposes the core system functions to client applications.offline-queue: Offline database command queue, handling request caching, retry scheduling with backoff policies, state mapping, and error reporting.core-string: Base localizable string assets, templates, and text resource mappings.delivery: Transportation network delivery layer for sending documents to remote servers.receipt-renderer: Print layout engine for building and formatting receipts in HTML and raw configurations, supporting multiple layouts, sizes (58mm, 80mm, Fullscreen), color themes, and multi-language translations (Russian, Kazakh, English).The core is not published to Maven Central. Every GitHub release carries the compiled library as superkassa-core-maven-<version>.zip: a Maven-layout repository with every module for all targets (JVM, Android, iOS), Gradle module metadata, and the exact builds of ofd-proto-codec, the protocol libraries (ofd-kt-proto, ofd-kt-proto-v204) and ofd-network-client the core was compiled against, none of which is in Maven Central; the remaining dependencies resolve from Maven Central and Google. The core's own build takes those libraries the same way — as compiled builds from their GitHub releases, never from sources.
superkassa-core-maven-<version>.zip from the release and unzip it into a folder, for example libs/superkassa-core.repositories {
maven(uri("libs/superkassa-core"))
// Third-party dependencies of the core (kotlinx, Ktor, Room, …)
mavenCentral()
google()
}
dependencies {
// Embedded core for Android, iOS and desktop applications
implementation("io.github.texport:superkassa-core-embedded:<version>")
// Or a single layer, e.g. the API facade
implementation("io.github.texport:superkassa-core-presentation:<version>")
}The iOS target is packaged as a unified SuperkassaCore binary XCFramework distributed via Swift Package Manager. Add the package reference to your Package.swift:
dependencies: [
.package(url: "https://github.com/texport/superkassa-core", from: "1.1.4")
]superkassa-core — это основная мультипроектная библиотека Kotlin Multiplatform (KMP) для фискальной системы Superkassa. Она реализует все бизнес-правила, валидацию данных, доменные сущности и сценарии использования (Use Cases), разделенные на семь модулей:
core-domain: Чистые сущности предметной области KMP (Receipt, KkmInfo, ShiftInfo) и интерфейсы портов (StoragePort, ClockPort, DeliveryPort).core-data: Реализации портов хранения, отправки документов в ОФД, политик повторных попыток и межпроцессных блокировок.core-presentation: Фасад презентационного слоя (SuperkassaApi), предоставляющий методы интеграции ядра с внешними клиентами.offline-queue: Очередь оффлайн-команд в базе данных, кэширование запросов, политики повторных отправлений (backoff) и статусное логирование.core-string: Базовые локализуемые строковые ресурсы, шаблоны и текстовые маппинги.delivery: Транспортный сетевой уровень для доставки фискальных документов на удаленные серверы.receipt-renderer: Движок генерации печатных форм чеков в формате HTML, поддерживающий различные макеты, размеры ленты (58мм, 80мм, Fullscreen), цветовые схемы и многоязыковую локализацию (русский, казахский, английский).Ядро не публикуется в Maven Central. Каждый выпуск на GitHub несёт собранную библиотеку файлом superkassa-core-maven-<версия>.zip: хранилище в раскладке Maven, в котором каждый модуль со всеми целями (JVM, Android, iOS), метаданные модулей Gradle и ровно те сборки кодека ofd-proto-codec, библиотек протокола (ofd-kt-proto, ofd-kt-proto-v204) и клиента сети ofd-network-client, с которыми собрано ядро, — в Maven Central их нет; остальные зависимости берутся из Maven Central и Google. Сборка самого ядра берёт эти библиотеки так же — готовыми сборками из их выпусков на GitHub, а не из исходников.
superkassa-core-maven-<версия>.zip из выпуска и распакуйте в папку, например libs/superkassa-core.repositories {
maven(uri("libs/superkassa-core"))
// Сторонние зависимости ядра (kotlinx, Ktor, Room, …)
mavenCentral()
google()
}
dependencies {
// Встраиваемое ядро для приложений Android, iOS и компьютеров
implementation("io.github.texport:superkassa-core-embedded:<версия>")
// Или отдельный слой, например фасад API
implementation("io.github.texport:superkassa-core-presentation:<версия>")
}Для iOS-проектов ядро скомпилировано в бинарный фреймворк SuperkassaCore.xcframework и распространяется через Swift Package Manager. Добавьте зависимость в ваш Package.swift:
dependencies: [
.package(url: "https://github.com/texport/superkassa-core", from: "1.1.4")
]superkassa-core provides out-of-the-box zero-config factory methods (SuperkassaCoreEngine) with embedded Room KMP SQLite storage, Ktor HTTP delivery, and ESC/POS receipt rendering for all platforms:
// In your Android Activity, Fragment, or ViewModel:
val api: SuperkassaApi = SuperkassaCoreEngine.createAndroid(dbName = "superkassa.db")// In your Swift App or Manager:
let api = SuperkassaCoreEngine.companion.createIos(dbName: "superkassa.db")// In your Compose for Desktop or Swing application:
val api: SuperkassaApi = SuperkassaCoreEngine.createDesktop(dbPath = "superkassa_desktop.db")// In your Spring Boot, Ktor, or Micronaut Server:
val api: SuperkassaApi = SuperkassaCoreEngine.createProduction(dbPath = "superkassa_server.db")Here is an example of registering a cashier sell receipt once initialized:
// 1. Initialize physical KKM. There is no default PIN: the administrator
// of the new cash register gets the PIN given here (4 to 10 characters).
val kkm = api.initKkm(
request = KkmInitDirectRequest(
ofdId = "kazakhtelecom",
ofdEnvironment = "prod",
ofdSystemId = "sys-12345",
ofdToken = "token-abc-123",
kkmKgdId = "123456789012",
factoryNumber = "SWK-0001",
manufactureYear = 2026,
adminPin = "7391"
)
)
// 2. Register sell receipt
val sellResult = api.createSellReceipt(
kkmId = kkm.id,
pin = "7391",
request = ReceiptSellRequest(
items = listOf(
ReceiptItemRequest(
name = "Фискальный товар",
price = 1500.0,
quantity = 1L,
vatGroup = "VAT_12",
measureUnitCode = "796"
)
),
payments = listOf(
ReceiptPaymentRequest(type = "CASH", sum = 1500.0)
),
idempotencyKey = "unique-receipt-key-1"
)
)
println("Receipt registered successfully with ticket number: ${sellResult.ticketNumber}")superkassa-core-testing is test tooling for applications and the node: the
embedded core on a data directory with an in-process BFD (FakeBfd) and a
movable clock, no external systems. Add it to test dependencies only:
testImplementation("io.github.texport:superkassa-core-testing:<version>")TestBench.open(SuperkassaPlatform(dataDir)).use { bench ->
// Registered the owner's way: BFD number and token, admin PIN, cashier PIN.
val kassa = bench.registerKassa(
KassaSetup(adminPin = "7391", cashierPin = "4826", vat = VatMode.Payer(VatGroup.VAT_16))
)
kassa.openShift()
val sale = kassa.sell()
kassa.refund(sale)
kassa.offlineSale() // the BFD is unreachable once: the document waits in the queue
bench.bfd.reject(CommandTypeEnum.COMMAND_TICKET, 13) // faults: unreachable, lost, held, refused
// Hand bench.superkassa and kassa.kkmId to the screen under test.
}The BFD substitution in the embedded assembly requires an explicit
@OptIn(ReplacedExternals::class), so production code cannot enable it by accident.
The project follows a strict Clean Architecture boundary design across all seven modules:
Receipt, ShiftInfo) are fully decoupled from serialization libraries (no @Serializable annotations) and have no framework dependencies.internal adapters to prevent detail leakage.SuperkassaApi and decoupled structures (like ReceiptSellRequest, UserRole) containing serialization descriptors, preventing leakage of serialization frameworks into the domain layer.To integrate superkassa-core into your host platform (JVM Server, Android App, iOS App), the developer must provide implementation adapters for the following core domain ports:
Для интеграции superkassa-core в целевую платформу (JVM Сервер, Android, iOS) разработчик должен предоставить реализации следующих портов:
StoragePort:
CoreSettingsRepositoryPort:
CoreSettings).CoreSettings).DeliveryPort:
ReceiptRenderPort & DocumentConvertPort:
OfdConnectionPort / OfdManagerPort:
ClockPort / IdGeneratorPort / PinHasherPort: