Skip to content

POS Terminal (Host Process)

1. Document Control

PropertyValue
Package@nx-app/sale-main
Crate Namebana
Library Namebana_lib
TypeDesktop Application (Host)
Version0.1.0
LanguageRust (Edition 2021)
FrameworkTauri 2.x

2. Scope & Objectives

2.1. Scope

This package constitutes the Host Process of the POS application. Built using Tauri (Rust), it bridges the gap between the web-based UI (sale-renderer) and the physical hardware/operating system. It provides native capabilities that cannot be achieved with web technologies alone.

2.2. Objectives

  • Hardware Abstraction: Unified API for printers, USB devices, and payment terminals.
  • Security: Secure storage of authentication tokens in OS keychain.
  • Offline Persistence: Local SQLite database for offline operations.
  • Window Management: Multi-window support (Customer Display).
  • Cross-Platform: Support for Windows, macOS, Linux, Android, and iOS.

3. Technology Stack

3.1. Core Dependencies

DependencyVersionPurpose
Tauri2.xDesktop application framework
SeaORM2.0.0-rcORM for SQLite database
SQLx0.8Async SQL toolkit
Tokio1.xAsync runtime
Serde1.xSerialization/Deserialization
Chrono0.4Date/time handling
UUID1.0Unique identifier generation

3.2. Tauri Plugins

PluginVersionPurpose
tauri-plugin-http2.xHTTP requests
tauri-plugin-fs2.0.0File system access
tauri-plugin-process2.xProcess management
tauri-plugin-os2.3.2OS information
tauri-plugin-opener2.xOpen URLs/files
tauri-plugin-log2.7.1Logging
tauri-plugin-localhost2.3.1Local HTTP server
tauri-plugin-machine-uid0.1.3Machine identification
tauri-plugin-updater2.xAuto-updates (Desktop)

3.3. Custom Tauri Plugins

PluginPathPurpose
tauri-plugin-external-display./tauri-plugin-external-displayCustomer display management
tauri-plugin-usb./tauri-plugin-usbUSB device communication
tauri-plugin-payment./tauri-plugin-paymentPayment terminal integration (Android phonepos feature)
tauri-plugin-signal./tauri-plugin-signalEncrypted WebSocket signaling (ECDH P-256 + AES-GCM)

3.4. Development Tools

ToolVersionPurpose
Specta2.0.0-rc.22TypeScript type generation
tauri-specta2.0.0-rc.21Tauri command type generation
dotenvy0.15.7Environment variables

4. Architecture

4.1. IPC Communication

4.2. Application Context

The application manages a shared state through the AppContext structure:

rust
pub struct AppContext {
    pub datasource: Datasource,
    pub services: ServiceContainer,
    pub repositories: RepositoryContainer,
}

4.3. Module Structure

lib.rs
├── application/           # Application bootstrap
│   ├── application.rs     # Main application builder
│   ├── context.rs         # Shared state & DI containers
│   └── logger.rs          # Logging configuration
├── controllers/           # Command handlers
├── datasource/            # Database configuration
├── entities/              # SeaORM entities
├── helpers/               # Utility functions
├── pubs/                  # Public command modules
└── services/              # Business logic services

5. Project Structure

