OrderCreatedEventQueueJob.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: shenyang
  5. * Date: 2017/9/18
  6. * Time: 下午3:46
  7. */
  8. namespace app\Jobs;
  9. use app\common\events\order\AfterOrderCreatedEvent;
  10. use app\common\facades\Setting;
  11. use app\common\facades\SiteSetting;
  12. use app\common\models\Order;
  13. use app\common\models\OrderCreatedJob;
  14. use app\frontend\modules\order\models\PreOrder;
  15. use Illuminate\Contracts\Queue\ShouldQueue;
  16. use Illuminate\Bus\Queueable;
  17. use Illuminate\Queue\SerializesModels;
  18. use Illuminate\Queue\InteractsWithQueue;
  19. use Illuminate\Support\Facades\DB;
  20. class OrderCreatedEventQueueJob implements ShouldQueue
  21. {
  22. use InteractsWithQueue, Queueable, SerializesModels;
  23. /**
  24. * @var PreOrder
  25. */
  26. protected $orderId;
  27. /**
  28. * OrderCreatedEventQueueJob constructor.
  29. * @param $orderId
  30. */
  31. public function __construct($orderId)
  32. {
  33. $queueCount = Order::queueCount();
  34. if ($queueCount) {
  35. $this->queue = 'order:' . ($orderId % Order::queueCount());
  36. }
  37. $this->orderId = $orderId;
  38. }
  39. /**
  40. * Execute the job.
  41. *
  42. * @return void
  43. */
  44. public function handle()
  45. {
  46. \Log::info('订单'.$this->orderId.'created任务开始执行');
  47. DB::transaction(function () {
  48. try {
  49. \YunShop::app()->uniacid = null;
  50. $orderId = $this->orderId;
  51. $order = Order::find($orderId);
  52. \YunShop::app()->uniacid = $order->uniacid;
  53. Setting::$uniqueAccountId = $order->uniacid;
  54. if(!$order->orderCreatedJob){
  55. $order->setRelation('orderCreatedJob',new OrderCreatedJob(['order_id'=>$order->id]));
  56. $order->orderCreatedJob->save();
  57. }
  58. if($order->orderCreatedJob->status == 'finished'){
  59. \Log::error('订单完成事件触发失败',"{$orderId}orderCreatedJob记录已");
  60. return;
  61. }
  62. $order->orderCreatedJob->status = 'finished';
  63. $order->orderCreatedJob->save();
  64. $event = new AfterOrderCreatedEvent($order);
  65. app('events')->safeFire($event,$order->id);
  66. }catch (\Exception $exception){
  67. \Log::error('订单'.$this->orderId.'created任务异常',$exception);
  68. throw $exception;
  69. }
  70. });
  71. \Log::info('订单'.$this->orderId.'created任务执行完成');
  72. }
  73. }