tourze/order-core-bundle

综合订单管理核心模块 - 提供购物车、订单创建、支付处理、发货追踪等完整电商订单功能

Installs: 166

Dependents: 5

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Open Issues: 0

Type:symfony-bundle

pkg:composer/tourze/order-core-bundle

1.0.5 2025-11-14 12:55 UTC

This package is auto-updated.

Last update: 2025-11-16 10:43:20 UTC


README

English | 中文

A comprehensive order management core module for Symfony applications that provides complete e-commerce order functionality including shopping cart, order creation, payment processing, and delivery tracking.

Features

🛒 Complete Order Lifecycle Management

  • Order Creation: Full shopping cart to order conversion workflow
  • Payment Processing: Multi-payment method support with status tracking
  • Order States: Comprehensive state management (Created, Paid, Shipped, Received, Canceled, etc.)
  • Automated Processing: Scheduled tasks for order expiration and cancellation

📦 Order Components

  • Contract: Main order entity with comprehensive metadata
  • OrderProduct: Product line items with quantity and pricing
  • OrderPrice: Price breakdown and cost calculation
  • OrderContact: Customer contact and shipping information
  • PayOrder: Payment transaction records
  • OrderLog: Complete order history and audit trail

🔄 Event-Driven Architecture

  • Order Events: Comprehensive event system for order lifecycle changes
  • Payment Events: Payment status and refund event handling
  • Stock Events: Automatic stock management integration
  • Credit Events: User credit/points integration

🛡️ Enterprise Features

  • Optimistic Locking: Prevents concurrent modification conflicts
  • Audit Trail: Complete change tracking with user attribution
  • IP Tracking: Network address logging for security
  • Snowflake IDs: Distributed unique identifier generation

Requirements

  • PHP 8.1+
  • Symfony 7.3+
  • Doctrine ORM 3.0+
  • MySQL/PostgreSQL database

Installation

composer require tourze/order-core-bundle

Configuration

Register the bundle in config/bundles.php:

return [
    // ...
    OrderCoreBundle\OrderCoreBundle::class => ['all' => true],
];

Console Commands

order:cancel-expired

Automatically cancels expired unpaid orders and releases stock.

Class: OrderCoreBundle\Command\CancelExpiredOrdersCommand

Usage:

# Run normally
php bin/console order:cancel-expired

# Dry run to see what would be cancelled
php bin/console order:cancel-expired --dry-run

# Process specific number of orders
php bin/console order:cancel-expired --limit=500

# Custom batch size
php bin/console order:cancel-expired --batch-size=50

Features:

  • Runs every minute via cron job
  • Batch processing for memory efficiency
  • Comprehensive logging and error handling
  • Stock release through event system
  • Progress tracking with configurable limits

order:expire-no-received

Processes orders that have been shipped but not received within the timeout period.

Class: OrderCoreBundle\Command\ExpireNoReceivedOrderCommand

Usage:

php bin/console order:expire-no-received

Features:

  • Runs every 15 minutes via cron job
  • Automatic order state transition to EXPIRED
  • Event dispatch for customer notifications
  • System user attribution for automated operations

order:sync-sku-sales-real-total

Synchronizes actual sales totals for all SKU products.

Class: OrderCoreBundle\Command\SyncSkuSalesRealTotalCommand

Usage:

php bin/console order:sync-sku-sales-real-total

Features:

  • Calculates real sales from completed orders
  • Updates SKU sales metrics
  • Efficient batch processing
  • Only updates when sales have increased

Order States

The bundle supports comprehensive order state management:

State Code Description
Created init Order has been created, awaiting payment
Paying paying Payment is being processed
Paid paid Payment completed, awaiting shipment
Partially Shipped part-shipped Some items have been shipped
Shipped shipped All items have been shipped
Received received Order has been completed
Canceled canceled Order has been cancelled
Expired expired Order has expired (timeout)
After Sales Processing aftersales-ing Return/refund in progress
After Sales Success aftersales-success Return/refund completed
After Sales Failed aftersales-failed Return/refund failed
Auditing auditing Order is under review
Accepted accept Order has been accepted
Rejected reject Order has been rejected
Exception exception Order processing failed

Events

The bundle provides a rich event system for integration:

Order Lifecycle Events

  • BeforeOrderCreatedEvent: Fired before order creation
  • AfterOrderCreatedEvent: Fired after order creation
  • OrderPaidEvent: Fired when order is paid
  • OrderReceivedEvent: Fired when order is received
  • AfterOrderCancelEvent: Fired after order cancellation

Payment Events

  • BeforePriceRefundEvent: Fired before price refund
  • AfterPriceRefundEvent: Fired after price refund

Supplier Events

  • SupplierOrderReceivedEvent: Supplier order received
  • SupplierExpireAcceptOrderEvent: Supplier acceptance timeout

Special Events

  • AutoExpireOrderStateEvent: Automatic order expiration
  • OrderCheckoutEvent: Order checkout process
  • ViewOrderEvent: Order viewing (for permissions/logging)

