Keyboard shortcuts

Press ← or β†’ to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Database Tables Analysis & ORM Mapping Plan

Overview

This document analyzes all database tables used in the Legacy ERP system and provides a roadmap for creating ORM mappings in the Efision project.

Total tables identified: 230+ tables

Current status: 15 Product-related tables mapped βœ…


Table Categories

1. πŸ“¦ Product Management (Priority: HIGH)

Current Status: 15/21 tables mapped (71%)

βœ… Already Mapped

  • Product - Main product table
  • ProductWheels - Wheel-specific attributes
  • ProductDesign - Design patterns
  • ProductBrand - Brand information
  • ProductPcd - PCD (bolt pattern)
  • ProductFinishType - Finish types
  • ProductBaseAppendantType - Base appendant types
  • Bolt - Bolt specifications
  • Cap - Cap specifications

βœ… Phase 1 Complete (2026-02-05)

  • ProductType - Product type definitions
  • ProductSeries - Product series groupings
  • ProductCategory - Product classification
  • ProductGallery - Product images
  • ProductBasePrice - Base pricing matrix
  • ProductBOM - Bill of Materials

⏳ To Be Mapped (Phase 2+)

  • ProductRelated - Related products
  • ProductRelation - Product relationships
  • ProductView - Product views/stats
  • Model - Product models
  • ProductModelCompanyPrice - Company-specific pricing
  • ProductCoupon - Product coupons

πŸ“Š Sub-categories

Tires:

  • ProductTire - Tire specifications
  • ProductDiameter - Tire diameters
  • ProductWidth - Tire widths

Clothing/Fabric:

  • ProductClothing - Clothing products
  • ProductFabric - Fabric products
  • ProductDesignClothing - Clothing designs

Molds:

  • ProductMold - Mold information
  • ProductMoldExtension - Mold extensions
  • ProductMoldExtensionCheck - Mold extension checks
  • ProductMoldExtensionCheckDetail - Check details

Semi-finished:

  • ProductSemi - Semi-finished products

Packing:

  • ProductPacking - Packing specifications
  • PackingSpec - Packing spec details
  • PackingSpecItem - Packing spec items

Other attributes:

  • ProductEt - ET (offset) values
  • ProductCb - CB values
  • ProductButtom - Button specifications
  • ProductNORelation - Product number relations

2. πŸ›’ Sales & Orders (Priority: HIGH)

Current Status: 0/20 tables mapped (0%)

Core Orders

  • Ordert - Main orders table
  • OrderDetail - Order line items
  • OrderLog - Order history logs
  • OrdersNotepad - Order notes
  • OrdersSalesCommissiom - Sales commissions
  • BackOrder - Back orders
  • BackOrderDetail - Back order details
  • BackOrderLog - Back order logs

Shopping Cart

  • ShoppingCart - Shopping carts
  • ShoppingCartItem - Cart items

Pricing & Discounts

  • PriceLevel - Price levels
  • Coupon - Coupons
  • CouponDetail - Coupon details
  • UserCoupon - User-specific coupons
  • ProductCustomAppendantPrice - Custom appendant pricing
  • ProductCustomBasePrice - Custom base pricing
  • ProductAppendantCategoryPrice - Appendant category pricing
  • ProductBaseAppendantPrice - Base appendant pricing

Tax

  • TaxRate - Tax rates
  • TaxReturn - Tax returns

3. πŸ“¦ Warehouse & Inventory (Priority: HIGH)

Current Status: 0/21 tables mapped (0%)

Stock Management

  • WarehouseStock - Current stock levels
  • WarehouseStockLog - Stock movement logs
  • StockLog - General stock logs
  • ClosingStock - Closing stock
  • ClosingStockDetail - Closing stock details

Stock In/Out

  • StockInOrder - Stock in orders
  • StockInOrderDetail - Stock in details
  • StockOutOrder - Stock out orders
  • StockOutOrderDetail - Stock out details

Stock Take

  • StockTake - Stock takes
  • WarehouseTakeStock - Warehouse stock takes
  • WarehouseTakeStockDetail - Stock take details

Warehouses

  • Warehouse - Warehouse information
  • WarehouseUsers - Warehouse users

Pallets & Containers

  • Pallet - Pallet tracking
  • Containers - Container tracking

Requisitions

  • Requisition - Material requisitions
  • RequisitionDetail - Requisition details
  • MarginRequistion - Margin requisitions

Purchase

  • PurchaseRequisition - Purchase requisitions
  • PurchaseRequisitionDetail - Purchase requisition details

4. πŸ’° Finance & Accounting (Priority: MEDIUM)

Current Status: 0/35+ tables mapped (0%)

Accounts

  • Account - Chart of accounts
  • Accounts - Account details
  • AccountingSubject - Accounting subjects
  • AccountLog - Account logs
  • AccountAllocation - Account allocations
  • AccountTransfer - Account transfers
  • AccountVerification - Account verifications
  • ReconcileAccount - Account reconciliations
  • ReconcileAccountItem - Reconciliation items

Vouchers & Ledgers

  • Acct_Voucher - Accounting vouchers
  • Acct_VoucherItem - Voucher items
  • Acct_Ledger - General ledger
  • Acct_LedgerAmount - Ledger amounts
  • Acct_LedgerCategory - Ledger categories
  • Acct_LedgerRegion - Ledger regions
  • Acct_Business - Business transactions
  • Acct_BusinessLedgerRelation - Business-ledger relations
  • Voucher - General vouchers
  • VoucherItem - Voucher line items

Payments

  • ReceivePayment - Payment receipts
  • ReceivePaymentDetail - Receipt details
  • ContraPayment - Contra payments
  • ContraPaymentDetail - Contra payment details
  • PaymentMethod - Payment methods
  • PaymentMethodNode - Payment method nodes
  • PaymentNode - Payment nodes
  • PaymentType - Payment types

Fixed Assets

  • FixedAsset - Fixed assets
  • FixedAssetDetail - Asset details
  • FixedAssetDepreciation - Depreciation
  • FixedAssetDepreciationDetail - Depreciation details

Currency & Exchange

  • Currency - Currency definitions
  • InitCurrency - Initial currency
  • ExchangeLosing - Exchange losses
  • ExchangeLosingDetail - Loss details
  • ExchangeLosingCurrency - Currency losses
  • ExchangeLoseDetail - Loss detail records

Financial Reports

  • IncomeStatement - Income statements
  • IncomeStatementDetail - Statement details
  • CashFlowSetting - Cash flow settings
  • CashFlowSettingDetail - Cash flow details

Banking

  • Bank - Bank accounts
  • LetterCredit - Letters of credit
  • Loan - Loans

Credits

  • Credits - Credit system
  • CreditsConfigure - Credit configuration

5. 🏭 Manufacturing (Priority: MEDIUM)

Current Status: 0/30+ tables mapped (0%)

Manufacturing Orders

  • MO - Manufacturing orders
  • MOItem - MO line items
  • ManufactureOrder - Manufacture orders
  • ManufactureOrderDetail - Order details
  • ManufacturePlan - Manufacturing plans
  • ManufacturePlanDetail - Plan details
  • ProduceSchedule - Production schedules
  • ProduceScheduleItem - Schedule items

BOM & MRP

  • BOM - Bill of Materials
  • BOMDetail - BOM details
  • MRP - Material Requirements Planning
  • MRPDetail - MRP details

Manufacturing Processes

  • Process - Process definitions
  • ProcessExchange - Process exchanges
  • ProcessExchangeDetail - Exchange details

CNC Operations

  • CNC - CNC machines/operations
  • ManufactureCNC - CNC manufacturing
  • ManufactureCNCDetail - CNC details

Packing Operations

  • ManufacturePacking - Packing operations
  • ManufacturePackingDetail - Packing details

Painting Operations

  • ManufacturePainting - Painting operations
  • ManufacturePaintingDetail - Painting details

Foundry

  • Foundry - Foundry operations
  • FoundryDetail - Foundry details
  • FoundryDetailLog - Foundry logs

Quality Control

  • AluminiumCheck - Aluminum quality checks
  • AluminiumCheckDetail - Check details

Melting

  • Melter - Melting operations

6. 🀝 CRM & Customers (Priority: MEDIUM)

Current Status: 0/15+ tables mapped (0%)

Customers

  • Customers - Customer information
  • CompanySales - Company sales data
  • CompanyUsers - Company users
  • OtherContacts - Other contacts

Custom Definitions

  • CustomerDefined - Customer definitions
  • CustomerDefinedDetail - Definition details

Complaints

  • Complain - Complaints
  • ComplainItem - Complaint items

Appointments

  • Appointment - Appointments

User Preferences

  • UserLastView - User last views
  • UserProductSeries - User product series
  • UserPriority - User priorities
  • CategoryProduct - Category products

7. πŸ‘₯ User & System Management (Priority: MEDIUM)

Current Status: 0/25+ tables mapped (0%)

Users

  • Users - User accounts
  • UserGroups - User groups
  • CheckUser - User checks

Permissions

  • Rights - User rights
  • RightsFlow - Rights flow
  • Action - Actions

System Logs

  • SystemLog - System logs
  • SystemType - System types
  • CsvDownloadLog - CSV download logs

Workflows

  • Flow - Workflow definitions
  • FlowObject - Flow objects

Messages

  • Messages - Messages
  • MessageSet - Message settings
  • MessageCategory - Message categories
  • MessageRelation - Message relations
  • UserMessage - User messages
  • UserOperateMessage - User operation messages

Email

  • SystemEmail - System emails
  • SystemEmailUser - Email users
  • EmailTemplate - Email templates
  • UserGroupsEmailTemplate - Group email templates

HR & Payroll

  • Attendance - Attendance records
  • LeaveForm - Leave forms
  • Payroll - Payroll
  • PayrollDetail - Payroll details
  • PayrollSetting - Payroll settings
  • PayrollSettingDetail - Payroll setting details
  • Reimbursement - Reimbursements
  • ReimbursementDetail - Reimbursement details

8. πŸ“‹ Invoicing & Documentation (Priority: MEDIUM)

Current Status: 0/5 tables mapped (0%)

  • InvoiceIn - Incoming invoices
  • InvoiceInDetail - Invoice details
  • PurchaseOrder - Purchase orders
  • PurchaseOrderItem - PO line items

9. 🌐 Content & Media (Priority: LOW)

Current Status: 0/15+ tables mapped (0%)

News & Help

  • News - News articles
  • NewsCategory - News categories
  • Help - Help content
  • HelpDetail - Help details

Resources

  • Resource - Resources
  • ResourceItem - Resource items
  • ResourceTag - Tags
  • ResourceTagRelationship - Tag relationships

Galleries

  • YongLe_Gallery - YongLe gallery

Syndication

  • Syndication - Syndication
  • SyndicationItem - Syndication items
  • SyndicationOld - Old syndication
  • SyndicationItemOld - Old syndication items

Advertisements

  • Advertisement - Advertisements

10. 🌍 Reference Data (Priority: LOW)

Current Status: 0/10+ tables mapped (0%)

  • Country - Countries
  • Port - Ports
  • ShippingAgent - Shipping agents
  • location - Locations
  • Entity - Generic entities
  • Sequence - Sequence generators

11. πŸ“Š Dashboard & Analytics (Priority: LOW)

Current Status: 0/2 tables mapped (0%)

  • dashboardModel - Dashboard models
  • dashboardRight - Dashboard rights

Implementation Roadmap

Phase 1: Core Product Tables βœ… COMPLETE (2026-02-05)

Goal: Complete Product module core tables

Completed tables:

  1. ProductType - Product type definitions (Python + Rust)
  2. ProductSeries - Series groupings (Python + Rust)
  3. ProductCategory - Hierarchical classification (Python + Rust)
  4. ProductGallery - Product images (Python + Rust)
  5. ProductBasePrice - Base pricing matrix (Python + Rust)
  6. ProductBOM - Bill of Materials (Python + Rust)

Completed tasks:

  • Create SQLModel mappings (Python) - 6 models
  • Create Domain models (Rust) - 6 structs
  • Create Repository traits (Rust) - 6 traits
  • Create SQL Server implementations (Rust) - 6 repos
  • Write integration tests - 24 Rust tests (3 regions Γ— 6 tables + 6 repo tests)
  • Write Python tests - 7 import tests + 22 DB tests
  • Update documentation

Phase 2: Sales & Orders (Week 2)

Goal: Enable order management

Priority tables:

  1. Ordert - Main orders
  2. OrderDetail - Order items
  3. Customers - Customer data
  4. PriceLevel - Pricing
  5. ShoppingCart - E-commerce

Phase 3: Warehouse & Inventory (Week 3)

Goal: Enable inventory tracking

Priority tables:

  1. WarehouseStock - Current stock
  2. StockInOrder - Stock in
  3. StockOutOrder - Stock out
  4. Warehouse - Warehouse info

