Skip to content

POS Terminal (Tiến trình Host)

1. Kiểm soát Tài liệu

Thuộc tínhGiá trị
Gói@nx-app/sale-main
Tên Cratebana
Tên Thư việnbana_lib
LoạiỨng dụng Desktop (Host)
Phiên bản0.1.0
Ngôn ngữRust (Edition 2021)
FrameworkTauri 2.x

2. Phạm vi & Mục tiêu

2.1. Phạm vi

Gói này tạo nên Tiến trình Host của ứng dụng POS. Được xây dựng bằng Tauri (Rust), nó là cầu nối giữa giao diện người dùng dựa trên web (sale-renderer) và phần cứng vật lý/hệ điều hành. Nó cung cấp các khả năng native mà chỉ công nghệ web không thể đạt được.

2.2. Mục tiêu

  • Trừu tượng hóa Phần cứng: API thống nhất cho máy in, thiết bị USB và terminal thanh toán.
  • Bảo mật: Lưu trữ an toàn token xác thực trong keychain của hệ điều hành.
  • Lưu trữ Ngoại tuyến: Cơ sở dữ liệu SQLite cục bộ cho các hoạt động ngoại tuyến.
  • Quản lý Cửa sổ: Hỗ trợ đa cửa sổ (Màn hình khách hàng).
  • Đa nền tảng: Hỗ trợ Windows, macOS, Linux, Android và iOS.

3. Ngăn xếp Công nghệ

3.1. Các phụ thuộc Cốt lõi

Phụ thuộcPhiên bảnMục đích
Tauri2.xFramework ứng dụng Desktop
SeaORM2.0.0-rcORM cho cơ sở dữ liệu SQLite
SQLx0.8Bộ công cụ SQL bất đồng bộ
Tokio1.xRuntime bất đồng bộ
Serde1.xTuần tự hóa/Giải tuần tự hóa
Chrono0.4Xử lý ngày/giờ
UUID1.0Tạo định danh duy nhất

3.2. Tauri Plugins

PluginPhiên bảnMục đích
tauri-plugin-http2.xYêu cầu HTTP
tauri-plugin-fs2.0.0Truy cập hệ thống tệp
tauri-plugin-process2.xQuản lý tiến trình
tauri-plugin-os2.3.2Thông tin hệ điều hành
tauri-plugin-opener2.xMở URL/tệp
tauri-plugin-log2.7.1Ghi nhật ký (Logging)
tauri-plugin-localhost2.3.1Máy chủ HTTP cục bộ
tauri-plugin-machine-uid0.1.3Nhận dạng máy
tauri-plugin-updater2.xTự động cập nhật (Desktop)

3.3. Tauri Plugins Tùy chỉnh

PluginĐường dẫnMục đích
tauri-plugin-external-display./tauri-plugin-external-displayQuản lý màn hình khách hàng
tauri-plugin-usb./tauri-plugin-usbGiao tiếp thiết bị USB
tauri-plugin-payment./tauri-plugin-paymentTích hợp terminal thanh toán (tính năng phonepos trên Android)
tauri-plugin-signal./tauri-plugin-signalTín hiệu WebSocket mã hóa (ECDH P-256 + AES-GCM)

3.4. Công cụ Phát triển

Công cụPhiên bảnMục đích
Specta2.0.0-rc.22Tạo kiểu TypeScript
tauri-specta2.0.0-rc.21Tạo kiểu lệnh Tauri
dotenvy0.15.7Biến môi trường

4. Kiến trúc

4.1. Giao tiếp IPC

4.2. Ngữ cảnh Ứng dụng (Application Context)

Ứng dụng quản lý trạng thái chia sẻ thông qua cấu trúc AppContext:

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

4.3. Cấu trúc Module

lib.rs
├── application/           # Khởi động ứng dụng
│   ├── application.rs     # Trình xây dựng ứng dụng chính
│   ├── context.rs         # Trạng thái chia sẻ & DI containers
│   └── logger.rs          # Cấu hình ghi nhật ký
├── controllers/           # Xử lý lệnh
├── datasource/            # Cấu hình cơ sở dữ liệu
├── entities/              # Các thực thể SeaORM
├── helpers/               # Các hàm tiện ích
├── pubs/                  # Các module lệnh công khai
└── services/              # Các dịch vụ logic nghiệp vụ

5. Cấu trúc Dự án

apps/sale-main/src-tauri/
├── src/
│   ├── main.rs                     # Điểm nhập ứng dụng
│   ├── lib.rs                      # Gốc thư viện (modules)
│   ├── prelude.rs                  # Import dùng chung
│   ├── application/                # Khởi động ứng dụng
│   │   ├── mod.rs
│   │   ├── application.rs          # Cấu hình Tauri builder
│   │   ├── context.rs              # AppState & containers
│   │   └── logger.rs               # Thiết lập Fern logger
│   ├── controllers/                # Xử lý lệnh
│   │   ├── mod.rs                  # Macro lệnh CRUD/tùy chỉnh
│   │   └── tcp_printer_controller.rs
│   ├── datasource/                 # Lớp cơ sở dữ liệu
│   │   ├── mod.rs
│   │   └── datasource.rs           # Kết nối SQLite
│   ├── entities/                   # Các thực thể SeaORM
│   │   ├── mod.rs
│   │   ├── prelude.rs
│   │   ├── payment_attempt.rs
│   │   ├── payment_result.rs
│   │   ├── transaction.rs
│   │   ├── transaction_item.rs
│   │   └── user_configuration.rs
│   ├── helpers/                    # Tiện ích
│   │   ├── mod.rs
│   │   ├── error.rs                # Xử lý lỗi
│   │   ├── network_request.rs      # HTTP helpers
│   │   ├── base_fetcher.rs         # Lấy dữ liệu
│   │   ├── date_time.rs            # Tiện ích ngày/giờ
│   │   ├── printer.rs              # Tiện ích máy in
│   │   └── request.rs              # Tiện ích yêu cầu
│   ├── repositories/               # Repository SeaORM
│   │   ├── mod.rs
│   │   ├── prelude.rs
│   │   ├── base_repository.rs
│   │   ├── payment_attempt_repository.rs
│   │   ├── payment_result_repository.rs
│   │   ├── transaction_repository.rs
│   │   └── transaction_item_repository.rs
│   ├── pubs/                       # Module lệnh Tauri (34 module *_pub)
│   │   ├── 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/                   # Dịch vụ nghiệp vụ (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/                         # Crate tiện ích chia sẻ
│   ├── Cargo.toml
│   └── src/
│       ├── lib.rs
│       ├── constant.rs             # Hằng số ứng dụng
│       ├── endpoint.rs             # Các điểm cuối API
│       ├── macros.rs               # Macros tiện ích
│       └── traits.rs               # Traits chia sẻ
├── macros/                         # Crate macros thủ tục
│   ├── Cargo.toml
│   └── src/
│       ├── lib.rs
│       ├── controller.rs           # Macro controller
│       └── scoped_log.rs           # Macro logging
├── migration/                      # Migrations SeaORM
│   ├── Cargo.toml
│   └── src/
│       ├── lib.rs
│       ├── main.rs
│       └── m20251222_050923_create_tables.rs
├── tauri-plugin-usb/               # Plugin thiết bị USB
│   ├── Cargo.toml
│   └── src/
│       ├── lib.rs
│       ├── commands.rs
│       ├── desktop.rs
│       ├── mobile.rs
│       ├── error.rs
│       └── models.rs
├── tauri-plugin-payment/           # Plugin terminal thanh toán
│   ├── Cargo.toml
│   └── src/
│       ├── lib.rs
│       ├── commands.rs
│       ├── desktop.rs
│       ├── mobile.rs
│       ├── error.rs
│       └── models.rs
├── tauri-plugin-external-display/  # Plugin màn hình khách hàng
│   ├── Cargo.toml
│   └── src/
│       ├── lib.rs
│       ├── commands.rs
│       ├── desktop.rs
│       ├── mobile.rs
│       ├── error.rs
│       └── models.rs
├── tauri-plugin-signal/            # Plugin tín hiệu WebSocket mã hóa
│   ├── Cargo.toml
│   └── src/
│       ├── lib.rs
│       ├── client.rs
│       ├── commands.rs
│       ├── crypto.rs
│       ├── desktop.rs
│       ├── error.rs
│       └── models.rs
├── Cargo.toml                      # Workspace manifest
├── tauri.conf.json                 # Cấu hình Tauri
└── build.rs                        # Script build

