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

Orders Order Laravel Package

baks-dev/orders-order

Laravel/Symfony модуль системных заказов: установка через Composer, интеграция с Centrifugo и Messenger (воркер orders-order), установка ассетов, расширение статусов через сервисы с тегом baks.order.status, поддержка миграций и тестов.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Order

  1. Install Dependencies:

    composer require baks-dev/orders-order baks-dev/payment baks-dev/users-address baks-dev/contacts-region baks-dev/centrifugo baks-dev/products-stocks baks-dev/delivery phpoffice/phpspreadsheet
    
  2. Run Asset Installation:

    php bin/console baks:assets:install
    
  3. Set Up Database Migrations:

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    
  4. Start Messenger Worker:

    php bin/console messenger:consume orders-order
    
  5. Create a Basic Order:

    use BaksDev\Orders\Order\Order;
    use BaksDev\Orders\Order\OrderRepository;
    
    $order = new Order();
    $order->setUserId(1);
    $order->setStatus('pending'); // Default status
    $orderRepository = app(OrderRepository::class);
    $orderRepository->save($order);
    
  6. Verify Real-Time Updates (if using Centrifugo):

    • Ensure Centrifugo server is running and configured in .env.
    • Subscribe to order updates via WebSocket in your frontend.

First Use Case: Order Creation with Status Transition

// Create a custom status (e.g., 'processing')
$order = new Order();
$order->setUserId(1);
$order->setStatus('pending');

// Transition to 'processing' (assuming you've implemented OrderStatusCustom)
$order->transitionTo('processing');
$orderRepository->save($order);

Implementation Patterns

Core Workflows

1. Order Lifecycle Management

  • Creation: Use OrderRepository to persist orders with initial status (e.g., pending).
  • Status Transitions: Implement OrderStatusInterface for custom statuses (e.g., processing, shipped, cancelled).
    #[AutoconfigureTag('baks.order.status')]
    class ProcessingStatus implements OrderStatusInterface {
        public function canTransitionFrom(Order $order, string $toStatus): bool {
            return $order->getStatus() === 'pending' && $toStatus === 'processing';
        }
    }
    
  • Validation: Override validateTransition() in your custom status class to enforce business rules.

2. Asynchronous Processing

  • Messenger Integration: Use Symfony Messenger to handle long-running tasks (e.g., inventory updates, email notifications).
    use Symfony\Component\Messenger\MessageBusInterface;
    
    $bus = app(MessageBusInterface::class);
    $bus->dispatch(new UpdateOrderStatusMessage($order->getId(), 'shipped'));
    
  • Worker Setup: Run the dedicated worker for orders-order:
    php bin/console messenger:consume orders-order
    

3. Real-Time Updates with Centrifugo

  • Publish Events: Dispatch events for status changes.
    use BaksDev\Orders\Order\Event\OrderStatusChanged;
    
    $event = new OrderStatusChanged($order);
    $dispatcher->dispatch($event);
    
  • Frontend Subscription: Subscribe to Centrifugo channels in your JavaScript:
    const channel = client.subscribe('orders.order.1'); // Order ID
    channel.on('order_status_changed', (data) => {
        console.log('Status updated:', data.status);
    });
    

4. Inventory and Delivery Sync

  • Stock Updates: Use products-stocks to deduct inventory when orders are confirmed.
    $order->transitionTo('confirmed'); // Triggers stock deduction via Messenger
    
  • Delivery Coordination: Integrate with delivery package for shipping labels and tracking.
    $deliveryService = app(\BaksDev\Delivery\DeliveryService::class);
    $deliveryService->createShipment($order);
    

Integration Tips

API Layer

  • RESTful Endpoints: Create controllers to expose order operations (e.g., OrderController@store, OrderController@updateStatus).
    public function updateStatus(Request $request, Order $order) {
        $order->transitionTo($request->input('status'));
        return response()->json(['status' => $order->getStatus()]);
    }
    
  • Validation: Use Laravel’s Form Requests to validate status transitions.
    public function rules() {
        return [
            'status' => ['required', 'string', Rule::in(['pending', 'processing', 'shipped', 'cancelled'])],
        ];
    }
    

