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 Stocks Laravel Package

baks-dev/products-stocks

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

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. Installation:

    composer require baks-dev/products-stocks
    php artisan baks:assets:install  # Installs config, views, and assets
    php artisan doctrine:migrations:diff  # Review schema changes
    php artisan doctrine:migrations:migrate  # Apply migrations
    
  2. First Use Case:

    • Check Stock Levels:
      use BaksDev\ProductsStocks\Services\StockService;
      
      $stockService = app(StockService::class);
      $stock = $stockService->getStockByProductAndWarehouse(
          productId: 1,
          warehouseId: 1
      );
      
    • Adjust Stock:
      $stockService->adjustStock(
          productId: 1,
          quantity: -5,  // Negative for deductions
          warehouseId: 1,
          reason: 'Order #12345'
      );
      
  3. Where to Look First:

    • Configuration: config/baks-products-stocks.php (override defaults).
    • Models: app/Models/BaksDev/ProductsStocks/ (extend if needed).
    • Services: app/Services/BaksDev/ProductsStocks/ (business logic).
    • Migrations: database/migrations/ (check for custom tables).

Implementation Patterns

Usage Patterns

1. Stock Management Workflow

  • Create/Update Stock:
    $stockService->createStock(
        productId: $product->id,
        warehouseId: $warehouse->id,
        quantity: 100,
        attributes: ['batch' => 'BATCH-2023']
    );
    
  • Transfer Between Warehouses:
    $stockService->transferStock(
        productId: 1,
        fromWarehouseId: 1,
        toWarehouseId: 2,
        quantity: 20,
        reference: 'TRANSFER-001'
    );
    

2. Event-Driven Extensions

  • Listen for stock events (if supported):
    // Example: Low stock alert
    event(new \BaksDev\ProductsStocks\Events\StockLow(
        productId: 1,
        currentStock: 5,
        threshold: 10
    ));
    
  • Custom Events: Extend the package by publishing your own events:
    class CustomStockEvent extends Event
    {
        public function __construct(public int $productId, public string $action) {}
    }
    

3. Repository Pattern Integration

  • Use repositories for database operations:
    $warehouseRepo = app(\BaksDev\ProductsStocks\Repositories\WarehouseRepository::class);
    $warehouses = $warehouseRepo->getAllWithStock();
    

4. API Integration

  • Expose stock endpoints (e.g., via Laravel API Resources):
    // routes/api.php
    Route::get('/stock/{product}', [StockController::class, 'show']);
    
  • Example Controller:
    public function show(StockService $stockService, $productId)
    {
        return new StockResource($stockService->getStockByProduct($productId));
    }
    

Workflows

Daily Developer Workflow

  1. Stock Adjustments:
    • Use StockService for CRUD operations (e.g., after order fulfillment).
  2. Audit Logs:
    • Query stock_movements table for historical tracking:
      $movements = \BaksDev\ProductsStocks\Models\StockMovement::where('product_id', 1)
          ->orderBy('created_at', 'desc')
          ->take(10)
          ->get();
      
  3. Low-Stock Alerts:
    • Schedule a cron job to check stock levels:
      // app/Console/Commands/CheckStock.php
      public function handle()
      {
          $lowStock = $stockService->getLowStockProducts(threshold: 10);
          // Send notifications...
      }
      

Integration with Other Modules

  • Orders Module:
    • Deduct stock during order processing:
      $stockService->adjustStock(
          productId: $orderItem->product_id,
          quantity: -$orderItem->quantity,
          warehouseId: $warehouseId,
          reason: 'Order #' . $order->id
      );
      
  • Supplier Module:
    • Restock products via supplier deliveries:
      $stockService->adjustStock(
          productId: $product->id,
          quantity: $delivery->quantity,
          warehouseId: $warehouse->id,
          reason: 'Supplier Delivery #' . $delivery->id
      );
      

Testing

  • Run package-specific tests:
    php artisan test --group=products-stocks
    
  • Example Test:
    public function testStockAdjustment()
    {
        $this->actingAs($adminUser);
        $initialStock = $stockService->getStockByProductAndWarehouse(1, 1);
        $stockService->adjustStock(1, -5, 1, 'Test');
        $this->assertEquals($initialStock - 5, $stockService->getStockByProductAndWarehouse(1, 1));
    }
    

Integration Tips

1. Extending Models

  • Add custom fields to Product or Warehouse:
    // app/Models/Product.php
    use BaksDev\ProductsStocks\Models\Product as BaseProduct;
    
    class Product extends BaseProduct
    {
        protected $casts = [
            'is_perishable' => 'boolean',
            'expiry_days' => 'integer',
        ];
    }
    

2. Custom Validation

  • Validate stock adjustments (e.g., prevent negative stock):
    // app/Providers/AppServiceProvider.php
    use BaksDev\ProductsStocks\Services\StockService;
    
    public function boot(StockService $stockService)
    {
        $stockService->setValidator(function ($productId, $quantity, $warehouseId) {
            $currentStock = $stockService->getStockByProductAndWarehouse($productId, $warehouseId);
            if ($currentStock + $quantity < 0) {
                throw new \Exception("Insufficient stock for product {$productId}");
            }
        });
    }
    

3. Multi-Warehouse Support

  • Use warehouse-specific logic:
    $warehouseStock = $stockService->getStockByProductAndWarehouse(
        productId: 1,
        warehouseId: $warehouseId
    );
    

4. Performance Optimization

  • Cache frequent stock queries:
    $stock = Cache::remember(
        "stock_{$productId}_{$warehouseId}",
        now()->addHours(1),
        fn() => $stockService->getStockByProductAndWarehouse($productId, $warehouseId)
    );
    

5. Localization

  • Override default translations:
    // resources/lang/en/stock.php
    return [
        'low_stock_alert' => 'Product {product} is running low (only {stock} left)!',
    ];
    

Gotchas and Tips

Pitfalls

1. Migration Conflicts

  • Issue: Schema conflicts if the database already has stock-related tables.
  • Fix: Review migrations before applying:
    php artisan doctrine:migrations:diff --dry-run
    
  • Workaround: Manually merge tables or use a custom migration.

2. Doctrine vs. Eloquent

  • Issue: The package uses Doctrine ORM, which may conflict with Eloquent.
  • Fix: Configure Laravel to use Doctrine as the primary ORM:
    // config/database.php
    'default' => 'doctrine',
    'connections' => [
        'doctrine' => [
            'driver' => 'doctrine',
            'host' => env('DB_HOST', '127.0.0.1'),
            // ...
        ],
    ],
    

3. Missing Event Support

  • Issue: The package may not publish events out of the box.
  • Fix: Manually listen for model events:
    \BaksDev\ProductsStocks\Models\StockMovement::created(function ($movement) {
        // Trigger custom logic (e.g., notifications)
    });
    

4. Artisan Command Conflicts

  • Issue: baks:assets:install may conflict with existing commands.
  • Fix: Rename or alias the command:
    php artisan baks:assets:install --name=custom-install
    

5. PHP 8.4+ Requirements

  • Issue: Older PHP versions will fail.
  • Fix: Upgrade PHP or use a Docker container:
    FROM php:8.4-cli
    

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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi