POS Terminal (Host Process)
1. Document Control
| Property | Value |
|---|---|
| Package | @nx-app/sale-main |
| Crate Name | bana |
| Library Name | bana_lib |
| Type | Desktop Application (Host) |
| Version | 0.1.0 |
| Language | Rust (Edition 2021) |
| Framework | Tauri 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
| Dependency | Version | Purpose |
|---|---|---|
| Tauri | 2.x | Desktop application framework |
| SeaORM | 2.0.0-rc | ORM for SQLite database |
| SQLx | 0.8 | Async SQL toolkit |
| Tokio | 1.x | Async runtime |
| Serde | 1.x | Serialization/Deserialization |
| Chrono | 0.4 | Date/time handling |
| UUID | 1.0 | Unique identifier generation |
3.2. Tauri Plugins
| Plugin | Version | Purpose |
|---|---|---|
| tauri-plugin-http | 2.x | HTTP requests |
| tauri-plugin-fs | 2.0.0 | File system access |
| tauri-plugin-process | 2.x | Process management |
| tauri-plugin-os | 2.3.2 | OS information |
| tauri-plugin-opener | 2.x | Open URLs/files |
| tauri-plugin-log | 2.7.1 | Logging |
| tauri-plugin-localhost | 2.3.1 | Local HTTP server |
| tauri-plugin-machine-uid | 0.1.3 | Machine identification |
| tauri-plugin-updater | 2.x | Auto-updates (Desktop) |
3.3. Custom Tauri Plugins
| Plugin | Path | Purpose |
|---|---|---|
| tauri-plugin-external-display | ./tauri-plugin-external-display | Customer display management |
| tauri-plugin-usb | ./tauri-plugin-usb | USB device communication |
| tauri-plugin-payment | ./tauri-plugin-payment | Payment terminal integration (Android phonepos feature) |
| tauri-plugin-signal | ./tauri-plugin-signal | Encrypted WebSocket signaling (ECDH P-256 + AES-GCM) |
3.4. Development Tools
| Tool | Version | Purpose |
|---|---|---|
| Specta | 2.0.0-rc.22 | TypeScript type generation |
| tauri-specta | 2.0.0-rc.21 | Tauri command type generation |
| dotenvy | 0.15.7 | Environment variables |
4. Architecture
4.1. IPC Communication
4.2. Application Context
The application manages a shared state through the AppContext structure:
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 services5. 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 script6. 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):
| Command | Module | Description |
|---|---|---|
asset_controller_i18n_file | asset_pub | Load i18n translations |
asset_controller_vnpay_qr_frame_image | asset_pub | Get VNPay QR frame image |
auth_controller_sign_in | login_pub | User authentication |
auth_controller_sign_out | login_pub | User logout |
auth_controller_who_am_i | login_pub | Get current user |
auth_controller_auth_token | login_pub | Get stored auth token |
auth_controller_refresh_token | login_pub | Refresh auth token |
user_controller_get_user_profile | user_pub | Get user profile |
configuration_controller_get_payment_provider_integration | configuration_pub | List payment-provider integrations |
finance_asset_controller_banks_vn | finance_asset_pub | Vietnamese banks registry |
sale_order_controller_draft | sale_order_pub | Create draft order |
sale_order_controller_add_item | sale_order_item_pub | Add item to order |
sale_order_controller_clear_items | sale_order_pub | Clear order items |
sale_order_controller_checkout | sale_order_pub | Checkout order |
sale_order_controller_revert_checkout | sale_order_pub | Revert checkout |
sale_order_controller_split | sale_order_pub | Split order |
sale_order_controller_cancel | sale_order_pub | Cancel order |
reservation_controller_check_in | reservation_pub | Check in reservation |
reservation_controller_cancel | reservation_pub | Cancel reservation |
payment_controller_checkout | payment_pub | Process payment |
payment_controller_cancel | payment_pub | Cancel payment |
payment_controller_system_ipn | payment_pub | Handle payment IPN |
payment_attempt_controller_find_by_id | payment_attempt_pub | Find payment attempt |
allocation_layout_controller_find_aggregate | allocation_layout_pub | Load layout aggregate |
allocation_usage_controller_reassign | allocation_usage_pub | Reassign allocation usage |
allocation_usage_controller_complete_batch | allocation_usage_pub | Complete usage batch |
allocation_usage_controller_available_units | allocation_usage_pub | List available units |
allocation_usage_controller_available_zones | allocation_usage_pub | List available zones |
pos_session_controller_get_current | pos_session_pub | Get current POS session |
pos_session_controller_open | pos_session_pub | Open POS session |
pos_session_controller_cash_movement | pos_session_pub | Record cash movement |
pos_session_controller_close | pos_session_pub | Close POS session |
pos_session_controller_z_report | pos_session_pub | Generate Z-report |
pos_session_controller_x_report | pos_session_pub | Generate X-report |
pin_auth_controller_mint | pin_auth_pub | Mint PIN auth token |
sale_report_controller_get_summary | sale_report_service | Sales summary report |
sale_report_controller_get_products | sale_report_service | Sales-by-product report |
sale_report_controller_get_categories | sale_report_service | Sales-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.
| Command | Description |
|---|---|
get_devices | List connected USB devices |
connect | Connect to USB device |
send | Send data to device |
disconnect | Disconnect from device |
get_connected_device | Get current device |
Platform Support:
- Desktop: Direct USB communication
- Mobile: Platform-specific implementation
7.2. Payment Plugin (tauri-plugin-payment)
Handles payment terminal integration.
| Command | Description |
|---|---|
open_payment | Open 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).
| Command | Description |
|---|---|
send_data | Send 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.
| Command | Description |
|---|---|
connect | Connect to the signaling server with a token |
disconnect | Disconnect the client |
send_message | Emit an event with a JSON payload |
join_rooms | Subscribe to rooms |
leave_rooms | Unsubscribe from rooms |
get_state | Get current connection state |
get_client_id | Get the assigned client id |
update_token | Update the auth token |
8. Services Layer
8.1. Service Architecture
Services encapsulate business logic and interact with external APIs:
| Service | Purpose |
|---|---|
| ApiNetworkService | HTTP client for the backend API |
| AuthService | Authentication & token management |
| UserService | User profile operations |
| AssetService | Asset & i18n file loading |
| ConfigurationService | Commerce configuration & payment-provider integration |
| FinanceAssetService | Finance asset registry (e.g. Vietnamese banks) |
| PaymentService | Payment checkout / cancel / IPN |
| PaymentAttemptService | Payment attempt tracking |
| PinAuthService | PIN authentication token minting |
| PosSessionService | POS session lifecycle & X/Z reports |
| ReservationService | Table reservation management |
| SaleOrderService | Sale order lifecycle (draft, checkout, split, cancel) |
| SaleReportService | Sales reports (summary, products, categories) |
| AllocationLayoutService | Restaurant floor-plan layouts |
| AllocationUsageService | Table/zone allocation usage |
| BaseService | Shared base service implementation |
| trait_services | Shared service traits |
8.2. Base Service Pattern
All services extend a base implementation:
pub trait BaseService {
fn new() -> Self;
// Common service methods
}9. Database Layer
9.1. Datasource Configuration
SQLite database with SeaORM for async operations:
pub struct Datasource {
pub connection: DatabaseConnection,
}
pub struct DatasourceConnectionOptions {
pub path: String,
}9.2. Database Location
| Environment | Path |
|---|---|
| Debug | app_data/db/{app_name}.sqlite |
| Release | OS app data directory |
9.3. Migrations
Database migrations are managed via SeaORM Migration:
Migrator::up(&datasource.connection, None).await?;10. Application Lifecycle
10.1. Bootstrap Flow
10.2. Events
| Event | Payload | Description |
|---|---|---|
init_ready | true | Application initialized successfully |
init_error | String | Initialization failed |
migration_error | String | Database migration failed |
11. Workspace Structure
11.1. Workspace Members
[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
| Crate | Purpose |
|---|---|
common | Shared constants, traits, and macros |
macros | Procedural macros (scoped_log, controller) |
migration | SeaORM database migrations |
12. Platform-Specific Features
12.1. Desktop Only
#[cfg(desktop)]
// Features only available on desktop platforms
- tauri-plugin-updater // Auto-updates
- printers crate // ESC/POS printer support12.2. Mobile Only (Android)
#[cfg(mobile)]
// Features only available on mobile platforms
- tauri-plugin-payment // Native payment SDK13. Build Configuration
13.1. Release Profile
Optimized for minimal binary size:
[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 symbols13.2. Build Artifacts
| Platform | Artifacts |
|---|---|
| Windows | .msi, .exe |
| macOS | .dmg, .app |
| Linux | .deb, .AppImage |
| Android | .apk, .aab |
14. Development
14.1. Prerequisites
| Requirement | Purpose |
|---|---|
| Rust | Latest stable toolchain |
| Tauri CLI | Build and development |
| libwebkit2gtk-4.0-dev | Linux WebView |
| build-essential | Linux compilation |
| Xcode CLI Tools | macOS compilation |
14.2. Environment Variables
| Variable | Purpose |
|---|---|
APP_ENV_APPLICATION_NAME | Database name prefix |
EXTERNAL_PORT | Local HTTP server port |
15. Code Statistics
| Metric | Count |
|---|---|
| Tauri Commands | 50+ |
| Custom Plugins | 4 |
| Services | 17 |
Command Modules (pubs/) | 34 |
| Database Entities | 5 |
| Workspace Members | 7 |