6. Các lệnh Tauri

6.1. Lệnh CRUD

Được tạo tự động qua macro create_crud_commands! (mỗi tài nguyên cung cấp find, find_one, create, update, delete). Các tài nguyên (từ 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. Lệnh Tùy chỉnh

Được tạo qua macro create_commands! (và một vài hàm tự do):

LệnhModuleMô tả
asset_controller_i18n_fileasset_pubTải bản dịch i18n
asset_controller_vnpay_qr_frame_imageasset_pubLấy ảnh khung QR VNPay
auth_controller_sign_inlogin_pubXác thực người dùng
auth_controller_sign_outlogin_pubĐăng xuất người dùng
auth_controller_who_am_ilogin_pubLấy người dùng hiện tại
auth_controller_auth_tokenlogin_pubLấy token xác thực đã lưu
auth_controller_refresh_tokenlogin_pubLàm mới token xác thực
user_controller_get_user_profileuser_pubLấy hồ sơ người dùng
configuration_controller_get_payment_provider_integrationconfiguration_pubLiệt kê tích hợp nhà cung cấp thanh toán
finance_asset_controller_banks_vnfinance_asset_pubDanh bạ ngân hàng Việt Nam
sale_order_controller_draftsale_order_pubTạo đơn nháp
sale_order_controller_add_itemsale_order_item_pubThêm mục vào đơn
sale_order_controller_clear_itemssale_order_pubXóa các mục của đơn
sale_order_controller_checkoutsale_order_pubCheckout đơn hàng
sale_order_controller_revert_checkoutsale_order_pubHoàn tác checkout
sale_order_controller_splitsale_order_pubTách đơn hàng
sale_order_controller_cancelsale_order_pubHủy đơn hàng
reservation_controller_check_inreservation_pubCheck-in đặt chỗ
reservation_controller_cancelreservation_pubHủy đặt chỗ
payment_controller_checkoutpayment_pubXử lý thanh toán
payment_controller_cancelpayment_pubHủy thanh toán
payment_controller_system_ipnpayment_pubXử lý IPN thanh toán
payment_attempt_controller_find_by_idpayment_attempt_pubTìm lần thử thanh toán
allocation_layout_controller_find_aggregateallocation_layout_pubTải aggregate sơ đồ
allocation_usage_controller_reassignallocation_usage_pubGán lại allocation usage
allocation_usage_controller_complete_batchallocation_usage_pubHoàn tất lô usage
allocation_usage_controller_available_unitsallocation_usage_pubLiệt kê unit khả dụng
allocation_usage_controller_available_zonesallocation_usage_pubLiệt kê zone khả dụng
pos_session_controller_get_currentpos_session_pubLấy phiên POS hiện tại
pos_session_controller_openpos_session_pubMở phiên POS
pos_session_controller_cash_movementpos_session_pubGhi nhận biến động tiền mặt
pos_session_controller_closepos_session_pubĐóng phiên POS
pos_session_controller_z_reportpos_session_pubTạo Z-report
pos_session_controller_x_reportpos_session_pubTạo X-report
pin_auth_controller_mintpin_auth_pubPhát hành token xác thực PIN
sale_report_controller_get_summarysale_report_serviceBáo cáo tổng hợp doanh số
sale_report_controller_get_productssale_report_serviceBáo cáo doanh số theo sản phẩm
sale_report_controller_get_categoriessale_report_serviceBáo cáo doanh số theo danh mục
get_app_env_name(root)Lấy tên môi trường build
set_header(root)Đặt header cho yêu cầu API

7. Plugins Tùy chỉnh

7.1. Plugin USB (tauri-plugin-usb)

Cung cấp giao tiếp thiết bị USB cho máy in nhiệt và các thiết bị ngoại vi khác.

LệnhMô tả
get_devicesLiệt kê các thiết bị USB đã kết nối
connectKết nối tới thiết bị USB
sendGửi dữ liệu tới thiết bị
disconnectNgắt kết nối thiết bị
get_connected_deviceLấy thiết bị đang kết nối

Hỗ trợ Nền tảng:

  • Desktop: Giao tiếp USB trực tiếp
  • Mobile: Triển khai riêng cho nền tảng

7.2. Plugin Thanh toán (tauri-plugin-payment)

Xử lý tích hợp terminal thanh toán.

LệnhMô tả
open_paymentMở giao diện thanh toán

Hỗ trợ Nền tảng:

  • Desktop: Chưa triển khai (sử dụng web API)
  • Mobile (Android): Tích hợp SDK thanh toán native

7.3. Plugin Màn hình Ngoài (tauri-plugin-external-display)

Quản lý màn hình hướng về phía khách hàng (màn hình phụ).

LệnhMô tả
send_dataGửi dữ liệu tới màn hình khách hàng

Tính năng:

  • Mở cửa sổ phụ trên màn hình ngoài
  • Hỗ trợ màn hình VFD và LCD
  • Cập nhật giỏ hàng thời gian thực

7.4. Plugin Tín hiệu (tauri-plugin-signal)

Một client WebSocket tín hiệu thời gian thực có mã hóa (trao đổi khóa ECDH P-256, HKDF, AES-GCM) dùng cho cập nhật đơn hàng/bếp trực tiếp.

LệnhMô tả
connectKết nối tới server tín hiệu bằng token
disconnectNgắt kết nối client
send_messagePhát một sự kiện kèm payload JSON
join_roomsĐăng ký các room
leave_roomsHủy đăng ký các room
get_stateLấy trạng thái kết nối hiện tại
get_client_idLấy client id được gán
update_tokenCập nhật token xác thực

8. Lớp Dịch vụ (Services Layer)

8.1. Kiến trúc Dịch vụ

Các dịch vụ đóng gói logic nghiệp vụ và tương tác với các API bên ngoài:

Dịch vụMục đích
ApiNetworkServiceHTTP client cho backend API
AuthServiceXác thực & quản lý token
UserServiceCác thao tác hồ sơ người dùng
AssetServiceTải tài sản & tệp i18n
ConfigurationServiceCấu hình commerce & tích hợp nhà cung cấp thanh toán
FinanceAssetServiceDanh bạ tài sản tài chính (ví dụ ngân hàng Việt Nam)
PaymentServiceCheckout / hủy / IPN thanh toán
PaymentAttemptServiceTheo dõi lần thử thanh toán
PinAuthServicePhát hành token xác thực PIN
PosSessionServiceVòng đời phiên POS & báo cáo X/Z
ReservationServiceQuản lý đặt bàn
SaleOrderServiceVòng đời đơn hàng (nháp, checkout, tách, hủy)
SaleReportServiceBáo cáo doanh số (tổng hợp, sản phẩm, danh mục)
AllocationLayoutServiceSơ đồ bố trí mặt bằng nhà hàng
AllocationUsageServiceSử dụng cấp phát bàn/khu vực
BaseServiceTriển khai dịch vụ cơ sở dùng chung
trait_servicesCác trait dịch vụ dùng chung

8.2. Mẫu Dịch vụ Cơ sở

Tất cả các dịch vụ đều kế thừa một triển khai cơ sở:

rust
pub trait BaseService {
    fn new() -> Self;
    // Các phương thức dịch vụ chung
}

9. Lớp Cơ sở dữ liệu

9.1. Cấu hình Datasource

Cơ sở dữ liệu SQLite với SeaORM cho các hoạt động bất đồng bộ:

rust
pub struct Datasource {
    pub connection: DatabaseConnection,
}

pub struct DatasourceConnectionOptions {
    pub path: String,
}

9.2. Vị trí Cơ sở dữ liệu

Môi trườngĐường dẫn
Debugapp_data/db/{app_name}.sqlite
ReleaseThư mục dữ liệu ứng dụng của HĐH

9.3. Migrations

Các migration cơ sở dữ liệu được quản lý thông qua SeaORM Migration:

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

10. Vòng đời Ứng dụng

10.1. Luồng Khởi động

10.2. Sự kiện

Sự kiệnPayloadMô tả
init_readytrueỨng dụng khởi tạo thành công
init_errorStringKhởi tạo thất bại
migration_errorStringMigration cơ sở dữ liệu thất bại

11. Cấu trúc Workspace

11.1. Các thành viên Workspace

toml
[workspace]
members = [
  ".",                              # Ứng dụng chính
  "macros",                         # Macros thủ tục
  "migration",                      # Migrations cơ sở dữ liệu
  "tauri-plugin-external-display",  # Plugin màn hình khách hàng
  "tauri-plugin-usb",               # Plugin giao tiếp USB
  "tauri-plugin-payment",           # Plugin tích hợp thanh toán
  "tauri-plugin-signal"             # Plugin tín hiệu mã hóa
]

11.2. Các Crates Nội bộ

CrateMục đích
commonCác hằng số, traits và macros dùng chung
macrosMacros thủ tục (scoped_log, controller)
migrationSeaORM database migrations

12. Các tính năng Đặc thù Nền tảng

12.1. Chỉ Desktop

rust
#[cfg(desktop)]
// Các tính năng chỉ có trên nền tảng desktop
- tauri-plugin-updater    // Tự động cập nhật
- printers crate          // Hỗ trợ máy in ESC/POS

12.2. Chỉ Mobile (Android)

rust
#[cfg(mobile)]
// Các tính năng chỉ có trên nền tảng di động
- tauri-plugin-payment    // SDK thanh toán native

13. Cấu hình Build

13.1. Profile Release

Tối ưu hóa cho kích thước binary nhỏ nhất:

toml
[profile.release]
opt-level = "z"      # Tối ưu hóa kích thước tối đa
lto = true           # Tối ưu hóa thời gian liên kết (Link Time Optimization)
codegen-units = 1    # Nén tốt hơn
panic = "abort"      # Loại bỏ mã unwinding
strip = true         # Loại bỏ các biểu tượng debug

13.2. Artifacts Build

Nền tảngArtifacts
Windows.msi, .exe
macOS.dmg, .app
Linux.deb, .AppImage
Android.apk, .aab

14. Phát triển

14.1. Điều kiện Tiên quyết

Yêu cầuMục đích
RustChuỗi công cụ ổn định mới nhất
Tauri CLIBuild và phát triển
libwebkit2gtk-4.0-devLinux WebView
build-essentialBiên dịch Linux
Xcode CLI ToolsBiên dịch macOS

14.2. Biến Môi trường

BiếnMục đích
APP_ENV_APPLICATION_NAMETiền tố tên cơ sở dữ liệu
EXTERNAL_PORTCổng máy chủ HTTP cục bộ

15. Thống kê Mã nguồn

Chỉ sốSố lượng
Lệnh Tauri50+
Plugin Tùy chỉnh4
Dịch vụ17
Module Lệnh (pubs/)34
Thực thể Cơ sở dữ liệu5
Thành viên Workspace7

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