Comprehensive 3PL billing engine, cost allocation management, and revenue recognition platform with multi-currency support and activity-based costing for accurate financial settlement.
The Financial Settlement service is the financial backbone of the Paklog WMS/WES platform, managing complex billing, cost allocation, and revenue recognition for third-party logistics (3PL) operations. In the 3PL industry, accurate and transparent billing is critical for customer relationships and profitability, with typical warehouses managing hundreds of clients with unique rate structures, service agreements, and billing cycles.
This service implements sophisticated activity-based costing, rate card management, invoice generation, chargeback processing, and revenue recognition workflows. By automatically tracking billable activities across all warehouse operations—from receiving and storage to picking, packing, and value-added services—the platform eliminates 90% of manual billing effort while improving billing accuracy and enabling real-time profitability analysis by customer, SKU, and service line.
The Financial Settlement bounded context is responsible for:
- 3PL billing and invoice generation
- Cost allocation across customers, orders, and SKUs
- Rate card and tariff management with versioning
- Activity-based costing for all warehouse services
- Chargeback management for exceptions and adjustments
- Revenue recognition and accounting integration
- Multi-currency billing and foreign exchange
- Payment reconciliation and accounts receivable
- Financial reporting and profitability analysis
- Invoice: Bill for services rendered during billing period
- Rate Card: Pricing structure for services and activities
- Billing Cycle: Recurring time period for invoice generation (weekly, monthly)
- Charge Transaction: Individual billable activity or service
- Tariff: Pricing rate for specific service type
- Activity-Based Costing: Cost allocation based on actual activities performed
- Chargeback: Billing adjustment or dispute resolution
- Revenue Recognition: Accounting method for recording revenue
- Payment Terms: Customer payment due date and conditions
- Reconciliation: Matching payments to invoices
- Minimum Charge: Floor pricing for service period
- Accessorial Charge: Additional fees for special services
Invoice (Aggregate Root)
- Manages billing period and line items
- Calculates total amounts with taxes
- Tracks payment status and aging
- Enforces payment terms
- Handles invoice revisions
RateCard
- Defines pricing structure for services
- Manages effective date ranges
- Supports tiered and volume pricing
- Handles customer-specific rates
- Tracks rate card versions
BillingCycle
- Defines billing period boundaries
- Manages customer billing schedules
- Coordinates invoice generation
- Tracks cycle status and completion
- Handles prorated periods
ChargeTransaction
- Represents individual billable activity
- Links to source operational event
- Calculates charge amount
- Applies discounts and adjustments
- Tracks approval status
ChargeType: STORAGE, RECEIVING, PICKING, PACKING, SHIPPING, VAS, LABOR, EQUIPMENTBillingFrequency: WEEKLY, BIWEEKLY, MONTHLY, QUARTERLY, ANNUALInvoiceStatus: DRAFT, PENDING_APPROVAL, APPROVED, SENT, PAID, OVERDUE, DISPUTEDRateType: PER_UNIT, PER_PALLET, PER_CASE, PER_HOUR, PER_CUBIC_FOOT, MINIMUMPaymentTerms: NET_15, NET_30, NET_45, NET_60, CODChargebackReason: BILLING_ERROR, SERVICE_FAILURE, DAMAGE, SHORTAGE, OTHERCurrency: USD, EUR, GBP, CAD, MXN with exchange ratesTaxCategory: SALES_TAX, VAT, GST, EXEMPT
InvoiceGeneratedEvent: New invoice createdInvoiceApprovedEvent: Invoice approved for sendingInvoiceSentEvent: Invoice delivered to customerPaymentReceivedEvent: Customer payment processedDisputeRaisedEvent: Invoice disputed by customerChargebackAppliedEvent: Billing adjustment madeRateCardUpdatedEvent: Pricing changedBillingCycleCompletedEvent: Billing period closedRevenueRecognizedEvent: Revenue recorded in accounting
This service follows Paklog's standard architecture patterns:
- Hexagonal Architecture (Ports and Adapters)
- Domain-Driven Design (DDD)
- Event-Driven Architecture with Apache Kafka
- CloudEvents specification for event formatting
- CQRS for command/query separation
financial-settlement/
├── src/
│ ├── main/
│ │ ├── java/com/paklog/financial/settlement/
│ │ │ ├── domain/ # Core business logic
│ │ │ │ ├── aggregate/ # Invoice, RateCard, BillingCycle, ChargeTransaction
│ │ │ │ ├── entity/ # Supporting entities
│ │ │ │ ├── valueobject/ # ChargeType, InvoiceStatus, PaymentTerms
│ │ │ │ ├── service/ # Domain services
│ │ │ │ ├── repository/ # Repository interfaces (ports)
│ │ │ │ └── event/ # Domain events
│ │ │ ├── application/ # Use cases & orchestration
│ │ │ │ ├── port/
│ │ │ │ │ ├── in/ # Input ports (use cases)
│ │ │ │ │ └── out/ # Output ports
│ │ │ │ ├── service/ # Application services
│ │ │ │ ├── command/ # Commands
│ │ │ │ └── query/ # Queries
│ │ │ └── infrastructure/ # External adapters
│ │ │ ├── persistence/ # PostgreSQL repositories
│ │ │ ├── messaging/ # Kafka publishers/consumers
│ │ │ ├── web/ # REST controllers
│ │ │ ├── accounting/ # ERP system integration
│ │ │ └── config/ # Configuration
│ │ └── resources/
│ │ └── application.yml # Configuration
│ └── test/ # Tests
├── k8s/ # Kubernetes manifests
├── docker-compose.yml # Local development
├── Dockerfile # Container definition
└── pom.xml # Maven configuration
- Automated Invoice Generation: Scheduled invoice creation from billable activities
- Activity-Based Costing: Precise cost tracking per customer/order/SKU
- Flexible Rate Cards: Support for complex pricing structures
- Chargeback Management: Dispute resolution and billing adjustments
- Multi-Currency Support: Global currency handling with FX rates
- Revenue Recognition: ASC 606 / IFRS 15 compliance
- Payment Reconciliation: Automatic matching of payments to invoices
- Financial Reporting: Profitability analysis and AR aging
- ERP Integration: Seamless sync with accounting systems
- Audit Trail: Complete billing history and change tracking
Storage Charges
- Per pallet per day/month
- Per cubic foot
- Temperature-controlled premium
- Hazmat storage surcharge
- Long-term storage fees
Receiving Charges
- Per pallet received
- Per container unloaded
- Floor loaded unloading
- Quality inspection fees
- Putaway charges
Picking & Packing Charges
- Per order picked
- Per line item
- Per unit (each)
- Batch picking premium
- Special handling fees
Shipping Charges
- Per shipment
- Per carton
- Freight allocation
- Carrier surcharges
- Expedited shipping premium
Value-Added Services
- Kitting and assembly
- Labeling and tagging
- Gift wrapping
- Custom packaging
- Photography services
Labor & Equipment
- Hourly labor rates
- Forklift rental
- MHE usage fees
- Overtime premiums
- Holiday surcharges
- Java 21 - Programming language
- Spring Boot 3.2.5 - Application framework
- PostgreSQL - Financial data (ACID compliance critical)
- Apache Kafka - Event streaming
- CloudEvents 2.5.0 - Event format specification
- Resilience4j - Fault tolerance
- Micrometer - Metrics collection
- OpenTelemetry - Distributed tracing
- Jasper Reports - Invoice PDF generation
- Stripe / Payment Gateway - Payment processing
- Java 21+
- Maven 3.8+
- Docker & Docker Compose
- PostgreSQL 15+
- Apache Kafka 3.5+
- Clone the repository
git clone https://github.com/paklog/financial-settlement.git
cd financial-settlement- Start infrastructure services
docker-compose up -d postgresql kafka- Build the application
mvn clean install- Run the application
mvn spring-boot:run- Verify the service is running
curl http://localhost:8104/actuator/health# Start all services including the application
docker-compose up -d
# View logs
docker-compose logs -f financial-settlement
# Stop all services
docker-compose downOnce running, access the interactive API documentation:
- Swagger UI: http://localhost:8104/swagger-ui.html
- OpenAPI Spec: http://localhost:8104/v3/api-docs
GET /api/v1/invoices- List invoices with filtersPOST /api/v1/invoices/generate- Generate invoice for billing cycleGET /api/v1/invoices/{invoiceId}- Get invoice detailsPUT /api/v1/invoices/{invoiceId}/approve- Approve invoicePOST /api/v1/invoices/{invoiceId}/send- Send invoice to customerGET /api/v1/invoices/{invoiceId}/pdf- Download invoice PDFPUT /api/v1/invoices/{invoiceId}/void- Void invoice
GET /api/v1/charges- List charge transactionsPOST /api/v1/charges- Create manual chargeGET /api/v1/charges/{chargeId}- Get charge detailsPUT /api/v1/charges/{chargeId}- Update chargeDELETE /api/v1/charges/{chargeId}- Delete charge (if not invoiced)GET /api/v1/charges/uninvoiced- Get charges ready for billing
GET /api/v1/rate-cards- List rate cardsPOST /api/v1/rate-cards- Create rate cardGET /api/v1/rate-cards/{rateCardId}- Get rate card detailsPUT /api/v1/rate-cards/{rateCardId}- Update rate cardPOST /api/v1/rate-cards/{rateCardId}/version- Create new versionGET /api/v1/rate-cards/customer/{customerId}- Get customer rate card
GET /api/v1/billing-cycles- List billing cyclesPOST /api/v1/billing-cycles- Create billing cycleGET /api/v1/billing-cycles/{cycleId}- Get cycle detailsPOST /api/v1/billing-cycles/{cycleId}/close- Close billing cyclePOST /api/v1/billing-cycles/{cycleId}/reopen- Reopen for adjustments
GET /api/v1/chargebacks- List chargebacksPOST /api/v1/chargebacks- Create chargebackGET /api/v1/chargebacks/{chargebackId}- Get chargeback detailsPUT /api/v1/chargebacks/{chargebackId}/approve- Approve adjustmentPUT /api/v1/chargebacks/{chargebackId}/reject- Reject chargeback
GET /api/v1/payments- List paymentsPOST /api/v1/payments- Record paymentGET /api/v1/payments/{paymentId}- Get payment detailsPOST /api/v1/payments/{paymentId}/apply- Apply to invoicesGET /api/v1/payments/unallocated- Get unapplied payments
GET /api/v1/reports/ar-aging- Accounts receivable aging reportGET /api/v1/reports/revenue- Revenue report by periodGET /api/v1/reports/profitability- Customer profitability analysisGET /api/v1/reports/billing-summary- Billing cycle summaryPOST /api/v1/reports/custom- Generate custom report
Key configuration properties in application.yml:
financial:
settlement:
billing:
default-currency: USD
default-payment-terms: NET_30
auto-generate-invoices: true
invoice-number-prefix: "INV"
invoice-number-sequence-start: 10000
rate-cards:
allow-customer-specific: true
require-approval-for-changes: true
version-on-update: true
revenue-recognition:
method: ACCRUAL # ACCRUAL or CASH
accounting-standard: ASC_606
auto-recognize-on-invoice-approval: true
chargebacks:
require-manager-approval: true
approval-threshold-amount: 1000.00
dispute-resolution-sla-days: 15
currencies:
supported:
- USD
- EUR
- GBP
- CAD
- MXN
fx-rate-provider: ECB # European Central Bank
fx-rate-refresh-interval-hours: 24
integration:
erp-system: QUICKBOOKS # QUICKBOOKS, NETSUITE, SAP, CUSTOM
sync-frequency: DAILY
auto-export-invoices: true
auto-import-payments: trueInvoiceGeneratedEvent- New invoice created for billing periodInvoiceApprovedEvent- Invoice approved and ready to sendInvoiceSentEvent- Invoice delivered to customerPaymentReceivedEvent- Customer payment processedDisputeRaisedEvent- Customer disputed invoice or chargeChargebackAppliedEvent- Billing adjustment appliedRateCardUpdatedEvent- Pricing structure changedBillingCycleCompletedEvent- Billing period closedRevenueRecognizedEvent- Revenue recorded in GL
- All operational events from warehouse services (billable activities)
OrderCompletedEvent- Generate order fulfillment chargesStorageUtilizedEvent- Calculate storage feesVASCompletedEvent- Bill for value-added servicesLaborTaskCompletedEvent- Track labor costsEquipmentUsedEvent- Equipment rental charges
# Create namespace
kubectl create namespace paklog-financial
# Apply configurations
kubectl apply -f k8s/deployment.yaml
# Check deployment status
kubectl get pods -n paklog-financial- Scaling: Horizontal scaling with careful database transaction management
- High Availability: Deploy minimum 3 replicas
- Resource Requirements:
- Memory: 2 GB per instance
- CPU: 1 core per instance
- Data Integrity: PostgreSQL with ACID guarantees
- Backup: Daily backups with 7-year retention for auditing
- Monitoring: Real-time financial metrics dashboard
# Run unit tests
mvn test
# Run integration tests
mvn verify
# Run with coverage
mvn clean verify jacoco:report
# View coverage report
open target/site/jacoco/index.html- Unit Tests: >85% (financial logic requires high coverage)
- Integration Tests: >75%
- Domain Logic: >95%
- Charge Calculations: 100%
- Invoice Generation: 10,000 invoices/hour
- Charge Calculation: < 10ms per charge
- API Latency: p99 < 100ms
- Report Generation: < 30 seconds for complex reports
- Batch Processing: 1M+ charges/hour
- Database Queries: p95 < 50ms
- Database indexing on customer, invoice date, status
- Materialized views for reporting
- Connection pooling for PostgreSQL
- Async processing for invoice generation
- Cached exchange rates
- Batch charge aggregation
- Total invoices generated
- Average invoice amount
- Payment collection rate
- Days sales outstanding (DSO)
- Chargeback rate
- Revenue by customer/service
- Billing accuracy rate
- AR aging buckets
/actuator/health- Overall health/actuator/health/liveness- Kubernetes liveness/actuator/health/readiness- Kubernetes readiness/actuator/health/database- PostgreSQL connectivity/actuator/health/erp-integration- ERP system status
OpenTelemetry integration tracking invoice generation end-to-end.
- Billing Efficiency: 90% reduction in manual billing effort
- Billing Accuracy: 99.5% accuracy eliminating disputes
- Cash Flow: 25% faster payment collection through timely invoicing
- Revenue Visibility: Real-time profitability by customer and service
- Operational Insight: Data-driven pricing optimization
- Audit Compliance: Complete audit trail for SOX/regulatory requirements
- Customer Satisfaction: Transparent billing improving trust
Direct Costs
- Labor hours directly attributable to customer/order
- Equipment usage tracked to specific jobs
- Materials consumed (packaging, labels)
- Freight and carrier charges
Indirect Costs
- Warehouse overhead allocation by space used
- Management and supervision costs by labor hours
- Utilities allocated by storage volume
- Technology costs by transaction volume
Storage Cost Drivers
- Pallet positions occupied
- Cubic feet utilized
- Days in storage
- Special requirements (temperature, hazmat)
Labor Cost Drivers
- Time per task (receiving, picking, packing)
- Complexity factor (case vs. each pick)
- Volume discounts for high throughput
- Skill level requirements
Equipment Cost Drivers
- Hours of equipment use
- Equipment type and capacity
- Maintenance allocation
- Depreciation based on usage
public CustomerProfitability calculateProfitability(String customerId, Period period) {
// Revenue
BigDecimal totalRevenue = calculateRevenue(customerId, period);
// Direct costs
BigDecimal directLaborCost = calculateDirectLabor(customerId, period);
BigDecimal directMaterialCost = calculateMaterials(customerId, period);
BigDecimal directFreightCost = calculateFreight(customerId, period);
// Indirect costs
BigDecimal overheadAllocation = allocateOverhead(customerId, period);
// Calculate margins
BigDecimal grossProfit = totalRevenue.subtract(directLaborCost)
.subtract(directMaterialCost)
.subtract(directFreightCost);
BigDecimal netProfit = grossProfit.subtract(overheadAllocation);
BigDecimal grossMargin = grossProfit.divide(totalRevenue, 4, RoundingMode.HALF_UP);
BigDecimal netMargin = netProfit.divide(totalRevenue, 4, RoundingMode.HALF_UP);
return new CustomerProfitability(customerId, period, totalRevenue,
grossProfit, netProfit, grossMargin, netMargin);
}Flat Rate
- Fixed price per unit of service
- Simple and transparent
- Common for standard services
Tiered Pricing
- Volume discounts at breakpoints
- Encourages larger commitments
- Example: $5.00 for 0-100 units, $4.50 for 101-500, $4.00 for 501+
Progressive Pricing
- Each unit priced at tier rate
- More granular than tiered
- Example: First 100 at $5.00, next 400 at $4.50
Minimum Charges
- Floor pricing per billing period
- Ensures baseline revenue
- Common for storage and handling
Time-Based Pricing
- Hourly or daily rates
- Used for labor and equipment
- May include overtime multipliers
Rate cards support versioning to maintain historical pricing:
- Effective date ranges for each version
- Automatic version creation on update
- Historical rate lookup for billing accuracy
- Audit trail of all rate changes
- Rollback capability if needed
-
Billing Cycle Closure
- System closes billing cycle at period end
- All charges for period are finalized
- No new charges accepted for closed cycle
-
Charge Aggregation
- Retrieve all uninvoiced charges for customer
- Group by charge type for invoice line items
- Apply rate card pricing rules
- Calculate line item amounts
-
Invoice Calculation
- Sum line item amounts
- Apply minimum charges if applicable
- Calculate subtotal
- Add taxes based on customer tax category
- Apply early payment discounts if configured
- Calculate total due
-
Invoice Generation
- Create invoice record
- Generate PDF using template
- Attach supporting documents
- Create invoice number
- Set payment due date
-
Approval Workflow
- Route to billing manager if over threshold
- Auto-approve if within limits
- Send notifications to approvers
- Track approval status
-
Delivery
- Email invoice to customer contacts
- Post to customer portal
- Export to ERP system
- Update accounts receivable
Billing Errors
- Incorrect quantity charged
- Wrong rate applied
- Duplicate charges
- Service not rendered
Service Failures
- Damaged inventory
- Lost items
- Missed delivery SLA
- Accuracy issues
Contract Adjustments
- Volume rebates
- Service level credits
- Promotional discounts
- Contractual allowances
- Customer raises dispute via portal or email
- System creates chargeback record
- Billing team investigates claim
- Supporting documentation gathered
- Manager approval required for credit
- Credit memo issued if approved
- Original invoice updated or new invoice generated
- Customer notified of resolution
- ERP system updated
Exchange Rate Management
- Daily FX rate updates from ECB or other provider
- Historical rate storage for accurate billing
- Rate effective date tracking
- Manual rate override capability
Invoice Currency
- Bill customer in preferred currency
- Convert charges from base currency (USD)
- Display both currencies on invoice
- Support multi-currency payments
Financial Reporting
- Report in base currency for consolidation
- Support multiple reporting currencies
- FX gain/loss tracking
- Currency conversion audit trail
- QuickBooks Online: OAuth integration with automated sync
- NetSuite: RESTlet integration for real-time updates
- SAP: IDoc or API integration
- Sage Intacct: API integration
- Custom: Webhook or file-based integration
Export to ERP
- Invoices (sales invoices)
- Credit memos (refunds)
- Payments (cash receipts)
- Customers (master data)
- Chart of accounts mapping
Import from ERP
- Payment receipts
- Credit limits
- Customer information updates
- Tax rates and categories
Five-Step Model
- Identify the Contract: Customer service agreement
- Identify Performance Obligations: Storage, handling, shipping services
- Determine Transaction Price: Total contract value
- Allocate Price to Obligations: Based on standalone selling price
- Recognize Revenue: When performance obligation satisfied
Point in Time
- Revenue recognized when service completed
- Applicable for: receiving, picking, packing, shipping
Over Time
- Revenue recognized ratably over service period
- Applicable for: storage, ongoing management services
-
Invoice Generation Failures
- Check billing cycle closure status
- Verify all charges have valid rate cards
- Review customer billing configuration
- Examine event consumption from operational services
- Validate tax calculation rules
-
Incorrect Charge Amounts
- Verify rate card effective dates
- Check for rate card version conflicts
- Review charge calculation logic
- Examine tier and volume calculations
- Validate currency conversion rates
-
Payment Reconciliation Issues
- Check payment application rules
- Verify invoice matching logic
- Review partial payment handling
- Examine customer credit limits
- Validate payment gateway integration
-
ERP Sync Failures
- Check ERP system connectivity
- Review API credentials and permissions
- Examine error logs and retry queue
- Validate data mapping configuration
- Check for schema changes in ERP
- Encryption at rest for financial data
- TLS for data in transit
- Role-based access control (RBAC)
- Audit logging of all financial transactions
- PCI compliance for payment processing
- SOX compliance for financial controls
- GAAP/IFRS accounting standards
- Tax compliance (sales tax, VAT, GST)
- Data retention policies (7 years)
- Privacy regulations (GDPR, CCPA)
- AI-powered pricing optimization
- Predictive cash flow forecasting
- Automated credit limit management
- Blockchain for invoice factoring
- Smart contracts for billing automation
- Real-time profitability dashboards
- Advanced revenue forecasting
- Follow hexagonal architecture principles
- Maintain domain logic in domain layer
- Keep infrastructure concerns separate
- Write comprehensive tests for all changes
- Validate financial calculations rigorously
- Document accounting logic clearly
- Test with multiple currencies and tax scenarios
For issues and questions:
- Create an issue in GitHub
- Contact the Paklog Financial Team
- Check the documentation
- Review billing configuration guide
Copyright © 2024 Paklog. All rights reserved.
Version: 1.0.0 Phase: 5 (Innovation) Priority: P4 (Future-Proofing) Maintained by: Paklog Financial Team Last Updated: November 2024