CLI Commands

  • Bulk Operations: Create custom commands for batch processing (e.g., cancel all pending orders).
    use Symfony\Component\Console\Command\Command;
    use Symfony\Component\Console\Input\InputInterface;
    use Symfony\Component\Console\Output\OutputInterface;
    
    class CancelPendingOrdersCommand extends Command {
        protected function execute(InputInterface $input, OutputInterface $output) {
            $orders = $this->orderRepository->findBy(['status' => 'pending']);
            foreach ($orders as $order) {
                $order->transitionTo('cancelled');
                $this->orderRepository->save($order);
            }
            $output->writeln('Cancelled ' . count($orders) . ' orders.');
        }
    }
    

Testing

  • Unit Tests: Test status transitions and validation logic.
    public function testCannotTransitionFromShippedToCancelled() {
        $order = new Order();
        $order->setStatus('shipped');
        $this->assertFalse($order->canTransitionTo('cancelled'));
    }
    
  • Feature Tests: Simulate full order flows with HTTP tests.
    public function testOrderWorkflow() {
        $response = $this->post('/orders', ['user_id' => 1]);
        $response->assertStatus(201);
    
        $response = $this->patch('/orders/1/status', ['status' => 'processing']);
        $response->assertStatus(200);
    }
    

Gotchas and Tips

Pitfalls

  1. Status Transition Logic Errors:

    • Issue: Custom status classes may allow invalid transitions (e.g., pendingshipped without processing).
    • Fix: Rigorously test canTransitionFrom() in all custom status implementations. Use PHPUnit to verify edge cases.
    • Tip: Add a validateTransition() method to your Order entity to centralize validation logic.
  2. Messenger Worker Stalls:

    • Issue: Orders may hang in intermediate states if the orders-order worker crashes or is overloaded.
    • Fix:
      • Monitor queue length with php bin/console messenger:failed-messages-list orders-order.
      • Implement retry logic with exponential backoff in your message handlers.
    • Tip: Use Laravel Horizon for a dashboard to monitor worker performance.
  3. Centrifugo Connection Issues:

    • Issue: Real-time updates may fail silently if Centrifugo is misconfigured or the WebSocket connection drops.
    • Fix:
      • Verify CENTRIFUGO_URL and CENTRIFUGO_API_KEY in .env.
      • Test WebSocket connectivity with a tool like Centrifugo CLI.
    • Tip: Implement a fallback to polling for critical updates (e.g., admin dashboards).
  4. Database Lock Contention:

    • Issue: High concurrency on the orders table can cause timeouts during status transitions.
    • Fix:
      • Use database transactions sparingly (only for critical operations).
      • Optimize queries with proper indexing on status and user_id.
    • Tip: Consider using optimistic locking (@Version) for high-contention scenarios.
  5. Dependency Conflicts:

    • Issue: Conflicts between baks-dev/orders-order and other packages (e.g., laravel/framework).
    • Fix:
      • Run composer why-not <package> to diagnose conflicts.
      • Use composer.lock to pin versions if necessary.
    • Tip: Test in a clean environment before merging changes.

Debugging Tips

  1. Log Order Events:

    • Extend the Order entity to log all status changes to a separate table.
    protected function logStatusChange(string $from, string $to) {
        \Log::info("Order {$this->id} status changed from {$from} to {$to}");
        // Optionally store in a database table for auditing
    }
    
  2. Enable Messenger Debugging:

    • Configure Symfony Messenger to log failed messages:
    # config/packages/messenger.yaml
    framework:
        messenger:
            failure_transport: failed
            transports:
                failed: 'doctrine://default?queue_name=failed'
    
  3. Centrifugo Debugging:

    • Enable debug mode in Centrifugo config:
    # centrifugo/config.json
    "debug": true,
    "log_level
    
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