Skip to content

Latest commit

Β 

History

2 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

🏷️ 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.

About

Enterprise-grade dynamic pricing and discount orchestration engine. Features zero-dependency domain architecture, audit-proof traceability, and real-time interactive Filament simulation.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages