Skip to content

itpzzi/BillingSystem

Repository files navigation

Recurring Billing & Tenant Management System

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.


📋 Table of Contents


Overview

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

Business Problem

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.


Architecture

Clean Architecture (Onion Layers)

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

Key Architectural Principles

  1. Dependency Inversion: Application layer defines interfaces; infrastructure implements them

    • IRepositorioContrato abstraction allows swapping Excel → SQL database
    • IEscritorDocumento abstraction supports multiple document formats
  2. Entity Aggregates: Contrato (Contract) as root aggregate

    • Enforces contract lifecycle rules
    • Guards billing period constraints
    • Validates associated items (clients, consumption)
  3. Value Objects: Immutable, self-validating types prevent invalid entity state

    • ValorMonetario (Monetary) with arithmetic operations and formatting
    • DataISO (ISO Date) with period calculations
    • PeriodicidadePlano (Billing Frequency) enum preventing invalid states
    • PeriodoContrato (Contract Period) with automatic calculations
  4. Unit of Work Pattern: UnitOfWorkExcel coordinates multiple repositories with shared adapters

    • Single point for transaction management
    • Consistency across related entities
  5. DTO Boundaries: Separate input/output contracts from domain entities

    • CobrancaGeracaoDTO for invoice generation requests
    • RelatorioEmissaoCobrancasDTO for batch operation results
  6. Strategy Pattern: Pluggable implementations for extensibility

    • Document writers for different formats (DOCX, PDF, etc.)
    • Repository implementations (Excel, future: SQL, NoSQL)

Technology Stack

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

Key Dependencies

[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

Project Structure

.
├── 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

Key Features

1. Invoice Generation Engine

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

2. Template-Driven Document Generation

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

3. Batch Invoice Processing

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 & errors

4. Excel-Based Persistence

Production 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

5. Contract Lifecycle Management

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()

6. Consumption Item Tracking

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

7. Occupancy Management UI

Visual grid interface for resource allocation:

  • Live occupancy status display
  • Allocation/deallocation tracking
  • Status indicators (occupied/available)
  • Batch update capabilities

8. Cross-Platform Support

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

Getting Started

Prerequisites

  • Python 3.8+
  • pip or Poetry (for dependency management)
  • Windows 10+ / Linux (with Tkinter)

Installation (Development)

  1. Clone the repository

    git clone <repository-url>
    cd SistemaDeCobrancas
  2. Create virtual environment

    python -m venv .venv
    # On Windows
    .venv\Scripts\activate
    # On Linux/Mac
    source .venv/bin/activate
  3. Install dependencies

    pip install -r requirements.txt
  4. Configure environment

    cp .env.example .env
    # Edit .env with your settings

Data Structure Setup

  1. Create data directory (auto-created on first run):

    Documents/GestaoCobrancas/dados/
    
  2. Prepare Excel master file (acompanhamento.xlsx) with sheets:

    • Contratos: Contract records
    • Clientes: Client data
    • Cobranças: Generated invoice tracking
  3. Create consumption tracking files:

    Documents/GestaoCobrancas/dados/itens_consumo/
    ├── 2024.xlsx  (sheets: 01, 02, ..., 12 for months)
    ├── 2025.xlsx
    └── ...
    

Running the Application

Start the UI:

python main.py

Command-line operations (future extension):

python -m scripts.gerar_cobrancas --mes 5 --ano 2024

Development

Code Quality Standards

Format & 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 -v

Adding New Features

Workflow for adding a new use case:

  1. Define domain entity/value object (if needed)

    # src/core/domain/entities/novo_entity.py
  2. Create protocols (abstractions)

    # src/core/application/protocols/repositorio_novo.py
  3. Implement use case

    # src/core/application/use_cases/novo_use_case.py
    class NovoUseCase:
        def executar(self, dto: NovoDTO) -> SaidaDTO:
            # Orchestrate domain logic
  4. Implement infrastructure

    # src/core/infra/excel/repositorios/repositorio_novo_excel.py
    class RepositorioNovoExcel(RepositorioNovo):
        # Implement persistence
  5. Write tests (TDD recommended)

    # tests/unit/core/application/test_novo_use_case.py
  6. Integrate into UI (if applicable)

    # src/core/infra/interface/aba_novo.py

Project Dependencies

Production (requirements.txt):

  • pydantic: Type validation and settings management
  • pandas: Data manipulation and analysis
  • openpyxl: Excel file reading/writing
  • python-docx: DOCX document creation

Development (requirements-dev.txt):

  • pytest: Test framework
  • pytest-cov: Coverage plugin
  • black: Code formatter
  • isort: Import sorter
  • mypy: Type checker
  • pylint: Code analyzer

Design Patterns

Patterns Implemented

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

Exception Handling

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).


Configuration

Environment Variables (.env)

# 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=false

Platform-Aware Paths

Automatic 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/

Application Factory Pattern

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

Performance & Scalability

Optimizations

  • 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

Limitations & Future Enhancements

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:

  1. Short-term: Implement transaction log to Excel
  2. Medium-term: Switch to SQLite for better transaction support
  3. Long-term: Migrate to PostgreSQL with proper ACID guarantees

Testing Strategy

Test Structure

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

Test Pyramid

  • Unit Tests (70%): Domain logic, value objects, use cases
  • Integration Tests (25%): Excel adapters, document generation
  • E2E Tests (5%): Full workflow validation

Coverage Goals

  • Domain layer: 90%+ coverage
  • Application layer: 85%+ coverage
  • Infrastructure: 60%+ coverage (external dependencies mocked)

Deployment

Standalone Executable (Windows)

Package as standalone EXE using PyInstaller:

# Install PyInstaller
pip install pyinstaller

# Create executable
pyinstaller --onefile --windowed --name GestaoCobrancas main.py

# Output: dist/GestaoCobrancas.exe

Features in bundled version:

  • No Python installation required
  • Embedded runtime
  • Platform detection for path configuration
  • Windows 11 native theming

Distribution

  • Installer: Use InnoSetup or NSIS to wrap EXE with wizard
  • Portable ZIP: Standalone EXE + data directory template
  • Docker (future): Containerized version for Linux servers

License

[Add your license information here]


Contributing

  1. Follow Clean Architecture principles
  2. Write tests for new features (TDD recommended)
  3. Maintain type safety with Pydantic
  4. Use consistent exception handling
  5. Document business logic in entity methods
  6. Follow PEP 8 (enforced by black/isort)

Technical Highlights for Portfolio

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


Contact & Questions

For questions about architecture, design patterns, or project structure, see individual module documentation in src/core/.=

About

A production-grade Domain-Driven Design desktop application for automating billing operations, occupancy tracking management, and document generation. Built with Clean Architecture, featuring Excel-based persistence, template-driven document generation, and a modern Tkinter UI.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages