Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Products Promotion Laravel Package

baks-dev/products-promotion

Модуль акций на продукцию для PHP 8.4+/Laravel/Symfony: установка через Composer, команда baks:assets:install для ресурсов, миграции Doctrine для обновления БД, тесты PHPUnit (group=products-promotion).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. Install the Package

    composer require baks-dev/products-promotion
    php artisan vendor:publish --provider="BaksDev\ProductsPromotion\ProductsPromotionServiceProvider" --tag="config"
    php artisan migrate
    
    • Verify the promotions and promotion_rules tables exist in your database.
  2. Configure Basic Promotion Edit config/promotions.php to set default values (e.g., currency, validation rules). Example:

    'default_currency' => 'USD',
    'validation' => [
        'min_quantity' => 1,
        'max_quantity' => null,
    ],
    
  3. Create a Simple Promotion Use the package’s facade or service to define a promotion:

    use BaksDev\ProductsPromotion\Facades\Promotion;
    
    // Create a 10% discount promotion
    $promotion = Promotion::create([
        'name' => 'Summer Sale',
        'type' => 'percentage', // or 'fixed', 'bundle'
        'value' => 10,
        'start_date' => now()->addDays(1),
        'end_date' => now()->addDays(7),
    ]);
    
    // Add a rule (e.g., apply to product ID 123)
    $promotion->addRule([
        'type' => 'product',
        'value' => 123,
    ]);
    
  4. Apply Promotion to a Cart Integrate with your cart logic:

    use BaksDev\ProductsPromotion\Services\PromotionApplier;
    
    $applier = app(PromotionApplier::class);
    $cart = $applier->applyPromotionsToCart($userCart);
    
  5. Test in Development Run the provided test group:

    php artisan test --group=products-promotion
    
    • Manually test by adding items to a cart and verifying discounts apply.

Implementation Patterns

Core Workflows

1. Promotion Definition and Management

  • Dynamic Configuration: Use YAML or database-driven promotion rules for flexibility.
    // Load promotions from a YAML file (if supported)
    $promotions = Promotion::loadFromYaml('promotions/summer.yml');
    
  • Bulk Operations: Create/update promotions via console commands or API endpoints.
    php artisan promotion:create --name="BlackFriday" --type="percentage" --value=20
    

2. Cart Integration

  • Hook into Cart Events: Listen for Cart::itemAdded or Cart::updated to auto-apply promotions.
    use BaksDev\ProductsPromotion\Events\PromotionApplied;
    
    event(new PromotionApplied($promotion, $cart));
    
  • Manual Application: Apply promotions programmatically during checkout.
    $order = $applier->applyPromotions($cart, $user);
    

3. Rule-Based Eligibility

  • Custom Rules: Extend the rule system for complex logic (e.g., user segments, geolocation).
    // Example: Create a rule for users with loyalty points > 100
    $promotion->addRule([
        'type' => 'user_segment',
        'value' => 'loyalty_points_gt_100',
    ]);
    
  • Chaining Rules: Combine multiple rules (e.g., product + user segment).
    $promotion->addRule(['type' => 'product', 'value' => 123]);
    $promotion->addRule(['type' => 'user', 'value' => 'premium']);
    

4. API and Frontend Integration

  • Expose Promotions via API:
    Route::get('/api/promotions', [PromotionController::class, 'index']);
    
  • Frontend Display: Use Blade directives or JavaScript to render promotions.
    @promotionBanner($promotion)
    
  • Real-Time Updates: Push promotion changes via Laravel Echo/Pusher if dynamic.

5. Testing and Validation

  • Unit Tests: Test promotion rules and cart integration.
    public function testPromotionAppliesToCart()
    {
        $cart = new Cart();
        $cart->addItem(123, 2);
    
        $this->assertEquals(80, $applier->applyPromotions($cart)->total);
    }
    
  • Integration Tests: Simulate full checkout flows with promotions.
  • Edge Cases: Test overlapping promotions, expired promotions, and rule conflicts.

Integration Tips

Laravel-Specific Patterns

  1. Service Provider Binding Override or extend the package’s service bindings in your AppServiceProvider:

    public function register()
    {
        $this->app->bind(
            PromotionApplier::class,
            function ($app) {
                return new CustomPromotionApplier(
                    $app->make(PromotionRepository::class)
                );
            }
        );
    }
    
  2. Middleware for Promotion Checks Protect promotion-heavy routes:

    Route::middleware(['promotion.eligible'])->group(function () {
        Route::get('/sale', [SaleController::class, 'index']);
    });
    
  3. Event Listeners React to promotion events (e.g., log applied promotions, send notifications):

    public function handle(PromotionApplied $event)
    {
        Log::info("Promotion applied: {$event->promotion->name}");
    }
    
  4. Command Bus for Complex Workflows Use Laravel’s command bus to handle promotion workflows (e.g., bulk creation):

    $bus->dispatch(new CreatePromotionCommand($promotionData));
    

Performance Optimization

  • Cache Promotion Rules:
    $rules = Cache::remember("promotion_rules_{$promotion->id}", now()->addHours(1), function () use ($promotion) {
        return $promotion->rules()->get();
    });
    
  • Lazy-Load Rules: Load rules only when needed (e.g., during cart evaluation).
  • Database Indexing: Ensure promotion_code, start_date, and end_date are indexed.

Extending Functionality

  1. Custom Promotion Types Extend the base Promotion model or create a new type:

    class TieredPromotion extends Promotion
    {
        protected $type = 'tiered';
    
        public function calculateDiscount($quantity)
        {
            // Custom logic for tiered discounts
        }
    }
    
  2. Third-Party Integrations

    • Payment Gateways: Hook into PaymentProcessed events to apply discounts.
    • Inventory Systems: Sync promotion-eligible stock levels.
    • Analytics: Track promotion performance via PromotionApplied events.
  3. Admin Panel Build a Laravel Nova or Filament resource for managing promotions:

    Nova::resources([
        \BaksDev\ProductsPromotion\Nova\Promotion::class,
    ]);
    

Gotchas and Tips

Pitfalls

  1. Migration Conflicts

    • Issue: Running migrations may fail if your database schema conflicts with the package’s tables.
    • Fix: Review the migration files (database/migrations/) before running php artisan migrate. Use --pretend to dry-run:
      php artisan migrate --pretend
      
    • Workaround: Manually resolve conflicts or use a database diff tool.
  2. Promotion Rule Conflicts

    • Issue: Overlapping promotions (e.g., two discounts on the same product) may cause unexpected behavior.
    • Fix: Implement a priority system or use Laravel’s policy system to resolve conflicts:
      $applier->applyPromotions($cart, $user, ['priority' => 'high']);
      
  3. Timezone Handling

    • Issue: Promotions with start_date/end_date may not work correctly if timezones are misconfigured.
    • Fix: Store dates in UTC and convert to user timezone in the frontend:
      $promotion->start_date->setTimezone($user->timezone);
      
  4. Caching Stale Data

    • Issue: Cached promotion rules may not update if promotions are modified dynamically.
    • Fix: Invalidate cache on promotion updates:
      Cache::forget("promotion_rules_{$promotion->id}");
      
  5. Dependency Version Locks

    • Issue: The package may require specific versions of Doctrine or other libraries, causing conflicts.
    • Fix: Pin exact versions in composer.json:
      "require": {
          "doctrine/dbal": "3.6.2",
          "doctrine/orm": "2.14.3"
      }
      
  6. Missing Documentation

    • Issue: Limited public documentation may obscure advanced features.
    • Fix: Explore the source code (`vendor/baks-dev/products-promotion
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky