QuellCode/CentronERP war nur als Gitlink (Submodul-Referenz auf 79c1142) getrackt, ohne .gitmodules und ohne erreichbares Remote. Der Untersuchungsgegenstand der Versuchsreihe war damit nicht reproduzierbar gesichert: Ein Klon haette ein leeres Verzeichnis erhalten, und die Belege der 3.287 Anforderungen waeren nicht ueberpruefbar gewesen. Umstellung: - Historie nach c:\DEV\CentronERP_git_snapshot_79c1142 ausgelagert (vollstaendig lesbar, enthaelt 79c1142 und Vorgaenger 89ccfd6) - Gitlink aus dem Index entfernt - Dateiinhalt aufgenommen: 24.557 Dateien, rund 333 MB Die verschachtelte .gitignore der Codebasis gilt weiter, Build-Artefakte bleiben ausgeschlossen. Details in Versuche/Versuch_01/_Codebasis-Nachweis.md
17 KiB
Contracts Backend Architecture
This document describes the specific backend implementation for contracts within the c-entron.NET receipts system. Contracts extend the generic receipt architecture with specialized functionality for recurring billing, service agreements, and customer asset management.
Overview
Contracts in c-entron.NET are specialized receipts that handle ongoing service agreements, maintenance contracts, and recurring billing scenarios. They extend the base receipt functionality with contract-specific features like billing intervals, contingent management, device tracking, and automated invoice generation.
Entity Architecture
ReceiptContract Entity
Location: src/backend/Centron.Entities/Entities/Sales/Receipts/ContractLists/ReceiptContract.cs
The ReceiptContract class extends ReceiptBase and implements IReceiptContract. It represents the main contract entity with comprehensive contract-specific properties.
Core Contract Properties
Customer and Project Information:
CustomerI3D: Primary customer referenceProjectNumber: Project identifier for the contractPurchaseOrderNumber: Customer's purchase order referenceAdditionalText: Supplementary contract description
Personnel Assignment:
SalesRepresentativeI3D: Assigned sales representativeOfficeStaffI3D: Internal staff responsible for contract management
Delivery and Billing Addresses:
DeliveryAddress,DeliveryAddressCustomerI3D: Service delivery locationInvoiceAddress,InvoiceAddressCustomerI3D: Billing address informationLicenseeAddress,LicenseeAddressCustomerI3D: Software licensing address
Contract Lifecycle:
DeliveryDate: Contract start or service delivery dateContractEnd: Contract termination dateContractTermination: Actual termination dateFirstPaidDate: Date of first payment receivedReminderDate: Follow-up reminder datePreparationDate: Contract preparation dateFinishDate: Contract completion date
Billing Configuration
Billing Intervals:
BillingIntervalKind: Type of billing cycle (Daily, Monthly, Quarterly, Yearly)BillingIntervalDuration: Number of intervals (e.g., 3 for quarterly when kind is Monthly)BillingKind: Billing methodology (enum BillingKinds)AutomatedBilling: Boolean flag for automatic invoice generation
Contract Calculation:
CalculationKind: How contract values are calculated (enum ContractCalculationKind)CalcNeedKind: Calculation requirements (enum ContractNeedCalcKind)IsNormalize: Whether to normalize billing amountsIsFullNormalizeAmount: Full normalization flag
Payment and Collection:
PaymentConditionI3D: Reference to payment termsPaymentConditionText: Custom payment terms descriptionCollectInvoice: Collection settingsMandatI3D: SEPA mandate reference
Advanced Contract Features
Contingent Management:
ContingentUsedHours: Hours consumed from contract contingentContingentUsedAmount: Monetary amount consumedContingentBalanceUsedHours: Balance hours utilizedContingentBalanceUsedAmount: Balance amount utilizedContingentBalanceArticleI3D: Article used for contingent balancingUseContingentBalanceArticle: Flag to enable balance article usageContingentResidualValueStart: Starting residual valueContingentResidualValueStartDate: Start date for residual calculation
Contingent Limits and Monitoring:
IsContingentLimitBilling: Enable contingent limit billingContingentLimitValue: Limit threshold valueContingentLimitKind: Type of limit (enum ContingentLimitKinds)IsMonitoring: Enable contract monitoringMonitoringValue: Monitoring threshold
Device and Asset Management:
- Contract-specific device relationships through master data lists
- Serial number tracking and device lifecycle management
- Click counter management for printer/copier contracts
Contract Automation
Prolongation and Renewals:
AutomatedProlongation: Automatic contract renewal flagLastSubsequentBillingDate: Date of last follow-up billing
Web Integration:
IsDisplayedOnWeb: Web portal visibility flagWebReportI3D: Associated web report
Database Schema
Contract Database Architecture
Contracts follow the dual-layer database architecture used throughout the receipts system, consisting of legacy German-named tables and modern English-named views.
Legacy Contract Tables
VertragKopf Table (Contract Headers)
Physical Table: dbo.VertragKopf
Entity Class: Centron.DAO.TemporaryEntities.VertragKopf
Mapping: Centron.DAO.Mappings.TemporaryEntities.VertragKopfMaps
The VertragKopf table inherits from ReceiptTable and contains contract header information.
Key Columns:
I3D- Primary key (identity)Nummer- Contract numberKundenI3D- Customer referenceDatum- Contract dateStatus- Contract stateBerechnungsart- Calculation methodAutoVerlaengerung- Auto-renewal flagAbrechnungsIntervallArt- Billing interval typeAbrechnungsIntervallDauer- Billing interval durationVertragsBeginn- Contract start dateVertragsEnde- Contract end dateKuendigungsDatum- Termination dateErsteBezahlung- First payment dateKontingentWert- Contingent valueKontingentArt- Contingent typeAutomatische Abrechnung- Automated billing flag
VertragPos Table (Contract Items)
Physical Table: dbo.VertragPos
Entity Class: Centron.DAO.TemporaryEntities.VertragPos
Mapping: Centron.DAO.Mappings.TemporaryEntities.VertragPosMaps
The VertragPos table contains contract line items and positions.
Key Columns:
I3D- Primary key (identity)VertragKopfI3D- Foreign key to contract headerPos- Position number for orderingArtikelI3D- Article/product referenceText- Item descriptionStk- QuantityVKKalk- Sales price calculationEK- Purchase priceMwstI3D- VAT rate referenceVertragI3D- Contract reference for recurring itemsLieferdatum- Delivery dateBenachrichtigungsdatum- Notification date
Contract Version Tables
Version History Tables:
VertragKopfVersions- Contract header version historyVertragPosVersions- Contract items version history
Critical Architecture Detail: Version tables are exact 1:1 copies of their corresponding original tables (VertragKopf and VertragPos). This means:
- Every column that exists in
VertragKopfmust also exist inVertragKopfVersionswith identical data types - Every column that exists in
VertragPosmust also exist inVertragPosVersionswith identical data types - The only exceptions are system columns (
I3D,OriginalI3D) which are handled specially - Additional versioning columns are added:
OriginalI3D(references original record) andKopfVersionsI3D(for position tables)
Contract Version Creation Process:
When a contract version is saved (using AssetHeadDAO.SaveAssetVersion mechanism):
-- Save contract header version
INSERT INTO VertragKopfVersions (all_columns_except_I3D, OriginalI3D)
SELECT all_columns_except_I3D, I3D AS OriginalI3D
FROM VertragKopf
WHERE I3D = @contractId
-- Save contract items version
INSERT INTO VertragPosVersions (all_columns_except_I3D, OriginalI3D, KopfVersionsI3D)
SELECT all_columns_except_I3D, I3D AS OriginalI3D, @headerVersionId AS KopfVersionsI3D
FROM VertragPos
WHERE VertragKopfI3D = @contractId
This enables complete audit trails of all contract modifications, rollback capability, and change tracking functionality.
⚠️ Schema Maintenance Warning: When adding new columns to VertragKopf or VertragPos, the identical columns must also be added to their corresponding version tables (VertragKopfVersions and VertragPosVersions). Failure to maintain this 1:1 correspondence will cause runtime errors during version saving operations.
Modern Contract Views
Contracts View (Contract Headers)
Database View: dbo.Contracts
Purpose: Clean, English-named view of VertragKopf for C# application use
Benefits:
- Consistent English naming convention
- Cleaner column structure
- Type safety improvements
- Better integration with ORM mapping
ContractItems View (Contract Items)
Database View: dbo.ContractItems
Purpose: Clean, English-named view of VertragPos for C# application use
Contract Version Views
Version Views:
ContractVersions- Clean view of VertragKopfVersionsContractItemVersions- Clean view of VertragPosVersions
Contract Logging Integration
AnlageLog Integration
Contracts integrate with the centralized AnlageLog table for audit logging:
Contract Log Entries:
AnlageArt = 22(Contract identifier)AnlageI3D- References contract I3D from VertragKopf- Log entries for contract creation, modifications, billing events, renewals, and terminations
Typical Log Events:
- Contract creation and approval
- Billing interval changes
- Contingent modifications
- Device associations/removals
- Automated billing execution
- Contract renewals and terminations
Business Logic Architecture
ReceiptContractBL
Location: src/backend/Centron.BL/Sales/Receipts/ContractLists/ReceiptContractBL.cs
The ReceiptContractBL class provides contract-specific business logic extending the base receipt functionality.
Key Responsibilities
Contract Invoice Management:
DeactivateContractInvoice(): Deactivate invoices generated from contractsGetContractInfosFromInvoices(): Extract contract information from invoicesExistsInvoiceForContract(): Check if invoices exist for a contract
Device and Counter Management:
ResetDeviceClickCounter(): Reset click counters for printer/copier contractsUpdateDeviceToContract(): Associate devices with contractsCheckCounterHistory(): Validate counter readings history
Contingent and Billing:
ContractContingentBalanceCalculation(): Calculate contingent balancesCalculateContingentWithRecalculationArticle(): Handle contingent recalculationsUpdateContractContingentBalanceCalculationForReceiptChange(): Adjust balances when receipts changeUpdateTakeRestAndOverBooking(): Handle remainder and overbooking scenarios
Master Data List Management:
AddMasteDateListsToContract(): Associate master data lists with contractsCreateMasterDataListsForNewMspArticles(): Create lists for new MSP articlesRemoveMasterDataList(): Remove master data list associationsCheckRemovedMasterDataList(): Validate removed associations
Contract-Specific Item Processing:
GetContractRelevantItems(): Retrieve items relevant for contract billingUpdatePriceForContractRelevantItem(): Update pricing for contract itemsSaveContractPositionCounter(): Persist counter readingsSaveContractFreeCopies(): Handle free copy allowances
ContractSpecificLogic
Location: src/backend/Centron.BL/Sales/Receipts/ContractLists/ContractSpecificLogic.cs
This class implements contract-specific operations that are called by the main ReceiptBL through the SpecificLogics pattern.
Related Business Logic Classes
ContractBL
Location: src/backend/Centron.BL/Sales/CustomerAssets/Contracts/ContractBL.cs
Handles broader contract asset management beyond the receipt functionality:
- Contract lifecycle management
- Device associations and management
- Contract analysis and reporting
- Integration with customer asset management
AutomaticFacturaBL.Contracts
Location: src/backend/Centron.BL/Sales/CustomerAssets/AutomaticFactura/AutomaticFacturaBL.Contracts.cs
Manages automated billing for contracts:
- Automatic invoice generation based on billing intervals
- RMM (Remote Monitoring and Management) integration
- Billing parameter calculation
- Multi-interval billing support
Contract Workflows
Contract Creation Process
-
Initialize Contract
var contract = new ReceiptContract { CustomerI3D = customerId, Date = DateTime.Now, BillingIntervalKind = BillingIntervalKinds.Monthly, BillingIntervalDuration = 1, AutomatedBilling = true }; -
Configure Billing Parameters
- Set billing intervals and calculation methods
- Define payment conditions and terms
- Configure contingent limits if applicable
-
Add Contract Items
- Products and services to be provided
- Pricing and quantity information
- Device associations for maintenance contracts
-
Set Up Automation
- Enable automated billing if required
- Configure renewal settings
- Set up monitoring and alerts
Automated Billing Process
The automated billing system (AutomaticFacturaBL) processes contracts based on their billing intervals:
-
Contract Evaluation
- Check contracts due for billing
- Validate billing parameters and dates
- Verify customer and contract status
-
Invoice Generation
- Create invoice based on contract items
- Apply pricing rules and calculations
- Handle contingent deductions
-
Post-Processing
- Update contract billing dates
- Generate documents and notifications
- Update contingent balances
Device Management Integration
For maintenance and service contracts:
-
Device Association
- Link devices to contracts through master data lists
- Track serial numbers and device information
- Monitor device status and warranty information
-
Counter Reading Management
- Collect meter readings for copiers/printers
- Calculate usage-based billing amounts
- Handle free copy allowances and overages
-
Service Integration
- Connect with RMM systems for automated data collection
- Process device monitoring data
- Generate alerts for maintenance requirements
Configuration Options
Billing Interval Configuration
BillingIntervalKind Options:
Daily: Daily billing cyclesMonthly: Monthly billing cyclesQuarterly: Quarterly billing cyclesYearly: Annual billing cycles
BillingIntervalDuration:
- Number of intervals (e.g., 3 months for quarterly when kind is Monthly)
- Supports flexible billing periods
Calculation Methods
ContractCalculationKind Options:
- Standard calculation methods for different contract types
- Custom calculation logic for specialized scenarios
ContractNeedCalcKind:
- Defines calculation requirements and triggers
- Controls when recalculations are needed
Integration Points
Customer Asset Management
- Integration with device and asset tracking systems
- Warranty and maintenance schedule management
- Service history and documentation
Accounting System
- Automated journal entry generation for contract billing
- Revenue recognition for service contracts
- Contingent liability tracking
External Systems
- RMM Integration: Remote monitoring and management systems
- Device APIs: Direct device communication for counter readings
- Customer Portals: Web-based contract management interfaces
Performance Considerations
Billing Performance
- Batch Processing: Large contract sets processed in batches
- Parallel Processing: Multiple contracts processed simultaneously where possible
- Caching: Frequently accessed contract data cached for performance
Database Optimization
- Indexed Relationships: Foreign keys properly indexed
- Partitioning: Large contract tables partitioned by date ranges
- Archive Strategy: Old contract data archived for performance
Security and Compliance
Access Control
- Role-Based Permissions: Different access levels for contract operations
- Branch Isolation: Contracts accessible only to authorized branches
- Customer Isolation: Cross-customer data protection
Audit Requirements
- Change Tracking: Complete audit trail for all contract modifications
- Billing History: Detailed logging of all billing operations
- Compliance Reporting: Support for regulatory reporting requirements
Best Practices
Contract Design
- Clear Billing Intervals: Use consistent and predictable billing cycles
- Contingent Management: Monitor contingent usage to prevent overruns
- Device Integration: Properly associate devices for accurate billing
Development Guidelines
- Use ContractBL: Leverage existing contract business logic
- Handle Contingents: Always consider contingent impacts in calculations
- Validate Intervals: Ensure billing interval consistency
- Test Automation: Thoroughly test automated billing scenarios
Troubleshooting
- Billing Issues: Check interval configuration and calculation settings
- Device Problems: Verify master data list associations
- Performance Issues: Review indexing and query optimization
- Integration Failures: Validate external system connections and data formats