tourze/order-core-bundle
最新稳定版本:1.0.5
Composer 安装命令:
composer require tourze/order-core-bundle
包简介
综合订单管理核心模块 - 提供购物车、订单创建、支付处理、发货追踪等完整电商订单功能
README 文档
README
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 creationAfterOrderCreatedEvent: Fired after order creationOrderPaidEvent: Fired when order is paidOrderReceivedEvent: Fired when order is receivedAfterOrderCancelEvent: Fired after order cancellation
Payment Events
BeforePriceRefundEvent: Fired before price refundAfterPriceRefundEvent: Fired after price refund
Supplier Events
SupplierOrderReceivedEvent: Supplier order receivedSupplierExpireAcceptOrderEvent: Supplier acceptance timeout
Special Events
AutoExpireOrderStateEvent: Automatic order expirationOrderCheckoutEvent: Order checkout processViewOrderEvent: 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 operationsPriceService: Price calculation and managementContractService: Contract/order lifecycle managementCollectionService: Order collection and reporting
Price Services
PriceCalculationHelper: Complex price calculationsPriceFormatter: Price formatting and displayPriceAggregator: Price aggregation for reportingProductPriceValidator: Price validation logic
Administration
AdminMenu: EasyAdmin integration for order managementAttributeControllerLoader: 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 managementOrderOrderPriceCrudController: Price managementOrderOrderProductCrudController: Product line itemsOrderOrderContactCrudController: Contact informationOrderOrderLogCrudController: Order historyOrderPayOrderCrudController: Payment records
JsonRPC Procedures
The bundle exposes JsonRPC procedures for remote integration:
ReceiveUserOrder: Order receiving operationsCancelUserOrder: Order cancellationCancelUserProduct: Product-level cancellationUserCheckoutOrder: Checkout processGetOrderTrackLogs: 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 dataOrderLogFixtures: Order historyPayOrderFixtures: Payment recordsOrderContactFixtures: Contact informationOrderPriceFixtures: Price data
Statistics
The bundle provides metrics for order statistics:
OrderCountMetricProvider: Order count metricsRevenueMetricProvider: 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
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- 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.
统计信息
- 总下载量: 170
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 0
- 依赖项目数: 5
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-11-05