Phase 4: Finance & Accounting (Week 4)

Goal: Enable financial reporting

Priority tables:

  1. Account - Chart of accounts
  2. Acct_Voucher - Vouchers
  3. ReceivePayment - Payments
  4. Currency - Currency

Phase 5: Manufacturing (Week 5+)

Goal: Enable production planning

Priority tables:

  1. MO - Manufacturing orders
  2. BOM - Bill of materials
  3. ManufacturePlan - Planning
  4. Process - Processes

Technical Implementation Guidelines

Domain Entity Template

#![allow(unused)]
fn main() {
// crates/core/src/domain/entities/{domain}/table_name.rs
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TableName {
    pub id: i32,
    pub field_name: Option<String>,
    pub created_at: Option<String>,
    pub foreign_id: Option<i32>,
}

impl TableName {
    pub fn new(id: i32) -> Self {
        Self {
            id,
            field_name: None,
            created_at: None,
            foreign_id: None,
        }
    }
    
    // Business logic methods here
}
}

Repository Trait Template

#![allow(unused)]
fn main() {
// crates/core/src/domain/repositories/{domain}/table_name_repository.rs
use crate::domain::entities::TableName;
use anyhow::Result;

#[async_trait::async_trait]
pub trait TableNameRepository: Send + Sync {
    async fn find_by_id(&self, id: i32) -> Result<Option<TableName>>;
    async fn find_all(&self) -> Result<Vec<TableName>>;
    async fn count(&self) -> Result<i32>;
}
}

Testing Template

#![allow(unused)]
fn main() {
// crates/core/tests/test_table_name.rs
#[cfg(test)]
mod tests {
    use efision_core::infrastructure::config::DatabaseConfig;
    use efision_core::infrastructure::sqlserver::TableNameRepo;
    use efision_core::domain::repositories::TableNameRepository;

    #[tokio::test]
    async fn test_count() {
        let config = DatabaseConfig::from_region("AU");
        let repo = TableNameRepo::new(config).await.unwrap();
        let count = repo.count().await.unwrap();
        assert!(count > 0);
        println!("Total records: {}", count);
    }
}
}

Naming Conventions

Rust (Snake Case for modules, PascalCase for types)

  • Module: table_name.rs
  • Struct: TableName
  • Repository trait: TableNameRepository
  • Implementation: SqlServerTableNameRepo
  • Service: TableNameService

Column Name Mapping Strategy

SQL Server uses PascalCase for column names (e.g., ProductID, CreateTime).

Python: Use sa_column_kwargs={"name": "ColumnName"} to map snake_case to PascalCase.

Rust: Use SQL aliases in queries: SELECT ProductID as product_id.


Database Connection Settings

All tables use the same connection settings as current implementation:

#![allow(unused)]
fn main() {
config.encryption(tiberius::EncryptionLevel::NotSupported);
config.application_name("efision");
config.readonly(true);
}

Documentation Requirements

For each new table mapping, create/update:

  1. Entity: Add to crates/core/src/domain/entities/{domain}/
  2. Repository: Add trait to crates/core/src/domain/repositories/{domain}/
  3. SQL Implementation: Add to crates/core/src/infrastructure/sqlserver/{domain}/
  4. Tests: Document test results
  5. Relationships: Document foreign key relationships (even if not enforced)
  6. Business logic: Document any business rules in domain models

Progress Tracking

Overall completion: 15/230+ tables (6.5%)

By category:

  • βœ… Product Management: 15/21 (71%)
  • ⏸️ Sales & Orders: 0/20 (0%)
  • ⏸️ Warehouse: 0/21 (0%)
  • ⏸️ Finance: 0/35+ (0%)
  • ⏸️ Manufacturing: 0/30+ (0%)
  • ⏸️ CRM: 0/15+ (0%)
  • ⏸️ User Management: 0/25+ (0%)
  • ⏸️ Invoicing: 0/5 (0%)
  • ⏸️ Content: 0/15+ (0%)
  • ⏸️ Reference Data: 0/10+ (0%)
  • ⏸️ Dashboard: 0/2 (0%)

Next Actions

  1. Review this document with Henry βœ…
  2. Confirm Phase 1 priority tables βœ…
  3. Phase 1 implementation βœ… (2026-02-05)
  4. Start Phase 2: Sales & Orders ⏳

Last updated: 2026-02-05 Maintained by: Lobster 🦞