Files
Masterarbeit/QuellCode/CentronERP/docs/reference/receipts/contracts-backend.md
T
Christoph Schwörer f045b99a25 Codebasis als Dateien ins Arbeitsrepo statt als Gitlink
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
2026-08-26 07:43:51 +02:00

436 lines
17 KiB
Markdown

# 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 reference
- `ProjectNumber`: Project identifier for the contract
- `PurchaseOrderNumber`: Customer's purchase order reference
- `AdditionalText`: Supplementary contract description
**Personnel Assignment:**
- `SalesRepresentativeI3D`: Assigned sales representative
- `OfficeStaffI3D`: Internal staff responsible for contract management
**Delivery and Billing Addresses:**
- `DeliveryAddress`, `DeliveryAddressCustomerI3D`: Service delivery location
- `InvoiceAddress`, `InvoiceAddressCustomerI3D`: Billing address information
- `LicenseeAddress`, `LicenseeAddressCustomerI3D`: Software licensing address
**Contract Lifecycle:**
- `DeliveryDate`: Contract start or service delivery date
- `ContractEnd`: Contract termination date
- `ContractTermination`: Actual termination date
- `FirstPaidDate`: Date of first payment received
- `ReminderDate`: Follow-up reminder date
- `PreparationDate`: Contract preparation date
- `FinishDate`: 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 amounts
- `IsFullNormalizeAmount`: Full normalization flag
**Payment and Collection:**
- `PaymentConditionI3D`: Reference to payment terms
- `PaymentConditionText`: Custom payment terms description
- `CollectInvoice`: Collection settings
- `MandatI3D`: SEPA mandate reference
#### Advanced Contract Features
**Contingent Management:**
- `ContingentUsedHours`: Hours consumed from contract contingent
- `ContingentUsedAmount`: Monetary amount consumed
- `ContingentBalanceUsedHours`: Balance hours utilized
- `ContingentBalanceUsedAmount`: Balance amount utilized
- `ContingentBalanceArticleI3D`: Article used for contingent balancing
- `UseContingentBalanceArticle`: Flag to enable balance article usage
- `ContingentResidualValueStart`: Starting residual value
- `ContingentResidualValueStartDate`: Start date for residual calculation
**Contingent Limits and Monitoring:**
- `IsContingentLimitBilling`: Enable contingent limit billing
- `ContingentLimitValue`: Limit threshold value
- `ContingentLimitKind`: Type of limit (enum ContingentLimitKinds)
- `IsMonitoring`: Enable contract monitoring
- `MonitoringValue`: 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 flag
- `LastSubsequentBillingDate`: Date of last follow-up billing
**Web Integration:**
- `IsDisplayedOnWeb`: Web portal visibility flag
- `WebReportI3D`: 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 number
- `KundenI3D` - Customer reference
- `Datum` - Contract date
- `Status` - Contract state
- `Berechnungsart` - Calculation method
- `AutoVerlaengerung` - Auto-renewal flag
- `AbrechnungsIntervallArt` - Billing interval type
- `AbrechnungsIntervallDauer` - Billing interval duration
- `VertragsBeginn` - Contract start date
- `VertragsEnde` - Contract end date
- `KuendigungsDatum` - Termination date
- `ErsteBezahlung` - First payment date
- `KontingentWert` - Contingent value
- `KontingentArt` - Contingent type
- `Automatische 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 header
- `Pos` - Position number for ordering
- `ArtikelI3D` - Article/product reference
- `Text` - Item description
- `Stk` - Quantity
- `VKKalk` - Sales price calculation
- `EK` - Purchase price
- `MwstI3D` - VAT rate reference
- `VertragI3D` - Contract reference for recurring items
- `Lieferdatum` - Delivery date
- `Benachrichtigungsdatum` - Notification date
##### Contract Version Tables
**Version History Tables:**
- `VertragKopfVersions` - Contract header version history
- `VertragPosVersions` - 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 `VertragKopf` must also exist in `VertragKopfVersions` with identical data types
- Every column that exists in `VertragPos` must also exist in `VertragPosVersions` with identical data types
- The only exceptions are system columns (`I3D`, `OriginalI3D`) which are handled specially
- Additional versioning columns are added: `OriginalI3D` (references original record) and `KopfVersionsI3D` (for position tables)
**Contract Version Creation Process:**
When a contract version is saved (using `AssetHeadDAO.SaveAssetVersion` mechanism):
```sql
-- 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 VertragKopfVersions
- `ContractItemVersions` - 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 contracts
- `GetContractInfosFromInvoices()`: Extract contract information from invoices
- `ExistsInvoiceForContract()`: Check if invoices exist for a contract
**Device and Counter Management:**
- `ResetDeviceClickCounter()`: Reset click counters for printer/copier contracts
- `UpdateDeviceToContract()`: Associate devices with contracts
- `CheckCounterHistory()`: Validate counter readings history
**Contingent and Billing:**
- `ContractContingentBalanceCalculation()`: Calculate contingent balances
- `CalculateContingentWithRecalculationArticle()`: Handle contingent recalculations
- `UpdateContractContingentBalanceCalculationForReceiptChange()`: Adjust balances when receipts change
- `UpdateTakeRestAndOverBooking()`: Handle remainder and overbooking scenarios
**Master Data List Management:**
- `AddMasteDateListsToContract()`: Associate master data lists with contracts
- `CreateMasterDataListsForNewMspArticles()`: Create lists for new MSP articles
- `RemoveMasterDataList()`: Remove master data list associations
- `CheckRemovedMasterDataList()`: Validate removed associations
**Contract-Specific Item Processing:**
- `GetContractRelevantItems()`: Retrieve items relevant for contract billing
- `UpdatePriceForContractRelevantItem()`: Update pricing for contract items
- `SaveContractPositionCounter()`: Persist counter readings
- `SaveContractFreeCopies()`: 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
1. **Initialize Contract**
```csharp
var contract = new ReceiptContract
{
CustomerI3D = customerId,
Date = DateTime.Now,
BillingIntervalKind = BillingIntervalKinds.Monthly,
BillingIntervalDuration = 1,
AutomatedBilling = true
};
```
2. **Configure Billing Parameters**
- Set billing intervals and calculation methods
- Define payment conditions and terms
- Configure contingent limits if applicable
3. **Add Contract Items**
- Products and services to be provided
- Pricing and quantity information
- Device associations for maintenance contracts
4. **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:
1. **Contract Evaluation**
- Check contracts due for billing
- Validate billing parameters and dates
- Verify customer and contract status
2. **Invoice Generation**
- Create invoice based on contract items
- Apply pricing rules and calculations
- Handle contingent deductions
3. **Post-Processing**
- Update contract billing dates
- Generate documents and notifications
- Update contingent balances
### Device Management Integration
For maintenance and service contracts:
1. **Device Association**
- Link devices to contracts through master data lists
- Track serial numbers and device information
- Monitor device status and warranty information
2. **Counter Reading Management**
- Collect meter readings for copiers/printers
- Calculate usage-based billing amounts
- Handle free copy allowances and overages
3. **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 cycles
- `Monthly`: Monthly billing cycles
- `Quarterly`: Quarterly billing cycles
- `Yearly`: 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