海南旅游SAAS
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

107 lines
2.7 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Common\OrderStatus;
  4. use App\Models\AgentProduct;
  5. use App\Models\AgentProductSpec;
  6. use App\Models\Order;
  7. use App\Models\Product;
  8. use App\Models\ProductSpec;
  9. use Illuminate\Console\Command;
  10. use Illuminate\Support\Facades\DB;
  11. class OrderTimeout extends Command
  12. {
  13. /**
  14. * The name and signature of the console command.
  15. *
  16. * @var string
  17. */
  18. protected $signature = 'order:timeout';
  19. /**
  20. * The console command description.
  21. *
  22. * @var string
  23. */
  24. protected $description = '订单超时未支付,取消订单并返回库存';
  25. /**
  26. * Create a new command instance.
  27. *
  28. * @return void
  29. */
  30. public function __construct()
  31. {
  32. parent::__construct();
  33. }
  34. /**
  35. * Execute the console command.
  36. *
  37. * @return int
  38. */
  39. public function handle()
  40. {
  41. //需要处理的订单状态
  42. $status_arr = [OrderStatus::UNPAID, OrderStatus::PAY_EARNEST, OrderStatus::OFFLINE_UNPAID];
  43. //记录最小ID,下次查询时按ID正序查询,只处理大于该ID的订单,避免重复扫描数据库
  44. /*$min_id = Order::query()
  45. ->whereIn('status', $status_arr)
  46. ->whereNotNull('timeout')
  47. ->min('id');*/
  48. $min_id = 0;
  49. while (true) {
  50. Order::with('orderProductItem')
  51. // ->where('id', '>=', $min_id)
  52. ->whereIn('status', $status_arr)
  53. ->whereNotNull('timeout')
  54. ->orderBy('id')
  55. ->chunk(100, function ($order) use (&$min_id) {
  56. foreach ($order as $v) {
  57. if (!is_null($v->timeout) && strtotime($v->timeout) < time()) {
  58. DB::beginTransaction();
  59. try {
  60. //取消订单
  61. $v->status = OrderStatus::CANCEL;
  62. $v->save();
  63. //供应商产品加库存
  64. Product::whereIn('id', explode(',', $v->product_ids))->increment('stock', $v->num);
  65. //代理商产品加库存
  66. AgentProduct::where('id', $v->agent_product_id)->increment('stock', $v->num);
  67. if (!$v->orderProductItem->isEmpty()) {
  68. $item = $v->orderProductItem->toArray();
  69. //供应商产品规格加库存
  70. $ids = array_column($item, 'product_spec_id');
  71. ProductSpec::whereIn('id', $ids)->increment('stock', $v->num);
  72. //代理商产品规格加库存
  73. $ids = array_column($item, 'agent_product_spec_id');
  74. AgentProductSpec::whereIn('id', $ids)->increment('stock', $v->num);
  75. }
  76. DB::commit();
  77. $min_id = $v->id;
  78. } catch (\Exception $exception) {
  79. DB::rollBack();
  80. $this->line("订单ID {$v->id} 错误:" . $exception->getMessage());
  81. }
  82. }
  83. }
  84. });
  85. //TODO 产品规格表加库存
  86. $this->line('[' . date('Y-m-d H:i:s') . "] ID游标:$min_id ,等待下一个任务");
  87. sleep(5);
  88. }
  89. return 0;
  90. }
  91. }