Skip to content

Latest commit

 

History

History
239 lines (184 loc) · 11.4 KB

File metadata and controls

239 lines (184 loc) · 11.4 KB

🏷️ Smart Pricing Engine

Enterprise-Grade Domain-Driven Design (DDD) & Explainable Pricing Platform

PHP Version Laravel Version Filament Version Pest Architecture License GitHub Stars

A pure, zero-dependency Domain Model wrapped in a reactive Filament 5 Admin Panel.
Engineered with strict Pest Architecture tests, commercial integer cent arithmetic, and transparent, waterfall-explainable pricing.


⭐ If this architecture inspires your enterprise projects, please star this repository! ⭐

Your star helps fellow developers discover clean Domain-Driven Design and strict architecture patterns in modern PHP 8.4.


💡 The Core Problem & Philosophy: Explainable Pricing

In typical e-commerce codebases, pricing logic quickly decays into deeply nested SQL queries, fragile floating-point math, and unexplainable black-box discounts. When a customer or B2B buyer asks:

„Why does this item cost exactly this price?“

...traditional systems cannot provide a proof. Smart Pricing Engine solves this permanently.

🔍 Deterministic Waterfall Proof Example:

Product:                  Premium T-Shirt (Base Price: 29.90 €)
Order Quantity:           25 pieces
Customer Group:           B2B (Business Account)
Active Campaign:          SUMMER2026 (15 % Off)

Sequential Rule Evaluation (Strict Priority Pipeline):
─────────────────────────────────────────────────────────────────────────────
1. Base Price                                                   29.90 €
2. Quantity Tier Discount (25–49 pcs, 15 %)        - 4.49 €  ➔  25.41 €
3. B2B Customer Group Discount (10 %)              - 2.54 €  ➔  22.87 €
4. Summer Campaign Discount (SUMMER2026, 15 %)      - 3.43 €  ➔  19.44 €
─────────────────────────────────────────────────────────────────────────────
Total Discount per piece:                         - 10.46 € (34.98 % Off)
Final Price per piece:                                          19.44 €
─────────────────────────────────────────────────────────────────────────────
Total Order Position (25 pieces):                              486.00 €
Total Position Savings:                           - 261.50 € (from 747.50 €)

Every single cent calculation uses commercial rounding (PHP_ROUND_HALF_UP), strictly respecting configurable Floor Prices (MinimumPrice) and full rule-rejection auditing.


🏛️ Architectural Blueprint: Hexagonal Onion DDD

flowchart TD
    subgraph InfrastructureLayer["Infrastructure Layer (Frameworks & Drivers)"]
        Filament["Filament 5 UI & Livewire 4"]
        MariaDB[("MariaDB 11 (Eloquent Data Mappers)")]
        RedisCache[("Redis 7 (Tagged Caching)")]
        AuditDB[("pricing_calculations (Immutable Audit Trail)")]
    end

    subgraph ApplicationLayer["Application Layer (Use Cases & Orchestration)"]
        CalculatePriceCommand["CalculatePriceCommand (Immutable DTO)"]
        CalculatePriceHandler["CalculatePriceHandler"]
        Ports["Repository & Lookup Ports (Interfaces)"]
    end

    subgraph DomainLayer["Core Domain Layer (PURE PHP 8.4 - ZERO FRAMEWORK DEPENDENCY)"]
        PricingEngine["PricingEngine (Sequential Pipeline)"]
        Rules["Rules: QuantityDiscountRule | CustomerGroupDiscountRule | CampaignDiscountRule | CouponDiscountRule"]
        ValueObjects["Value Objects: Money | Percentage | Quantity | Discount | RulePriority | CustomerGroup"]
        Results["Results: PricingResult | AppliedPricingRule | RejectedPricingRule"]
    end

    Filament --> CalculatePriceCommand
    CalculatePriceCommand --> CalculatePriceHandler
    CalculatePriceHandler --> Ports
    Ports --> MariaDB
    CalculatePriceHandler --> PricingEngine
    PricingEngine --> Rules
    Rules --> ValueObjects
    PricingEngine --> Results
    CalculatePriceHandler --> AuditDB
Loading

Layer Separation & Invariant Guarantees

  1. Domain Layer (app/Domain/Pricing/) — PURE PHP 8.4:
    • Zero Framework Footprint: Imports absolutely no framework classes (Illuminate\*, Filament\*, Symfony\*). Enforced automatically by Pest Arch tests on every commit.
    • Immutable Value Objects: All Value Objects are readonly class with cent-integer arithmetic (int $amountInCents). Floating-point money bugs are mathematically impossible.
    • Floor Price Ceiling Protection: No combination of volume discounts, VIP status, or vouchers can breach the merchant's configured minimum floor price (FloorPrice).
  2. Application Layer (app/Application/Pricing/):
    • Pure CQRS-style commands (CalculatePriceCommand) and handlers (CalculatePriceHandler).
    • Completely agnostic of whether requests originate from the Filament Admin Panel, REST API, CLI, or GraphQL.
  3. Infrastructure Layer (app/Infrastructure/):
    • Data Mapper Pattern: Clean separation where Eloquent models (ProductModel, CustomerModel, PricingRuleModel) are purely persistence mappers. They never bleed into Domain logic.
    • Immutable Audit Trail: Calculations automatically write immutable audit records to pricing_calculations for auditing and compliance.

