--- name: financial-management-module version: 1.0.0 description: Complete production-ready implementation of Financial Management module with order-level receivables and payments management, following all established development conventions. trigger_conditions: - User requests to implement financial management functionality - Task involves order-level receivables and payments tracking - Development follows the standard module structure with bricks frontend and sqlor database backend - Integration with existing contract_management and order management modules is required --- # Financial Management Module ## Overview This module provides comprehensive financial management capabilities with order-level granularity for receivables and payments. It integrates seamlessly with the existing contract management and order management modules, following the standard module development specification. ## Features Implemented ### 2.4.1 收支管理 #### 应收款管理(订单维度优化) - **自动立应收**: 按订单生成应收计划,每个订单对应独立应收记录,显示"订单应收金额""应收日期""关联合同号" - **账期监控**: 支持按订单维度跟踪账期,超期30天自动推送至销售及财务,合同详情页汇总展示所有关联订单的应收状态 #### 收款管理(新增订单关联) - **收款录入**: 财务录入收款时,需优先选择"关联订单",系统校验收款金额≤该订单应收金额,避免超收;支持批量关联多个订单 - **收款分配**: 支持手动分配收款比例(如"订单A收50%,订单B收50%"),系统自动记录每个订单的"已收款金额/剩余应收金额" - **凭证生成**: 收款凭证同时显示合同编号与订单编号,便于财务对账 #### 订单与合同的财务数据联动 - **合同层面**: 自动汇总所有关联订单的"总应收金额/总已收款金额/总剩余应收金额",展示"合同收款完成率" - **订单层面**: 完成收款后,自动更新对应订单状态为"已收款",并同步触发合同履约进度 #### 支出管理 - **支出关联**: 提交支出需关联已核销(确认收款的审批)对应合同的已收款 ## Critical Implementation Notes ### Proper awaitify Usage - **Only wrap synchronous functions** with `awaitify()` - **Never wrap async/await functions** - they are already coroutines - All exposed functions in `init.py` should be directly assigned if they are already async ### Database Table Definition Compliance - Must follow the exact 4-section JSON structure: `summary`, `fields`, `indexes`, `codes` - Field definitions require: `name`, `title`, `type`, `length` (for str/decimal), `nullable`, `comments` - Use proper field types: `str` (with length), `decimal` (with length/dec), `date`, `timestamp`, `long` (for integers) - Indexes must have unique names and specify `idxtype` as "unique" or "index" - Codes section properly references lookup tables with `valuefield` and `textfield` ### Production-Ready Development - All code must be production-ready, not example/demonstration code - Strict adherence to established specifications is mandatory - Complete error handling and validation required - Organization-based data isolation implemented throughout ### Database Schema Design **Core Tables:** - `receivables` - Order-level receivable records with due date tracking - `receipts` - Payment receipt records with allocation support - `receipt_allocations` - Multi-order payment allocation records - `payments` - Expense records linked to verified contract receipts - `financial_vouchers` - Financial vouchers showing both contract and order numbers **Design Principles:** - All tables include `org_id` for multi-tenant data isolation - Use `label` and `comment` fields (not `description`) per table definition规范 - Leverage appbase `appcodes` table for status and method categorization - Complex joins handled through CRUD configuration for performance ### Core Business Logic Architecture **Module Structure:** - `financial_core.py` - Primary financial operations with async/await pattern - Comprehensive validation for payment amounts and allocations - Automatic contract fulfillment triggering on payment completion - Overdue receivable detection and notification system **Key Patterns:** - Async-first design using proper await patterns - Organization-based database connection routing via `getDBP(org_id)` - Transaction-safe payment allocation with proper validation - Scheduled task integration for overdue notifications ### Frontend Implementation **Bricks Framework Components:** - `receivables_list.ui` - Receivable records with order and contract information - `receipts_edit.ui` - Payment entry form with multi-order allocation support - `payments_edit.ui` - Expense entry with contract verification - `financial_vouchers_list.ui` - Financial vouchers showing contract/order details **UI/UX Best Practices:** - Responsive layout using VBox/HBox with maxWidth constraints - Clear navigation between related financial entities - Proper field labeling and organization in forms - Money and date formatting applied consistently ### Integration Points **Contract Management Integration:** - Automatic receivable creation from orders - Contract fulfillment progress updates on payment completion - Financial summary aggregation at contract level **Order Management Integration:** - Order status updates to "paid" on full payment - Real-time financial data synchronization **RBAC Integration:** - All operations include `org_id` parameter for data isolation - User permissions enforced through existing RBAC framework - Multi-tenant security model with organization boundaries ## Implementation Workflow ### Step 1: Setup Module Structure ```bash mkdir -p financial_management/{financial_management,wwwroot,models,json,init,skill} ``` ### Step 2: Define Database Tables Create JSON table definitions in `models/` directory following the规范: - Include `label` and `comment` for each field - Add `org_id` for multi-tenant isolation - Define proper data types and constraints ### Step 3: Implement Core Logic - Create `financial_core.py` with comprehensive validation - Implement proper error handling and transaction safety - Expose functions via `init.py` with proper async patterns ### Step 4: Develop Frontend - Create .ui files in `wwwroot/` using bricks components - Implement proper navigation and data binding - Follow responsive design principles ### Step 5: Configure CRUD Operations - Define CRUD JSON files in `json/` directory - Configure field visibility, widths, and alterations - Set up complex joins for related entity display ### Step 6: Test Integration - Verify module loads via `load_financial_management()` - Test all CRUD operations with sample data - Validate payment allocation and validation logic - Ensure proper contract and order integration ## Common Pitfalls and Solutions ### Pitfall 1: Incorrect Payment Validation **Issue:** Not properly validating payment amounts against receivable limits **Solution:** Implement comprehensive validation in `create_receipt()` function with proper decimal arithmetic ### Pitfall 2: Missing Organization Isolation **Issue:** Forgetting `org_id` in queries leading to data leakage **Solution:** Include `org_id` in all database operations and validate in business logic ### Pitfall 3: Incomplete Contract Fulfillment Integration **Issue:** Payment completion not triggering contract milestone updates **Solution:** Implement `_update_order_and_contract_fulfillment()` with proper milestone mapping ### Pitfall 4: Poor Performance on Financial Summaries **Issue:** Slow contract financial summary queries **Solution:** Use optimized SQL with proper indexing and avoid N+1 query patterns ## Verification Checklist - [ ] Module directory structure matches specification - [ ] All table definitions use `label`/`comment` fields correctly - [ ] Core functions are properly async and exposed via ServerEnv - [ ] Frontend uses bricks components with proper CSS styling - [ ] CRUD definitions include proper field configurations and joins - [ ] Payment validation prevents over-collection - [ ] Multi-order allocation works correctly - [ ] Financial vouchers show both contract and order numbers - [ ] Overdue notification system functions properly - [ ] Package builds successfully with pyproject.toml ## Extension Points - Add additional payment methods by extending appcodes - Customize financial reporting by adding new summary functions - Modify UI templates for specific business requirements - Integrate with external accounting systems - Add workflow automation for payment approval processes