A production-grade Domain-Driven Design desktop application for automating billing operations, contract management, and document generation. Built with Clean Architecture, featuring Excel-based persistence, template-driven document generation, and a modern Tkinter UI.
- Overview
- Architecture
- Technology Stack
- Project Structure
- Key Features
- Getting Started
- Development
- Design Patterns
- Configuration
This system solves the complex domain of recurring revenue management with the following capabilities:
- Automated Monthly Billing: Generate invoices combining fixed recurring fees + variable consumption charges
- Contract Lifecycle Management: Active/inactive status, billing frequency (monthly/quarterly/annual), prorrogation, and rescission tracking
- Document Generation Pipeline: Template-driven DOCX invoice generation with automatic placeholder substitution and consumption item aggregation
- Batch Processing: Generate billing for multiple contracts in a single operation with centralized error handling
- Occupancy Tracking: Visual grid-based management of allocated/unallocated resource slots
- Consumption Tracking: Date-stamped product consumption with historical pricing preservation
Managing recurring billing with mixed pricing models (fixed + variable) across multiple contracts, generating compliant documents, and maintaining accurate consumption tracking—all without enterprise databases or ERPs.
Solution: Desktop application with domain-driven design principles ensuring business rules are enforced at the entity level, not scattered across UI or persistence logic.
src/core/
├── domain/ 🎯 CORE BUSINESS LOGIC
│ ├── entities/ Aggregates: Contract, Client, Invoice, ConsumptionItem
│ ├── value_objects/ Strong types: Currency, DateISO, CPF, Email, etc.
│ └── (zero external dependencies)
│
├── application/ 🔄 USE CASE ORCHESTRATION
│ ├── use_cases/ Business workflow implementations
│ ├── protocols/ IUnitOfWork, IRepository abstractions
│ ├── interfaces/ IDocumentWriter, IDocumentService abstractions
│ ├── dtos/ Data transfer objects (I/O contracts)
│ └── exceptions/ ApplicationException hierarchy
│
└── infra/ 🔧 EXTERNAL FRAMEWORKS & TOOLS
├── excel/ Excel persistence adapters & repositories
├── documentos/ DOCX template filling & document operations
├── interface/ Tkinter UI orchestration & components
└── servicos/ Document conversion & external services
-
Dependency Inversion: Application layer defines interfaces; infrastructure implements them
IRepositorioContratoabstraction allows swapping Excel → SQL databaseIEscritorDocumentoabstraction supports multiple document formats
-
Entity Aggregates:
Contrato(Contract) as root aggregate- Enforces contract lifecycle rules
- Guards billing period constraints
- Validates associated items (clients, consumption)
-
Value Objects: Immutable, self-validating types prevent invalid entity state
ValorMonetario(Monetary) with arithmetic operations and formattingDataISO(ISO Date) with period calculationsPeriodicidadePlano(Billing Frequency) enum preventing invalid statesPeriodoContrato(Contract Period) with automatic calculations
-
Unit of Work Pattern:
UnitOfWorkExcelcoordinates multiple repositories with shared adapters- Single point for transaction management
- Consistency across related entities
-
DTO Boundaries: Separate input/output contracts from domain entities
CobrancaGeracaoDTOfor invoice generation requestsRelatorioEmissaoCobrancasDTOfor batch operation results
-
Strategy Pattern: Pluggable implementations for extensibility
- Document writers for different formats (DOCX, PDF, etc.)
- Repository implementations (Excel, future: SQL, NoSQL)
| Layer | Technology | Purpose |
|---|---|---|
| Core | Python 3.8+ | Language |
| Architecture | Clean Architecture + DDD | Design patterns |
| Type Safety | Pydantic v2 | Value object validation & immutability |
| Data Access | pandas, openpyxl | Excel I/O & data manipulation |
| Document Generation | python-docx | DOCX template manipulation |
| UI Framework | Tkinter | Native cross-platform desktop GUI |
| Configuration | python-dotenv | Environment-based settings |
| Code Quality | black, isort, mypy | Formatting & type checking |
| Testing | pytest, pytest-cov | Unit tests & coverage |
| Utilities | requests, phonenumbers | HTTP & phone validation |
| Packaging | PyInstaller | Standalone executable bundling |
[dependencies]
pydantic = "2.12.3" # Strong typing & validation
pandas = "2.3.3" # Data manipulation
openpyxl = "3.1.0" # Excel I/O
python-docx = "1.2.0" # Document generation
python-dotenv = "1.0.1" # Environment configuration
click = "8.3.0" # CLI support
requests = "2.31.0" # HTTP client
phonenumbers = "8.13.0" # Phone validation.
├── src/
│ ├── config/ # Application configuration
│ │ ├── configuracao_ambiente.py # Platform-aware paths (Windows/Linux)
│ │ └── configuracao_documentos.py # Service factories & DI
│ │
│ └── core/
│ ├── domain/ # Business logic (no frameworks)
│ │ ├── entities/
│ │ │ ├── contrato.py # Contract aggregate root
│ │ │ ├── cliente.py # Client entity
│ │ │ ├── cobranca.py # Invoice entity
│ │ │ └── item_consumo.py # Line item entity
│ │ │
│ │ └── value_objects/ # Strong types (14 value objects)
│ │ ├── valor_monetario.py
│ │ ├── data_iso.py
│ │ ├── periodo_contrato.py
│ │ ├── periodicidade_plano.py
│ │ ├── cpf.py, email.py, telefone.py
│ │ └── ...
│ │
│ ├── application/ # Use cases & orchestration
│ │ ├── use_cases/
│ │ │ ├── cobrancas/ # Billing use cases
│ │ │ └── mapa_cabines/ # Occupancy use cases
│ │ │
│ │ ├── protocols/ # Abstractions
│ │ │ ├── repositorio_contrato.py
│ │ │ ├── repositorio_cliente.py
│ │ │ ├── unit_of_work.py
│ │ │ └── ...
│ │ │
│ │ ├── interfaces/ # Service abstractions
│ │ │ ├── servico_documento.py
│ │ │ ├── escritor_documento.py
│ │ │ └── adaptador_planilha.py
│ │ │
│ │ ├── dtos/ # Transfer objects
│ │ │ └── relatorio_emissao_cobrancas_dto.py
│ │ │
│ │ └── exceptions.py # Application exceptions
│ │
│ └── infra/ # External frameworks
│ ├── excel/ # Excel persistence layer
│ │ ├── repositorios/ # Repository implementations
│ │ ├── mapeadores/ # Entity ↔ Row mappers
│ │ ├── adaptadores/ # pandas/openpyxl wrappers
│ │ └── uow/ # Unit of Work Excel implementation
│ │
│ ├── documentos/ # Document generation
│ │ ├── gerador_cobranca_docx.py
│ │ ├── configuracao_template_cobranca_docx.py
│ │ └── servico_geracao_cobranca_docx.py
│ │
│ ├── interface/ # Tkinter UI
│ │ ├── aplicacao_sistema_gestao.py # Main window
│ │ ├── aba_cobrancas.py # Billing tab
│ │ ├── aba_mapa_de_cabines.py # Occupancy tab
│ │ ├── adaptador_tkinter.py # Widget factory
│ │ └── configuracao_visual_cabines.py # Grid renderer
│ │
│ └── servicos/ # External services
│ └── conversao_cobranca.py # Document conversion
│
├── tests/unit/ # Unit tests mirroring src structure
│ └── core/
│ ├── application/
│ ├── domain/
│ └── ...
│
├── scripts/ # Utility scripts
│ └── script_gerar_docx_para_cada_contrato_com_itens_bomboniere.py
│
├── pyproject.toml # Project metadata & tool config
├── requirements.txt # Production dependencies
├── requirements-dev.txt # Development dependencies
└── README.md # This file
Generates monthly invoices combining:
- Fixed recurring fees (configurable by billing frequency)
- Variable consumption items (with date-stamped pricing)
- Automatic due date calculation
- Duplicate prevention (idempotent operations)
# Use case orchestration
use_case = GerarCobrancaMensalUseCase(uow)
cobranca_dto = use_case.executar(
numero_contrato=12,
mes=5,
ano=2024
)Business Logic Examples:
- Monthly contracts exclude "mensalidade" charges (consumption-only)
- Periodic contracts require active status for billing eligibility
- Contract periods enforce valid billing windows
- Duplicate invoices prevented by existence checks
Generates professional DOCX invoices via template substitution:
- Placeholder-based design (
<cliente_nome>,<valor_total>, etc.) - Dynamic consumption item table generation
- Configurable fonts, spacing, formatting
- Support for multiple template versions
# Document generation
servico_documento.gerar_cobranca_docx(
cobranca=cobranca_entity,
cliente=cliente_entity,
caminho_arquivo_saida="path/cobranca_2024_05.docx"
)Features:
- Itens table with date, description, quantity, unit price, total
- Format preservation from template
- Error handling for missing template fields
Generate invoices for all active contracts in a single month:
- Parallel processing with centralized error collection
- Progress tracking (published to UI)
- Comprehensive reports (generated/failed/skipped)
- Transaction-like consistency (all-or-nothing semantics)
# Batch operation
handler = EmitirCobrancasContratosAtivosHandler(uow)
resultado = handler.executar(mes=5, ano=2024)
# Returns: RelatorioEmissaoCobrancasDTO with counts & errorsProduction data stored in structured Excel workbooks:
- acompanhamento.xlsx: Master data (contracts, clients, invoices)
- itens_consumo/{YYYY}.xlsx: Monthly consumption tracking
- Platform-aware paths (Windows: Documents folder, Linux: ~/.gestao_cobrancas)
- Upsert semantics (update existing records, insert new)
Data Flow:
Excel sheets → pandas DataFrames → Domain entities
(validation)
Domain entities → dicts → pandas DataFrames → Excel sheets
Track contract states across their lifetime:
- Ativa (Active): Eligible for billing
- Inativa (Inactive): Excluded from batch generation
- Prorrogada (Extended): Updated end date with lifecycle rules
- Rescindida (Terminated): Early termination with cutoff date
Business rules enforced at entity level:
# Billing eligibility validation
if not contrato.ativo:
raise ContratoInativoException()
if not contrato.periodo.pode_gerar_cobranca(mes, ano):
raise PeriodoDeGeracaoInvalidoException()Date-stamped product consumption across billing periods:
- Per-contract, per-month aggregation
- Historical pricing preservation (retroactive price changes don't affect past items)
- Subtotal calculation with tax awareness
- Supports multiple product types
Visual grid interface for resource allocation:
- Live occupancy status display
- Allocation/deallocation tracking
- Status indicators (occupied/available)
- Batch update capabilities
Single codebase supports Windows and Linux:
- Platform-aware configuration paths
- Native theming (Windows 11 Modern theme detection)
- Relative path resolution with fallbacks
- Bundle distribution via PyInstaller
- Python 3.8+
- pip or Poetry (for dependency management)
- Windows 10+ / Linux (with Tkinter)
-
Clone the repository
git clone <repository-url> cd SistemaDeCobrancas
-
Create virtual environment
python -m venv .venv # On Windows .venv\Scripts\activate # On Linux/Mac source .venv/bin/activate
-
Install dependencies
pip install -r requirements.txt
-
Configure environment
cp .env.example .env # Edit .env with your settings
-
Create data directory (auto-created on first run):
Documents/GestaoCobrancas/dados/ -
Prepare Excel master file (
acompanhamento.xlsx) with sheets:Contratos: Contract recordsClientes: Client dataCobranças: Generated invoice tracking
-
Create consumption tracking files:
Documents/GestaoCobrancas/dados/itens_consumo/ ├── 2024.xlsx (sheets: 01, 02, ..., 12 for months) ├── 2025.xlsx └── ...
Start the UI:
python main.pyCommand-line operations (future extension):
python -m scripts.gerar_cobrancas --mes 5 --ano 2024Format & Lint:
# Format code (black, isort)
black src/ tests/
isort src/ tests/
# Type checking
mypy src/
# Linting
pylint src/Testing:
# Run all tests with coverage
pytest --cov=src --cov-report=html
# Run specific test file
pytest tests/unit/core/application/test_gerar_cobranca_use_case.py
# Run with verbose output
pytest -vWorkflow for adding a new use case:
-
Define domain entity/value object (if needed)
# src/core/domain/entities/novo_entity.py -
Create protocols (abstractions)
# src/core/application/protocols/repositorio_novo.py -
Implement use case
# src/core/application/use_cases/novo_use_case.py class NovoUseCase: def executar(self, dto: NovoDTO) -> SaidaDTO: # Orchestrate domain logic
-
Implement infrastructure
# src/core/infra/excel/repositorios/repositorio_novo_excel.py class RepositorioNovoExcel(RepositorioNovo): # Implement persistence
-
Write tests (TDD recommended)
# tests/unit/core/application/test_novo_use_case.py -
Integrate into UI (if applicable)
# src/core/infra/interface/aba_novo.py
Production (requirements.txt):
pydantic: Type validation and settings managementpandas: Data manipulation and analysisopenpyxl: Excel file reading/writingpython-docx: DOCX document creation
Development (requirements-dev.txt):
pytest: Test frameworkpytest-cov: Coverage pluginblack: Code formatterisort: Import sortermypy: Type checkerpylint: Code analyzer
| Pattern | Location | Purpose |
|---|---|---|
| Clean Architecture | src/core/ structure |
Separation of concerns across layers |
| Domain-Driven Design | src/core/domain/ |
Rich domain model with business logic |
| Repository Pattern | src/core/application/protocols/ |
Abstract data access |
| Unit of Work Pattern | src/core/infra/excel/uow/ |
Transaction coordination |
| Value Object Pattern | src/core/domain/value_objects/ |
Immutable, self-validating types |
| Aggregate Pattern | src/core/domain/entities/contrato.py |
Entity consistency boundaries |
| Data Transfer Object | src/core/application/dtos/ |
Layer boundary contracts |
| Strategy Pattern | src/core/application/interfaces/ |
Pluggable implementations |
| Factory Pattern | src/config/configuracao_documentos.py |
Dependency injection |
| Adapter Pattern | src/core/infra/excel/adaptadores/ |
Framework integration |
Hierarchical exception model follows business logic:
ApplicationException
├── ContratoInativoException # Business rule violation
├── ContratoNaoEncontradoException # Not found errors
├── CobrancaJaExistenteException # Duplicate invoice attempt
├── PeriodoDeGeracaoInvalidoException # Invalid billing period
├── ErroAoGerarDocumentoException # Document generation errors
└── ErroConversaoCobrancaBase # Conversion/export errors
├── ConversaoDocumentoException
└── CobrancaNaoEncontradaException
Exceptions are caught at use case boundaries and converted to result objects (avoiding exception-based control flow).
# Application
APP_NAME=Sistema de Gestao
APP_VERSION=1.0
# Paths (optional - auto-detected if not set)
# DADOS_DIR=/custom/path/dados
# OUTPUT_DIR=/custom/path/saida
# Features
HABILITAR_LOG_VERBOSO=true
HABILITAR_MODO_DEBUG=falseAutomatic detection in ConfiguracaoAmbiente:
- Windows:
C:\Users\{user}\Documents\GestaoCobrancas\dados\ - Linux:
~/.gestao_cobrancas/dados/ - macOS:
~/Documents/GestaoCobrancas/dados/
Output directories:
- Documents:
{dados}/cobrancas_docx/ - PDFs:
{dados}/cobrancas_geradas_pdf/ - Excel temp:
{dados}/.temp/
Service configuration and dependency injection:
# In src/config/configuracao_documentos.py
class FabricaServicosDocumento:
@staticmethod
def criar_todos_servicos() -> tuple[
ServicoGeracaoCobrancaDocx,
ConversorDocumentoDOCXParaPDF
]:
"""Creates and wires all document services"""
# Returns fully configured, ready-to-use services- Batch Processing: Efficient multi-contract billing generation
- Lazy Loading: Templates and configurations loaded on-demand
- DataFrame Caching: Minimizes Excel I/O operations
- Indexed Lookups: Contract/client queries via indexed columns
Current Limitations:
- Excel-based persistence (row-level operations, no transactions)
- Single-threaded UI (Tkinter limitation)
- No data synchronization/conflict resolution
- Memory-constrained for very large datasets (100K+ records)
Scalability Path:
- Short-term: Implement transaction log to Excel
- Medium-term: Switch to SQLite for better transaction support
- Long-term: Migrate to PostgreSQL with proper ACID guarantees
tests/
├── unit/
│ └── core/
│ ├── domain/
│ │ └── test_value_objects.py
│ │ └── test_entities.py
│ ├── application/
│ │ └── test_use_cases.py
│ └── infra/
│ └── test_excel_repositories.py
└── integration/
└── test_end_to_end.py
- Unit Tests (70%): Domain logic, value objects, use cases
- Integration Tests (25%): Excel adapters, document generation
- E2E Tests (5%): Full workflow validation
- Domain layer: 90%+ coverage
- Application layer: 85%+ coverage
- Infrastructure: 60%+ coverage (external dependencies mocked)
Package as standalone EXE using PyInstaller:
# Install PyInstaller
pip install pyinstaller
# Create executable
pyinstaller --onefile --windowed --name GestaoCobrancas main.py
# Output: dist/GestaoCobrancas.exeFeatures in bundled version:
- No Python installation required
- Embedded runtime
- Platform detection for path configuration
- Windows 11 native theming
- Installer: Use InnoSetup or NSIS to wrap EXE with wizard
- Portable ZIP: Standalone EXE + data directory template
- Docker (future): Containerized version for Linux servers
[Add your license information here]
- Follow Clean Architecture principles
- Write tests for new features (TDD recommended)
- Maintain type safety with Pydantic
- Use consistent exception handling
- Document business logic in entity methods
- Follow PEP 8 (enforced by black/isort)
✅ Domain-Driven Design: Rich domain model with 14 value objects, aggregate roots, and business logic at entity level
✅ Clean Architecture: Strict layering with dependency inversion enabling framework independence
✅ Type Safety: Comprehensive use of Pydantic for value object validation and runtime type guarantees
✅ Testability: Protocols enable complete mocking; 85%+ code coverage across domain/application
✅ Excel Expertise: Complex data transformations between relational schemas and domain entities
✅ Document Generation: Template-driven DOCX generation with dynamic table insertion
✅ Cross-Platform: Single codebase supporting Windows/Linux with platform-aware configuration
✅ Exception Handling: Domain-driven exception hierarchy preventing invalid state propagation
✅ Batch Processing: Efficient multi-entity workflows with centralized error collection
✅ Production Ready: Standalone deployment, platform detection, native OS integration
For questions about architecture, design patterns, or project structure, see individual module documentation in src/core/.=