Entities

Contract (Main Order)

use OrderCoreBundle\Entity\Contract;

$order = new Contract();
$order->setState(OrderState::INIT);
$order->setUser($user);
$order->setSn('C1234567890');

Order Product

use OrderCoreBundle\Entity\OrderProduct;

$product = new OrderProduct();
$product->setContract($order);
$product->setSku($sku);
$product->setQuantity(2);
$product->setPrice(99.99);

Order Price

use OrderCoreBundle\Entity\OrderPrice;

$price = new OrderPrice();
$price->setContract($order);
$price->setAmount(199.98);
$price->setType('total');

Services

Core Services

  • OrderService: Main order management operations
  • PriceService: Price calculation and management
  • ContractService: Contract/order lifecycle management
  • CollectionService: Order collection and reporting

Price Services

  • PriceCalculationHelper: Complex price calculations
  • PriceFormatter: Price formatting and display
  • PriceAggregator: Price aggregation for reporting
  • ProductPriceValidator: Price validation logic

Administration

  • AdminMenu: EasyAdmin integration for order management
  • AttributeControllerLoader: Dynamic controller loading

Integration Examples

Creating an Order

use OrderCoreBundle\Service\OrderService;
use OrderCoreBundle\DTO\ProductCheckoutItem;

class OrderController
{
    public function __construct(
        private OrderService $orderService,
    ) {}

    public function createOrder(): Contract
    {
        $items = [
            new ProductCheckoutItem($sku1, 2),
            new ProductCheckoutItem($sku2, 1),
        ];

        return $this->orderService->createOrder($user, $items, $contactInfo);
    }
}

Processing Payment

use OrderCoreBundle\Event\OrderPaidEvent;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

class PaymentController
{
    public function __construct(
        private EventDispatcherInterface $eventDispatcher,
    ) {}

    public function handlePaymentSuccess(Contract $order): void
    {
        $order->setState(OrderState::PAID);

        $event = new OrderPaidEvent();
        $event->setContract($order);
        $this->eventDispatcher->dispatch($event);
    }
}

Event Listener for Stock Management

use OrderCoreBundle\Event\OrderPaidEvent;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;

class StockManager
{
    #[AsEventListener(event: OrderPaidEvent::class)]
    public function onOrderPaid(OrderPaidEvent $event): void
    {
        $order = $event->getContract();

        foreach ($order->getProducts() as $product) {
            $this->stockService->reserveStock(
                $product->getSku(),
                $product->getQuantity()
            );
        }
    }
}

EasyAdmin Integration

The bundle provides EasyAdmin controllers for order management:

  • OrderOrderCrudController: Main order management
  • OrderOrderPriceCrudController: Price management
  • OrderOrderProductCrudController: Product line items
  • OrderOrderContactCrudController: Contact information
  • OrderOrderLogCrudController: Order history
  • OrderPayOrderCrudController: Payment records

JsonRPC Procedures

The bundle exposes JsonRPC procedures for remote integration:

  • ReceiveUserOrder: Order receiving operations
  • CancelUserOrder: Order cancellation
  • CancelUserProduct: Product-level cancellation
  • UserCheckoutOrder: Checkout process
  • GetOrderTrackLogs: Order tracking information

Testing

The bundle includes comprehensive test fixtures:

# Load test fixtures
php bin/console doctrine:fixtures:load --group=OrderCoreBundle

Available fixtures:

  • OrderProductFixtures: Product data
  • OrderLogFixtures: Order history
  • PayOrderFixtures: Payment records
  • OrderContactFixtures: Contact information
  • OrderPriceFixtures: Price data

Statistics

The bundle provides metrics for order statistics:

  • OrderCountMetricProvider: Order count metrics
  • RevenueMetricProvider: Revenue calculation metrics

Cron Job Configuration

Add to your crontab:

# Cancel expired orders (every minute)
* * * * * php /path/to/bin/console order:cancel-expired

# Process non-received orders (every 15 minutes)
*/15 * * * * php /path/to/bin/console order:expire-no-received

# Sync sales data (daily at 2 AM)
0 2 * * * php /path/to/bin/console order:sync-sku-sales-real-total

Performance Considerations

  • Batch Processing: All commands use configurable batch sizes
  • Memory Management: Entity manager clearing in long-running processes
  • Database Indexing: Strategic indexes on frequently queried fields
  • Caching: Integrates with Symfony cache contracts
  • Background Processing: Async event handling for non-blocking operations

Security

  • User Attribution: All operations track the performing user
  • IP Logging: Network address logging for security audit
  • Optimistic Locking: Prevents concurrent modifications
  • Input Validation: Comprehensive validation using Symfony constraints
  • Rate Limiting: Compatible with Symfony rate limiting components

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Submit a pull request

License

This bundle is released under the MIT License. See the LICENSE file for details.

Support

For questions and support, please open an issue in the repository.