# ============================================================ # ENTERPRISE CODING STANDARD # CodeIgniter 3 HMVC # PHP 5.6 # MariaDB 10 # Enterprise ERP Framework # Version 1.0 # ============================================================ Purpose This document defines mandatory coding standards for the ERP project. All AI Agents and Developers shall comply with this standard. ============================================================ GENERAL PRINCIPLES ============================================================ Code shall prioritize: Business Correctness Maintainability Readability Consistency Auditability Reusability Backward Compatibility ============================================================ SUPPORTED TECHNOLOGY ============================================================ Framework CodeIgniter 3 HMVC Language PHP 5.6 Database MariaDB 10.x Frontend HTML5 CSS3 JavaScript jQuery Bootstrap ============================================================ NAMING CONVENTION ============================================================ Controller Sales.php Purchase.php Inventory.php -------------------------------- Model Sales_model.php Purchase_model.php -------------------------------- Library StockCalculator.php -------------------------------- Helper stock_helper.php -------------------------------- Method camelCase() -------------------------------- Variable camelCase -------------------------------- Constant UPPER_CASE ============================================================ DIRECTORY RESPONSIBILITY ============================================================ Controller Receive Request Validate Input Call Service/Library/Model Return Response Controller shall NOT contain: Business Calculation Tax Formula Accounting Logic Large SQL ============================================================ MODEL RESPONSIBILITY ============================================================ Model is responsible for: Database Query CRUD Transaction Repository Logic Model shall NOT contain: HTML View Rendering Business Workflow ============================================================ HELPER RESPONSIBILITY ============================================================ Helper is responsible only for: Formatting Date Utility Number Utility String Utility Small Generic Functions Helper shall NOT contain: Business Workflow Accounting Logic Tax Logic Approval Logic Inventory Logic ============================================================ LIBRARY RESPONSIBILITY ============================================================ Library contains reusable business components. Examples Price Calculator Stock Calculator Discount Calculator Tax Calculator Journal Generator ============================================================ VIEW RESPONSIBILITY ============================================================ View shall contain presentation only. View shall NOT contain: SQL Business Rule Complex Calculation ============================================================ SQL STANDARD ============================================================ Never use SELECT * Always specify columns. Use Query Builder whenever practical. Avoid duplicated SQL. Avoid N+1 Query. Use transaction for business critical operations. ============================================================ SESSION STANDARD ============================================================ Session stores only necessary information. Large business objects shall not be stored in session. Session shall not become a temporary database. ============================================================ FUNCTION STANDARD ============================================================ Function shall perform one responsibility. Recommended maximum length 50 lines Absolute maximum 100 lines Beyond this requires refactoring. ============================================================ CONTROLLER STANDARD ============================================================ Recommended maximum 300 lines Warning 500 lines Critical 800 lines ============================================================ MODEL STANDARD ============================================================ Recommended maximum 500 lines Warning 800 lines Critical 1200 lines ============================================================ METHOD STANDARD ============================================================ Recommended 30 lines Warning 50 lines Critical 80 lines ============================================================ QUERY STANDARD ============================================================ Avoid Query inside Loop. Avoid duplicated query. Avoid unnecessary JOIN. Use Index. Review execution plan. ============================================================ TRANSACTION STANDARD ============================================================ Critical business process shall use: Begin Transaction Commit Rollback Error Handling ============================================================ ERROR HANDLING ============================================================ Never ignore exception. Never suppress database error silently. Log every critical failure. ============================================================ LOGGING ============================================================ Log Business Error Database Error Security Event Critical Exception Integration Failure ============================================================ DOCUMENTATION ============================================================ Every public function shall describe: Purpose Input Output Business Impact ============================================================ REVIEW CHECKLIST ============================================================ Business Rule Architecture Database Accounting Tax Security Performance Maintainability Readability Documentation ============================================================ FORBIDDEN ============================================================ Business Logic inside View Business Logic inside Helper Duplicated Tax Formula Duplicated Accounting Formula Hardcoded Configuration Hardcoded Tax Rate SQL inside View Nested Transaction without reason SELECT * Copy Paste Programming Magic Number Magic String ============================================================ DEFINITION OF GOOD CODE ============================================================ Good code is: Easy to read. Easy to modify. Easy to test. Easy to review. Easy to extend. Easy to maintain. ============================================================ END OF DOCUMENT ============================================================ # ============================================================ # ENTERPRISE ARCHITECTURE STANDARD # CodeIgniter 3 HMVC # PHP 5.6 # MariaDB 10 # Enterprise ERP # Version 1.0 # ============================================================ Purpose Define mandatory architecture standards for the ERP project. ============================================================ ARCHITECTURE PRINCIPLES ============================================================ Architecture shall prioritize Business Correctness Low Coupling High Cohesion Maintainability Scalability Readability Backward Compatibility ============================================================ APPLICATION LAYERS ============================================================ Presentation Layer ↓ Controller Layer ↓ Business Layer (Library / Service) ↓ Repository Layer (Model) ↓ Database ============================================================ CONTROLLER ============================================================ Responsibilities Receive Request Validate Request Authentication Authorization Call Business Service Return Response Controller SHALL NOT Contain SQL Contain Business Calculation Contain Accounting Logic Contain Tax Logic Contain Inventory Logic ============================================================ BUSINESS LAYER ============================================================ Business Layer contains Business Workflow Business Validation Approval Flow Calculation Inventory Logic Accounting Preparation Tax Preparation Business Layer SHALL NOT Generate HTML Execute Direct SQL ============================================================ MODEL ============================================================ Model Responsibilities CRUD Query Builder Database Transaction Repository Pattern Data Mapping Model SHALL NOT Calculate Tax Generate Journal Approve Workflow Render HTML ============================================================ VIEW ============================================================ View Responsibilities Display Data Formatting Template View SHALL NEVER Run SQL Business Logic Accounting Logic Tax Formula ============================================================ MODULE STRUCTURE ============================================================ Each Module controllers/ models/ views/ libraries/ helpers/ config/ language/ ============================================================ DEPENDENCY RULE ============================================================ Allowed Controller ↓ Library ↓ Model ↓ Database Forbidden Model → Controller View → Model View → Database Helper → Model ============================================================ BUSINESS RULE ============================================================ Business Rules shall exist only in one place. Duplicate Business Rules are prohibited. ============================================================ ACCOUNTING RULE ============================================================ Accounting shall be centralized. Journal generation shall not be duplicated. ============================================================ TAX RULE ============================================================ Tax calculation shall be centralized. Hardcoded tax formulas are prohibited. ============================================================ DATABASE ACCESS ============================================================ Database access shall occur only inside Model. ============================================================ TRANSACTION ============================================================ Critical business process BEGIN COMMIT ROLLBACK Mandatory. ============================================================ ERROR HANDLING ============================================================ Business Error ↓ Application Log ↓ User Friendly Message Never expose SQL Error. ============================================================ CONFIGURATION ============================================================ Configuration shall not be hardcoded. Environment specific configuration shall be isolated. ============================================================ CODE DUPLICATION ============================================================ Avoid Duplicate SQL Duplicate Validation Duplicate Tax Duplicate Journal Duplicate Workflow ============================================================ ANTI PATTERN ============================================================ Fat Controller Fat Model God Object Circular Dependency Hidden Dependency Business Logic in View Business Logic in Helper Business Logic in Controller ============================================================ ARCHITECTURE REVIEW CHECKLIST ============================================================ Layer Separation Dependency Responsibility Business Logic Database Access Maintainability Scalability Readability Reusability ============================================================ SUCCESS CRITERIA ============================================================ Architecture shall be Predictable Simple Consistent Reusable Maintainable ============================================================ END OF DOCUMENT ============================================================ # ============================================================ # ENTERPRISE DATABASE STANDARD # MariaDB 10.x # ERP Framework # Version 1.0 # ============================================================ Purpose This document defines mandatory database standards for the ERP project. Applies to all database design, schema changes, SQL development, migration, optimization and review. ============================================================ DATABASE PRINCIPLES ============================================================ Database shall prioritize Data Integrity Consistency Normalization Performance Auditability Maintainability Scalability Recoverability Backward Compatibility ============================================================ DATABASE ENGINE ============================================================ Database MariaDB 10.x Storage Engine InnoDB Character Set utf8mb4 Collation utf8mb4_unicode_ci ============================================================ NAMING STANDARD ============================================================ Database lower_case Table snake_case Column snake_case Primary Key id Foreign Key _id Example customer_id invoice_id product_id ============================================================ TABLE STANDARD ============================================================ Each table shall have Primary Key Created Date Updated Date Created By Updated By Status Soft Delete Flag (when applicable) ============================================================ PRIMARY KEY ============================================================ Primary Key BIGINT UNSIGNED AUTO_INCREMENT Primary Key shall never contain business meaning. ============================================================ FOREIGN KEY ============================================================ Every relationship shall be explicit. Use Foreign Key whenever possible. Or document the reason if omitted. ============================================================ NORMALIZATION ============================================================ Target Third Normal Form (3NF) Denormalization only when Performance justification exists. ============================================================ INDEX STANDARD ============================================================ Create Index for Primary Key Foreign Key Search Column Join Column Filter Column Unique Business Key ============================================================ UNIQUE KEY ============================================================ Business uniqueness shall use UNIQUE INDEX Never rely only on application validation. ============================================================ NULL STANDARD ============================================================ Avoid NULL whenever practical. Always define DEFAULT VALUE where appropriate. ============================================================ DATA TYPE ============================================================ Use smallest suitable datatype. Money DECIMAL Never FLOAT Date DATE Datetime DATETIME Boolean TINYINT(1) ============================================================ MONEY STANDARD ============================================================ Money shall always use DECIMAL(x,2) Never FLOAT Never DOUBLE ============================================================ DATE STANDARD ============================================================ Business Date DATE Transaction Timestamp DATETIME ============================================================ AUDIT STANDARD ============================================================ Critical Transaction shall record Created By Updated By Created Date Updated Date Source Module Reference Number ============================================================ TRANSACTION STANDARD ============================================================ Business Critical Operation BEGIN COMMIT ROLLBACK Mandatory ============================================================ DELETE STANDARD ============================================================ Master Data Soft Delete Transaction Data Never Physical Delete Unless approved. ============================================================ SQL STANDARD ============================================================ Avoid SELECT * Nested Loop Query Repeated Query Dynamic SQL Implicit Join Cartesian Join ============================================================ QUERY STANDARD ============================================================ Prefer Query Builder Parameterized Query Indexed Search Batch Insert Batch Update ============================================================ PERFORMANCE ============================================================ Review Execution Plan Index Usage Slow Query Large Scan Temporary Table Filesort ============================================================ BUSINESS RULE ============================================================ Database shall NOT contain Business Workflow Approval Logic Accounting Logic Tax Logic Except Triggers specifically approved. ============================================================ TRIGGER ============================================================ Triggers are discouraged. Allowed only when Business justification exists. Must be documented. ============================================================ VIEW ============================================================ Database View Read Only Reporting Aggregation View shall not replace business logic. ============================================================ STORED PROCEDURE ============================================================ Avoid unless Performance Legacy Compatibility Bulk Processing Approved by Architect. ============================================================ MIGRATION ============================================================ Every schema change shall include Purpose Risk Rollback Plan Migration Script Validation Script ============================================================ BACKUP ============================================================ Every structural change Requires Backup. ============================================================ REVIEW CHECKLIST ============================================================ Normalization Primary Key Foreign Key Index Constraint Naming Performance Transaction Audit Trail Recoverability ============================================================ FORBIDDEN ============================================================ SELECT * Money using FLOAT Duplicate Column Duplicate Table Business Logic in Trigger Hardcoded ID Missing Primary Key Missing Index Missing Audit Information Circular Reference ============================================================ SUCCESS CRITERIA ============================================================ Database shall be Consistent Normalized Indexed Auditable Recoverable Scalable Maintainable ============================================================ END OF DOCUMENT ============================================================ # ============================================================ # ENTERPRISE REVIEW STANDARD # ERP Engineering Review Standard # Version 1.0 # ============================================================ Purpose This document defines the mandatory review standard for all source code, database, architecture, business process, accounting, taxation, security and performance reviews. Every review shall be objective, evidence-based and measurable. ============================================================ REVIEW PRINCIPLES ============================================================ Review shall Be Objective Be Evidence Based Be Repeatable Be Traceable Be Actionable Be Measurable Review shall improve software quality. ============================================================ REVIEW ORDER ============================================================ 1 Business 2 Accounting 3 Tax 4 Architecture 5 Database 6 Security 7 Performance 8 Coding Standard 9 Documentation 10 Testing ============================================================ REVIEW OUTPUT ============================================================ Every review shall contain Executive Summary Scope Finding Evidence Impact Risk Recommendation Priority Estimated Effort ============================================================ SEVERITY ============================================================ Critical System Failure Accounting Error Tax Error Security Risk Data Corruption -------------------------------- High Business Risk Architecture Violation Performance Risk Database Risk -------------------------------- Medium Maintainability Readability Technical Debt -------------------------------- Low Documentation Naming Formatting ============================================================ PRIORITY ============================================================ P1 Immediate P2 High P3 Normal P4 Low ============================================================ FINDING FORMAT ============================================================ Finding ID Category Severity Priority File Line Evidence Violation Recommendation Estimated Effort ============================================================ EVIDENCE ============================================================ Every finding shall include evidence. Examples File Name Method Name SQL Statement Database Table Controller Model View Configuration ============================================================ BUSINESS REVIEW ============================================================ Review Workflow Approval Business Rule Validation Integration Business Continuity ============================================================ ACCOUNTING REVIEW ============================================================ Review Journal Posting Ledger Balance Closing Opening Balance Audit Trail ============================================================ TAX REVIEW ============================================================ Review PPN PPh Tax Configuration Tax Formula Tax Report e-Faktur ============================================================ ARCHITECTURE REVIEW ============================================================ Review Layer Dependency Coupling Cohesion Responsibility Code Duplication Architecture Smell ============================================================ DATABASE REVIEW ============================================================ Review Normalization Primary Key Foreign Key Index Constraint Transaction Query ============================================================ SECURITY REVIEW ============================================================ Review Authentication Authorization SQL Injection XSS CSRF Session Sensitive Data Logging ============================================================ PERFORMANCE REVIEW ============================================================ Review Slow Query N+1 Query Memory Loop Repeated Query Large Session Caching ============================================================ CODING REVIEW ============================================================ Review Naming Function Length Controller Size Model Size Complexity Readability Consistency ============================================================ DOCUMENTATION REVIEW ============================================================ Review Comments Function Description Business Flow Architecture Diagram Database Diagram Change History ============================================================ TESTING REVIEW ============================================================ Review Unit Test Integration Test Regression Test Manual Test Business Scenario ============================================================ SCORING ============================================================ Architecture 0-100 Database 0-100 Business 0-100 Accounting 0-100 Tax 0-100 Security 0-100 Performance 0-100 Maintainability 0-100 Documentation 0-100 Testing 0-100 ============================================================ OVERALL SCORE ============================================================ 90 - 100 Excellent 80 - 89 Good 70 - 79 Fair 60 - 69 Poor Below 60 Critical ============================================================ REVIEW REPORT TEMPLATE ============================================================ Executive Summary Overall Score Critical Findings High Findings Medium Findings Low Findings Risk Summary Recommendations Roadmap ============================================================ FORBIDDEN ============================================================ Opinion without evidence Recommendation without reason Changing business rules without analysis Ignoring accounting impact Ignoring tax impact Ignoring backward compatibility Ignoring technical debt ============================================================ SUCCESS CRITERIA ============================================================ Every review shall Identify Risks Provide Evidence Provide Recommendations Follow Standards Improve Software Quality ============================================================ END OF DOCUMENT ============================================================ # ============================================================ # ENTERPRISE PERFORMANCE STANDARD # CodeIgniter 3 HMVC # PHP 5.6 # MariaDB 10 # ERP Framework # Version 1.0 # ============================================================ Purpose This document defines mandatory performance standards for the ERP. Performance optimization shall never sacrifice business correctness, accounting integrity or data consistency. ============================================================ PERFORMANCE PRINCIPLES ============================================================ Optimize after measuring. Database First. Business Correctness First. Avoid Premature Optimization. Readable Code First. ============================================================ PERFORMANCE TARGET ============================================================ Normal Page < 2 Seconds Heavy Report < 10 Seconds AJAX < 1 Second Database Query < 300 ms ============================================================ DATABASE PERFORMANCE ============================================================ Use Index Avoid Full Table Scan Avoid SELECT * Avoid Duplicate Query Optimize JOIN Review Execution Plan ============================================================ QUERY STANDARD ============================================================ Never SELECT * SELECT inside Loop Repeated Query Unused JOIN Cartesian JOIN Dynamic SQL ============================================================ N+1 QUERY ============================================================ Detect Controller Model Library Repository Always replace with JOIN Batch Query IN() ============================================================ TRANSACTION ============================================================ Keep transaction short. Avoid user interaction during transaction. Rollback on failure. ============================================================ INDEX ============================================================ Mandatory Primary Key Foreign Key Search Field JOIN Field ORDER BY Field ============================================================ PAGINATION ============================================================ Mandatory for Master Data Transaction List Report History Log ============================================================ LOOP ============================================================ Avoid Query inside Loop Heavy Calculation inside Loop Nested Loop without justification ============================================================ MEMORY ============================================================ Avoid Large Array Large Session Large Temporary Object Unused Variable ============================================================ SESSION ============================================================ Store only User Role Permission Branch Company Language Never store Report Result Invoice Journal Inventory Object ============================================================ CACHE ============================================================ Cache Master Data Configuration Lookup Table Reference Data Never Cache Financial Transaction Journal Posting Result ============================================================ FILE ============================================================ Large Import Use Batch Processing Large Export Use Streaming ============================================================ REPORT ============================================================ Large Report Pagination Background Process Temporary Table (if approved) ============================================================ PHP STANDARD ============================================================ Avoid Recursive Loop Huge Include Unused Object Large Global Variable ============================================================ CI3 STANDARD ============================================================ Reuse Loaded Library Reuse Loaded Model Avoid Multiple Load Use Config Use Helper correctly ============================================================ MARIADB STANDARD ============================================================ Review EXPLAIN Slow Query Log Index Usage Temporary Table Filesort ============================================================ IMPORT ============================================================ Batch Insert Transaction Progress Log Rollback ============================================================ EXPORT ============================================================ Stream Output Avoid Large Memory Allocation Split Large Export ============================================================ LOGGING ============================================================ Log Slow Query Memory Peak Large Transaction Performance Warning ============================================================ PERFORMANCE REVIEW CHECKLIST ============================================================ Query Index Loop Memory Session Cache Transaction Report Import Export ============================================================ FORBIDDEN ============================================================ SELECT * Query inside Loop Large Session Large Controller Large Model Duplicate Query Repeated Calculation Loading Same Library Multiple Times ============================================================ SUCCESS CRITERIA ============================================================ Application shall Respond Quickly Scale Predictably Use Resources Efficiently Maintain Data Integrity Remain Easy to Maintain ============================================================ END OF DOCUMENT ============================================================ # ============================================================ # ENTERPRISE DOCUMENTATION STANDARD # ERP Engineering Documentation Standard # Version 1.0 # ============================================================ Purpose This document defines mandatory documentation standards for the ERP project. Documentation is part of the software. Undocumented implementation is considered incomplete. ============================================================ DOCUMENTATION PRINCIPLES ============================================================ Accurate Consistent Complete Maintainable Traceable Versioned Auditable ============================================================ REQUIRED DOCUMENTATION ============================================================ Project Documentation Architecture Documentation Business Documentation Database Documentation API Documentation Configuration Documentation Deployment Documentation Change Log ADR RFC Technical Debt Known Issues ============================================================ SOURCE CODE ============================================================ Every Public Method shall document Purpose Parameters Return Value Business Impact Dependencies Exceptions ============================================================ MODULE DOCUMENTATION ============================================================ Every Module shall document Purpose Business Process Dependencies Input Output Database Tables Related Modules ============================================================ DATABASE DOCUMENTATION ============================================================ Every Table shall document Purpose Primary Key Foreign Keys Relationships Business Rules Indexes Owner Module ============================================================ API DOCUMENTATION ============================================================ Every API shall document Endpoint Method Authentication Request Response Error Code Example ============================================================ CONFIGURATION ============================================================ Every Configuration shall document Purpose Default Value Environment Dependency Risk ============================================================ BUSINESS FLOW ============================================================ Document Workflow Approval Flow Accounting Impact Tax Impact Inventory Impact ============================================================ ARCHITECTURE ============================================================ Document Layers Dependencies Module Diagram Data Flow Integration ============================================================ CHANGE LOG ============================================================ Every Change shall record Date Version Author Description Impact Reference ============================================================ ADR ============================================================ Every Architecture Decision shall record Problem Decision Reason Alternative Risk Impact Migration Strategy ============================================================ RFC ============================================================ Every Major Change shall document Objective Scope Reason Affected Module Risk Rollback Plan Approval ============================================================ TECHNICAL DEBT ============================================================ Record Problem Severity Evidence Recommendation Status Owner ============================================================ KNOWN ISSUE ============================================================ Record Issue Module Impact Workaround Status ============================================================ REVIEW CHECKLIST ============================================================ Completeness Accuracy Consistency Traceability Version Readability ============================================================ FORBIDDEN ============================================================ Missing Documentation Outdated Documentation Undocumented API Undocumented Database Undocumented Configuration ============================================================ SUCCESS CRITERIA ============================================================ Documentation shall Explain Guide Support Maintenance Support Audit Support Future Development ============================================================ END OF DOCUMENT ============================================================ # ============================================================ # ENTERPRISE TESTING STANDARD # ERP Testing Standard # Version 1.0 # ============================================================ Purpose This document defines mandatory testing standards for the ERP. Every implementation shall be verified before deployment. ============================================================ TESTING PRINCIPLES ============================================================ Test Business First Test Critical Path Test Regression Test Security Test Performance ============================================================ TEST TYPES ============================================================ Unit Test Integration Test Business Test Database Test Security Test Performance Test Regression Test User Acceptance Test ============================================================ BUSINESS TEST ============================================================ Verify Workflow Approval Posting Inventory Accounting Tax ============================================================ ACCOUNTING TEST ============================================================ Verify Journal Ledger Trial Balance Financial Report Closing Opening ============================================================ TAX TEST ============================================================ Verify PPN PPh Tax Posting Tax Report Tax Configuration ============================================================ DATABASE TEST ============================================================ Verify CRUD Transaction Rollback Constraint Index Migration ============================================================ SECURITY TEST ============================================================ Verify Authentication Authorization SQL Injection XSS CSRF Session ============================================================ PERFORMANCE TEST ============================================================ Verify Slow Query Large Report Import Export Memory Concurrency ============================================================ REGRESSION TEST ============================================================ Verify Existing Feature Business Flow Accounting Tax Reporting ============================================================ DEPLOYMENT TEST ============================================================ Verify Migration Rollback Configuration Permission ============================================================ TEST RESULT ============================================================ Every Test shall record Test ID Scenario Input Expected Result Actual Result Status Tester Date ============================================================ DEFECT ============================================================ Record Severity Priority Module Description Evidence Recommendation ============================================================ SEVERITY ============================================================ Critical High Medium Low ============================================================ TEST CHECKLIST ============================================================ Business Accounting Tax Architecture Database Security Performance Documentation ============================================================ SUCCESS CRITERIA ============================================================ No Critical Defect No High Defect Business Validated Accounting Balanced Tax Validated ============================================================ END OF DOCUMENT ============================================================