🖥️ Modern Filament 5 UI & Real-Time Simulator

The engine includes a 100% native Filament 5 administrative interface:

Feature Description
Interactive Simulator Real-time pricing calculation with 1-click test scenarios (B2B Bulk, Retail, Coupon Valid, Coupon Rejected).
Waterfall Explanation Interactive table dissecting every deduction step, initial price, running price, and rule metadata.
Dual-Mode Discounts Rules support both Percentage (%) and Fixed Euro Amount (€) deductions.
Dynamic Form Validation Rule parameters dynamically adapt per type (QUANTITY, CUSTOMER_GROUP, CAMPAIGN, COUPON) with strict validation.
Audit Log Inspection Read-only inspection of all historic price calculations with full JSON explainability dumps.

🧩 Applied Design Patterns

  • Chain of Responsibility / Pipeline: Dynamic sequential rule processing ordered by RulePriority.
  • Specification Pattern: Business rules encapsulate criteria (minQuantity, targetGroup, dateRange, minCartValue) and return explicit rejection reasons.
  • Strategy Pattern: Polymorphic discount calculations supporting both relative percentages and absolute currency amounts.
  • Data Mapper Pattern: Bidirectional translation between relational tables and immutable domain entities.
  • Value Object Pattern: Money, Percentage, Quantity, Discount eliminating Primitive Obsession.

⚡ 1-Minute Quick Start

Get the entire application and database running locally with Docker via ./zenv:

1. Clone & Start Containers

git clone https://github.com/allgorithm/zenv.git smart-pricing-engine
cd smart-pricing-engine
./zenv up

2. Run Migrations & Seeders

./zenv artisan migrate --seed

Creates demo catalog (T-Shirt, Jeans, Hoodie), customer accounts (B2B, VIP), and standard pricing rules.

3. Open Admin Panel


🛡️ Strict Quality Assurance & Pest Architecture

The test suite runs with Pest 5 and Pest Arch Plugin:

./zenv pest
 PASS  Tests\Architecture\LayerRulesTest
  ✓ domain layer must not depend on external frameworks or infrastructure
  ✓ application layer only depends on domain and support, never on infrastructure
  ✓ no debugging statements left in production code
  ✓ strict types are enforced across the entire application

 PASS  Tests\Architecture\PricingDomainArchTest
  ✓ pricing domain layer must not depend on illuminate or framework infrastructure
  ✓ pricing value objects must be readonly classes
  ✓ pricing domain exceptions must extend DomainException or Exception

 PASS  Tests\Unit\Domain\Pricing\BoundaryRulesTest
  ✓ Quantity Discount Boundary Tests (4, 5, 9, 10, 24, 25, 49, 50+ pieces)
  ✓ Campaign Date Boundary Tests (Before start, during window, after expiration)
  ✓ Coupon Cart Value Boundary Tests (49,99 € rejected vs 50,00 € applied)

 PASS  Tests\Feature\CalculatePriceFeatureTest
  ✓ it calculates pricing end-to-end using database-backed repositories
  ✓ it calculates fixed euro discount rule correctly

Tests: 42 passed (127 assertions)

Run Code Style verification:

./zenv vendor/bin/pint --test

📂 Project Structure

app/
├── Domain/Pricing/                     # 🛡️ PURE PHP 8.4 (ZERO FRAMEWORK DEPS)
│   ├── Context/PricingContext.php
│   ├── Exceptions/                     # Domain Exceptions (FloorPrice, NegativeMoney, etc.)
│   ├── Ports/                          # Repository & Lookup Interfaces
│   ├── Results/                        # Explainable Result Objects
│   ├── Rules/                          # Strategy & Specification Pricing Rules
│   ├── Services/PricingEngine.php      # Sequential Domain Engine
│   └── ValueObjects/                   # Immutable Money, Quantity, Percentage, Discount
│
├── Application/Pricing/                # ⚙️ APPLICATION LAYER
│   ├── Commands/CalculatePriceCommand.php
│   └── Handlers/CalculatePriceHandler.php
│
├── Infrastructure/                     # 🔌 INFRASTRUCTURE LAYER
│   ├── Persistence/Eloquent/           # Eloquent Models & Data Mappers
│   └── Providers/PricingServiceProvider.php
│
└── Filament/                           # 🎨 PRESENTATION LAYER (FILAMENT 5)
    ├── Pages/PricingSimulator.php      # Livewire Simulator & Explainability Page
    └── Resources/                      # Product, Customer, Rule & Audit Resources

🤝 Contributing

Contributions are welcome! Please ensure:

  1. All changes adhere strictly to the DDD layers (keep Domain/ framework-free).
  2. All new Value Objects and Domain Rules include full boundary unit tests.
  3. Architecture tests pass (./zenv pest).
  4. Code passes style checks (./zenv vendor/bin/pint).

⭐ Don't forget to star the repo if you found this helpful! ⭐

Built with clean architecture by the Google DeepMind Antigravity Team & Alex Krivonos.