Skip to content

POS Terminal (Host Process)

1. Document Control

PropertyValue
Package@nx-app/sale-main
Crate NameBANA
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-usb./tauri-plugin-usbUSB device communication
tauri-plugin-payment./tauri-plugin-paymentPayment terminal integration
tauri-plugin-external-display./tauri-plugin-external-displayCustomer display management

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

React UI
Tauri IPC
Rust Commands
Hardware / OS

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)
│   ├── application/                # Application bootstrap
│   │   ├── mod.rs
│   │   ├── application.rs          # Tauri builder configuration
│   │   ├── context.rs              # AppState & containers
│   │   └── logger.rs               # Fern logger setup
│   ├── controllers/                # Command handlers
│   │   └── mod.rs
│   ├── datasource/                 # Database layer
│   │   ├── mod.rs
│   │   └── datasource.rs           # SQLite connection
│   ├── entities/                   # SeaORM entities
│   │   ├── mod.rs
│   │   ├── prelude.rs
│   │   └── user_configuration.rs
│   ├── helpers/                    # Utilities
│   │   ├── mod.rs
│   │   ├── error.rs                # Error handling
│   │   ├── network_request.rs      # HTTP helpers
│   │   ├── base_fetcher.rs         # Data fetching
│   │   └── request.rs              # Request utilities
│   ├── pubs/                       # Tauri commands (16 modules)
│   │   ├── mod.rs
│   │   ├── asset_pub.rs
│   │   ├── cart_pub.rs
│   │   ├── category_pub.rs
│   │   ├── common_pub.rs
│   │   ├── login_pub.rs
│   │   ├── merchant_pub.rs
│   │   ├── order_pub.rs
│   │   ├── organizer_pub.rs
│   │   ├── payment_attempt.rs
│   │   ├── payment_pub.rs
│   │   ├── permission_pub.rs
│   │   ├── product_pub.rs
│   │   ├── product_variant_pub.rs
│   │   ├── role_pub.rs
│   │   ├── sale_channel_pub.rs
│   │   └── user_pub.rs
│   └── services/                   # Business services (11 modules)
│       ├── mod.rs
│       ├── api_network_service.rs
│       ├── asset_service.rs
│       ├── auth_service.rs
│       ├── base_service.rs
│       ├── cart_service.rs
│       ├── cart_item_service.rs
│       ├── order_service.rs
│       ├── payment_service.rs
│       ├── payment_attempt_service.rs
│       ├── trail_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
├── Cargo.toml                      # Workspace manifest
├── tauri.conf.json                 # Tauri configuration
└── build.rs                        # Build script

6. Tauri Commands

6.1. CRUD Commands

Generated automatically for common operations via macros:

ResourceOperations
merchantfind, find_one, create, update, delete
categoryfind, find_one, create, update, delete
productfind, find_one, create, update, delete
product_variantfind, find_one, create, update, delete
organizerfind, find_one, create, update, delete
sale_channelfind, find_one, create, update, delete
cartfind, find_one, create, update, delete
cart_itemfind, find_one, create, update, delete

6.2. Custom Commands

CommandModuleDescription
asset_controller_i18n_fileasset_pubLoad i18n translations
asset_controller_vnpay_qr_frame_imageasset_pubGet VNPay QR frame
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 auth token
user_controller_get_user_profileuser_pubGet user profile
cart_controller_cart_itemscart_pubGet cart items
cart_controller_add_itemcart_pubAdd item to cart
cart_controller_clear_cartcart_pubClear cart
cart_item_controller_update_quantitycart_pubUpdate item quantity
order_controller_checkoutorder_pubCreate order from cart
order_controller_revert_checkoutorder_pubCancel checkout
payment_controller_checkoutpayment_pubProcess payment
payment_controller_cancelpayment_pubCancel payment
payment_controller_system_ipnpayment_pubHandle payment IPN
payment_attempt_controller_find_by_idpayment_attemptFind payment attempt

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

8. Services Layer

8.1. Service Architecture

Services encapsulate business logic and interact with external APIs:

ServicePurpose
ApiNetworkServiceHTTP client for backend API
AuthServiceAuthentication & token management
UserServiceUser profile operations
AssetServiceAsset/file management
CartServiceShopping cart logic
CartItemServiceCart item management
OrderServiceOrder creation & management
PaymentServicePayment processing
PaymentAttemptServicePayment attempt tracking
TrailServicesAudit trail logging

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

1. Application::new()
   └── Get base directory
2. Application::build()
   ├── Create Tauri Builder
   ├── Manage options & base_dir
   ├── bind_plugins() - Attach all plugins
   ├── bind_commands() - Register IPC commands
   └── setup() - Async initialization
       ├── configure() - Setup datasource & state
       │   ├── Configure SQLite database
       │   ├── Create ServiceContainer
       │   ├── Create RepositoryContainer
       │   └── Manage AppState
       ├── Emit "init_ready" event
       └── migrate() - Run database migrations
           └── Emit "migration_error" on failure
3. builder.run() - Start Tauri runtime

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
]

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
Rust Source Files~75
Tauri Commands50+
Custom Plugins3
Services11
Database Entities1+
Workspace Crates7

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