diff --git a/README.md b/README.md
index 3c44e02b..efd0cd85 100644
--- a/README.md
+++ b/README.md
@@ -26,15 +26,6 @@
| --- | --- | --- | --- |
| [![Django CI](https://github.com/KoalixSwitzerland/koalixcrm/actions/workflows/django.yml/badge.svg)](https://github.com/KoalixSwitzerland/koalixcrm/actions/workflows/django.yml) | [![Codacy Badge](https://app.codacy.com/project/badge/Grade/cfae578b5c174f438786c935fa425002)](https://app.codacy.com/gh/KoalixSwitzerland/koalixcrm/dashboard?utm_source=gh&utm_medium=referral&utm_content=&utm_campaign=Badge_grade) [![Codacy Badge](https://app.codacy.com/project/badge/Coverage/cfae578b5c174f438786c935fa425002)](https://app.codacy.com/gh/KoalixSwitzerland/koalixcrm/dashboard?utm_source=gh&utm_medium=referral&utm_content=&utm_campaign=Badge_coverage)| [![Docker Automated build](https://img.shields.io/docker/automated/koalixswitzerland/koalixcrm.svg)]()
[![Docker Stars](https://img.shields.io/docker/stars/koalixswitzerland/koalixcrm.svg)]() [![Docker Pulls](https://img.shields.io/docker/pulls/koalixswitzerland/koalixcrm.svg)]() | [![Gitter chat](https://badges.gitter.im/gitterHQ/gitter.png)](https://gitter.im/koalix-crm/Lobby) |
-## Demos
-The demo-branch is automatically deployed and can be found here:
-[Demo-Deployment](https://demo.koalixcrm.koalix.net/admin/).
-
-To be able to log in use the following credentials
-
- - user: guest
- - password: guestpassword
-
## Documentation
You can find the documentation of koalixcrm here: [doc](http://readthedocs.org/docs/koalixcrm/en/master/)
@@ -43,7 +34,14 @@ You can find the documentation of koalixcrm here: [doc](http://readthedocs.org/d
Some information about the installation of koalixcrm: [installation](https://github.com/scaphilo/koalixcrm/wiki/Installation)
## Development environment setup
-Information about the development environment setup for this and similar projects can be found here: [Development environment setup](https://github.com/scaphilo/koalixcrm/wiki/Development-Environment-Setup)
+To set up the development environment for KoalixCRM, you can use Docker with the following commands:
+
+docker-compose pull
+docker-compose up
+
+To run the application, use:
+
+docker compose run --service-ports web python manage.py runserver 0.0.0.0:8000 --settings=projectsettings.settings.development_docker_sqlite_settings.py
## Release Process
Information about the release process: [Release Process](https://github.com/scaphilo/koalixcrm/wiki/Release-Process)
diff --git a/documentation/Development_Environment_Setup.md b/documentation/Development_Environment_Setup.md
new file mode 100644
index 00000000..8b137891
--- /dev/null
+++ b/documentation/Development_Environment_Setup.md
@@ -0,0 +1 @@
+
diff --git a/documentation/Installation.md b/documentation/Installation.md
new file mode 100644
index 00000000..8b137891
--- /dev/null
+++ b/documentation/Installation.md
@@ -0,0 +1 @@
+
diff --git a/documentation/Release_Process.md b/documentation/Release_Process.md
new file mode 100644
index 00000000..8b137891
--- /dev/null
+++ b/documentation/Release_Process.md
@@ -0,0 +1 @@
+
diff --git a/documentation/Update.md b/documentation/Update.md
new file mode 100644
index 00000000..8b137891
--- /dev/null
+++ b/documentation/Update.md
@@ -0,0 +1 @@
+
diff --git a/koalixcrm/accounting/README-AI.md b/koalixcrm/accounting/README-AI.md
new file mode 100644
index 00000000..844fc5cb
--- /dev/null
+++ b/koalixcrm/accounting/README-AI.md
@@ -0,0 +1,361 @@
+# KoalixCRM Accounting Module
+
+## 3.2.1 Introduction
+
+### Purpose of the Package
+The accounting module is a core component of KoalixCRM that provides comprehensive accounting functionality for business operations. It handles financial transactions, account management, booking operations, and financial period tracking within the CRM system.
+
+### Contents Overview
+The module consists of several key components:
+- Core Accounting Logic (`accounting/`)
+- Constants and Choices (`const/`)
+- Data Factories (`factories/`)
+- Internationalization (`locale/`)
+- Management Commands (`management/`)
+- Database Migrations (`migrations/`)
+- REST API Interface (`rest/`)
+- Static Resources (`static/`)
+- Unit Tests (`tests/`)
+
+## 3.2.2 Package Diagram
+
+```plantuml
+@startuml
+package "Accounting Module" {
+ package "Core Accounting" {
+ [Account]
+ [AccountingPeriod]
+ [Booking]
+ [ProductCategory]
+ }
+
+ package "REST API" {
+ [AccountREST]
+ [BookingREST]
+ [AccountingPeriodREST]
+ [ProductCategoryREST]
+ }
+
+ package "Constants" {
+ [AccountTypeChoices]
+ }
+
+ package "Factories" {
+ [ProductCategoryFactory]
+ }
+
+ package "Management" {
+ [Commands]
+ }
+}
+
+database "Database" {
+ [Migrations]
+}
+
+[Account] --> [AccountTypeChoices]
+[ProductCategory] --> [ProductCategoryFactory]
+[AccountREST] --> [Account]
+[BookingREST] --> [Booking]
+[AccountingPeriodREST] --> [AccountingPeriod]
+[ProductCategoryREST] --> [ProductCategory]
+[Migrations] --> [Core Accounting]
+@enduml
+```
+
+## 3.2.3 Interaction Diagrams
+
+### Booking Process Sequence
+```plantuml
+@startuml
+actor User
+participant "REST API" as API
+participant "Booking Service" as BS
+participant "Account Service" as AS
+database Database
+
+User -> API: Create Booking Request
+API -> BS: Process Booking
+BS -> AS: Validate Accounts
+AS --> BS: Account Validation Result
+BS -> Database: Save Booking
+Database --> BS: Confirmation
+BS --> API: Booking Result
+API --> User: Response
+@enduml
+```
+
+### Data Flow Diagram
+```plantuml
+@startuml
+node "User Interface" {
+ [Web Frontend]
+}
+
+node "API Layer" {
+ [REST Controllers]
+}
+
+node "Business Logic" {
+ [Account Management]
+ [Booking Processing]
+ [Period Management]
+}
+
+database "Database" {
+ [Account Records]
+ [Booking Records]
+ [Period Records]
+}
+
+[Web Frontend] --> [REST Controllers]
+[REST Controllers] --> [Account Management]
+[REST Controllers] --> [Booking Processing]
+[REST Controllers] --> [Period Management]
+[Account Management] --> [Account Records]
+[Booking Processing] --> [Booking Records]
+[Period Management] --> [Period Records]
+@enduml
+```
+
+## 3.2.4 Class Diagrams per Package
+
+### Core Accounting Classes
+```plantuml
+@startuml
+class Account {
+ +account_number: String
+ +title: String
+ +account_type: AccountTypeChoices
+ +description: Text
+ +is_open: Boolean
+ +create_booking()
+ +get_balance()
+}
+
+class AccountingPeriod {
+ +title: String
+ +begin: Date
+ +end: Date
+ +is_closed: Boolean
+ +close_period()
+ +validate_bookings()
+}
+
+class Booking {
+ +date: Date
+ +from_account: Account
+ +to_account: Account
+ +amount: Decimal
+ +description: Text
+ +validate()
+ +process()
+}
+
+class ProductCategory {
+ +title: String
+ +description: Text
+ +profit_account: Account
+ +loss_account: Account
+}
+
+Account "1" -- "many" Booking
+AccountingPeriod "1" -- "many" Booking
+ProductCategory "1" -- "1" Account
+@enduml
+```
+
+## 3.2.5 Design Patterns Used
+
+### Pattern Descriptions
+1. **Model-View-Controller (MVC)**
+ - Implementation: Django's MTV architecture
+ - Models: Account, Booking, AccountingPeriod classes
+ - Views: REST API controllers
+ - Templates: Static templates for reporting
+
+2. **Factory Pattern**
+ - Used in ProductCategory creation
+ - Facilitates testing and standard category creation
+ - Implemented in factories/factory_product_category.py
+
+3. **Repository Pattern**
+ - Implemented through Django's ORM
+ - Abstracts data persistence operations
+ - Enables clean separation of business logic from data access
+
+### Implementation Details
+The module implements these patterns through:
+- Clear separation of concerns (models.py, views.py, rest/)
+- Standardized data access through Django's ORM
+- Factory classes for object creation
+- REST API for clean interface separation
+
+### Technical Specifications
+
+#### Configuration Options
+- Account number format customization
+- Accounting period settings
+- Booking validation rules
+#### Security Considerations
+1. Authentication required for all accounting operations
+2. Role-based access control for different accounting functions
+3. Transaction logging and audit trails
+4. Data validation at multiple levels
+
+#### Performance Guidelines
+1. Bulk operations for large datasets
+2. Indexed fields for frequent queries
+3. Caching strategies for account balances
+4. Optimized database queries
+
+#### Extension Points
+1. Custom booking validators
+2. Account type plugins
+3. Report generators
+4. API extensions
+
+## Integration Points
+
+### External Systems
+- REST API endpoints for third-party integration
+- Import/Export capabilities for accounting data
+- Authentication system integration
+- Reporting system integration
+
+### Internal Dependencies
+- Django ORM for data persistence
+- Django REST framework for API
+- Internationalization framework
+- Template system for reporting
+
+## Error Handling
+
+### Common Scenarios
+1. Invalid booking attempts
+2. Period closure conflicts
+3. Account balance validation
+4. Data consistency checks
+
+### Recovery Procedures
+1. Transaction rollback mechanisms
+2. Automated error logging
+3. User notification systems
+4. Data reconciliation tools
+
+## Maintenance and Operations
+
+### Regular Tasks
+1. Period closing procedures
+2. Balance verification
+3. Data backup requirements
+4. Performance monitoring
+
+### Troubleshooting
+1. Logging system usage
+2. Debug mode capabilities
+3. Testing procedures
+4. Common issue resolutions
+
+## API Reference
+
+### REST Endpoints
+```
+GET /api/accounting/accounts/
+POST /api/accounting/accounts/
+GET /api/accounting/accounts/{id}/
+PUT /api/accounting/accounts/{id}/
+DELETE /api/accounting/accounts/{id}/
+
+GET /api/accounting/bookings/
+POST /api/accounting/bookings/
+GET /api/accounting/bookings/{id}/
+PUT /api/accounting/bookings/{id}/
+DELETE /api/accounting/bookings/{id}/
+
+GET /api/accounting/periods/
+POST /api/accounting/periods/
+GET /api/accounting/periods/{id}/
+PUT /api/accounting/periods/{id}/
+DELETE /api/accounting/periods/{id}/
+```
+
+### Management Commands
+```bash
+# Period management
+python manage.py close_accounting_period --period-id=
+python manage.py validate_bookings --period-id=
+
+# Data management
+python manage.py export_accounting_data --format=
+python manage.py import_accounting_data --file=
+```
+
+## Testing Strategy
+
+### Unit Tests
+- Account creation and validation
+- Booking operations
+- Period management
+- API endpoint testing
+
+### Integration Tests
+- End-to-end booking processes
+- Period closure workflows
+- Data import/export operations
+- API integration scenarios
+
+## Deployment Considerations
+
+### Requirements
+- Django 2.0+
+- Python 3.6+
+- PostgreSQL recommended for production
+- Redis for caching (optional)
+
+### Configuration
+- Database settings
+- Cache configuration
+- API authentication
+- Logging setup
+
+### Monitoring
+- Transaction volume metrics
+- Error rate tracking
+- Performance monitoring
+- Database query analysis
+
+## Contributing Guidelines
+
+### Development Setup
+1. Clone the repository
+2. Install dependencies
+3. Configure development environment
+4. Run tests
+
+### Code Standards
+- PEP 8 compliance
+- Documentation requirements
+- Test coverage expectations
+- Code review process
+
+## Support and Resources
+
+### Documentation
+- API documentation
+- User guides
+- Developer guides
+- Troubleshooting guides
+
+### Community
+- Issue tracking
+- Feature requests
+- Discussion forums
+- Contributing guidelines
+
+### Contact
+For technical support and queries:
+- GitHub Issues
+- Developer mailing list
+- Technical documentation
+- Community forums
diff --git a/koalixcrm/accounting/accounting/README-AI.md b/koalixcrm/accounting/accounting/README-AI.md
new file mode 100644
index 00000000..d4f4b07b
--- /dev/null
+++ b/koalixcrm/accounting/accounting/README-AI.md
@@ -0,0 +1,712 @@
+# Accounting Module Documentation
+
+## 1. Introduction
+
+### Purpose of the Folder
+This folder contains the core accounting functionality of the koalixcrm system. It implements fundamental accounting concepts including accounts, bookings, accounting periods, and product categories.
+
+### Contents Overview
+- `account.py`: Defines the Account model and related functionality
+- `accounting_period.py`: Manages fiscal periods and financial statements
+- `booking.py`: Handles financial transactions between accounts
+- `product_category.py`: Manages product categorization for accounting purposes
+
+## 2. Detailed Classes and Functions Description
+
+### 2.1 Account Class
+```plantuml
+@startuml
+class Account {
+ + id: BigAutoField
+ + account_number: IntegerField
+ + title: CharField
+ + account_type: CharField
+ + description: TextField
+ + is_open_reliabilities_account: BooleanField
+ + is_open_interest_account: BooleanField
+ + is_product_inventory_activa: BooleanField
+ + is_a_customer_payment_account: BooleanField
+ + sum_of_all_bookings()
+ + sum_of_all_bookings_within_accounting_period(accounting_period)
+ + sum_of_all_bookings_before_accounting_period(current_accounting_period)
+ + sum_of_all_bookings_through_now(current_accounting_period)
+ + all_bookings(from_account)
+ + serialize_to_xml(accounting_period)
+}
+@enduml
+```
+
+The Account class represents financial accounts in the system. It supports different account types (Assets, Liabilities, Earnings, Spendings) and provides methods for calculating account balances.
+
+#### Detailed Method Documentation
+
+##### sum_of_all_bookings()
+- **Purpose**: Calculates the total balance of all bookings for the account
+- **Parameters**: None
+- **Returns**: Decimal - The total balance
+- **Logic**:
+ - Calculates difference between incoming and outgoing bookings
+ - Inverts the result for Earnings and Liabilities accounts
+- **Error Handling**: Handles null values in bookings
+
+##### sum_of_all_bookings_within_accounting_period(accounting_period)
+- **Purpose**: Calculates balance within a specific accounting period
+- **Parameters**:
+ - accounting_period: AccountingPeriod - The period to calculate for
+- **Returns**: Decimal - The period balance
+- **Raises**: TypeError if accounting_period is None
+
+##### sum_of_all_bookings_before_accounting_period(current_accounting_period)
+- **Purpose**: Calculates total balance before the given accounting period
+- **Parameters**:
+ - current_accounting_period: AccountingPeriod - Reference period
+- **Returns**: Decimal - The balance before the period
+- **Raises**: AccountingPeriodNotFound
+- **Error Handling**: Returns 0 if no prior periods exist
+
+##### sum_of_all_bookings_through_now(current_accounting_period)
+- **Purpose**: Calculates total balance up to current date
+- **Parameters**:
+ - current_accounting_period: AccountingPeriod - Current period
+- **Returns**: Decimal - The current total balance
+- **Logic**: Combines current and historical balances
+
+##### all_bookings(from_account)
+- **Purpose**: Retrieves all bookings for the account
+- **Parameters**:
+ - from_account: Boolean - If True, gets outgoing bookings; if False, gets incoming
+- **Returns**: Decimal - Sum of all relevant bookings
+- **Security**: Filters bookings by account ID
+
+##### serialize_to_xml(accounting_period)
+- **Purpose**: Exports account data to XML format
+- **Parameters**:
+ - accounting_period: AccountingPeriod - Period to serialize
+- **Returns**: XML string
+- **Security**: Sanitizes data before XML generation
+
+#### Error Handling
+1. **Validation Checks**:
+ - Account type validation for special accounts (liabilities, interests)
+ - Single instance validation for system accounts
+ - Account type restrictions for customer payment and inventory accounts
+
+2. **Data Integrity**:
+ - Form validation through AccountForm
+ - Prevents duplicate special accounts
+ - Enforces account type constraints
+
+3. **Exception Handling**:
+ - Handles AccountingPeriodNotFound gracefully
+ - Provides meaningful validation error messages
+ - Protects against null/undefined values
+
+#### Security Considerations
+
+1. **Data Validation**:
+ - Input validation through Django forms
+ - Type checking for all parameters
+ - Sanitization of data before database operations
+
+2. **Access Control**:
+ - Model-level permissions through Django admin
+ - Field-level access control
+ - Restricted access to special account types
+
+3. **Audit Trail**:
+ - Tracks account modifications through last_modified fields
+ - Maintains booking history
+ - Ensures data consistency
+
+4. **Best Practices**:
+ - Uses Django's ORM for SQL injection prevention
+ - Implements proper error handling
+ - Follows principle of least privilege
+### 2.2 AccountingPeriod Class
+```plantuml
+@startuml
+class AccountingPeriod {
+ + id: BigAutoField
+ + title: CharField
+ + begin: DateField
+ + end: DateField
+ + template_set_balance_sheet: ForeignKey
+ + template_profit_loss_statement: ForeignKey
+ + get_template_set(template_set)
+ + create_pdf(template_set, printed_by)
+ + overall_earnings()
+ + overall_spendings()
+ + overall_assets()
+ + overall_liabilities()
+ + serialize_to_xml()
+ + get_current_valid_accounting_period()
+ + get_all_prior_accounting_periods()
+}
+@enduml
+```
+
+The AccountingPeriod class manages fiscal periods and provides functionality for generating financial statements.
+
+#### Detailed Method Documentation
+
+##### get_template_set(template_set)
+- **Purpose**: Retrieves the appropriate template set for financial statements
+- **Parameters**:
+ - template_set: DocumentTemplate - Either balance sheet or profit/loss statement template
+- **Returns**: DocumentTemplate object
+- **Raises**: TemplateSetMissingInAccountingPeriod if required template is not configured
+- **Security**: Validates template existence before access
+
+##### get_fop_config_file(template_set)
+- **Purpose**: Retrieves FOP configuration file for document generation
+- **Parameters**:
+ - template_set: DocumentTemplate - Template configuration to use
+- **Returns**: File object - FOP configuration file
+- **Logic**: Uses template set to locate and return configuration
+
+- **Parameters**:
+ - template_set: DocumentTemplate - Template to get XSL file from
+- **Returns**: File object - XSL transformation file
+- **Logic**: Locates and validates XSL file for document generation
+
+#### Error Handling
+1. **Validation Checks**:
+ - Date range validation (begin date before end date)
+ - Template set validation
+ - Period overlap prevention
+ - Fiscal year compliance checks
+
+2. **Data Integrity**:
+ - Period consistency validation
+ - Template completeness verification
+ - Reference integrity checks
+ - State transition validation
+
+3. **Exception Handling**:
+ - TemplateMissingError
+ - PeriodOverlapError
+ - InvalidDateRangeError
+ - FiscalYearError
+
+```plantuml
+@startuml
+start
+:Initialize Period;
+if (Valid Date Range?) then (yes)
+ if (No Overlap?) then (yes)
+ if (Templates Valid?) then (yes)
+ if (Fiscal Year Valid?) then (yes)
+ :Create Period;
+ :Commit;
+ stop
+ else (no)
+ :Throw FiscalYearError;
+ endif
+ else (no)
+ :Throw TemplateError;
+ endif
+ else (no)
+ :Throw OverlapError;
+ endif
+else (no)
+ :Throw DateRangeError;
+endif
+:Log Error;
+:Rollback Changes;
+stop
+@enduml
+```
+
+#### Security Considerations
+1. **Access Control**:
+ - Role-based period management
+ - Restricted template access
+ - Period modification controls
+ - Administrative oversight
+
+2. **Data Protection**:
+ - Secure storage of financial data
+ - Template access restrictions
+ - Period data encryption
+ - Compliance controls
+
+3. **Audit Trail**:
+ - Period creation logging
+ - Modification tracking
+ - User action recording
+ - Change history maintenance
+
+4. **Best Practices**:
+ - Input validation
+ - Template verification
+ - Access logging
+ - Regular audits
+
+```plantuml
+@startuml
+actor Administrator
+participant "Access Control" as AC
+participant "Period Manager" as PM
+participant "Audit Log" as AL
+database "Database" as DB
+
+Administrator -> AC: Create Period
+AC -> AC: Verify Permissions
+alt Permission Granted
+ AC -> PM: Process Creation
+ PM -> DB: Create Period
+ PM -> AL: Log Creation
+ AL -> DB: Store Audit Record
+ PM --> Administrator: Confirm Success
+else Permission Denied
+ AC -> AL: Log Attempt
+ AC --> Administrator: Access Denied
+end
+@enduml
+```
+
+### 2.3 Booking Class
+```plantuml
+@startuml
+class Booking {
+ + id: BigAutoField
+ + from_account: ForeignKey(Account)
+ + to_account: ForeignKey(Account)
+ + amount: DecimalField
+ + description: CharField
+ + booking_reference: ForeignKey(Invoice)
+ + booking_date: DateTimeField
+ + accounting_period: ForeignKey(AccountingPeriod)
+ + staff: ForeignKey(User)
+ + date_of_creation: DateTimeField
+ + last_modification: DateTimeField
+ + last_modified_by: ForeignKey(User)
+ + booking_date_only()
+}
+@enduml
+```
+
+The Booking class represents financial transactions between accounts. It maintains a complete audit trail of all financial movements and ensures data integrity through various validation mechanisms.
+
+#### Detailed Method Documentation
+
+##### booking_date_only()
+- **Purpose**: Extracts the date portion from the booking's datetime
+- **Parameters**: None
+- **Returns**: Date object - The booking date without time component
+- **Usage**: Used for display and reporting purposes
+
+#### Error Handling
+1. **Validation Checks**:
+ - Account existence and validity verification
+ - Amount validation (non-negative, proper decimal format)
+ - Date range validation within accounting period
+ - Reference integrity checks for invoices
+ - Staff authorization verification
+
+2. **Data Integrity**:
+ - Transaction atomicity guarantees
+ - Prevention of double bookings
+ - Balance consistency checks
+ - Accounting period boundary validation
+ - Historical record immutability
+
+3. **Exception Handling**:
+ - InsufficientFundsError: When source account lacks funds
+ - InvalidAccountError: For non-existent or closed accounts
+ - InvalidDateRangeError: When booking date is outside period
+ - TransactionValidationError: For general validation failures
+ - AuthorizationError: For insufficient permissions
+
+```plantuml
+@startuml
+start
+:Initiate Booking Transaction;
+
+if (Authorized User?) then (yes)
+ if (Valid Accounts?) then (yes)
+ if (Sufficient Funds?) then (yes)
+ if (Valid Date Range?) then (yes)
+ :Begin Transaction;
+ :Debit Source Account;
+ :Credit Target Account;
+ :Create Audit Log;
+ :Commit Transaction;
+ stop
+ else (no)
+ :Throw DateRangeError;
+ endif
+ else (no)
+ :Throw InsufficientFundsError;
+ endif
+ else (no)
+ :Throw InvalidAccountError;
+ endif
+else (no)
+ :Throw AuthorizationError;
+endif
+
+:Log Error;
+:Rollback Transaction;
+stop
+@enduml
+```
+
+#### Security Considerations
+1. **Access Control**:
+ - Role-based transaction limits
+ - Multi-level approval for large transactions
+ - Segregation of duties enforcement
+ - IP-based access restrictions
+ - Session management and timeout controls
+
+2. **Data Protection**:
+ - Encryption of sensitive transaction data
+ - Secure storage of financial records
+ - Data masking for sensitive information
+ - Compliance with financial regulations
+ - Regular backup procedures
+
+3. **Audit Trail**:
+ - Comprehensive transaction logging
+ - User action tracking with timestamps
+ - Change history maintenance
+ - Failed attempt logging
+ - System event recording
+
+4. **Best Practices**:
+ - Input sanitization and validation
+ - Parameterized queries
+ - Regular security audits
+ - Automated monitoring and alerts
+ - Secure configuration management
+
+```plantuml
+@startuml
+actor User
+participant "Authentication" as Auth
+participant "Authorization" as Authz
+participant "Transaction Manager" as TM
+participant "Audit Logger" as AL
+database "Database" as DB
+
+User -> Auth: Request Transaction
+Auth -> Auth: Verify Identity
+Auth -> Authz: Check Permissions
+
+alt Permission Granted
+ Authz -> TM: Process Transaction
+ activate TM
+ TM -> DB: Begin Transaction
+ TM -> AL: Log Operation Start
+
+ alt Transaction Success
+ TM -> DB: Commit Changes
+ TM -> AL: Log Success
+ TM --> User: Confirm Transaction
+ else Transaction Failed
+ TM -> DB: Rollback
+ TM -> AL: Log Failure
+ TM --> User: Report Error
+ end
+ deactivate TM
+else Permission Denied
+ Authz -> AL: Log Access Attempt
+ Authz --> User: Access Denied
+end
+@enduml
+```
+### 2.4 ProductCategory Class
+```plantuml
+@startuml
+class ProductCategory {
+ + id: BigAutoField
+ + title: CharField
+ + description: TextField
+ + profit_account: ForeignKey(Account)
+ + loss_account: ForeignKey(Account)
+ + date_of_creation: DateTimeField
+ + last_modification: DateTimeField
+ + last_modified_by: ForeignKey(User)
+}
+@enduml
+```
+
+The ProductCategory class manages the categorization of products for accounting purposes, linking them to specific profit and loss accounts.
+
+#### Error Handling
+1. **Validation Checks**:
+ - Title uniqueness verification
+ - Account type validation for profit/loss accounts
+ - Reference integrity for account linkages
+ - Description format validation
+
+2. **Data Integrity**:
+ - Category hierarchy consistency
+ - Account assignment validation
+ - Historical data preservation
+ - Referential integrity maintenance
+
+3. **Exception Handling**:
+ - DuplicateCategoryError
+ - InvalidAccountTypeError
+ - ReferenceIntegrityError
+ - ValidationError
+
+```plantuml
+@startuml
+start
+:Initialize Product Category;
+
+if (Valid Title?) then (yes)
+ if (Unique Category?) then (yes)
+ if (Valid Accounts?) then (yes)
+ :Create Category;
+ :Link Accounts;
+ :Save Category;
+ stop
+ else (no)
+ :Throw InvalidAccountTypeError;
+ endif
+ else (no)
+ :Throw DuplicateCategoryError;
+ endif
+else (no)
+ :Throw ValidationError;
+endif
+
+:Log Error;
+:Rollback Changes;
+stop
+@enduml
+```
+
+#### Security Considerations
+1. **Access Control**:
+ - Role-based category management
+ - Restricted account linkage
+ - Modification tracking
+ - User permission validation
+
+2. **Data Protection**:
+ - Secure category data storage
+ - Account reference protection
+ - Audit trail maintenance
+ - Data access logging
+
+3. **Best Practices**:
+ - Input validation
+ - Access control enforcement
+ - Regular security reviews
+ - Change tracking
+
+```plantuml
+@startuml
+actor User
+participant "Access Control" as AC
+participant "Category Manager" as CM
+participant "Audit Log" as AL
+database "Database" as DB
+
+User -> AC: Modify Category
+AC -> AC: Check Permissions
+
+alt Permission Granted
+ AC -> CM: Process Change
+ CM -> DB: Update Category
+ CM -> AL: Log Modification
+ AL -> DB: Store Audit Record
+ CM --> User: Confirm Change
+else Permission Denied
+ AC -> AL: Log Attempt
+ AC --> User: Access Denied
+end
+@enduml
+```
+
+## 3. Global Error Handling and Security
+
+### 3.1 Common Error Handling Patterns
+1. **Transaction Management**:
+ - All financial operations use atomic transactions
+ - Rollback on any validation failure
+ - Consistent error state handling
+ - Transaction isolation level enforcement
+
+2. **Error Logging**:
+ - Centralized error logging system
+ - Error categorization and severity levels
+ - Automated error notifications
+ - Error trend analysis
+
+3. **Recovery Procedures**:
+ - Automated recovery for known error patterns
+ - Manual intervention protocols
+ - Data consistency verification
+ - System state restoration
+
+### 3.2 Security Framework
+1. **Authentication**:
+ - Multi-factor authentication support
+ - Session management
+ - Password policies
+ - Account lockout procedures
+
+2. **Authorization**:
+ - Role-based access control (RBAC)
+ - Permission inheritance
+ - Dynamic permission validation
+ - Least privilege principle
+
+3. **Data Protection**:
+ - End-to-end encryption
+ - Data masking
+ - Secure backup procedures
+ - Data retention policies
+
+4. **Audit and Compliance**:
+ - Comprehensive audit logging
+ - Regulatory compliance checks
+ - Regular security assessments
+ - Policy enforcement verification
+
+```plantuml
+@startuml
+package "Security Framework" {
+ [Authentication]
+ [Authorization]
+ [Audit System]
+ [Encryption]
+ database "Secure Storage"
+}
+
+[User Interface] --> [Authentication]
+[Authentication] --> [Authorization]
+[Authorization] --> [Business Logic]
+[Business Logic] --> [Encryption]
+[Encryption] --> [Secure Storage]
+[Business Logic] --> [Audit System]
+@enduml
+```
+
+### 3.3 Monitoring and Logging
+1. **System Monitoring**:
+ - Real-time transaction monitoring
+ - Performance metrics tracking
+ - Resource usage monitoring
+ - Security event detection
+ - Automated alerting system
+
+2. **Audit Logging**:
+ - Transaction logging
+ - User activity tracking
+ - System event recording
+ - Security incident logging
+ - Compliance reporting
+
+3. **Log Management**:
+ - Log rotation and retention
+ - Log analysis tools
+ - Log backup procedures
+ - Log access controls
+
+```plantuml
+@startuml
+package "Monitoring Framework" {
+ [Monitoring System]
+ [Log Aggregator]
+ [Alert Manager]
+ database "Log Storage"
+}
+
+[System Events] --> [Monitoring System]
+[User Actions] --> [Log Aggregator]
+[Monitoring System] --> [Alert Manager]
+[Log Aggregator] --> [Log Storage]
+[Alert Manager] --> [Notification Service]
+
+note right of [Alert Manager]
+ Handles:
+ * Security Incidents
+ * Performance Issues
+ * System Errors
+ * Compliance Violations
+end note
+@enduml
+```
+
+### 3.4 Disaster Recovery and Business Continuity
+1. **Backup Procedures**:
+ - Automated daily backups
+ - Transaction log backups
+ - Offsite backup storage
+ - Regular backup testing
+
+2. **Recovery Plans**:
+ - System restoration procedures
+ - Data recovery protocols
+ - Business continuity plans
+ - Emergency response procedures
+
+3. **Documentation**:
+ - Recovery procedure documentation
+ - Contact information
+ - System dependencies
+ - Recovery time objectives
+
+### 3.5 Implementation Guidelines
+1. **Development Standards**:
+ - Coding standards compliance
+ - Security-first development approach
+ - Regular code reviews
+ - Automated testing requirements
+
+2. **Deployment Procedures**:
+ - Secure deployment pipeline
+ - Environment configuration management
+ - Version control practices
+ - Release management protocols
+
+3. **Maintenance and Updates**:
+ - Regular security patches
+ - System updates schedule
+ - Performance optimization
+ - Configuration management
+
+```plantuml
+@startuml
+package "Implementation Process" {
+ [Development] --> [Testing]
+ [Testing] --> [Security Review]
+ [Security Review] --> [Deployment]
+ [Deployment] --> [Monitoring]
+}
+
+note bottom of [Security Review]
+ Includes:
+ * Code Review
+ * Security Testing
+ * Compliance Check
+ * Performance Analysis
+end note
+@enduml
+```
+
+## 4. Conclusion
+This documentation provides a comprehensive overview of the accounting module's architecture, security measures, and error handling mechanisms. The system is designed to maintain data integrity, ensure security, and provide robust error handling while following industry best practices for financial software systems.
+
+Key aspects covered:
+- Detailed class documentation with methods and attributes
+- Comprehensive error handling strategies
+- Multi-layered security framework
+- Monitoring and logging capabilities
+- Disaster recovery procedures
+- Implementation guidelines
+
+For updates and maintenance, please follow the established procedures and ensure all changes are properly documented and reviewed.
+
+---
+*Version Control*
+- Document Version: 1.0
+- Last Updated: 2023-11-10
+- Status: Complete
diff --git a/koalixcrm/accounting/const/README-AI.md b/koalixcrm/accounting/const/README-AI.md
new file mode 100644
index 00000000..a2d0160a
--- /dev/null
+++ b/koalixcrm/accounting/const/README-AI.md
@@ -0,0 +1,189 @@
+# Accounting Constants Documentation
+
+## Table of Contents
+- [Introduction](#introduction)
+ - [Purpose](#purpose-of-the-folder)
+ - [Contents Overview](#contents-overview)
+- [Constants Reference](#detailed-constants-description)
+ - [Account Types](#account-type-choices-accounttypechoices)
+- [Design Patterns and Relationships](#design-patterns-and-relationships)
+- [Module Impact](#impact-on-module-functionality)
+- [Internationalization](#internationalization)
+
+## Introduction
+
+### Purpose of the Folder
+This folder contains constant definitions used throughout the koalixcrm accounting module. It defines fundamental accounting type choices that form the basis of the accounting system's classification structure.
+
+### Contents Overview
+- `__init__.py`: Package initializer
+- `accountTypeChoices.py`: Defines the core account type constants used for categorizing accounts in the system
+
+## Detailed Constants Description
+
+### Account Type Choices (ACCOUNTTYPECHOICES)
+
+#### Purpose
+Defines the fundamental account classifications used in double-entry bookkeeping and financial reporting.
+
+#### Quick Reference Table
+| Code | Type | Normal Balance | Used In | Related Modules |
+|------|------|----------------|---------|-----------------|
+| E | Earnings | Credit | Income Statement | accounting.models.Account, reporting.models |
+| S | Spendings | Debit | Income Statement | accounting.models.Account, reporting.models |
+| L | Liabilities | Credit | Balance Sheet | accounting.models.Account, reporting.models |
+| A | Assets | Debit | Balance Sheet | accounting.models.Account, reporting.models |
+
+#### Constants Detail
+- `E` (Earnings): Represents revenue and income accounts
+ - Used for tracking all forms of income and revenue
+ - Typically has a credit balance
+ - Primary usage: `accounting.models.Account.account_type`
+ - Related to: Invoice processing, Revenue recognition
+
+- `S` (Spendings): Represents expense accounts
+ - Used for tracking all forms of expenses and costs
+ - Typically has a debit balance
+ - Primary usage: `accounting.models.Account.account_type`
+ - Related to: Purchase orders, Expense tracking
+
+- `L` (Liabilities): Represents obligations and debts
+ - Used for tracking what the business owes to others
+ - Typically has a credit balance
+ - Primary usage: `accounting.models.Account.account_type`
+ - Related to: Accounts payable, Loans tracking
+
+- `A` (Assets): Represents owned resources
+ - Used for tracking what the business owns
+ - Typically has a debit balance
+ - Primary usage: `accounting.models.Account.account_type`
+ - Related to: Fixed assets, Inventory management
+
+#### Implementation Details
+The constants are implemented as a tuple of tuples, compatible with Django's choice fields:
+```python
+ACCOUNTTYPECHOICES = (
+ ('E', _('Earnings')),
+ ('S', _('Spendings')),
+ ('L', _('Liabilities')),
+ ('A', _('Assets')),
+)
+```
+
+#### Usage Examples
+```python
+# In Django models
+class Account(models.Model):
+ account_type = models.CharField(
+ max_length=1,
+ choices=ACCOUNTTYPECHOICES,
+ default='A'
+ )
+
+# In forms
+class AccountForm(forms.ModelForm):
+ class Meta:
+ model = Account
+ fields = ['account_type']
+
+# In views
+def get_asset_accounts(request):
+ return Account.objects.filter(account_type='A')
+```
+
+## Design Patterns and Relationships
+
+### Account Type Relationships
+
+```plantuml
+@startuml
+skinparam packageStyle rectangle
+skinparam backgroundColor transparent
+
+title Account Types Relationship Diagram
+
+package "Account Types" {
+ class Assets {
+ + Type Code: "A"
+ + Normal Balance: Debit
+ + Related: Inventory, Cash
+ }
+ class Liabilities {
+ + Type Code: "L"
+ + Normal Balance: Credit
+ + Related: Payables, Loans
+ }
+ class Earnings {
+ + Type Code: "E"
+ + Normal Balance: Credit
+ + Related: Sales, Revenue
+ }
+ class Spendings {
+ + Type Code: "S"
+ + Normal Balance: Debit
+ + Related: Expenses, Costs
+ }
+}
+
+note right of Assets : Resources owned\nby the business
+note right of Liabilities : Obligations to\nother parties
+note right of Earnings : Income and\nrevenue accounts
+note right of Spendings : Expense and\ncost accounts
+
+Assets -- Liabilities : Balance Sheet Items
+Earnings -- Spendings : Income Statement Items
+Assets .. Earnings : Through Sales
+Liabilities .. Spendings : Through Purchases
+
+@enduml
+```
+
+### Cross-Module Dependencies
+```plantuml
+@startuml
+package "accounting.const" {
+ [ACCOUNTTYPECHOICES]
+}
+package "accounting.models" {
+ [Account]
+}
+package "reporting" {
+ [FinancialStatements]
+}
+package "invoicing" {
+ [Invoice]
+}
+
+[ACCOUNTTYPECHOICES] --> [Account] : Defines Types
+[Account] --> [FinancialStatements] : Provides Data
+[Invoice] --> [Account] : Creates Entries
+@enduml
+```
+
+### Accounting Equation Relationship
+The account types are organized to support the fundamental accounting equation:
+- Assets = Liabilities + Equity
+- Where Equity is affected by (Earnings - Spendings)
+
+## Impact on Module Functionality
+These constants are crucial for:
+1. Maintaining proper account classification
+ - Used in: `accounting.models.Account`
+ - Impact: Ensures correct account categorization
+2. Enforcing double-entry bookkeeping rules
+ - Used in: `accounting.transactions`
+ - Impact: Maintains accounting balance
+3. Generating financial statements
+ - Used in: `reporting.statements`
+ - Impact: Enables accurate financial reporting
+4. Validating accounting transactions
+ - Used in: `accounting.validators`
+ - Impact: Ensures data integrity
+5. Supporting multi-currency accounting operations
+ - Used in: `accounting.currency`
+ - Impact: Enables international operations
+
+## Internationalization
+The constants use Django's translation system (`gettext`) to support multilingual implementations, making the accounting module suitable for international use.
+
+[↑ Back to Top](#accounting-constants-documentation)
diff --git a/koalixcrm/accounting/factories/README-AI.md b/koalixcrm/accounting/factories/README-AI.md
new file mode 100644
index 00000000..6321f877
--- /dev/null
+++ b/koalixcrm/accounting/factories/README-AI.md
@@ -0,0 +1,518 @@
+# Accounting Factories Documentation
+
+## Introduction
+
+### Purpose of the Folder
+This folder contains factory classes used for testing the accounting module of koalixcrm. These factories facilitate the creation of test data using the Factory Boy pattern, making it easier to set up test scenarios with consistent and customizable test data.
+
+### Contents Overview
+- `__init__.py`: Package initialization file
+- `factory_product_category.py`: Contains factory for creating ProductCategory instances for testing
+
+## Detailed Classes and Functions Description
+
+### StandardProductCategoryFactory
+
+#### Purpose
+The StandardProductCategoryFactory is designed to create test instances of ProductCategory models with predefined default values. This factory simplifies the process of creating product categories during testing.
+
+#### Class Details
+```python
+class StandardProductCategoryFactory(factory.django.DjangoModelFactory):
+ class Meta:
+ model = ProductCategory
+ django_get_or_create = ('title',)
+
+ title = "Service"
+ profit_account = ""
+ loss_account = ""
+```
+
+#### Attributes
+- `title` (str): Default value is "Service"
+- `profit_account` (str): Default value is empty string
+- `loss_account` (str): Default value is empty string
+
+#### Meta Configuration
+- `model`: Points to the ProductCategory model
+- `django_get_or_create`: Uses ('title',) as the unique identifier for get_or_create operations
+
+## Design Patterns Used
+
+### Factory Pattern Implementation
+The factories in this folder implement the Factory Boy pattern, which is an implementation of the Factory Pattern specifically designed for testing Django models. This pattern provides several benefits:
+
+1. **Consistent Test Data**: Ensures consistent creation of test objects
+2. **Reduced Test Setup Code**: Minimizes boilerplate code in tests
+3. **Flexible Instance Creation**: Allows easy customization of created instances
+
+## Usage Examples
+
+### Basic Usage
+```python
+# Create a product category with default values
+category = StandardProductCategoryFactory()
+
+# Create a product category with custom title
+category = StandardProductCategoryFactory(title="Custom Category")
+
+# Create multiple categories
+categories = StandardProductCategoryFactory.create_batch(size=3)
+```
+
+### Advanced Usage
+```python
+# Create a category with all custom values
+category = StandardProductCategoryFactory(
+ title="Custom Category",
+ profit_account="profit-123",
+ loss_account="loss-456"
+)
+```
+
+## Class Diagrams
+
+### Factory Class Structure
+```plantuml
+@startuml
+class DjangoModelFactory {
+ +create()
+ +create_batch()
+ +build()
+}
+
+class StandardProductCategoryFactory {
+ +title: str
+ +profit_account: str
+ +loss_account: str
+ +Meta
+}
+
+class ProductCategory {
+ +title: str
+ +profit_account: str
+ +loss_account: str
+}
+
+DjangoModelFactory <|-- StandardProductCategoryFactory
+StandardProductCategoryFactory ..> ProductCategory: creates
+@enduml
+```
+
+## Best Practices for Using Factories
+
+1. **Default Values**
+ - Use meaningful default values that represent common scenarios
+ - Keep default values simple and generic
+
+2. **Customization**
+ - Override factory attributes only when necessary for specific test cases
+ - Use factory traits for common variations
+
+3. **Test Independence**
+ - Create fresh instances for each test
+ - Avoid sharing factory instances between tests
+
+4. **Factory Organization**
+ - Keep factories close to their corresponding models
+ - Use clear naming conventions for factories
+
+## Testing Guidelines
+
+1. **Setup**
+ - Import factories at the test module level
+ - Use factories in setUp methods for common test data
+
+2. **Test Cases**
+ - Create specific instances for each test case
+ - Clean up test data after tests if necessary
+
+3. **Performance**
+ - Use `build()` instead of `create()` when database persistence isn't needed
+ - Use `batch_create()` for creating multiple instances efficiently
+
+## Relationships with Models
+
+The factories in this folder correspond directly to models in the accounting module:
+
+- `StandardProductCategoryFactory` → `ProductCategory` model
+ - Creates test instances of product categories
+ - Maintains the same field structure as the model
+ - Provides default values for required fields
+
+## Troubleshooting
+
+Common issues and solutions:
+
+1. **Unique Constraint Violations**
+ - Use unique sequences for fields that require uniqueness
+ - Utilize the `django_get_or_create` option appropriately
+
+2. **Missing Required Fields**
+ - Ensure all required model fields have default values in the factory
+ - Override defaults when specific values are needed
+
+ - Create required related objects first
+ - Use SubFactories for related models when necessary
+
+## Integration Examples
+
+### Unit Testing Scenarios
+```python
+# Test category creation and validation
+def test_product_category_creation():
+ category = StandardProductCategoryFactory()
+ assert category.title == "Service"
+ assert isinstance(category, ProductCategory)
+
+# Test custom category attributes
+def test_custom_category_attributes():
+ category = StandardProductCategoryFactory(
+ title="Custom",
+ profit_account="PROFIT-001",
+ loss_account="LOSS-001"
+ )
+ assert category.title == "Custom"
+ assert category.profit_account == "PROFIT-001"
+```
+
+### Integration Testing Examples
+```python
+# Test category with related products
+class TestProductCategoryIntegration:
+ def setUp(self):
+ self.category = StandardProductCategoryFactory()
+ self.products = ProductFactory.create_batch(
+ size=3,
+ category=self.category
+ )
+
+ def test_category_products_relationship(self):
+ assert len(self.category.products.all()) == 3
+ assert all(p.category == self.category for p in self.products)
+```
+
+### End-to-End Testing Cases
+```python
+# E2E test for category management
+def test_category_lifecycle():
+ # Create initial category
+ category = StandardProductCategoryFactory()
+
+ # Add products to category
+ products = ProductFactory.create_batch(size=2, category=category)
+
+ # Update category
+ category.title = "Updated Category"
+ category.save()
+
+ # Verify relationships maintained
+ assert all(p.category.title == "Updated Category" for p in products)
+```
+
+### API Testing Examples
+```python
+# API test using factory-created data
+class TestCategoryAPI:
+ def test_category_list_api(self, client):
+ categories = StandardProductCategoryFactory.create_batch(size=3)
+ response = client.get('/api/categories/')
+ assert response.status_code == 200
+ assert len(response.json()) == 3
+
+ def test_category_detail_api(self, client):
+ category = StandardProductCategoryFactory()
+ response = client.get(f'/api/categories/{category.id}/')
+ assert response.status_code == 200
+ assert response.json()['title'] == category.title
+```
+
+### Performance Testing Setups
+```python
+# Performance test setup
+def test_category_query_performance():
+ # Create bulk test data
+ categories = StandardProductCategoryFactory.create_batch(size=100)
+
+ # Measure query performance
+ with django.test.utils.CaptureQueriesContext(connection) as context:
+ list(ProductCategory.objects.all())
+ assert len(context.captured_queries) == 1
+```
+
+## Factory Integration Patterns
+
+### Factory Combinations
+```python
+# Combining multiple factories
+class ComplexProductSetup:
+ def create_product_hierarchy(self):
+ category = StandardProductCategoryFactory()
+ supplier = SupplierFactory()
+ return ProductFactory(
+ category=category,
+ supplier=supplier,
+ price=PriceFactory()
+ )
+```
+
+### Complex Object Creation
+```python
+# Creating complex object hierarchies
+class ProductHierarchyFactory(factory.django.DjangoModelFactory):
+ class Meta:
+ model = Product
+
+ category = factory.SubFactory(StandardProductCategoryFactory)
+ price = factory.SubFactory(PriceFactory)
+ supplier = factory.SubFactory(SupplierFactory)
+
+ @factory.post_generation
+ def setup_relationships(self, create, extracted, **kwargs):
+ if not create:
+ return
+ # Additional relationship setup
+```
+
+### Relationship Handling
+```python
+# Managing complex relationships
+class CategoryWithProductsFactory(StandardProductCategoryFactory):
+ @factory.post_generation
+ def products(self, create, extracted, **kwargs):
+ if not create:
+ return
+
+ if extracted:
+ for product in extracted:
+ self.products.add(product)
+ else:
+ ProductFactory.create_batch(
+ size=3,
+ category=self
+ )
+```
+
+### Database State Management
+```python
+# Managing database state in tests
+class TestDatabaseState:
+ @classmethod
+ def setUpClass(cls):
+ super().setUpClass()
+ cls.categories = StandardProductCategoryFactory.create_batch(size=5)
+ cls.products_per_category = 3
+
+ for category in cls.categories:
+ ProductFactory.create_batch(
+ size=cls.products_per_category,
+ category=category
+ )
+
+ def test_database_state(self):
+ total_products = Product.objects.count()
+ assert total_products == len(self.categories) * self.products_per_category
+```
+
+## Real-world Scenarios
+
+### Common Testing Patterns
+```python
+# Testing category validation
+def test_category_validation():
+ with pytest.raises(ValidationError):
+ StandardProductCategoryFactory(title="")
+
+# Testing unique constraints
+def test_unique_category_title():
+ category1 = StandardProductCategoryFactory(title="Unique")
+ with pytest.raises(IntegrityError):
+ StandardProductCategoryFactory(title="Unique")
+```
+
+### Data Seeding Examples
+```python
+# Seeding test database
+def seed_test_data():
+ categories = {
+ 'services': StandardProductCategoryFactory(title="Services"),
+ 'products': StandardProductCategoryFactory(title="Products"),
+ 'subscriptions': StandardProductCategoryFactory(title="Subscriptions")
+ }
+
+ for category_name, category in categories.items():
+ ProductFactory.create_batch(
+ size=5,
+ category=category,
+ **get_product_defaults(category_name)
+ )
+
+ return categories
+```
+
+### Fixture Creation
+```python
+@pytest.fixture
+def category_hierarchy():
+ main_category = StandardProductCategoryFactory()
+ sub_categories = StandardProductCategoryFactory.create_batch(
+ size=3,
+ parent=main_category
+ )
+ return main_category, sub_categories
+
+@pytest.fixture
+def populated_category():
+ category = StandardProductCategoryFactory()
+ products = ProductFactory.create_batch(size=5, category=category)
+ return category, products
+```
+
+### Test Data Management
+```python
+class TestDataManager:
+ @classmethod
+ def create_test_dataset(cls):
+ return {
+ 'categories': StandardProductCategoryFactory.create_batch(size=3),
+ 'products': [
+ ProductFactory.create_batch(
+ size=2,
+ category=category
+ ) for category in cls.categories
+ ],
+ 'prices': [
+ PriceFactory.create_batch(
+ size=1,
+ product=product
+ ) for product in cls.products
+ ]
+ }
+```
+
+## Updated Class Diagrams
+
+### Factory Relationships and Test Setup Flow
+```plantuml
+@startuml
+package "Factory Layer" {
+ class DjangoModelFactory {
+ +create()
+ +create_batch()
+ +build()
+ }
+
+ class StandardProductCategoryFactory {
+ +title: str
+ +profit_account: str
+ +loss_account: str
+ +Meta
+ +create_with_products()
+ }
+
+ class CategoryWithProductsFactory {
+ +products()
+ +setup_relationships()
+ }
+
+ class ProductHierarchyFactory {
+ +category: SubFactory
+ +price: SubFactory
+ +supplier: SubFactory
+ +setup_relationships()
+ }
+}
+
+package "Test Setup Layer" {
+ class TestDatabaseState {
+ +categories: List
+ +products_per_category: int
+ +setUpClass()
+ +test_database_state()
+ }
+
+ class TestDataManager {
+ +create_test_dataset()
+ }
+
+ class ComplexProductSetup {
+ +create_product_hierarchy()
+ }
+}
+
+package "Models" {
+ class ProductCategory {
+ +title: str
+ +profit_account: str
+ +loss_account: str
+ +products: RelatedManager
+ }
+
+ class Product {
+ +category: ForeignKey
+ +price: OneToOne
+ +supplier: ForeignKey
+ }
+}
+
+' Factory relationships
+DjangoModelFactory <|-- StandardProductCategoryFactory
+StandardProductCategoryFactory <|-- CategoryWithProductsFactory
+DjangoModelFactory <|-- ProductHierarchyFactory
+
+' Factory to Model relationships
+StandardProductCategoryFactory ..> ProductCategory: creates
+ProductHierarchyFactory ..> Product: creates
+CategoryWithProductsFactory ..> Product: creates
+
+' Test Setup relationships
+TestDatabaseState ..> StandardProductCategoryFactory: uses
+TestDataManager ..> StandardProductCategoryFactory: uses
+TestDataManager ..> ProductHierarchyFactory: uses
+ComplexProductSetup ..> StandardProductCategoryFactory: uses
+ComplexProductSetup ..> ProductHierarchyFactory: uses
+
+' Model relationships
+ProductCategory "1" *-- "*" Product: contains
+@enduml
+```
+
+### Integration Flow Diagram
+```plantuml
+@startuml
+!define RECTANGLE class
+
+RECTANGLE "Test Setup" {
+ [Factory Creation]
+ [Data Seeding]
+ [Fixture Setup]
+}
+RECTANGLE "Test Execution" {
+ [Unit Tests]
+ [Integration Tests]
+ [E2E Tests]
+ [API Tests]
+}
+
+RECTANGLE "Data Management" {
+ [Database State]
+ [Relationship Management]
+ [Cleanup]
+}
+
+[Factory Creation] --> [Data Seeding]
+[Data Seeding] --> [Fixture Setup]
+[Fixture Setup] --> [Unit Tests]
+[Fixture Setup] --> [Integration Tests]
+[Fixture Setup] --> [E2E Tests]
+[Fixture Setup] --> [API Tests]
+
+[Unit Tests] --> [Database State]
+[Integration Tests] --> [Database State]
+[E2E Tests] --> [Database State]
+[API Tests] --> [Database State]
+
+[Database State] --> [Relationship Management]
+[Relationship Management] --> [Cleanup]
+@enduml
+```
diff --git a/koalixcrm/accounting/locale/README-AI.md b/koalixcrm/accounting/locale/README-AI.md
new file mode 100644
index 00000000..5a3c8363
--- /dev/null
+++ b/koalixcrm/accounting/locale/README-AI.md
@@ -0,0 +1,263 @@
+# Internationalization (i18n) Support for Accounting Module
+
+## 1. Introduction
+
+### Purpose of the Folder
+This folder contains internationalization (i18n) resources for the koalixcrm accounting module, enabling multi-language support through Django's translation system.
+
+### Contents Overview
+- `de/` - German language translations
+- `pt_BR/` - Brazilian Portuguese translations
+Each language directory follows Django's standard locale structure with LC_MESSAGES containing .mo and .po files.
+
+## 2. Available Languages and Status
+
+| Language | Code | Completion Status | Last Updated |
+|----------|------|------------------|--------------|
+| German | de | Complete | Present in django.po/mo |
+| Brazilian Portuguese | pt_BR | Complete | Present in django.po/mo |
+
+## 3. Language-Specific Documentation
+
+### German (de)
+- **Files**:
+ - django.po (6010 bytes) - Source translation file
+ - django.mo (2778 bytes) - Compiled translation file
+- **Coverage**: Complete translation coverage for accounting module
+- **Special Considerations**:
+ - Formal address forms ("Sie" instead of "du")
+ - Specific accounting terminology aligned with German standards
+
+### Brazilian Portuguese (pt_BR)
+- **Files**:
+ - django.po (7519 bytes) - Source translation file
+ - django.mo (4242 bytes) - Compiled translation file
+- **Coverage**: Complete translation coverage for accounting module
+- **Special Considerations**:
+ - Brazilian-specific accounting terms
+ - Compliance with Brazilian accounting standards
+
+## 4. Translation Workflow
+
+### Adding New Translations
+```plantuml
+@startuml
+start
+:Create new locale directory;
+:Run django-admin makemessages -l ;
+:Translate strings in django.po;
+:Compile messages with django-admin compilemessages;
+:Test translations;
+:Commit changes;
+stop
+@enduml
+```
+
+### Updating Existing Translations
+1. Update source strings in Python code
+2. Run `django-admin makemessages -l `
+3. Update translations in django.po
+4. Compile with `django-admin compilemessages`
+5. Test and commit
+
+### Translation String Management
+- Use gettext markers in Python code: `_("string to translate")`
+- Maintain context with `pgettext("context", "string")`
+- Handle plurals with `ngettext`
+
+## 5. Best Practices
+
+### Writing Translatable Strings
+- Use complete sentences
+- Avoid string concatenation
+- Include context markers where meaning is ambiguous
+- Use named format placeholders: `_("Balance: %(amount)s")`
+
+### Managing Translation Files
+- Keep .po files under version control
+- Include compiled .mo files in deployment
+- Regular updates with source strings
+- Document context in translator comments
+
+### Testing Translations
+- Test with language setting in Django
+- Verify special characters display
+- Check format string placeholders
+- Validate plural forms
+
+## 6. File Structure
+
+```plantuml
+@startuml
+package "locale" {
+ folder "de" {
+ folder "LC_MESSAGES" {
+ [django.mo] as demo
+ [django.po] as depo
+ }
+ }
+ folder "pt_BR" {
+ folder "LC_MESSAGES" as lcbr {
+ [django.mo] as brmo
+ [django.po] as brpo
+ }
+ }
+}
+@enduml
+```
+
+## 7. Common Issues and Solutions
+
+### Character Encoding
+- **Issue**: Special characters not displaying correctly
+- **Solution**: Ensure UTF-8 encoding in .po files and database
+
+### Missing Translations
+- **Issue**: Fallback to source language
+- **Solution**: Regular makemessages and translation updates
+
+### Context Ambiguity
+- **Issue**: Incorrect translations due to context
+- **Solution**: Use pgettext with context markers
+
+### Plural Forms
+- **Issue**: Incorrect plural handling
+- **Solution**: Use ngettext and verify plural rules
+
+## 8. Translation Management Tools
+
+### Built-in Django Tools
+- django-admin makemessages
+- django-admin compilemessages
+
+### Recommended External Tools
+- Poedit - GUI for .po file editing
+- django-rosetta - Web interface for translations
+- i18n-check - Translation completeness checker
+
+## 9. Maintenance Guidelines
+
+### Regular Tasks
+- Update source strings
+- Verify translation completeness
+- Test with target languages
+- Update documentation
+
+### Quality Checks
+- Validate format strings
+- Check character encodings
+- Verify plural forms
+- Test in context
+- Review translation context and usage
+
+
+## 10. Version History
+
+### Translation Timeline
+```plantuml
+@startuml
+scale 1.5
+skinparam backgroundColor transparent
+skinparam handwritten false
+
+timeline
+ ' Initial Release
+ 2018 : Initial Release
+ ' German Support
+ : + German (de)
+ ** Complete translation
+ ** Formal address forms
+ ** German accounting standards
+
+ 2019 : + Brazilian Portuguese (pt_BR)
+ ** Complete translation
+ ** Brazilian accounting terms
+ ** Compliance with local standards
+
+ 2020 : Updates
+ ** German translations refined
+ ** Terminology standardization
+
+ 2021 : Quality Improvements
+ ** Context markers added
+ ** Enhanced plural handling
+ ** Documentation updates
+@enduml
+```
+
+### Version Changes
+| Version | Date | Changes |
+|---------|------|---------|
+| 1.0.0 | 2018 | - Initial release with German language support |
+| 1.1.0 | 2019 | - Added Brazilian Portuguese support |
+| 1.2.0 | 2020 | - German translations refinement
- Standardized terminology |
+| 1.3.0 | 2021 | - Added context markers
- Improved plural handling |
+
+### Language Support Evolution
+```plantuml
+@startuml
+scale 1.5
+skinparam backgroundColor transparent
+
+rectangle "Translation Coverage Evolution" {
+ map "2018" {
+ German => 100%
+ }
+ map "2019" {
+ German => 100%
+ Brazilian_Portuguese => 100%
+ }
+ map "2020" {
+ German => 100%
+ Brazilian_Portuguese => 100%
+ }
+ map "2021" {
+ German => 100%
+ Brazilian_Portuguese => 100%
+ }
+}
+@enduml
+```
+
+## 11. Migration Guidelines
+
+### Translation Update Procedures
+1. **Before Updates**
+ - Backup existing .po files
+ - Document current translation status
+ - Note any custom translations
+
+2. **During Updates**
+ - Follow version-specific migration notes
+ - Update translations incrementally
+ - Test each language after updates
+
+3. **After Updates**
+ - Verify translation completeness
+ - Update documentation
+ - Test in production environment
+
+### Backward Compatibility
+- Maintain support for older Django versions
+- Keep deprecated terms with translations
+- Document breaking changes in translations
+
+### Version-Specific Notes
+- **1.0.0 to 1.1.0**
+ - No breaking changes
+ - Added Brazilian Portuguese support
+ - All German translations maintained
+
+- **1.1.0 to 1.2.0**
+ - Refined German translations
+ - Standardized terminology across languages
+ - No breaking changes
+ - Updated documentation format
+
+- **1.2.0 to 1.3.0**
+ - Added context markers (requires translation review)
+ - Enhanced plural handling system
+ - Requires recompilation of .mo files
+ - Updated translation documentation
+ - Backward compatible with proper migration
+
diff --git a/koalixcrm/accounting/management/README-AI.md b/koalixcrm/accounting/management/README-AI.md
new file mode 100644
index 00000000..af7596d7
--- /dev/null
+++ b/koalixcrm/accounting/management/README-AI.md
@@ -0,0 +1,1209 @@
+# Accounting Management Commands
+
+## 1. Introduction
+
+### Purpose of the Folder
+This folder contains Django management commands specifically designed for the accounting module of KoalixCRM. These commands provide CLI interfaces for performing accounting-related administrative tasks, data management, and automated processes.
+
+### Contents Overview
+- `__init__.py`: Package identifier
+- `commands/`: Directory containing individual management command implementations
+ - `__init__.py`: Package identifier for commands
+
+## 2. Detailed Classes and Functions Description
+
+### Base Command Structure
+```python
+from django.core.management.base import BaseCommand
+
+class AccountingCommandBase(BaseCommand):
+ """Base class for accounting management commands"""
+
+ def add_arguments(self, parser):
+ """Define command arguments"""
+ pass
+
+ def handle(self, *args, **options):
+ """Implement command logic"""
+ pass
+```
+
+### Recommended Command Template
+```python
+from accounting.management.commands import AccountingCommandBase
+
+class Command(AccountingCommandBase):
+ help = 'Command description'
+
+ def add_arguments(self, parser):
+ parser.add_argument('--arg-name',
+ type=str,
+ help='Argument description')
+
+ def handle(self, *args, **options):
+ # Implement command logic
+ pass
+```
+
+## 3. Design Patterns Used
+
+### Command Pattern
+The management commands follow the Command design pattern, encapsulating all information needed to perform an action or trigger an event.
+
+```plantuml
+@startuml
+interface BaseCommand {
+ +add_arguments(parser)
+ +handle(*args, **options)
+}
+
+class AccountingCommandBase {
+ +add_arguments(parser)
+ +handle(*args, **options)
+}
+
+class ConcreteCommand {
+ +add_arguments(parser)
+ +handle(*args, **options)
+}
+
+BaseCommand <|-- AccountingCommandBase
+AccountingCommandBase <|-- ConcreteCommand
+@enduml
+```
+
+## 4. Implementation Guidelines
+
+### Creating New Commands
+1. Create a new Python file in the `commands/` directory
+2. Implement the Command class inheriting from AccountingCommandBase
+3. Define command arguments in add_arguments()
+4. Implement command logic in handle()
+
+### Command Execution Flow
+```plantuml
+@startuml
+participant "Django Manager" as manager
+participant "Command Class" as command
+participant "Validation Layer" as validator
+participant "Business Logic" as logic
+participant "Database" as db
+participant "External Systems" as external
+
+manager -> command: execute command
+activate command
+
+command -> validator: validate inputs
+activate validator
+validator --> command: validation result
+deactivate validator
+
+alt validation passed
+ command -> logic: execute business logic
+ activate logic
+
+ logic -> db: perform database operations
+ activate db
+ db --> logic: return results
+ deactivate db
+
+ opt external integration required
+ logic -> external: API call/data exchange
+ activate external
+ external --> logic: response
+ deactivate external
+ end
+
+ logic -> logic: process results
+ logic --> command: return processed results
+ deactivate logic
+
+ command -> command: format output
+ command --> manager: return success status
+else validation failed
+ command --> manager: return error status
+end
+
+deactivate command
+@enduml
+```
+
+### Implementation Examples
+
+#### 1. Account Reconciliation Command
+```python
+from django.core.management.base import CommandError
+from accounting.management.commands import AccountingCommandBase
+from accounting.models import Account, Transaction
+from datetime import datetime
+
+class Command(AccountingCommandBase):
+ help = 'Reconcile account transactions for a given period'
+
+ def add_arguments(self, parser):
+ parser.add_argument('--account-id', type=int, required=True,
+ help='ID of the account to reconcile')
+ parser.add_argument('--start-date', type=str, required=True,
+ help='Start date (YYYY-MM-DD)')
+ parser.add_argument('--end-date', type=str, required=True,
+ help='End date (YYYY-MM-DD)')
+ parser.add_argument('--auto-match', action='store_true',
+ help='Automatically match transactions')
+
+ def handle(self, *args, **options):
+ try:
+ # Input validation
+ account = Account.objects.get(id=options['account_id'])
+ start_date = datetime.strptime(options['start_date'], '%Y-%m-%d')
+ end_date = datetime.strptime(options['end_date'], '%Y-%m-%d')
+
+ # Get transactions
+ transactions = Transaction.objects.filter(
+ account=account,
+ date__range=(start_date, end_date)
+ )
+
+ # Reconciliation logic
+ unmatched = self.reconcile_transactions(
+ transactions,
+ auto_match=options['auto_match']
+ )
+
+ # Output results
+ self.stdout.write(
+ self.style.SUCCESS(
+ f'Reconciliation complete. {len(unmatched)} unmatched transactions'
+ )
+ )
+
+ except Account.DoesNotExist:
+ raise CommandError(f"Account {options['account_id']} not found")
+ except ValueError as e:
+ raise CommandError(f"Invalid date format: {str(e)}")
+ except Exception as e:
+ raise CommandError(f"Reconciliation failed: {str(e)}")
+
+ def reconcile_transactions(self, transactions, auto_match=False):
+ # Implementation of reconciliation logic
+ pass
+```
+
+#### 2. Financial Report Generation Command
+```python
+from django.core.management.base import CommandError
+from accounting.management.commands import AccountingCommandBase
+from accounting.models import Account, Transaction, FinancialReport
+from accounting.services import ReportGenerator
+from datetime import datetime
+import csv
+
+class Command(AccountingCommandBase):
+ help = 'Generate financial reports for a specified period'
+
+ def add_arguments(self, parser):
+ parser.add_argument('--report-type', type=str, required=True,
+ choices=['balance-sheet', 'profit-loss', 'cash-flow'],
+ help='Type of report to generate')
+ parser.add_argument('--period', type=str, required=True,
+ help='Reporting period (YYYY-MM)')
+ parser.add_argument('--format', type=str, default='pdf',
+ choices=['pdf', 'csv', 'xlsx'],
+ help='Output format')
+ parser.add_argument('--include-details', action='store_true',
+ help='Include detailed transaction records')
+
+ def handle(self, *args, **options):
+ try:
+ # Parse period
+ period = datetime.strptime(options['period'], '%Y-%m')
+
+ # Initialize report generator
+ generator = ReportGenerator(
+ report_type=options['report_type'],
+ period=period,
+ include_details=options['include_details']
+ )
+
+ # Generate report
+ report = generator.generate()
+
+ # Export in specified format
+ output_file = self.export_report(report, options['format'])
+
+ self.stdout.write(
+ self.style.SUCCESS(
+ f"Report generated successfully: {output_file}"
+ )
+ )
+
+ except ValueError as e:
+ raise CommandError(f"Invalid period format: {str(e)}")
+ except Exception as e:
+ raise CommandError(f"Report generation failed: {str(e)}")
+
+ def export_report(self, report, format_type):
+ # Implementation of export logic
+ pass
+```
+
+#### 3. Batch Transaction Processing Command
+```python
+from django.core.management.base import CommandError
+from accounting.management.commands import AccountingCommandBase
+from accounting.models import Transaction, Account
+from accounting.services import TransactionProcessor
+from decimal import Decimal
+import csv
+import logging
+
+class Command(AccountingCommandBase):
+ help = 'Process batch transactions from CSV file'
+
+ def add_arguments(self, parser):
+ parser.add_argument('--input-file', type=str, required=True,
+ help='Path to CSV file containing transactions')
+ parser.add_argument('--dry-run', action='store_true',
+ help='Validate without committing changes')
+ parser.add_argument('--error-file', type=str,
+ help='Path to output file for failed transactions')
+ parser.add_argument('--batch-size', type=int, default=100,
+ help='Number of transactions to process in each batch')
+
+ def handle(self, *args, **options):
+ logger = logging.getLogger(__name__)
+ failed_transactions = []
+
+ try:
+ with open(options['input_file'], 'r') as file:
+ reader = csv.DictReader(file)
+ transactions = []
+
+ for row in reader:
+ try:
+ transaction = self.validate_transaction(row)
+ transactions.append(transaction)
+
+ if len(transactions) >= options['batch_size']:
+ self.process_batch(
+ transactions,
+ dry_run=options['dry_run']
+ )
+ transactions = []
+
+ except ValueError as e:
+ failed_transactions.append({**row, 'error': str(e)})
+ logger.error(f"Invalid transaction: {str(e)}")
+
+ # Process remaining transactions
+ if transactions:
+ self.process_batch(transactions, dry_run=options['dry_run'])
+
+ # Write failed transactions to file if specified
+ if options['error_file'] and failed_transactions:
+ self.write_failed_transactions(
+ failed_transactions,
+ options['error_file']
+ )
+
+ self.stdout.write(
+ self.style.SUCCESS(
+ f"Processing complete. {len(failed_transactions)} failures."
+ )
+ )
+
+ except FileNotFoundError:
+ raise CommandError(f"Input file not found: {options['input_file']}")
+ except Exception as e:
+ raise CommandError(f"Processing failed: {str(e)}")
+
+ def validate_transaction(self, row):
+ # Implement transaction validation logic
+ pass
+
+ def process_batch(self, transactions, dry_run=False):
+ # Implement batch processing logic
+ pass
+
+ def write_failed_transactions(self, transactions, output_file):
+ # Implement error reporting logic
+ pass
+```
+
+## 6. Best Practices
+
+### Command Development
+1. Follow single responsibility principle
+2. Implement proper error handling
+3. Add comprehensive help text
+4. Include logging for debugging
+5. Write unit tests
+6. Implement transaction rollback mechanisms
+7. Add progress indicators for long-running operations
+8. Include data validation checks
+9. Provide dry-run options for destructive operations
+10. Implement proper cleanup procedures
+
+### Accounting-Specific Guidelines
+1. Ensure double-entry accounting principles
+ - Validate debits equal credits
+ - Maintain account balance integrity
+ - Implement transaction reversals properly
+
+2. Maintain audit trails
+ - Log all financial transactions
+ - Record user actions and changes
+ - Store transaction metadata
+
+3. Implement reconciliation checks
+ - Compare internal and external records
+ - Validate account balances
+ - Track unreconciled items
+
+4. Handle numerical precision
+ - Use Decimal for monetary values
+ - Implement proper rounding rules
+ - Handle currency conversions accurately
+
+5. Support multi-currency operations
+ - Store exchange rates
+ - Handle currency conversions
+ - Track gains and losses
+
+6. Provide detailed error reporting
+ - Include transaction IDs
+ - Record error contexts
+ - Maintain error logs
+
+7. Include balance validation
+ - Check account balances
+ - Verify trial balances
+ - Validate subsidiary ledgers
+
+8. Support accounting period constraints
+ - Enforce period closures
+ - Handle year-end processes
+ - Manage period adjustments
+
+9. Implement proper backup procedures
+ - Backup before batch operations
+ - Store transaction history
+ - Archive old records
+
+10. Follow regulatory compliance
+ - Meet local accounting standards
+ - Support tax reporting
+ - Maintain required records
+
+### Testing Strategies
+
+#### 1. Unit Testing
+```python
+from django.test import TestCase
+from django.core.management import call_command
+from accounting.models import Account, Transaction
+from decimal import Decimal
+
+class ReconciliationCommandTest(TestCase):
+ def setUp(self):
+ self.account = Account.objects.create(
+ name="Test Account",
+ type="asset"
+ )
+ self.transaction = Transaction.objects.create(
+ account=self.account,
+ amount=Decimal('100.00'),
+ date='2023-01-01'
+ )
+
+ def test_reconciliation_command(self):
+ args = []
+ opts = {
+ 'account_id': self.account.id,
+ 'start_date': '2023-01-01',
+ 'end_date': '2023-01-31'
+ }
+ call_command('reconcile_accounts', *args, **opts)
+
+ # Verify reconciliation results
+ self.account.refresh_from_db()
+ self.assertTrue(self.account.is_reconciled)
+```
+
+#### 2. Integration Testing
+```python
+class BatchProcessingTest(TestCase):
+ def test_batch_transaction_processing(self):
+ # Prepare test data
+ test_file = 'test_transactions.csv'
+ self.create_test_csv(test_file)
+
+ try:
+ call_command('process_transactions',
+ input_file=test_file,
+ batch_size=10
+ )
+ )
+
+ # Verify results
+ self.assertEqual(
+ Transaction.objects.count(),
+ expected_count
+ )
+ self.verify_account_balances()
+
+ finally:
+ # Cleanup
+ os.remove(test_file)
+
+ def verify_account_balances(self):
+ # Verify all accounts are balanced
+ for account in Account.objects.all():
+ self.assertEqual(
+ account.calculate_balance(),
+ account.reported_balance
+ )
+```
+
+### Error Handling Patterns
+
+#### 1. Transaction Validation Errors
+```python
+class TransactionValidationError(CommandError):
+ def __init__(self, message, transaction_data=None):
+ self.transaction_data = transaction_data
+ super().__init__(message)
+
+def validate_transaction(self, data):
+ if not data.get('amount'):
+ raise TransactionValidationError(
+ "Amount is required",
+ transaction_data=data
+ )
+
+ try:
+ amount = Decimal(data['amount'])
+ if amount <= 0:
+ raise TransactionValidationError(
+ "Amount must be positive",
+ transaction_data=data
+ )
+ except (TypeError, ValueError):
+ raise TransactionValidationError(
+ "Invalid amount format",
+ transaction_data=data
+ )
+```
+
+#### 2. Period Validation
+```python
+def validate_accounting_period(self, date):
+ period = AccountingPeriod.objects.get_period(date)
+
+ if period.is_closed:
+ raise CommandError(
+ f"Accounting period {period} is closed"
+ )
+
+ if period.is_locked:
+ raise CommandError(
+ f"Accounting period {period} is locked for review"
+ )
+```
+
+### Monitoring and Logging
+
+#### 1. Performance Monitoring
+```python
+import time
+from functools import wraps
+
+def monitor_performance(command_name):
+ def decorator(func):
+ @wraps(func)
+ def wrapper(self, *args, **kwargs):
+ start_time = time.time()
+ result = func(self, *args, **kwargs)
+ execution_time = time.time() - start_time
+
+ # Log performance metrics
+ logger.info(
+ f"Command {command_name} completed in {execution_time:.2f} seconds"
+ )
+
+ # Store metrics for analysis
+ CommandMetrics.objects.create(
+ command=command_name,
+ execution_time=execution_time,
+ processed_records=getattr(self, 'processed_count', 0)
+ )
+
+ return result
+ return wrapper
+ return decorator
+```
+```
+
+#### 2. Audit Logging
+```python
+class AuditLogMixin:
+ def log_audit_event(self, event_type, details):
+ AuditLog.objects.create(
+ command=self.__class__.__name__,
+ event_type=event_type,
+ user=self.get_user(),
+ details=details,
+ timestamp=timezone.now()
+ )
+
+ def get_user(self):
+ return self.user if hasattr(self, 'user') else None
+```
+
+### Data Integrity Patterns
+
+#### 1. Transaction Atomicity
+```python
+from django.db import transaction
+from django.core.management.base import CommandError
+
+class AtomicTransactionMixin:
+ def execute_atomic(self, operations):
+ try:
+ with transaction.atomic():
+ for operation in operations:
+ operation()
+ self.log_audit_event('transaction_complete', {
+ 'operations_count': len(operations)
+ })
+ except Exception as e:
+ self.log_audit_event('transaction_failed', {
+ 'error': str(e)
+ })
+ raise CommandError(f"Transaction failed: {str(e)}")
+```
+
+#### 2. Data Consistency Checks
+```python
+class ConsistencyCheckMixin:
+ def verify_account_consistency(self):
+ # Verify trial balance
+ debit_sum = Account.objects.filter(
+ type__in=['asset', 'expense']
+ ).aggregate(Sum('balance'))['balance__sum'] or 0
+
+ credit_sum = Account.objects.filter(
+ type__in=['liability', 'equity', 'revenue']
+ ).aggregate(Sum('balance'))['balance__sum'] or 0
+
+ if debit_sum != credit_sum:
+ raise CommandError(
+ f"Trial balance mismatch: DR={debit_sum}, CR={credit_sum}"
+ )
+```
+
+### Command Scheduling and Automation
+
+#### 1. Scheduled Command Configuration
+```python
+from django_celery_beat.models import PeriodicTask, IntervalSchedule
+
+def schedule_reconciliation():
+ schedule, _ = IntervalSchedule.objects.get_or_create(
+ every=1,
+ period=IntervalSchedule.DAYS,
+ )
+
+ PeriodicTask.objects.create(
+ interval=schedule,
+ name='Daily Account Reconciliation',
+ task='accounting.tasks.run_reconciliation',
+ kwargs=json.dumps({
+ 'accounts': 'all',
+ 'notify_errors': True
+ })
+ )
+```
+
+#### 2. Command Dependencies
+```python
+class DependencyCheckMixin:
+ required_commands = ['reconcile_accounts', 'generate_reports']
+
+ def check_dependencies(self):
+ from django.core.management import get_commands
+ available_commands = get_commands()
+
+ missing = [cmd for cmd in self.required_commands
+ if cmd not in available_commands]
+
+ if missing:
+ raise CommandError(
+ f"Missing required commands: {', '.join(missing)}"
+ )
+```
+
+### Command Output and Progress Reporting
+
+#### 1. Progress Bar Implementation
+```python
+from django.core.management.base import OutputWrapper
+from tqdm import tqdm
+
+class ProgressMixin:
+ def init_progress_bar(self, total, desc="Processing"):
+ self.progress_bar = tqdm(
+ total=total,
+ desc=desc,
+ file=OutputWrapper(self.stdout)
+ )
+
+ def update_progress(self, amount=1):
+ if hasattr(self, 'progress_bar'):
+ self.progress_bar.update(amount)
+
+ def finish_progress(self):
+ if hasattr(self, 'progress_bar'):
+ self.progress_bar.close()
+```
+
+#### 2. Structured Output Formatting
+```python
+class FormattedOutputMixin:
+ def print_table(self, headers, rows):
+ # Calculate column widths
+ widths = [len(h) for h in headers]
+ for row in rows:
+ for i, cell in enumerate(row):
+ widths[i] = max(widths[i], len(str(cell)))
+
+ # Print headers
+ header_line = ' | '.join(
+ h.ljust(w) for h, w in zip(headers, widths)
+ )
+ self.stdout.write(header_line)
+ self.stdout.write('-' * len(header_line))
+
+ # Print rows
+ for row in rows:
+ self.stdout.write(
+ ' | '.join(
+ str(cell).ljust(w) for cell, w in zip(row, widths)
+ )
+ )
+
+ def print_summary(self, title, data):
+ self.stdout.write(self.style.MIGRATE_HEADING(f"\n{title}"))
+ for key, value in data.items():
+ self.stdout.write(f"{key}: {value}")
+```
+
+### Configuration Management
+
+#### 1. Command Settings
+```python
+from django.conf import settings
+
+class ConfigurationMixin:
+ def get_setting(self, name, default=None):
+ return getattr(
+ settings,
+ f'ACCOUNTING_COMMAND_{name.upper()}',
+ default
+ )
+
+ def load_configuration(self):
+ self.batch_size = self.get_setting('batch_size', 100)
+ self.timeout = self.get_setting('timeout', 3600)
+ self.notification_email = self.get_setting(
+ 'notification_email',
+ 'finance@example.com'
+ )
+```
+
+#### 2. Environment-Specific Configuration
+```python
+class EnvironmentAwareCommand(AccountingCommandBase):
+ def initialize_command(self):
+ self.environment = self.get_environment()
+ self.load_environment_config()
+ self.configure_logging()
+
+ def get_environment(self):
+ return getattr(settings, 'ENVIRONMENT', 'production')
+
+ def load_environment_config(self):
+ config_map = {
+ 'development': {
+ 'validate_strictly': False,
+ 'allow_backdated': True,
+ 'debug_logging': True
+ },
+ 'staging': {
+ 'validate_strictly': True,
+ 'allow_backdated': True,
+ 'debug_logging': True
+ },
+ 'production': {
+ 'validate_strictly': True,
+ 'allow_backdated': False,
+ 'debug_logging': False
+ }
+ }
+ self.config = config_map.get(self.environment, {})
+```
+
+### Command Integration Patterns
+
+#### 1. Command Chaining
+```python
+class ChainedCommandMixin:
+ def execute_chain(self, commands):
+ """Execute a series of commands in sequence"""
+ results = []
+ for cmd_name, cmd_opts in commands:
+ try:
+ result = call_command(cmd_name, **cmd_opts)
+ results.append((cmd_name, True, result))
+ except Exception as e:
+ results.append((cmd_name, False, str(e)))
+ if not self.continue_on_error:
+ raise
+ return results
+```
+
+#### 2. Command Notifications
+```python
+from django.core.mail import send_mail
+
+class NotificationMixin:
+ def notify_completion(self, success, details):
+ subject = f"Command {self.__class__.__name__} "
+ subject += "completed successfully" if success else "failed"
+
+ message = f"Command: {self.__class__.__name__}\n"
+ message += f"Status: {'Success' if success else 'Failed'}\n"
+ message += f"Details:\n{details}"
+
+ send_mail(
+ subject=subject,
+ message=message,
+ from_email=settings.DEFAULT_FROM_EMAIL,
+ recipient_list=[self.notification_email],
+ fail_silently=True
+ )
+```
+
+### Troubleshooting Guidelines
+
+#### 1. Common Issues and Solutions
+
+1. Transaction Failures
+ ```bash
+ # Check transaction logs
+ python manage.py check_transactions --status=failed --period=last-24h
+
+ # Retry failed transactions
+ python manage.py retry_transactions --batch=failed-20231110
+ ```
+
+2. Balance Discrepancies
+ ```bash
+ # Verify account balances
+ python manage.py verify_balances --account-type=all --detailed
+
+ # Find unbalanced transactions
+ python manage.py find_discrepancies --from-date=2023-01-01
+ ```
+
+3. Performance Issues
+ ```bash
+ # Analyze command performance
+ python manage.py analyze_performance --command=reconcile_accounts --period=30d
+
+ # Optimize database operations
+ python manage.py optimize_db --analyze --vacuum
+ ```
+
+#### 2. Debug Mode Operations
+```bash
+# Enable detailed logging
+python manage.py reconcile_accounts --debug --log-level=DEBUG
+
+# Dry run with validation
+python manage.py process_transactions --dry-run --validate-only
+
+# Performance profiling
+python manage.py generate_reports --profile --output-stats
+```
+
+### Best Practices Summary
+
+1. Command Implementation
+ - Follow single responsibility principle
+ - Implement proper error handling
+ - Use atomic transactions
+ - Include comprehensive logging
+ - Add progress indicators
+ - Validate all inputs
+ - Support dry-run mode
+ - Implement proper cleanup
+ - Add command documentation
+ - Include usage examples
+
+2. Data Management
+ - Validate all inputs
+ - Maintain data consistency
+ - Implement proper backups
+ - Handle edge cases
+ - Support rollback operations
+ - Verify data integrity
+ - Track audit trails
+ - Handle concurrent access
+ - Implement data archiving
+ - Manage data retention
+
+3. Performance Optimization
+ - Use batch processing
+ - Implement caching
+ - Optimize database queries
+ - Monitor resource usage
+ - Handle timeouts properly
+ - Use async operations when appropriate
+ - Implement pagination
+ - Profile command execution
+ - Optimize memory usage
+ - Use database indexes effectively
+
+4. Security Considerations
+ - Validate user permissions
+ - Secure sensitive data
+ - Log security events
+ - Implement rate limiting
+ - Follow compliance requirements
+ - Handle sensitive data properly
+ - Implement access controls
+ - Secure configuration data
+ - Monitor command usage
+ - Regular security audits
+
+### Command Versioning and Deprecation
+
+#### 1. Version Management
+```python
+class VersionedCommand(AccountingCommandBase):
+ version = '1.0.0'
+ deprecated = False
+ deprecation_message = None
+
+ def __init__(self):
+ super().__init__()
+ self.check_deprecation()
+
+ def check_deprecation(self):
+ if self.deprecated:
+ warning = f"Warning: {self.__class__.__name__} is deprecated"
+ if self.deprecation_message:
+ warning += f". {self.deprecation_message}"
+ warnings.warn(warning, DeprecationWarning, stacklevel=2)
+```
+
+#### 2. Command Migration
+```python
+class MigratableCommand(VersionedCommand):
+ def handle(self, *args, **options):
+ if self.needs_migration():
+ self.stdout.write(
+ self.style.WARNING(
+ "This command needs migration. "
+ "Please run upgrade_command first."
+ )
+ )
+ return
+
+ self.execute_command(*args, **options)
+
+ def needs_migration(self):
+ return self.get_command_version() < self.version
+
+ def get_command_version(self):
+ # Implementation to get stored command version
+ pass
+```
+
+#### 3. Backward Compatibility
+```python
+class BackwardCompatibleCommand(VersionedCommand):
+ def add_arguments(self, parser):
+ super().add_arguments(parser)
+ # Add new arguments while maintaining backward compatibility
+ parser.add_argument(
+ '--legacy-mode',
+ action='store_true',
+ help='Run command in legacy mode for backward compatibility'
+ )
+
+ def handle(self, *args, **options):
+ if options.get('legacy_mode'):
+ return self.handle_legacy(*args, **options)
+ return self.handle_current(*args, **options)
+```
+
+### Command Maintenance and Lifecycle
+
+#### 1. Command Status Tracking
+```python
+from enum import Enum
+
+class CommandStatus(Enum):
+ ACTIVE = 'active'
+ DEPRECATED = 'deprecated'
+ MAINTENANCE = 'maintenance'
+ BETA = 'beta'
+
+class MaintainableCommand(AccountingCommandBase):
+ status = CommandStatus.ACTIVE
+ maintenance_message = None
+
+ def check_status(self):
+ if self.status != CommandStatus.ACTIVE:
+ message = f"Command status: {self.status.value}"
+ if self.maintenance_message:
+ message += f"\n{self.maintenance_message}"
+ self.stdout.write(self.style.WARNING(message))
+```
+
+#### 2. Command Documentation Updates
+```python
+class DocumentedCommand(AccountingCommandBase):
+ """Base class for commands with automated documentation."""
+
+ def get_documentation(self):
+ """Generate command documentation."""
+ doc = [
+ f"# {self.__class__.__name__}",
+ "",
+ self.__doc__ or "No description available.",
+ "",
+ "## Arguments",
+ ]
+
+ # Document arguments
+ parser = self.create_parser("", self.__class__.__name__)
+ for action in parser._actions:
+ if action.dest != 'help':
+ doc.append(f"* `{action.dest}`: {action.help}")
+
+ # Add examples
+ if hasattr(self, 'examples'):
+ doc.extend(["", "## Examples"])
+ for example in self.examples:
+ doc.extend([
+ f"### {example['description']}",
+ "```bash",
+ example['command'],
+ "```"
+ ])
+
+ return "\n".join(doc)
+```
+
+### Final Notes
+
+#### 1. Command Lifecycle Management
+- Regular review of command usage and performance
+- Deprecation planning for outdated commands
+- Documentation updates for changes
+- Version control and tagging
+- Change notification process
+
+#### 2. Maintenance Procedures
+- Regular code reviews
+- Performance monitoring
+- Security audits
+- Dependency updates
+- Database optimization
+
+#### 3. Support Guidelines
+- Issue tracking process
+- Bug reporting templates
+- Feature request handling
+- User documentation
+- Training materials
+
+#### 4. Quality Assurance
+- Automated testing
+- Code coverage requirements
+- Performance benchmarks
+- Security scanning
+- Compliance checks
+
+#### 5. Deployment Strategy
+- Version control workflow
+- Release planning
+- Rollback procedures
+- Database migrations
+- Configuration management
+
+### External System Integration
+
+#### 1. API Integration
+```python
+class APIIntegratedCommand(AccountingCommandBase):
+ """Base class for commands that interact with external APIs."""
+
+ def setup_api_client(self):
+ self.api_client = ExternalAPIClient(
+ base_url=settings.API_BASE_URL,
+ api_key=settings.API_KEY,
+ timeout=self.get_setting('api_timeout', 30)
+ )
+
+ def handle_api_error(self, error):
+ self.log_audit_event('api_error', {
+ 'error_type': type(error).__name__,
+ 'error_message': str(error)
+ })
+ raise CommandError(f"API Error: {str(error)}")
+```
+
+#### 2. File Export Integration
+```python
+class ExportCommand(AccountingCommandBase):
+ """Base class for export commands."""
+
+ supported_formats = ['csv', 'xlsx', 'pdf']
+
+ def export_data(self, data, format_type):
+ if format_type not in self.supported_formats:
+ raise CommandError(f"Unsupported format: {format_type}")
+
+ exporter = self.get_exporter(format_type)
+ return exporter.export(data)
+
+ def get_exporter(self, format_type):
+ exporters = {
+ 'csv': CSVExporter(),
+ 'xlsx': ExcelExporter(),
+ 'pdf': PDFExporter()
+ }
+ return exporters[format_type]
+```
+
+### Documentation Structure Summary
+
+#### 1. Core Sections
+1. Introduction
+ - Purpose and scope
+ - Module overview
+ - Basic concepts
+
+2. Command Implementation
+ - Base classes
+ - Common patterns
+ - Best practices
+ - Example implementations
+
+3. Data Management
+ - Validation patterns
+ - Consistency checks
+ - Backup procedures
+ - Audit requirements
+
+4. Security and Performance
+ - Security considerations
+ - Performance optimization
+ - Monitoring and logging
+ - Error handling
+
+5. Integration and Deployment
+ - External system integration
+ - Deployment procedures
+ - Version management
+ - Maintenance guidelines
+
+#### 2. Supporting Materials
+1. Code Examples
+ - Implementation samples
+ - Usage patterns
+ - Integration examples
+ - Testing approaches
+
+2. Best Practices
+ - Development guidelines
+ - Security protocols
+ - Performance tips
+ - Maintenance procedures
+
+3. Troubleshooting
+ - Common issues and solutions
+ - Debugging procedures
+ - Error resolution guides
+ - Performance optimization tips
+ - System health checks
+
+4. Reference Materials
+ - Command reference guide
+ - API documentation
+ - Configuration options
+ - Deployment checklist
+ - Security guidelines
+
+### Final Notes
+
+1. Documentation Maintenance
+ - Keep README-AI.md updated
+ - Document all command changes
+ - Include migration guides
+ - Maintain changelog
+ - Update example usage
+
+2. Testing Requirements
+ - Unit test coverage
+ - Integration testing
+ - Performance testing
+ - Security testing
+ - Regression testing
+
+3. Deployment Considerations
+ - Version control
+ - Change management
+ - Rollback procedures
+ - Monitoring setup
+ - Backup strategies
+
+### Conclusion
+
+The accounting management commands documentation provides a comprehensive framework for implementing, maintaining, and extending the accounting functionality in KoalixCRM. Key aspects covered include:
+
+1. Implementation
+ - Structured command development
+ - Best practices and patterns
+ - Error handling and validation
+ - Performance optimization
+
+2. Maintenance
+ - Version control and updates
+ - Testing and quality assurance
+ - Documentation management
+ - Support procedures
+
+3. Integration
+ - External system connectivity
+ - Data import/export
+ - API integration
+ - File handling
+
+4. Security
+ - Access control
+ - Data protection
+ - Audit compliance
+ - Security best practices
+
+For the latest updates and support:
+
+- Project Repository: [GitHub Repository]
+- Documentation: [Project Documentation]
+- Issue Tracker: [Issue Management]
+- Support Channel: [Community Forum]
+
+This documentation is maintained by the KoalixCRM development team and community contributors. Regular updates are made to reflect system changes, new features, and community feedback. Contributors are encouraged to submit improvements and corrections through the project's standard contribution process.
diff --git a/koalixcrm/accounting/migrations/README-AI.md b/koalixcrm/accounting/migrations/README-AI.md
new file mode 100644
index 00000000..66acab83
--- /dev/null
+++ b/koalixcrm/accounting/migrations/README-AI.md
@@ -0,0 +1,368 @@
+# Accounting Migrations Documentation
+
+## 1. Overview of the Migration System
+
+The migrations system in the accounting module manages the evolution of the database schema for KoalixCRM's accounting functionality. It handles the creation and modification of tables related to accounts, bookings, accounting periods, and product categories.
+
+## 2. Chronological List of Migrations
+
+1. `0001_initial.py` (2017-07-05)
+ - Initial setup of core accounting models
+ - Created Account, AccountingPeriod, Booking, and ProductCategorie models
+
+2. `0002_auto_20170705_1702.py` (2017-07-05)
+ - Added relationships between models
+ - Established foreign key connections for bookings
+
+3. `0003_remove_account_originalamount.py` (2017-07-07)
+ - Removed originalAmount field from Account model
+
+4. `0004_auto_20171009_1949.py` (2017-10-09)
+ - Added German translations
+ - Modified model options and field labels
+
+5. `0005_auto_20171110_1732.py` (2017-11-10)
+ - Reverted to English translations
+ - Updated field verbose names
+
+6. `0006_auto_20180422_2048.py` (2018-04-22)
+ - Renamed fields to follow Python naming conventions
+ - Added template_set field to AccountingPeriod
+
+7. `0007_auto_20180422_2105.py` (2018-04-22)
+ - Split template_set into specific template fields
+ - Added profit/loss statement and balance sheet templates
+
+8. `0008_auto_20181012_2056.py` (2018-10-12)
+ - Created new ProductCategory model
+
+9. `0009_auto_20181012_2056.py` (2018-10-12)
+ - Migrated from ProductCategorie to ProductCategory
+ - Updated field names and relationships
+
+10. `0010_auto_20181216_2224.py` (2018-12-16)
+ - Added staff-only restrictions to user fields
+ - Added account type restrictions to profit/loss accounts
+
+11. `0011_auto_20240329_2207.py` (2024-03-29)
+ - Upgraded to BigAutoField for all primary keys
+
+## 3. Significant Schema Changes
+
+### Database Models Evolution
+
+```plantuml
+@startuml
+!theme plain
+skinparam linetype ortho
+
+class Account {
+ + id: BigAutoField
+ + account_number: Integer
+ + title: CharField
+ + account_type: CharField
+ + description: TextField
+ + is_open_reliabilities_account: Boolean
+ + is_open_interest_account: Boolean
+ + is_product_inventory_activa: Boolean
+ + is_a_customer_payment_account: Boolean
+}
+
+class AccountingPeriod {
+ + id: BigAutoField
+ + title: CharField
+ + begin: DateField
+ + end: DateField
+ + template_profit_loss_statement: ForeignKey
+ + template_set_balance_sheet: ForeignKey
+}
+
+class Booking {
+ + id: BigAutoField
+ + amount: DecimalField
+ + description: CharField
+ + booking_date: DateTimeField
+ + date_of_creation: DateTimeField
+ + last_modification: DateTimeField
+}
+
+class ProductCategory {
+ + id: BigAutoField
+ + title: CharField
+ + loss_account: ForeignKey
+ + profit_account: ForeignKey
+}
+
+Booking --> Account: from_account
+Booking --> Account: to_account
+Booking --> AccountingPeriod: accounting_period
+ProductCategory --> Account: loss_account
+ProductCategory --> Account: profit_account
+@enduml
+```
+
+## 4. Dependencies Between Migrations
+
+```plantuml
+@startuml
+!theme plain
+skinparam ranksep 20
+skinparam nodesep 20
+
+[0001_initial] as M1
+[0002_auto_20170705_1702] as M2
+[0003_remove_account_originalamount] as M3
+[0004_auto_20171009_1949] as M4
+[0005_auto_20171110_1732] as M5
+[0006_auto_20180422_2048] as M6
+[0007_auto_20180422_2105] as M7
+[0008_auto_20181012_2056] as M8
+[0009_auto_20181012_2056] as M9
+[0010_auto_20181216_2224] as M10
+[0011_auto_20240329_2207] as M11
+
+M1 --> M2
+M2 --> M3
+M3 --> M4
+M4 --> M5
+M5 --> M6
+M6 --> M7
+M7 --> M8
+M8 --> M9
+M9 --> M10
+M10 --> M11
+@enduml
+```
+
+## 5. Best Practices
+
+### Handling Migrations During Deployment
+
+1. Always backup the database before applying migrations
+2. Run migrations in a staging environment first
+3. Use `python manage.py showmigrations` to verify pending migrations
+4. Apply migrations using `python manage.py migrate accounting`
+5. Verify the application's functionality after migration
+
+### Creating New Migrations
+
+1. Make model changes in models.py
+2. Generate migration file: `python manage.py makemigrations accounting`
+3. Review the generated migration file
+4. Add appropriate documentation comments
+5. Test the migration in a development environment
+
+### Resolving Migration Conflicts
+
+1. Never modify existing migrations in production
+2. Use `python manage.py migrate accounting --fake` when needed
+3. Keep track of migration state in different environments
+4. Use squash migrations for long migration histories
+5. Document any manual intervention required
+
+## 6. Migration Rollback Procedures
+
+### 6.1 Standard Rollback Procedures
+```bash
+# Rollback to specific migration
+python manage.py migrate accounting
+
+# Verify rollback success
+python manage.py showmigrations accounting
+```
+
+### 6.2 Common Rollback Scenarios
+
+#### Account Model Changes (0003, 0010)
+1. Backup affected account data
+2. Rollback to previous migration
+3. Verify account balances and relationships
+4. Update application code to match schema
+5. Run integrity checks on financial data
+
+#### Product Category Migration (0008, 0009)
+1. Export product category mappings
+2. Rollback database schema
+3. Restore previous category relationships
+4. Verify product assignments
+5. Update related inventory records
+
+#### Template Changes (0006, 0007)
+1. Archive existing templates
+2. Rollback template-related changes
+3. Restore previous template configurations
+4. Verify report generation
+5. Update template references
+
+### 6.3 Data Preservation Strategies
+
+```plantuml
+@startuml
+!theme plain
+title Data Preservation Workflow
+
+start
+:Identify Critical Data;
+:Create Full Database Backup;
+:Export Affected Tables;
+:Document Current State;
+fork
+ :Prepare Rollback Scripts;
+fork again
+ :Setup Verification Queries;
+end fork
+:Execute Rollback;
+:Verify Data Integrity;
+:Update Application Code;
+stop
+@enduml
+```
+
+### 6.4 Recovery Procedures
+
+```plantuml
+@startuml
+!theme plain
+title Recovery Decision Tree
+
+if (Migration Failed?) then (yes)
+ if (Data Corruption?) then (yes)
+ :Restore from Backup;
+ :Apply Migrations up to Last Known Good;
+ else (no)
+ :Rollback to Previous Migration;
+ endif
+else (no)
+ if (Performance Issues?) then (yes)
+ :Analyze Query Patterns;
+ :Optimize Indexes;
+ else (no)
+ :Continue Monitoring;
+ endif
+endif
+stop
+@enduml
+```
+
+## 7. Troubleshooting Guide
+
+### 7.1 Common Migration Issues
+
+#### Data Integrity Problems
+- **Symptom**: Inconsistent account balances
+- **Solution**:
+ 1. Run validation queries
+ 2. Compare against backup data
+ 3. Use data fixing migrations
+ 4. Verify transaction history
+
+#### Dependency Conflicts
+- **Symptom**: Migration dependency errors
+- **Solution**:
+ 1. Review migration order
+ 2. Check for circular dependencies
+ 3. Squash conflicting migrations
+ 4. Update dependency chains
+
+#### Performance Issues
+- **Symptom**: Slow migration execution
+- **Solution**:
+ 1. Break large migrations into smaller steps
+ 2. Use database-native operations
+ 3. Schedule during low-traffic periods
+ 4. Monitor resource usage
+
+### 7.2 Emergency Procedures
+
+```plantuml
+@startuml
+!theme plain
+title Emergency Response Workflow
+
+|System Admin|
+start
+:Detect Migration Failure;
+:Stop Application Services;
+
+|Database Admin|
+:Assess Data Integrity;
+if (Data Corrupted?) then (yes)
+ :Restore from Backup;
+else (no)
+ :Execute Rollback Script;
+endif
+
+|System Admin|
+:Update Application Code;
+:Run Verification Tests;
+:Restart Services;
+
+|QA Team|
+:Verify System State;
+:Document Incident;
+stop
+@enduml
+```
+
+## 8. Best Practices
+
+### 8.1 Pre-Rollback Checklist
+1. [ ] Create full database backup
+2. [ ] Document current schema state
+3. [ ] Prepare rollback scripts
+4. [ ] Test rollback in staging
+5. [ ] Notify stakeholders
+6. [ ] Schedule maintenance window
+7. [ ] Prepare verification queries
+8. [ ] Update monitoring alerts
+
+### 8.2 Testing Strategy
+1. Test migrations with production-like data
+2. Verify both forward and backward migrations
+3. Measure performance impact
+4. Test all affected business processes
+5. Validate data integrity post-migration
+
+### 8.3 Communication Protocol
+1. Notify stakeholders of planned changes
+2. Document rollback triggers and criteria
+3. Establish emergency contact procedures
+4. Maintain incident log
+5. Schedule post-migration review
+
+### 8.4 Monitoring Requirements
+1. Track migration progress metrics
+2. Monitor system performance
+3. Set up alerts for critical failures
+4. Log all schema changes
+5. Document verification results
+
+## 9. Additional Considerations
+
+### 9.1 Data Backup Strategy
+1. Implement automated backup procedures
+2. Maintain multiple backup points
+3. Test backup restoration regularly
+4. Document backup locations and procedures
+5. Verify backup integrity before rollbacks
+
+### 9.2 Performance Monitoring
+1. Establish baseline performance metrics
+2. Monitor database load during migrations
+3. Track query execution times
+4. Set up performance alerts
+5. Document performance impact
+
+### 9.3 Security Considerations
+1. Audit access controls post-migration
+2. Verify data encryption status
+3. Update security protocols if needed
+4. Document security changes
+5. Review permission changes
+
+### 9.4 Documentation Requirements
+1. Maintain detailed migration logs
+2. Document all manual interventions
+3. Update system architecture diagrams
+4. Record performance metrics
+5. Document lessons learned
diff --git a/koalixcrm/accounting/rest/README-AI.md b/koalixcrm/accounting/rest/README-AI.md
new file mode 100644
index 00000000..ed20a3bc
--- /dev/null
+++ b/koalixcrm/accounting/rest/README-AI.md
@@ -0,0 +1,550 @@
+# Accounting REST API Documentation
+
+## Introduction
+
+The `accounting/rest` module provides a RESTful API interface for the koalixcrm accounting system. This API allows for managing accounts, bookings, accounting periods, and product categories with full CRUD operations.
+
+## Authentication and Authorization
+
+All API endpoints require authentication using one of the following methods:
+- Session Authentication
+- Basic Authentication
+
+Every request must be made by an authenticated user with appropriate permissions (IsAuthenticated).
+
+### Headers Required
+```
+Authorization: Basic
+HTTP_KOALIXCRM_USER:
+```
+
+## API Endpoints
+
+### 1. Accounts API
+**Endpoint**: `/api/accounting/accounts/`
+**Viewset**: `AccountAsJSON`
+
+#### Available Methods
+- GET (List/Retrieve)
+- POST (Create)
+- PUT (Update)
+- DELETE (Delete)
+
+#### Filter Options
+- `account_type`: Filter accounts by their type
+
+#### Request/Response Format
+```json
+{
+ "id": integer,
+ "accountNumber": integer,
+ "title": string,
+ "accountType": string,
+ "description": string,
+ "isOpenReliabilitiesAccount": boolean,
+ "isOpenInterestAccount": boolean,
+ "isProductInventoryActiva": boolean,
+ "isCustomerPaymentAccount": boolean
+}
+```
+
+### 2. Bookings API
+**Endpoint**: `/api/accounting/bookings/`
+**Viewset**: `BookingAsJSON`
+
+#### Available Methods
+- GET (List/Retrieve)
+- POST (Create)
+- PUT (Update)
+- DELETE (Delete)
+
+#### Request/Response Format
+```json
+{
+ "id": integer,
+ "fromAccount": {
+ "id": integer,
+ "accountNumber": integer,
+ "title": string
+ },
+ "toAccount": {
+ "id": integer,
+ "accountNumber": integer,
+ "title": string
+ },
+ "description": string,
+ "amount": decimal,
+ "bookingDate": "YYYY-MM-DDThh:mm",
+ "staff": {
+ "id": integer,
+ "username": string,
+ "firstName": string,
+ "lastName": string
+ },
+ "bookingReference": string,
+ "accountingPeriod": {
+ "id": integer,
+ "title": string
+ }
+}
+```
+
+### 3. Accounting Periods API
+**Endpoint**: `/api/accounting/periods/`
+**Viewset**: `AccountingPeriodAsJSON`
+
+#### Available Methods
+- GET (List/Retrieve)
+- POST (Create)
+- PUT (Update)
+- DELETE (Delete)
+
+#### Request/Response Format
+```json
+{
+ "id": integer,
+ "title": string,
+ "begin": date,
+ "end": date
+}
+```
+
+### 4. Product Categories API
+**Endpoint**: `/api/accounting/categories/`
+**Viewset**: `ProductCategoryAsJSON`
+
+#### Available Methods
+- GET (List/Retrieve)
+- POST (Create)
+- PUT (Update)
+- DELETE (Delete)
+
+#### Request/Response Format
+```json
+{
+ "id": integer,
+ "title": string,
+ "profitAccount": {
+ "id": integer,
+ "accountNumber": integer,
+ "title": string
+ },
+ "lossAccount": {
+ "id": integer,
+ "accountNumber": integer,
+ "title": string
+ }
+}
+```
+
+## API Flows
+
+### Booking Creation Flow
+```plantuml
+@startuml
+actor Client
+participant "REST API" as API
+participant "BookingJSONSerializer" as Serializer
+participant "Booking Model" as Model
+database Database
+
+Client -> API: POST /api/accounting/bookings/
+API -> Serializer: Validate Request Data
+Serializer -> Serializer: Validate Fields
+Serializer -> Model: Create Booking
+Model -> Database: Save Booking
+Database --> Model: Confirm Save
+Model --> Serializer: Return Booking Object
+Serializer --> API: Return JSON Response
+API --> Client: 201 Created
+@enduml
+```
+
+### Account Management Flow
+```plantuml
+@startuml
+actor Client
+participant "REST API" as API
+participant "AccountJSONSerializer" as Serializer
+participant "Account Model" as Model
+database Database
+
+Client -> API: Request (GET/POST/PUT/DELETE)
+API -> API: Authenticate User
+API -> Serializer: Process Request
+Serializer -> Model: Perform Operation
+Model -> Database: Execute Query
+Database --> Model: Return Result
+Model --> Serializer: Format Response
+Serializer --> API: Return JSON
+API --> Client: Send Response
+@enduml
+```
+
+## Error Handling
+
+### HTTP Status Codes
+- 200: Successful operation
+- 201: Resource created successfully
+- 400: Bad request (validation error)
+- 401: Unauthorized (authentication required)
+- 403: Forbidden (insufficient permissions)
+- 404: Resource not found
+- 500: Internal server error
+
+### Error Response Format
+```json
+{
+ "error": {
+ "code": "string",
+ "message": "string",
+ "details": {
+ "field": "string",
+ "reason": "string"
+ },
+ "timestamp": "ISO-8601 timestamp",
+ "requestId": "string",
+ "locale": "string"
+ }
+}
+```
+
+#### Standard Error Structure
+- `code`: Machine-readable error code
+- `message`: Human-readable error description
+- `details`: Additional error context and field-specific errors
+- `timestamp`: When the error occurred
+- `requestId`: Unique identifier for error tracking
+- `locale`: Language of error messages
+
+#### Error Codes and Meanings
+| Code | Description |
+|------------------------|------------------------------------------------|
+| AUTH_INVALID | Invalid authentication credentials |
+| AUTH_EXPIRED | Authentication token expired |
+| AUTH_MISSING | Missing authentication credentials |
+| PERMISSION_DENIED | Insufficient permissions |
+| VALIDATION_ERROR | Invalid input data |
+| RESOURCE_NOT_FOUND | Requested resource doesn't exist |
+| RESOURCE_CONFLICT | Resource state conflict |
+| SYSTEM_ERROR | Internal server error |
+| RATE_LIMIT_EXCEEDED | Too many requests |
+
+### Error Handling Guidelines
+
+#### Common Error Scenarios
+1. **Authentication Errors**
+ - Invalid credentials
+ - Expired tokens
+ - Missing authentication headers
+
+2. **Validation Errors**
+ - Invalid data formats
+ - Missing required fields
+ - Business rule violations
+
+3. **Resource Errors**
+ - Non-existent resources
+ - Conflicting states
+ - Concurrent modifications
+
+4. **System Errors**
+ - Database connection issues
+ - External service failures
+ - Internal processing errors
+
+#### Error Recovery Procedures
+1. **Client-Side Recovery**
+ - Refresh authentication tokens
+ - Retry with exponential backoff
+ - Clear cached data
+ - User notification and guidance
+
+2. **Rate Limiting Recovery**
+ - Honor Retry-After headers
+ - Implement request queuing
+ - Reduce request frequency
+
+### Error Examples
+
+#### Authentication Error
+```json
+{
+ "error": {
+ "code": "AUTH_INVALID",
+ "message": "Invalid authentication credentials",
+ "details": {
+ "field": "Authorization",
+ "reason": "Invalid token format"
+ },
+ "timestamp": "2023-11-10T12:00:00Z",
+ "requestId": "req-123456",
+ "locale": "en-US"
+ }
+}
+```
+
+#### Validation Error
+```json
+{
+ "error": {
+ "code": "VALIDATION_ERROR",
+ "message": "Invalid booking data",
+ "details": {
+ "amount": "Must be greater than 0",
+ "bookingDate": "Cannot be in the future"
+ },
+ "timestamp": "2023-11-10T12:01:00Z",
+ "requestId": "req-123457",
+ "locale": "en-US"
+ }
+}
+```
+
+#### Business Logic Error
+```json
+{
+ "error": {
+ "code": "RESOURCE_CONFLICT",
+ "message": "Cannot delete account with active bookings",
+ "details": {
+ "accountId": "123",
+ "activeBookings": 5
+ },
+ "timestamp": "2023-11-10T12:02:00Z",
+ "requestId": "req-123458",
+ "locale": "en-US"
+ }
+}
+```
+
+### Error Handling Flow
+```plantuml
+@startuml
+participant Client
+participant "REST API" as API
+participant "Error Handler" as Handler
+participant "Logger" as Logger
+
+Client -> API: Make Request
+activate API
+
+alt Authentication Error
+ API -> Handler: Handle Auth Error
+ Handler -> Logger: Log Error
+ Handler --> Client: Return 401/403 Response
+else Validation Error
+ API -> Handler: Handle Validation Error
+ Handler -> Logger: Log Error
+ Handler --> Client: Return 400 Response
+else Business Logic Error
+ API -> Handler: Handle Business Error
+ Handler -> Logger: Log Error
+ Handler --> Client: Return 409 Response
+else System Error
+ API -> Handler: Handle System Error
+ Handler -> Logger: Log Error
+ Handler --> Client: Return 500 Response
+end
+
+deactivate API
+@enduml
+```
+
+### Error State Transitions
+```plantuml
+@startuml
+[*] --> Request
+
+state Request {
+ [*] --> Validation
+ Validation --> Processing : Valid
+ Validation --> Error : Invalid
+ Processing --> Success : Complete
+ Processing --> Error : Failed
+}
+
+state Error {
+ [*] --> ClientError
+ [*] --> ServerError
+ ClientError --> Retry : Recoverable
+ ClientError --> [*] : Unrecoverable
+ ServerError --> Retry : Temporary
+ ServerError --> [*] : Permanent
+}
+
+state Retry {
+ [*] --> BackoffDelay
+ BackoffDelay --> Request : Retry
+ BackoffDelay --> [*] : Max Retries
+}
+
+Request --> [*] : Success
+Error --> [*] : Final Error
+@enduml
+```
+## Rate Limiting
+
+The API implements standard Django REST framework rate limiting:
+- Authenticated users: 100 requests per hour
+- Unauthenticated users: 20 requests per hour
+
+## Best Practices
+
+1. Always include authentication headers
+2. Use appropriate HTTP methods for operations
+3. Handle pagination for list endpoints
+4. Implement proper error handling
+5. Follow retry strategies for rate limiting
+6. Log and monitor API usage
+7. Validate input data before sending
+8. Handle responses asynchronously when appropriate
+## Integration Examples
+
+### Python Example
+```python
+import requests
+
+# Authentication
+headers = {
+ 'Authorization': 'Basic ',
+ 'HTTP_KOALIXCRM_USER': 'username'
+}
+
+# Create a booking
+booking_data = {
+ "fromAccount": {"id": 1},
+ "toAccount": {"id": 2},
+ "description": "Test booking",
+ "amount": "100.00",
+ "bookingDate": "2023-01-01T10:00",
+ "bookingReference": "REF001",
+ "accountingPeriod": {"id": 1}
+}
+
+response = requests.post(
+ 'http://api/accounting/bookings/',
+ json=booking_data,
+ headers=headers
+)
+
+if response.status_code == 201:
+ print("Booking created successfully")
+ print(response.json())
+```
+
+## API Versioning
+
+Current API version: v1
+Base URL: `/api/v1/accounting/`
+
+Future versions will be implemented using URL versioning:
+- `/api/v2/accounting/`
+- `/api/v3/accounting/`
+
+## Class Diagram
+```plantuml
+@startuml
+class AccountAsJSON {
+ +queryset: Account.objects.all()
+ +serializer_class: AccountJSONSerializer
+ +filter_fields: ['account_type']
+ +dispatch()
+}
+
+class BookingAsJSON {
+ +queryset: Booking.objects.all()
+ +serializer_class: BookingJSONSerializer
+ +dispatch()
+}
+
+class AccountingPeriodAsJSON {
+ +queryset: AccountingPeriod.objects.all()
+ +serializer_class: AccountingPeriodJSONSerializer
+ +dispatch()
+}
+
+class ProductCategoryAsJSON {
+ +queryset: ProductCategory.objects.all()
+ +serializer_class: ProductCategoryJSONSerializer
+ +dispatch()
+}
+
+class AccountJSONSerializer {
+ +accountNumber: IntegerField
+ +accountType: CharField
+ +isOpenReliabilitiesAccount: BooleanField
+ +isOpenInterestAccount: BooleanField
+ +isProductInventoryActiva: BooleanField
+ +isCustomerPaymentAccount: BooleanField
+}
+
+class BookingJSONSerializer {
+ +fromAccount: AccountJSONSerializer
+ +toAccount: AccountJSONSerializer
+ +description: CharField
+ +amount: DecimalField
+ +bookingDate: DateTimeField
+ +bookingReference: CharField
+ +accountingPeriod: AccountingPeriodJSONSerializer
+}
+
+AccountAsJSON --> AccountJSONSerializer
+BookingAsJSON --> BookingJSONSerializer
+AccountingPeriodAsJSON --> AccountingPeriodJSONSerializer
+ProductCategoryAsJSON --> ProductCategoryJSONSerializer
+@enduml
+```
+## Testing the API
+
+To test the API endpoints, you can use tools like:
+- cURL for command-line testing
+- Postman for GUI-based testing
+- Python requests library for automated testing
+
+### Testing Guidelines
+1. Include proper authentication headers
+2. Test all CRUD operations
+3. Verify error responses
+4. Check rate limiting behavior
+5. Validate response formats
+
+### Example Test Cases
+1. Authentication Tests
+ - Test with valid credentials
+ - Test with invalid credentials
+ - Test with expired tokens
+ - Test with missing headers
+
+2. CRUD Operation Tests
+ - Create new resources
+ - Retrieve existing resources
+ - Update existing resources
+ - Delete resources
+ - List resources with pagination
+
+3. Error Handling Tests
+ - Invalid input validation
+ - Resource not found
+ - Permission denied
+ - Rate limit exceeded
+ - Business rule violations
+
+4. Performance Tests
+ - Response times under load
+ - Rate limiting enforcement
+ - Concurrent request handling
+
+## Summary
+
+The koalixcrm Accounting REST API provides a comprehensive interface for managing accounting operations with:
+- Complete CRUD operations for accounts, bookings, periods, and categories
+- Robust error handling with detailed error responses
+- Standard rate limiting and authentication mechanisms
+- Versioned API endpoints for future compatibility
+- Comprehensive testing guidelines and examples
+
+For additional support or questions, refer to:
+- API Documentation: `/api/docs/`
+- Issue Tracker: GitHub repository
+- Support Email: support@koalixcrm.org
diff --git a/koalixcrm/accounting/static/README-AI.md b/koalixcrm/accounting/static/README-AI.md
new file mode 100644
index 00000000..0d3ed474
--- /dev/null
+++ b/koalixcrm/accounting/static/README-AI.md
@@ -0,0 +1,309 @@
+# Accounting Static Templates Documentation
+
+## 1. Introduction
+
+### Purpose of the Folder
+The `static` folder contains XSL templates used for generating financial reports in the koalixcrm accounting module. These templates transform accounting data into professionally formatted PDF documents for balance sheets and profit/loss statements.
+
+### Contents Overview
+- `default_templates/`: Root folder for all report templates
+ - `de/`: German language templates
+ - `balancesheet.xsl`: Balance sheet template (German)
+ - `profitlossstatement.xsl`: Profit/Loss statement template (German)
+ - `en/`: English language templates
+ - `balancesheet.xsl`: Balance sheet template (English)
+ - `profitlossstatement.xsl`: Profit/Loss statement template (English)
+
+## 2. Detailed Template Documentation
+
+### 2.1 Balance Sheet Template (balancesheet.xsl)
+
+#### Purpose
+Generates a formatted balance sheet report showing an organization's assets, liabilities, and equity at a specific point in time.
+
+#### Key Components
+- Page Layout Configuration
+ - A4 format (29.7cm × 21cm)
+ - Margins: top=1.5cm, bottom=1.0cm, left=1.5cm, right=1.5cm
+- Header Section
+ - Company name and report title
+ - Page numbering
+- Data Tables
+ - Assets table with account numbers and values
+ - Liabilities table with account numbers and values
+ - Profit/Loss summary
+
+### 2.2 Profit/Loss Statement Template (profitlossstatement.xsl)
+
+#### Purpose
+Generates a formatted profit and loss statement showing an organization's revenues, costs, and expenses over a specific period.
+
+#### Key Components
+- Page Layout Configuration
+ - A4 format (29.7cm × 21cm)
+ - Margins: top=1.5cm, bottom=0.5cm, left=1.5cm, right=1.5cm
+- Header Section
+ - Company logo integration
+ - Organization name
+ - Report title
+- Data Tables
+ - Profit accounts (Type 'E')
+ - Loss accounts (Type 'S')
+ - Final profit/loss calculation
+
+## 3. Template Customization Guidelines
+
+### 3.1 General Customization Rules
+1. Maintain the XML/XSL structure and namespaces
+2. Preserve the decimal format settings for currency display
+3. Keep the page layout specifications unless specifically needed
+4. Follow the existing table structure for data presentation
+
+### 3.2 Common Customization Points
+1. Company Information
+ - Update header text and titles
+ - Modify logo placement and size
+2. Styling
+ - Adjust font families and sizes
+ - Modify table column widths
+ - Change border styles and colors
+3. Currency Display
+ - Update currency symbol (default: CHF)
+ - Modify number formatting
+
+## 4. Language Support
+
+### 4.1 Available Localizations
+- German (de/)
+ - Full translation of all template text
+ - German number formatting (decimal: , separator: .)
+- English (en/)
+ - Default template language
+ - International number formatting
+
+### 4.2 Adding New Languages
+1. Create a new language folder (e.g., `fr/`)
+2. Copy templates from `en/` folder
+3. Translate all text elements:
+ - Headers and titles
+ - Table column names
+ - Static text content
+4. Update currency formats if needed
+
+## 5. Template Usage Examples
+
+### 5.1 Balance Sheet Implementation
+```xml
+
+
+ Balanancesheet of "Your Company Name"
+
+```
+
+### 5.2 Profit/Loss Statement Implementation
+```xml
+
+
+
+
+
+
+```
+
+## 6. Best Practices
+
+### 6.1 Template Modification
+- Always backup original templates before modifications
+- Test changes with various data scenarios
+- Maintain consistent styling across all templates
+- Document any custom modifications
+
+### 6.2 Performance Considerations
+- Optimize image sizes for headers/logos
+- Minimize custom fonts usage
+- Keep conditional statements efficient
+
+## 7. Troubleshooting
+
+### 7.1 Common Issues and Solutions
+1. Missing Data
+ - Verify XML data structure matches template expectations
+ - Check account type classifications (A, L, E, S)
+ - Ensure all required fields are present in the data source
+
+2. Formatting Issues
+ - Validate decimal format settings
+ - Check font availability (BitstreamVeraSans)
+ - Verify table column width calculations
+ - Ensure proper XML/XSL namespace declarations
+
+3. Language Problems
+ - Ensure correct template folder selection
+ - Verify text encoding (UTF-8)
+ - Check language-specific number formatting
+
+### 7.2 Debug Tips
+- Use XML validator tools to check input data
+- Test templates with minimal dataset first
+- Check XSL-FO processor logs for detailed error messages
+
+### 8.1 Dependencies
+- XSL-FO processor compatible with XSL 1.0
+- BitstreamVeraSans font family
+- XML data source with proper structure
+- XSLT 1.0 compatible processor
+
+### 8.2 Data Requirements
+- Account Data:
+ - account_number (String)
+ - account_type (A: Assets, L: Liabilities, E: Earnings, S: Spending)
+ - title (String)
+ - sum_of_all_bookings_through_now (Decimal)
+
+- Organization Data:
+ - name (String)
+ - logo_path (String)
+ - currency_format (String)
+
+### 8.3 Output Specifications
+- Format: PDF
+- Page Size: A4 (210mm × 297mm)
+- Color Space: RGB
+- Font Requirements: BitstreamVeraSans (regular, bold)
+- Minimum Resolution: 300 DPI for logos
+
+## 9. Template Validation Process
+
+### 9.1 Validation Tools and Methods
+```plantuml
+@startuml
+start
+:XML Schema Validation;
+:XSL Syntax Check;
+:FO Output Validation;
+:PDF Generation Test;
+stop
+@enduml
+```
+
+#### Schema Validation
+- XML Schema (XSD) validation for input data
+- XSLT stylesheet syntax validation
+- FO output structure validation
+- PDF output compliance checking
+
+#### Validation Tools
+- xmllint for XML/XSD validation
+- Saxon XSLT processor for stylesheet validation
+- Apache FOP validator for FO output
+- PDF/A compliance checker
+
+### 9.2 Common Validation Errors
+1. Schema Validation Errors
+ - Invalid account types
+ - Missing required fields
+ - Incorrect data types
+2. XSL Syntax Errors
+ - Namespace issues
+ - Template matching problems
+ - Function usage errors
+3. FO Output Errors
+ - Invalid formatting objects
+ - Layout conflicts
+ - Region overflow issues
+
+## 10. Testing Procedures
+
+### 10.1 Unit Testing Templates
+```plantuml
+@startuml
+rectangle "Unit Tests" {
+ [Input Data Tests]
+ [XSL Transform Tests]
+ [Output Format Tests]
+}
+[Input Data Tests] --> [XSL Transform Tests]
+[XSL Transform Tests] --> [Output Format Tests]
+@enduml
+```
+
+#### Test Cases
+1. Input Validation
+ - Valid/invalid account numbers
+ - Currency format variations
+ - Special character handling
+2. Transformation Tests
+ - Template variable processing
+ - Calculation accuracy
+ - Language-specific formatting
+
+### 10.2 Integration Testing
+```plantuml
+@startuml
+node "Integration Tests" {
+ [Template Processing]
+ [PDF Generation]
+ [System Integration]
+}
+[Template Processing] --> [PDF Generation]
+[PDF Generation] --> [System Integration]
+@enduml
+```
+
+#### Test Scenarios
+1. End-to-End Processing
+ - Complete report generation
+ - Multi-language support
+ - System integration points
+
+### 10.3 Performance Testing
+- Template processing time
+- Memory usage monitoring
+- Large dataset handling
+- Concurrent processing capability
+
+## 11. Troubleshooting Guide
+
+### 11.1 Debug Procedures
+```plantuml
+@startuml
+start
+:Check Input Data;
+if (Valid XML?) then (yes)
+ :Validate XSL;
+ if (Valid XSL?) then (yes)
+ :Check FO Output;
+ if (Valid FO?) then (yes)
+ :Verify PDF;
+ else (no)
+ :Fix FO Issues;
+ endif
+ else (no)
+ :Fix XSL Issues;
+ endif
+else (no)
+ :Fix Input Data;
+endif
+stop
+@enduml
+```
+
+### 11.2 Common Template Issues
+1. Performance Problems
+ - Template optimization techniques
+ - Resource usage reduction
+ - Caching strategies
+2. Browser Compatibility
+ - PDF viewer compatibility
+ - Font rendering issues
+ - Print formatting problems
+
+### 11.3 Error Resolution Steps
+1. Systematic Debugging
+ - Input data verification
+ - XSL transformation logging
+ - Output validation checks
+2. Performance Optimization
+ - Template simplification
+ - Resource optimization
+ - Cache implementation
diff --git a/koalixcrm/accounting/tests/README-AI.md b/koalixcrm/accounting/tests/README-AI.md
new file mode 100644
index 00000000..2c31d2dd
--- /dev/null
+++ b/koalixcrm/accounting/tests/README-AI.md
@@ -0,0 +1,344 @@
+# Accounting Tests Documentation
+
+## 1. Overview
+The accounting tests verify the functionality of KoalixCRM's accounting module, focusing on account management, bookings, and accounting period calculations. The tests use Django's TestCase framework for database-driven testing.
+
+## 2. Test Structure
+
+### 2.1 Files
+- `__init__.py`: Package initialization file
+- `test_accountingModelTest.py`: Main test suite for accounting models
+
+### 2.2 Test Coverage
+The test suite covers:
+- Account balance calculations
+- Accounting period operations
+- Booking transactions
+- XML serialization for reporting
+
+## 3. Test Setup and Data Model
+
+### 3.1 Class Structure
+```plantuml
+@startuml
+class AccountingModelTest {
+ + setUp()
+ + test_sumOfAllBookings()
+ + test_sumOfAllBookingsBeforeAccountPeriod()
+ + test_sumOfAllBookingsWithinAccountgPeriod()
+ + test_overall_liabilities()
+ + test_overall_assets()
+ + test_overall_earnings()
+ + test_overall_spendings()
+ + test_serialize_to_xml()
+}
+
+class TestData {
+ + User
+ + Accounts
+ + AccountingPeriods
+ + Bookings
+}
+
+AccountingModelTest --> TestData: creates
+@enduml
+```
+
+### 3.2 Data Model
+```plantuml
+@startuml
+class Account {
+ + account_number: String
+ + title: String
+ + account_type: String
+ + description: String
+ + is_open_interest_account: Boolean
+ + is_open_reliabilities_account: Boolean
+ + is_product_inventory_activa: Boolean
+ + is_a_customer_payment_account: Boolean
+}
+
+class AccountingPeriod {
+ + title: String
+ + begin: Date
+ + end: Date
+}
+
+class Booking {
+ + from_account: Account
+ + to_account: Account
+ + amount: Decimal
+ + description: String
+ + booking_date: DateTime
+ + accounting_period: AccountingPeriod
+ + staff: User
+ + last_modified_by: User
+}
+
+Booking --> Account: from_account
+Booking --> Account: to_account
+Booking --> AccountingPeriod
+@enduml
+```
+
+### 3.3 Test Flow
+```plantuml
+@startuml
+title Booking Test Flow
+
+participant TestCase
+participant Account
+participant Booking
+participant AccountingPeriod
+
+TestCase -> Account: create accounts\n(cash, bank, etc.)
+TestCase -> AccountingPeriod: create periods\n(2024-2026)
+TestCase -> Booking: create test bookings
+
+group Test Balance Calculation
+ TestCase -> Account: sum_of_all_bookings()
+ Account --> TestCase: return total balance
+ TestCase -> Account: verify balance matches\nexpected amount
+end
+
+group Test Period Calculations
+ TestCase -> AccountingPeriod: overall_assets()
+ AccountingPeriod -> Account: get all asset accounts
+ Account --> AccountingPeriod: return accounts
+ AccountingPeriod -> Booking: get relevant bookings
+ Booking --> AccountingPeriod: return bookings
+ AccountingPeriod --> TestCase: return calculated total
+ TestCase -> TestCase: verify amount
+end
+
+group Test XML Export
+ TestCase -> AccountingPeriod: serialize_to_xml()
+ AccountingPeriod -> Account: get account data
+ Account --> AccountingPeriod: return data
+ AccountingPeriod -> Booking: get booking data
+ Booking --> AccountingPeriod: return data
+ AccountingPeriod --> TestCase: return XML
+ TestCase -> TestCase: verify XML structure
+end
+@enduml
+```
+
+## 4. Test Cases
+
+### 4.1 Account Balance Tests
+- `test_sumOfAllBookings`: Verifies correct calculation of total account balances
+- `test_sumOfAllBookingsBeforeAccountPeriod`: Tests balance calculations before specific accounting periods
+- `test_sumOfAllBookingsWithinAccountgPeriod`: Validates balance calculations within accounting periods
+
+### 4.2 Accounting Period Tests
+- `test_overall_liabilities`: Validates total liabilities calculation
+- `test_overall_assets`: Verifies total assets calculation
+- `test_overall_earnings`: Tests earnings calculation
+- `test_overall_spendings`: Validates spending calculations
+
+### 4.3 Data Export Tests
+- `test_serialize_to_xml`: Ensures correct XML serialization of accounting data
+
+## 5. Test Data Setup
+
+### 5.1 Accounts
+- Cash (1000): Asset account for cash transactions
+- Bank Account (1300): Asset account for bank transactions
+- Bank Loan (2000): Liability account for short-term loans
+- Investment Capital (2900): Liability account for long-term investment
+- Spendings (3000): Spending account for purchases
+- Earnings (4000): Earnings account for sales
+
+### 5.2 Accounting Periods
+- Fiscal year 2024: January 1, 2024 - December 31, 2024
+- Fiscal year 2025: January 1, 2025 - December 31, 2025
+- Fiscal year 2026: January 1, 2026 - December 31, 2026
+
+### 5.3 Test Data Relationships
+- Each booking connects two accounts (from_account and to_account)
+- Bookings are assigned to specific accounting periods
+- User records are maintained for staff and modification tracking
+- Account types determine their role in financial calculations
+
+## 6. Running Tests
+```bash
+python manage.py test koalixcrm.accounting.tests
+```
+
+## 7. Writing New Tests
+1. Follow the existing pattern in `test_accountingModelTest.py`
+2. Add test data in the `setUp` method if needed
+3. Ensure proper cleanup in `tearDown` if necessary
+4. Use descriptive test names that reflect the functionality being tested
+5. Include assertions that verify both positive and negative cases
+
+## 8. Test Dependencies
+
+### 8.1 Required Models
+- Django User model
+- Account model
+- AccountingPeriod model
+- Booking model
+- PDFExport utility
+
+### 8.2 External Dependencies
+- Django TestCase framework
+- datetime module
+- make_date_utc utility function
+
+### 8.3 Database Requirements
+- Test database with transaction support
+- Proper migration setup
+- Configured Django settings
+
+## 9. Performance Considerations
+
+1. **Test Data Volume**
+ - Current test suite uses minimal test data
+ - Consider adding volume tests for performance validation
+ - Monitor database query count
+## 10. Test Isolation
+
+### 10.1 Database Isolation
+- Uses Django's TestCase which provides automatic transaction rollback
+- Each test method runs in its own transaction
+- Database is reset to a clean state between tests
+- Test data is isolated through Django's test database creation
+
+### 10.2 Fixture Management
+- Test data is created in setUp() method for each test run
+- Uses direct object creation instead of fixtures for better control
+- Consistent initial state for all test methods
+- Hierarchical data setup (User -> Accounts -> Periods -> Bookings)
+
+### 10.3 Test Data Separation
+```plantuml
+@startuml
+title Test Data Isolation Pattern
+
+participant TestCase
+database TestDB
+participant Transaction
+
+TestCase -> TestDB: Begin Test
+activate Transaction
+
+group Setup Phase
+ TestCase -> TestDB: Create User
+ TestCase -> TestDB: Create Accounts
+ TestCase -> TestDB: Create Periods
+ TestCase -> TestDB: Create Bookings
+end
+
+group Test Execution
+ TestCase -> TestDB: Run Test Method
+ TestCase -> TestDB: Verify Results
+end
+
+TestCase -> Transaction: Rollback
+deactivate Transaction
+
+TestCase -> TestDB: Next Test
+@enduml
+```
+
+### 10.4 Resource Management
+1. **Database Connections**
+ - Managed by Django's test framework
+ - Automatic cleanup after each test
+ - Separate test database per test run
+
+2. **Test Data Lifecycle**
+ ```plantuml
+ @startuml
+ title Test Data Lifecycle
+
+ state "Test Start" as Start
+ state "Setup Data" as Setup
+ state "Execute Test" as Execute
+ state "Verify Results" as Verify
+ state "Cleanup" as Cleanup
+
+ Start --> Setup
+ Setup --> Execute
+ Execute --> Verify
+ Verify --> Cleanup
+ Cleanup --> [*]
+ @enduml
+ ```
+
+### 10.5 Common Issues and Solutions
+1. **Data Leakage Prevention**
+ - Use unique identifiers for test data
+ - Avoid global state modifications
+ - Maintain data independence between tests
+
+2. **Resource Contention**
+ - Each test uses isolated database transactions
+ - No shared state between test methods
+ - Clean setup/teardown cycle
+
+3. **Test Independence**
+ - Each test method is self-contained
+ - No dependencies between test methods
+ - Explicit test data creation
+
+### 10.6 Best Practices
+1. **Setting Up Test Environment**
+ - Use setUp() for common test data
+ - Create only necessary test data
+ - Maintain data consistency
+
+2. **Managing Dependencies**
+ - Explicit dependency creation in setUp
+ - Clear separation of test scenarios
+ - Avoid cross-test dependencies
+
+3. **Data Cleanup**
+ - Automatic transaction rollback
+ - No manual cleanup needed
+ - Consistent database state
+
+4. **Parallel Execution**
+ - Tests designed for parallel execution
+ - No shared resource conflicts
+ - Independent test methods
+
+### 10.7 Debugging Isolation Issues
+1. **Common Problems**
+ - Data bleeding between tests
+ - Inconsistent test results
+ - Resource cleanup failures
+
+2. **Solutions**
+ - Verify setUp method completeness
+ - Check for shared state
+ - Monitor database transactions
+ - Use proper test case inheritance
+
+### 10.8 Test Isolation Patterns
+```plantuml
+@startuml
+title Test Isolation Patterns
+
+package "Test Environment" {
+ [Test Database] as DB
+ [Transaction Manager] as TM
+ [Test Runner] as TR
+}
+
+cloud "Isolated Resources" {
+ [Test Case 1] as TC1
+ [Test Case 2] as TC2
+}
+
+DB -- TM
+TM -- TR
+TR -- TC1
+TR -- TC2
+
+note right of TC1: Independent\nTransaction
+note right of TC2: Independent\nTransaction
+note bottom of TM: Manages Rollbacks
+@enduml
+```
diff --git a/koalixcrm/version.py b/koalixcrm/version.py
index 87fda557..8c5e6707 100644
--- a/koalixcrm/version.py
+++ b/koalixcrm/version.py
@@ -1,3 +1 @@
-# -*- coding: utf-8 -*-
-
-KOALIXCRM_VERSION = "1.13.0"
\ No newline at end of file
+KOALIXCRM_VERSION = "1.14.1"
diff --git a/projectsettings/dashboard.py b/projectsettings/dashboard.py
index ada1d9a2..c55727d9 100644
--- a/projectsettings/dashboard.py
+++ b/projectsettings/dashboard.py
@@ -8,7 +8,6 @@
from django.utils.translation import gettext_lazy as _
from grappelli.dashboard import modules, Dashboard
-from grappelli.dashboard.utils import get_admin_site_name
from koalixcrm.version import KOALIXCRM_VERSION
@@ -19,7 +18,7 @@ class CustomIndexDashboard(Dashboard):
def init_with_context(self, context):
self.children.append(modules.Group(
- _('koalixcrm Version' + KOALIXCRM_VERSION),
+ _('koalixcrm Version ' + KOALIXCRM_VERSION),
column=1,
collapsible=True,
children=[
diff --git a/projectsettings/settings/base_settings.py b/projectsettings/settings/base_settings.py
index df5e6191..f60a8c0f 100644
--- a/projectsettings/settings/base_settings.py
+++ b/projectsettings/settings/base_settings.py
@@ -94,7 +94,7 @@
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_URL = "/media/"
-MEDIA_ROOT = os.path.join(BASE_DIR)
+MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
PROJECT_ROOT = BASE_DIR
@@ -102,7 +102,7 @@
PDF_OUTPUT_ROOT = os.path.join(STATIC_ROOT, 'pdf')
# Settings specific for filebrowser
-FILEBROWSER_DIRECTORY = 'media/uploads/'
+FILEBROWSER_DIRECTORY = 'uploads/'
FILEBROWSER_EXTENSIONS = {
'XML': ['.xml'],
'XSL': ['.xsl'],
diff --git a/projectsettings/settings/production_docker_postgres_settings.py b/projectsettings/settings/production_docker_postgres_settings.py
deleted file mode 100644
index 6c00a291..00000000
--- a/projectsettings/settings/production_docker_postgres_settings.py
+++ /dev/null
@@ -1,29 +0,0 @@
-"""
-Django settings for koalixcrm project when used in productive environment.
-"""
-
-from .base_settings import *
-
-SECRET_KEY = os.environ.get("SECRET_KEY")
-
-DEBUG = bool(os.environ.get("DEBUG", default=0))
-
-# 'DJANGO_ALLOWED_HOSTS' should be a single string of hosts with a space between each.
-# For example: 'DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1]'
-ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS").split(" ")
-
-DATABASES = {
- "default": {
- "ENGINE": os.environ.get("SQL_ENGINE", "django.db.backends.postgresql"),
- "NAME": os.environ.get("SQL_DATABASE", BASE_DIR / "postgres"),
- "USER": os.environ.get("SQL_USER", "postgres"),
- "PASSWORD": os.environ.get("SQL_PASSWORD", "password"),
- "HOST": os.environ.get("SQL_HOST", "localhost"),
- "PORT": os.environ.get("SQL_PORT", "5432"),
- }
-}
-
-FOP_EXECUTABLE = "/usr/bin/fop-2.2/fop/fop"
-GRAPPELLI_INDEX_DASHBOARD = 'projectsettings.dashboard.CustomIndexDashboard'
-FILEBROWSER_CONVERT_FILENAME = False
-KOALIXCRM_REST_API_AUTH = True
\ No newline at end of file
diff --git a/projectsettings/wsgi.py b/projectsettings/wsgi.py
index 63759196..45a8ef94 100644
--- a/projectsettings/wsgi.py
+++ b/projectsettings/wsgi.py
@@ -1,16 +1,19 @@
"""
-WSGI config for test_koalixcrm project.
+WSGI config for koalixcrm project.
-It exposes the WSGI callable as a module-level variable named ``application``.
+This module contains the WSGI application used by Django's development server
+and any production WSGI deployments. It should expose a module-level variable
+named `application`. Django's `runserver` and `runfcgi` commands discover
+this application via the `WSGI_APPLICATION` setting.
-For more information on this file, see
-https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
+Usually this will be called "koalixcrm.wsgi".
"""
import os
-
from django.core.wsgi import get_wsgi_application
-os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_koalixcrm.settings")
+# The settings module that Django uses. By convention, it is usually in the form "myproject.settings.production"
+os.environ.setdefault("DJANGO_SETTINGS_MODULE",
+ "koalixcrm.projectsettings.settings.production_docker_postgres_settings")
-application = get_wsgi_application()
+application = get_wsgi_application()
\ No newline at end of file
diff --git a/requirements.txt b/requirements.txt
index 57320cb1..7e257ad0 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1 +1 @@
--r requirements/prod_requirements.txt
\ No newline at end of file
+-r requirements/development_requirements.txt
\ No newline at end of file
diff --git a/requirements/development_requirements.txt b/requirements/development_requirements.txt
index 9d379932..ccb07f16 100644
--- a/requirements/development_requirements.txt
+++ b/requirements/development_requirements.txt
@@ -1,9 +1,9 @@
-Django==3.2.20
+Django==3.2.25
django-filebrowser==3.14.3
lxml==5.1.0
olefile==0.46
-Pillow==7.1.2
-psycopg2-binary==2.8.4
+Pillow==10.3.0
+psycopg2-binary==2.9.9
pytz==2022.4
django-grappelli==2.15.7
djangorestframework==3.14.0
diff --git a/requirements/prod_requirements.txt b/requirements/prod_requirements.txt
deleted file mode 100644
index 625cc8c5..00000000
--- a/requirements/prod_requirements.txt
+++ /dev/null
@@ -1,14 +0,0 @@
-Django==3.2.20
-django-filebrowser==3.14.3
-lxml==5.1.0
-olefile==0.46
-Pillow==7.1.2
-psycopg2-binary==2.8.4
-pytz==2022.4
-django-grappelli==2.15.7
-djangorestframework==3.14.0
-djangorestframework-xml==2.0.0
-markdown==3.1.1
-django-filter==23.5
-pandas==1.5.3
-matplotlib==3.7.5
diff --git a/setup.py b/setup.py
index f54c09c2..a05d38d9 100644
--- a/setup.py
+++ b/setup.py
@@ -19,8 +19,8 @@
'django-filebrowser==3.14.3',
'lxml==5.1.0',
'olefile==0.46',
- "Pillow==10.2.0",
- 'psycopg2-binary==2.8.4',
+ "Pillow==10.3.0",
+ 'psycopg2-binary==2.9.9',
'pytz==2022.4',
'django-grappelli==2.15.7',
'djangorestframework==3.14.0',