apps/sale-main/src-tauri/
├── src/
│   ├── main.rs                     # Application entry point
│   ├── lib.rs                      # Library root (modules)
│   ├── prelude.rs                  # Shared imports
│   ├── application/                # Application bootstrap
│   │   ├── mod.rs
│   │   ├── application.rs          # Tauri builder configuration
│   │   ├── context.rs              # AppState & containers
│   │   └── logger.rs               # Fern logger setup
│   ├── controllers/                # Command handlers
│   │   ├── mod.rs                  # CRUD/custom command macros
│   │   └── tcp_printer_controller.rs
│   ├── datasource/                 # Database layer
│   │   ├── mod.rs
│   │   └── datasource.rs           # SQLite connection
│   ├── entities/                   # SeaORM entities
│   │   ├── mod.rs
│   │   ├── prelude.rs
│   │   ├── payment_attempt.rs
│   │   ├── payment_result.rs
│   │   ├── transaction.rs
│   │   ├── transaction_item.rs
│   │   └── user_configuration.rs
│   ├── helpers/                    # Utilities
│   │   ├── mod.rs
│   │   ├── error.rs                # Error handling
│   │   ├── network_request.rs      # HTTP helpers
│   │   ├── base_fetcher.rs         # Data fetching
│   │   ├── date_time.rs            # Date/time helpers
│   │   ├── printer.rs              # Printer helpers
│   │   └── request.rs              # Request utilities
│   ├── repositories/               # SeaORM repositories
│   │   ├── mod.rs
│   │   ├── prelude.rs
│   │   ├── base_repository.rs
│   │   ├── payment_attempt_repository.rs
│   │   ├── payment_result_repository.rs
│   │   ├── transaction_repository.rs
│   │   └── transaction_item_repository.rs
│   ├── pubs/                       # Tauri command modules (34 *_pub modules)
│   │   ├── mod.rs
│   │   ├── allocation_layout_pub.rs
│   │   ├── allocation_unit_pub.rs
│   │   ├── allocation_usage_pub.rs
│   │   ├── allocation_zone_pub.rs
│   │   ├── asset_pub.rs
│   │   ├── category_pub.rs
│   │   ├── common_pub.rs
│   │   ├── configuration_pub.rs
│   │   ├── device_pub.rs
│   │   ├── finance_account_pub.rs
│   │   ├── finance_asset_pub.rs
│   │   ├── finance_category_pub.rs
│   │   ├── finance_transaction_pub.rs
│   │   ├── invoice_pub.rs
│   │   ├── kitchen_ticket_pub.rs
│   │   ├── login_pub.rs
│   │   ├── merchant_pub.rs
│   │   ├── organizer_pub.rs
│   │   ├── payment_attempt_pub.rs
│   │   ├── payment_pub.rs
│   │   ├── permission_pub.rs
│   │   ├── pin_auth_pub.rs
│   │   ├── pos_session_pub.rs
│   │   ├── product_pub.rs
│   │   ├── product_variant_pub.rs
│   │   ├── receipt_template_pub.rs
│   │   ├── reservation_pub.rs
│   │   ├── role_pub.rs
│   │   ├── sale_channel_pub.rs
│   │   ├── sale_customer_pub.rs
│   │   ├── sale_order_item_pub.rs
│   │   ├── sale_order_pub.rs
│   │   ├── setting_pub.rs
│   │   └── user_pub.rs
│   └── services/                   # Business services (17 modules)
│       ├── mod.rs
│       ├── allocation_layout_service.rs
│       ├── allocation_usage_service.rs
│       ├── api_network_service.rs
│       ├── asset_service.rs
│       ├── auth_service.rs
│       ├── base_service.rs
│       ├── configuration_service.rs
│       ├── finance_asset_service.rs
│       ├── payment_attempt_service.rs
│       ├── payment_service.rs
│       ├── pin_auth_service.rs
│       ├── pos_session_service.rs
│       ├── reservation_service.rs
│       ├── sale_order_service.rs
│       ├── sale_report_service.rs
│       ├── trait_services.rs
│       └── user_service.rs
├── common/                         # Shared utilities crate
│   ├── Cargo.toml
│   └── src/
│       ├── lib.rs
│       ├── constant.rs             # Application constants
│       ├── endpoint.rs             # API endpoints
│       ├── macros.rs               # Utility macros
│       └── traits.rs               # Shared traits
├── macros/                         # Procedural macros crate
│   ├── Cargo.toml
│   └── src/
│       ├── lib.rs
│       ├── controller.rs           # Controller macro
│       └── scoped_log.rs           # Logging macro
├── migration/                      # SeaORM migrations
│   ├── Cargo.toml
│   └── src/
│       ├── lib.rs
│       ├── main.rs
│       └── m20251222_050923_create_tables.rs
├── tauri-plugin-usb/               # USB device plugin
│   ├── Cargo.toml
│   └── src/
│       ├── lib.rs
│       ├── commands.rs
│       ├── desktop.rs
│       ├── mobile.rs
│       ├── error.rs
│       └── models.rs
├── tauri-plugin-payment/           # Payment terminal plugin
│   ├── Cargo.toml
│   └── src/
│       ├── lib.rs
│       ├── commands.rs
│       ├── desktop.rs
│       ├── mobile.rs
│       ├── error.rs
│       └── models.rs
├── tauri-plugin-external-display/  # Customer display plugin
│   ├── Cargo.toml
│   └── src/
│       ├── lib.rs
│       ├── commands.rs
│       ├── desktop.rs
│       ├── mobile.rs
│       ├── error.rs
│       └── models.rs
├── tauri-plugin-signal/            # Encrypted WebSocket signaling plugin
│   ├── Cargo.toml
│   └── src/
│       ├── lib.rs
│       ├── client.rs
│       ├── commands.rs
│       ├── crypto.rs
│       ├── desktop.rs
│       ├── error.rs
│       └── models.rs
├── Cargo.toml                      # Workspace manifest
├── tauri.conf.json                 # Tauri configuration
└── build.rs                        # Build script

6. Tauri Commands

6.1. CRUD Commands

Generated automatically via the create_crud_commands! macro (each resource exposes find, find_one, create, update, delete). Resources (from controllers/mod.rs):

merchant, device, configuration, category, product, product_variant, organizer, sale_channel, receipt_template, invoice, finance_account, finance_category, finance_transaction, setting, sale_order, sale_order_item, sale_customer, reservation, allocation_layout, allocation_zone, allocation_unit, allocation_usage, pos_session.

6.2. Custom Commands

Generated via the create_commands! macro (and a few free functions):

CommandModuleDescription
asset_controller_i18n_fileasset_pubLoad i18n translations
asset_controller_vnpay_qr_frame_imageasset_pubGet VNPay QR frame image
auth_controller_sign_inlogin_pubUser authentication
auth_controller_sign_outlogin_pubUser logout
auth_controller_who_am_ilogin_pubGet current user
auth_controller_auth_tokenlogin_pubGet stored auth token
auth_controller_refresh_tokenlogin_pubRefresh auth token
user_controller_get_user_profileuser_pubGet user profile
configuration_controller_get_payment_provider_integrationconfiguration_pubList payment-provider integrations
finance_asset_controller_banks_vnfinance_asset_pubVietnamese banks registry
sale_order_controller_draftsale_order_pubCreate draft order
sale_order_controller_add_itemsale_order_item_pubAdd item to order
sale_order_controller_clear_itemssale_order_pubClear order items
sale_order_controller_checkoutsale_order_pubCheckout order
sale_order_controller_revert_checkoutsale_order_pubRevert checkout
sale_order_controller_splitsale_order_pubSplit order
sale_order_controller_cancelsale_order_pubCancel order
reservation_controller_check_inreservation_pubCheck in reservation
reservation_controller_cancelreservation_pubCancel reservation
payment_controller_checkoutpayment_pubProcess payment
payment_controller_cancelpayment_pubCancel payment
payment_controller_system_ipnpayment_pubHandle payment IPN
payment_attempt_controller_find_by_idpayment_attempt_pubFind payment attempt
allocation_layout_controller_find_aggregateallocation_layout_pubLoad layout aggregate
allocation_usage_controller_reassignallocation_usage_pubReassign allocation usage
allocation_usage_controller_complete_batchallocation_usage_pubComplete usage batch
allocation_usage_controller_available_unitsallocation_usage_pubList available units
allocation_usage_controller_available_zonesallocation_usage_pubList available zones
pos_session_controller_get_currentpos_session_pubGet current POS session
pos_session_controller_openpos_session_pubOpen POS session
pos_session_controller_cash_movementpos_session_pubRecord cash movement
pos_session_controller_closepos_session_pubClose POS session
pos_session_controller_z_reportpos_session_pubGenerate Z-report
pos_session_controller_x_reportpos_session_pubGenerate X-report
pin_auth_controller_mintpin_auth_pubMint PIN auth token
sale_report_controller_get_summarysale_report_serviceSales summary report
sale_report_controller_get_productssale_report_serviceSales-by-product report
sale_report_controller_get_categoriessale_report_serviceSales-by-category report
get_app_env_name(root)Get build environment name
set_header(root)Set an API request header

7. Custom Plugins

7.1. USB Plugin (tauri-plugin-usb)

Provides USB device communication for thermal printers and other peripherals.

CommandDescription
get_devicesList connected USB devices
connectConnect to USB device
sendSend data to device
disconnectDisconnect from device
get_connected_deviceGet current device

Platform Support:

  • Desktop: Direct USB communication
  • Mobile: Platform-specific implementation

7.2. Payment Plugin (tauri-plugin-payment)

Handles payment terminal integration.

CommandDescription
open_paymentOpen payment interface

Platform Support:

  • Desktop: Not implemented (uses web API)
  • Mobile (Android): Native payment SDK integration

7.3. External Display Plugin (tauri-plugin-external-display)

Manages customer-facing displays (secondary screens).

CommandDescription
send_dataSend data to customer display

Features:

  • Opens secondary window on external display
  • Supports VFD and LCD displays
  • Real-time cart updates

7.4. Signal Plugin (tauri-plugin-signal)

An encrypted real-time WebSocket signaling client (ECDH P-256 key exchange, HKDF, AES-GCM) used for live order/kitchen updates.

CommandDescription
connectConnect to the signaling server with a token
disconnectDisconnect the client
send_messageEmit an event with a JSON payload
join_roomsSubscribe to rooms
leave_roomsUnsubscribe from rooms
get_stateGet current connection state
get_client_idGet the assigned client id
update_tokenUpdate the auth token

8. Services Layer

8.1. Service Architecture

Services encapsulate business logic and interact with external APIs:

ServicePurpose
ApiNetworkServiceHTTP client for the backend API
AuthServiceAuthentication & token management
UserServiceUser profile operations
AssetServiceAsset & i18n file loading
ConfigurationServiceCommerce configuration & payment-provider integration
FinanceAssetServiceFinance asset registry (e.g. Vietnamese banks)
PaymentServicePayment checkout / cancel / IPN
PaymentAttemptServicePayment attempt tracking
PinAuthServicePIN authentication token minting
PosSessionServicePOS session lifecycle & X/Z reports
ReservationServiceTable reservation management
SaleOrderServiceSale order lifecycle (draft, checkout, split, cancel)
SaleReportServiceSales reports (summary, products, categories)
AllocationLayoutServiceRestaurant floor-plan layouts
AllocationUsageServiceTable/zone allocation usage
BaseServiceShared base service implementation
trait_servicesShared service traits

8.2. Base Service Pattern

All services extend a base implementation:

rust
pub trait BaseService {
    fn new() -> Self;
    // Common service methods
}

9. Database Layer

9.1. Datasource Configuration

SQLite database with SeaORM for async operations:

rust
pub struct Datasource {
    pub connection: DatabaseConnection,
}

pub struct DatasourceConnectionOptions {
    pub path: String,
}

9.2. Database Location

EnvironmentPath
Debugapp_data/db/{app_name}.sqlite
ReleaseOS app data directory

9.3. Migrations

Database migrations are managed via SeaORM Migration:

rust
Migrator::up(&datasource.connection, None).await?;

10. Application Lifecycle

10.1. Bootstrap Flow

10.2. Events

EventPayloadDescription
init_readytrueApplication initialized successfully
init_errorStringInitialization failed
migration_errorStringDatabase migration failed

11. Workspace Structure

11.1. Workspace Members

toml
[workspace]
members = [
  ".",                              # Main application
  "macros",                         # Procedural macros
  "migration",                      # Database migrations
  "tauri-plugin-external-display",  # Customer display plugin
  "tauri-plugin-usb",               # USB communication plugin
  "tauri-plugin-payment",           # Payment integration plugin
  "tauri-plugin-signal"             # Encrypted signaling plugin
]

11.2. Internal Crates

CratePurpose
commonShared constants, traits, and macros
macrosProcedural macros (scoped_log, controller)
migrationSeaORM database migrations

12. Platform-Specific Features

12.1. Desktop Only

rust
#[cfg(desktop)]
// Features only available on desktop platforms
- tauri-plugin-updater    // Auto-updates
- printers crate          // ESC/POS printer support

12.2. Mobile Only (Android)

rust
#[cfg(mobile)]
// Features only available on mobile platforms
- tauri-plugin-payment    // Native payment SDK

13. Build Configuration

13.1. Release Profile

Optimized for minimal binary size:

toml
[profile.release]
opt-level = "z"      # Maximum size optimization
lto = true           # Link Time Optimization
codegen-units = 1    # Better compression
panic = "abort"      # Remove unwinding code
strip = true         # Strip debug symbols

13.2. Build Artifacts

PlatformArtifacts
Windows.msi, .exe
macOS.dmg, .app
Linux.deb, .AppImage
Android.apk, .aab

14. Development

14.1. Prerequisites

RequirementPurpose
RustLatest stable toolchain
Tauri CLIBuild and development
libwebkit2gtk-4.0-devLinux WebView
build-essentialLinux compilation
Xcode CLI ToolsmacOS compilation

14.2. Environment Variables

VariablePurpose
APP_ENV_APPLICATION_NAMEDatabase name prefix
EXTERNAL_PORTLocal HTTP server port

15. Code Statistics

MetricCount
Tauri Commands50+
Custom Plugins4
Services17
Command Modules (pubs/)34
Database Entities5
Workspace Members7

Proprietary and Confidential. Unauthorized copying, distribution, or use of this software is strictly prohibited.