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

Sale Laravel Package

ekyna/sale

Laravel/PHP interfaces and traits for sales management. Provides core abstractions to model and manage sale workflows and related behaviors (e.g., timestampable traits). Lightweight component intended for integration into larger commerce/payment systems.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require ekyna/sale
    

    Add the service provider to config/app.php:

    'providers' => [
        // ...
        Ekyna\Sale\SaleServiceProvider::class,
    ],
    
  2. Publish Config

    php artisan vendor:publish --provider="Ekyna\Sale\SaleServiceProvider" --tag="config"
    

    Locate the config file at config/sale.php and adjust discount rules, tax settings, or currency defaults.

  3. First Use Case: Basic Sale Creation

    use Ekyna\Sale\Sale;
    
    $sale = new Sale();
    $sale->addItem('Product A', 10.00, 2); // name, unit price, quantity
    $sale->calculateTotal();
    echo $sale->getTotal(); // Outputs: 20.00
    

Key Entry Points

  • Sale class: Core class for managing sales, discounts, and taxes.
  • SaleRepository: Interface for persisting sales (if using database integration).
  • Config file: Centralize tax rates, discount rules, and currency formats.

Implementation Patterns

Workflow: Discount Application

  1. Define Discount Rules in Config
    'discounts' => [
        'bulk' => [
            'condition' => ['quantity' => 5],
            'value' => 0.1, // 10% discount
        ],
    ],
    
  2. Apply Discounts Automatically
    $sale = new Sale();
    $sale->addItem('Product B', 5.00, 6); // Quantity triggers bulk discount
    $sale->applyDiscounts();
    echo $sale->getDiscountedTotal(); // Outputs: ~$27.00 (after 10% off)
    

Workflow: Tax Calculation

  1. Configure Tax Rates
    'taxes' => [
        'default' => 0.08, // 8% tax
        'exempt' => [123], // Product IDs exempt from tax
    ],
    
  2. Calculate Taxes
    $sale->calculateTaxes();
    echo $sale->getTaxAmount(); // Outputs: tax amount
    

Integration with Laravel Ecosystem

  • Events: Listen to sale.created or sale.updated for post-sale logic.
    Event::listen('sale.created', function ($sale) {
        // Send notification, log, etc.
    });
    
  • API Responses: Serialize sales with SaleResource (if using Laravel API tools).
  • Database: Implement SaleRepository to persist sales to a sales table.

Common Use Cases

Use Case Implementation
Cart System Extend Sale to track items pre-purchase.
Checkout Flow Use Sale to compute totals before DB commit.
Reporting Query sales table for analytics.
Multi-Currency Override getTotal() to handle currency conversion.

Gotchas and Tips

Pitfalls

  1. Deprecated Package

    • Last updated in 2015; test thoroughly for compatibility with modern PHP/Laravel.
    • May lack support for PHP 8+ features (e.g., named arguments, union types).
  2. No Built-in Database Schema

    • Requires manual migration for sales table. Example:
      Schema::create('sales', function (Blueprint $table) {
          $table->id();
          $table->decimal('total', 8, 2);
          $table->decimal('tax', 8, 2);
          $table->json('items'); // Store items as JSON
          $table->timestamps();
      });
      
  3. Discount/Tax Logic in Config

    • Hard to override dynamically. Extend the Sale class to add runtime logic:
      class CustomSale extends Sale {
          public function applyCustomDiscount() {
              if ($this->getTotal() > 1000) {
                  $this->addDiscount(0.15); // 15% for large orders
              }
          }
      }
      
  4. Floating-Point Precision

    • Use bcmath or round() for financial calculations to avoid precision errors:
      $total = bcdiv($sale->getTotal(), '1', 2); // Round to 2 decimal places
      

Debugging Tips

  • Enable Logging Add to config/sale.php:

    'debug' => env('SALE_DEBUG', false),
    

    Logs calculations to storage/logs/sale.log.

  • Test Discounts/Taxes Temporarily set debug: true to inspect applied rules:

    $sale->setDebug(true);
    $sale->calculateTotal();
    // Check logs for breakdown of discounts/taxes.
    

Extension Points

  1. Custom Calculations Override methods like calculateTotal() or applyDiscounts() in a child class.

  2. Payment Integration Hook into sale.paid event to sync with payment gateways:

    Event::listen('sale.paid', function ($sale, $paymentMethod) {
        // Update order status, trigger webhooks, etc.
    });
    
  3. Localization Extend SaleFormatter to customize currency/tax displays:

    class CustomFormatter extends SaleFormatter {
        public function formatCurrency($amount) {
            return '$' . number_format($amount, 2, ',', '.');
        }
    }
    
  4. Testing Use mock SaleRepository for unit tests:

    $repository = Mockery::mock(SaleRepository::class);
    $sale = new Sale($repository);
    
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.
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
spatie/mailcoach-vapor