海南旅游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.

79 lines
1.8 KiB

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