លំហសិក្សាកម្ពុជា
V1.0
Small and Medium Enterprises (SMEs) frequently experience operational friction due to an over-reliance on manual record-keeping, non-centralized spreadsheets, and informal accounting practices1. These traditional tracking methods introduce stock quantity drift, pricing mismatches, untraceable refund actions, and an inability to analyze daily or monthly gross and net profitability1. This research paper presents a comprehensive structural and technical analysis of the SME Point-of-Sale (POS) and Inventory Management System—a multi-tier web application engineered to centralize inventory tracking, terminal transactions, role-based governance, and financial reporting1. Built upon Python 3.12/3.13, Flask 3.x, and MySQL 8.0, the application implements a layered architectural topology comprising Model, Repository, Service, and Controller/Route layers1. The system heavily leverages advanced Object-Oriented Programming (OOP) paradigms, including validated dataclasses with controlled properties, Strategy patterns for dynamic calculation of discounts and payment processing, Template Method patterns for multi-format report exports, Factory patterns for standardized entity instantiation, and Repository composition for isolated database operations1. System security is maintained through Bcrypt password hashing, time-bound email One-Time Passwords (OTP) stored via cryptographic SHA-256 digests, dynamic Role-Based Access Control (RBAC), parameterized SQL queries, and strict activity auditing1. Transactional safety during concurrent terminal sales is guaranteed through database-level pessimistic row locking (SELECT ... FOR UPDATE) alongside a tokenized short-term stock reservation engine1. The resulting codebase spans approximately 3,300 lines of application code, 14 relational database tables, over 40 HTTP endpoints, and a suite of automated unit tests1. This paper provides an exhaustive architectural decomposition, evaluates empirical test results, analyzes an identified design flaw in eager strategy instantiation, and outlines necessary engineering enhancements for enterprise production readiness1.
|
Project Info |
SME POS System:
Point-of-Sale and Inventory Management |
|
Team Members |
Phengmeng Visal, Sansokthy
Reach, Line William, Pheap Pheasothearum |
|
Course / Class |
Advanced OOP with Python |
|
Lecturer |
SEK SOCHEAT |
|
Semester / Year |
Term2/Year2 |
|
Submission Type |
Final Report |
Point-of-Sale (POS) systems represent a fundamental operational software category responsible for recording transaction data, processing tender payments, and adjusting inventory balances in real time1. Within Small and Medium Enterprises (SMEs), these operational logs provide critical analytical insights into revenue velocity, product demand, tax liabilities, and employee accountability1. While commercial off-the-shelf POS software platforms exist, they frequently impose recurring licensing fees, rely on proprietary cloud infrastructures, and package overly complex feature sets tailored for large enterprise retail chains1. A self-hosted, domain-focused web application serves as an effective alternative, providing SMEs with full data ownership while serving as an ideal platform for demonstrating modern software engineering principles1.
Retail operations in small enterprises are traditionally managed using physical paper receipts, disjointed spreadsheets, or informal memory-based tracking1. This reliance on uncoordinated manual processes introduces severe systemic vulnerabilities1:
Stock Drift and Loss: Discrepancies between recorded inventory levels and physical shelf counts accumulate over time, resulting in stockouts or unrecorded inventory shrinkage1.
Pricing and Ledger Mismatches: Hand-calculated taxes, ad-hoc discounts, and manual arithmetic introduce ledger inaccuracies and financial loss1.
Audit and Governance Deficits: Cashier activities, pricing alterations, and refund requests lack identity attribution, leaving business owners unable to verify transaction history or detect insider fraud1.
Concurrency Conflicts: Simultaneous sales across multiple checkout counters frequently cause over-selling or negative inventory counts due to delayed stock updates1.
To resolve these operational challenges, this project engineered a web-based POS and inventory management system designed around clean software architecture and object-oriented principles1. The implementation was evaluated against five key technical and functional milestones1.
The functional boundaries of the application focus on core store workflows1. In-scope capabilities include email OTP registration verification, multi-role authorization across three system roles (Admin, Stock Manager, Cashier), full product catalog CRUD operations, manual stock movement logging, a web-based POS terminal supporting cash and card sales, configurable tax and service charge rates, single-refund invoice processing, and financial reporting with CSV and JSON exports1.
External payment gateway processing (e.g., credit card terminal APIs), physical receipt printer drivers, barcode scanner hardware protocols, multi-branch multi-store networking, partial line-item refunds, and cloud deployment scripts are explicitly out of scope for this initial release1.
Modern web application design emphasizes the separation of concerns to maximize testability, maintainability, and code reusability2. The Model-View-Controller (MVC) design pattern isolates data models and business rules from the user interface rendering layer2. In complex enterprise applications, pure MVC can result in bloated controller classes that mix HTTP parsing with core domain logic2. To prevent this architectural anti-pattern, modern software engineering advocates multi-tier layered topologies—specifically separating data access (Repositories) and business orchestration (Services) from HTTP handlers (Routes/Controllers)1.
Design patterns provide standardized, reusable solutions to recurring software engineering challenges4. In object-oriented application development, the Gang of Four (GoF) design patterns are categorized into Creational, Structural, and Behavioral patterns4:
Strategy Pattern: Defines a family of algorithms, encapsulating each one, and making them interchangeable at runtime4. This pattern is widely applied in billing, pricing, and payment processing engines1.
Template Method Pattern: Defines the skeleton of an algorithm in a base class method, deferring specific primitive steps to subclasses4. This enables consistent execution flows across different format exporters (e.g., JSON and CSV generation)1.
Factory Pattern: Abstracts object creation logic, ensuring that complex initialization and validation checks are executed in a centralized factory method4.
Repository Pattern: Mediates between the domain mapping layer and data mapping layers using a collection-like interface for accessing domain objects, isolating raw SQL or ORM queries1.
In multi-user transactional web systems, concurrent access to shared resources introduces severe race conditions7. Concurrency control strategies are broadly divided into optimistic and pessimistic concurrency models7:
Optimistic Concurrency Control: Assumes resource conflicts are rare and verifies data consistency at transaction commit time (e.g., using version checks)7. If a conflict occurs, the transaction is aborted and rolled back7.
Pessimistic Concurrency Control: Assumes resource contention will occur and acquires strict locks on target rows when data is first read7. In SQL systems, pessimistic locking is implemented via SELECT ... FOR UPDATE constructs within an explicit ACID transaction block1. This forces concurrent threads to wait until the lock is released, preventing double-spend and over-allocation defects in inventory checkouts1.
The software stack was chosen to provide execution efficiency, strict data typing, robust relational constraints, and clean object orientation1.
The application enforces a five-tiered layered architecture, maintaining a single directional request flow1:
Presentation Layer (Jinja2 HTML Templates): Renders dynamic web pages, adapting navigation elements based on active user role permissions1.
Controller/Route Layer (Flask Blueprints): Handles HTTP requests, extracts parameters, evaluates authentication/permission decorators, delegates work to services, and formats responses1.
Application Service Layer (Business Domain Services): Implements business workflows, manages strategy selection, calculates invoice financial totals, and coordinates transactions1.
Data Access Repository Layer: Encapsulates parameterised SQL queries, mapping database rows to strongly typed Python model entities1.
Database Storage Layer (MySQL Engine): Persists relational tables, enforcing foreign keys, unique constraints, check constraints, and row-level locks1.
The codebase incorporates key object-oriented paradigms to promote modularity and prevent invalid state assignment1.
The checkout pipeline delegates calculation tasks to strategy classes implementing abstract interfaces1. DiscountStrategy mandates a calculate_discount(subtotal) method1. Concrete classes include NoDiscount, PercentageDiscount, FixedDiscount, and VIPDiscount1. PaymentStrategy abstracts tender settlement, where CashPayment calculates change due and CardPayment verifies authorization coverage1.
ReportExporter implements a unified export(report_data) template method1. This method normalizes raw model collection data into standard tabular key-value dictionaries before delegating file formatting to abstract serialize() implementations in JsonReportExporter and CsvReportExporter1.
The relational schema comprises 14 tables categorized into four domain modules1:
Identity Module: users, roles, permissions, user_roles, role_permissions, otp_tokens1.
Catalog Module: categories, products, stock_movements, sale_reservations1.
Sales Module: sales, sale_items, refunds1.
System Module: app_settings, activity_logs1.
To guarantee that past financial records remain accurate despite future product price changes or tax adjustments, the system executes immutable financial snapshotting during checkout1:
sales.tax_rate and sales.extra_charges persist active store tax settings at transaction time1.
sale_items.unit_price and sale_items.unit_cost persist unit retail prices and wholesale costs at the exact moment of sale1.
Financial invoice line totals, sub-totals, tax additions, and final totals are calculated using exact decimal arithmetic:
To prevent race conditions during concurrent checkouts across multiple cashiers, the application combines short-term tokenized cart reservations with database pessimistic row locking1:
Adding items to a terminal cart reserves stock in sale_reservations for 15 minutes1. Available stock for other terminals is calculated dynamically:
During transaction execution, SaleRepository.create_atomic() opens a transaction block and executes SELECT ... FOR UPDATE across target product rows1. This acquires exclusive row locks in MySQL, forcing concurrent transactions targeting the same products to wait until the holding transaction issues a COMMIT or ROLLBACK1.
User authentication uses salted password hashing via Flask-Bcrypt1. New account registration implements a multi-step verification pipeline1:
Registration details submitted via POST /auth/register are validated and held in staging memory1.
A random six-digit OTP is generated, converted into a SHA-256 digest, and stored with a 10-minute expiration window1.
The plain six-digit code is dispatched to the user's email address using Flask-Mailman1.
Upon submitting the matching OTP via POST /auth/verify, the digest is confirmed and the user record is committed to the database1.
Access control is governed by ten system permissions mapped across three default roles1:
Permissions are evaluated dynamically on every HTTP request via custom decorators (@require_permission), returning HTTP 403 Forbidden when access is denied1.
The @log_action decorator automatically writes request metadata to activity_logs1. Sensitive fields (such as password, otp, card_number) are redacted from the request payload before JSON serialization1. All SQL operations use parameterized queries (%s), preventing SQL injection attacks1.
Automated testing was executed via pytest, achieving a 100% pass rate across 10 unit test cases1.
Manual workflow testing verified eight core user interaction scenarios1:
System testing identified a bug where entering a fixed discount greater than $100.00 raises an unhandled exception1.
SaleService.checkout() eagerly instantiates all strategy classes before evaluating the requested discount type1:
Python
# Eager Instantiation Defect in SaleService.checkout()
def checkout(self, sale_data, discount_type, discount_value):
no_discount = NoDiscount()
pct_discount = PercentageDiscount(discount_value) # Raises ValueError if discount_value > 100
fixed_discount = FixedDiscount(discount_value)
strategy_map = {
"none": no_discount,
"percentage": pct_discount,
"fixed": fixed_discount
}
selected_strategy = strategy_map.get(discount_type)
When a user submits a valid fixed discount of $150.00, PercentageDiscount(150) executes during eager instantiation, validating that percentage values satisfy 1. This raises an exception before the code can select fixed_discount1.
The issue is resolved by implementing lazy factory evaluation:
Python
# Refactored Lazy Factory Construction
STRATEGY_FACTORIES = {
"none": lambda val: NoDiscount(),
"percentage": lambda val: PercentageDiscount(val),
"fixed": lambda val: FixedDiscount(val)
}
def checkout(self, sale_data, discount_type, discount_value):
factory = STRATEGY_FACTORIES.get(discount_type)
if not factory:
raise ValueError(f"Unsupported discount strategy: {discount_type}")
selected_strategy = factory(discount_value)
Volatile Memory Staging: Pending registrations and OTP digests are stored in process memory, causing loss of staging state upon server restarts1.
CSRF Protection: State-changing requests rely on SameSite=Lax cookies; anti-CSRF tokens should be added prior to production1.
Service Test Coverage: Automated tests focus primarily on domain models; integration testing should be expanded to cover SaleService and transactional repository routines1.
This project successfully designed and evaluated a Point-of-Sale and Inventory Management System tailored for SMEs1. By organizing the codebase into Model, Repository, Service, and Route layers, the application enforces a clean separation of concerns1. Object-oriented design patterns—including Strategy, Template Method, and Factory patterns—were applied to decouple complex business rules1. Database-level pessimistic locking and immutable snapshotting ensure data integrity and financial precision during concurrent multi-terminal checkouts1. Addressing identified strategy construction defects and expanding automated integration tests will further prepare this system for enterprise commercial deployment1.
SME POS Project Development Team. (2024). SME Point-of-Sale and Inventory Management System Technical Documentation. Final Project Report, Advanced Object-Oriented Programming with Python1.
Gamma, E., Helm, R., Johnson, R., & Vlissides, J. (1994). Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley1.
Leff, A., & Rayfield, J. T. (2001). Web-application development using the Model/View/Controller design pattern. Proceedings Fifth IEEE International Enterprise Distributed Object Computing Conference, 118–1273.
IEEE Computer Society. (2023). Employing MVC-based design patterns and multi-tier architectural strategies for web application development. IEEE CISES Proceedings, 1–62.
IEEE Software Engineering Group. (2022). Evaluation of Creational and Behavioral Design Patterns in Web and Distributed Systems. IEEE IC3I Proceedings, 10–165.
Database Systems & Distributed Infrastructure Research. (2023). Concurrency Control, Row-Level Locking, and Transaction Isolation in Multi-User Relational Systems7.
The following checklist details missing project metadata identified during document parsing. These placeholders must be completed prior to submitting the final paper:
Semester / Year Placeholder (Section 1 Title Block): Update the project cover block with the current academic period (e.g., Semester I, 2024–2025)1.
Field Observation / Interview Notes (Section 1.2): Insert empirical field observation notes or shop interview details gathered during initial requirements gathering1.
User Interface Screenshots (Section 4.8): Embed verified application screenshots depicting:
Login & OTP Verification View
Product Catalog Management Table
Active POS Terminal with Cart Items
Issued Receipt View
Sales History & Refund View
Financial & Shift Reporting Dashboards
Administration Users & Roles Control Panel1.
Manual Test Execution Log (Section 5.2): Record Pass/Fail execution statuses and attach supporting screenshots for manual test scenarios 1 through 81.
Team Member Contribution Matrix (Appendix B): Complete the team contribution breakdown using assigned team member names (Phengmeng Visal, Sansokthy Reach, Line William, Pheap Pheasothearum)1:
Line William: [Assign primary role, e.g., Systems Analyst / Project Lead, and list specific modules/commits]1
Sansokthy Reach: [Assign primary role, e.g., Backend & OOP Designer, and list specific modules/commits]1
Phengmeng Visal: [Assign primary role, e.g., Database Architect & Integration Lead, and list specific modules/commits]1
Pheap Pheasothearum: [Assign primary role, e.g., UI Developer & QA Testing Lead, and list specific modules/commits]1
Version Control Evidence (Appendix C): Attach commit history logs or pull request statistics demonstrating collaborative development across all team members1.
Exploring Modern Design Patterns within the MVC Framework, https://ieeexplore.ieee.org/iel7/10183385/10182405/10183582.pdf
Web-application development using the Model/View/Controller, https://ieeexplore.ieee.org/document/950428/
Software design pattern - Wikipedia, https://en.wikipedia.org/wiki/Software_design_pattern
Software design pattern on the Edge - IEEE Xplore, https://ieeexplore.ieee.org/iel7/9987724/9987729/09987912.pdf
Design patterns in software development - ResearchGate, https://www.researchgate.net/publication/252028814_Design_patterns_in_software_development
Pessimistic vs Optimistic Locking - ByteByteGo, https://bytebytego.com/guides/pessimistic-vs-optimistic-locking/
A Systematic Literature Review - Design Patterns - ResearchGate, https://www.researchgate.net/publication/339257854_Software_Design_Patterns_Recommendation_A_Systematic_Literature_Review
Software Engineering and Design Patterns Research Guide, https://papersflow.ai/research/topics/software-engineering-and-design-patterns
Master Database Concurrency: Pessimistic vs. Optimistic Locking, https://medium.com/@mriduaayu123/master-database-concurrency-pessimistic-vs-optimistic-locking-1476b133381f
Pessimistic Concurrency Control (Locking) - SAP Help Portal, https://help.sap.com/docs/abap-cloud/abap-rap/pessimistic-concurrency-control-locking
Software Design Patterns and Architecture Patterns –A Study Explored, https://ieeexplore.ieee.org/document/10073279/
មតិយោបល់ 0