OrderClean.php 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace app\data\command;
  3. use app\data\service\OrderService;
  4. use think\admin\Command;
  5. use think\admin\Exception;
  6. use think\console\Input;
  7. use think\console\Output;
  8. /**
  9. * 商城订单自动清理
  10. * Class OrderClean
  11. * @package app\data\command
  12. */
  13. class OrderClean extends Command
  14. {
  15. protected function configure()
  16. {
  17. $this->setName('xdata:OrderClean');
  18. $this->setDescription('批量清理商城订单数据');
  19. }
  20. /**
  21. * 业务指令执行
  22. * @param Input $input
  23. * @param Output $output
  24. * @return void
  25. * @throws Exception
  26. */
  27. protected function execute(Input $input, Output $output)
  28. {
  29. $this->_autoCancelOrder();
  30. $this->_autoRemoveOrder();
  31. }
  32. /**
  33. * 自动取消30分钟未支付的订单
  34. * @throws Exception
  35. */
  36. private function _autoCancelOrder()
  37. {
  38. try {
  39. $map = [['status', '<', 3], ['payment_status', '=', 0]];
  40. $map[] = ['create_at', '<', date('Y-m-d H:i:s', strtotime('-30 minutes'))];
  41. [$total, $count] = [$this->app->db->name('ShopOrder')->where($map)->count(), 0];
  42. $this->app->db->name('ShopOrder')->where($map)->select()->map(function ($item) use ($total, &$count) {
  43. $this->queue->message($total, ++$count, "开始取消未支付的订单 {$item['order_no']}");
  44. $this->app->db->name('ShopOrder')->where(['order_no' => $item['order_no']])->update([
  45. 'status' => 0,
  46. 'cancel_status' => 1,
  47. 'cancel_datetime' => date('Y-m-d H:i:s'),
  48. 'cancel_remark' => '30分钟未完成支付已自动取消',
  49. ]);
  50. OrderService::instance()->stock($item['order_no']);
  51. $this->queue->message($total, $count, "完成取消未支付的订单 {$item['order_no']}", 1);
  52. });
  53. } catch (\Exception $exception) {
  54. $this->queue->error($exception->getMessage());
  55. }
  56. }
  57. /**
  58. * 自动清理已经取消的订单
  59. * @throws Exception
  60. */
  61. private function _autoRemoveOrder()
  62. {
  63. try {
  64. $map = [['status', '=', 0], ['payment_status', '=', 0]];
  65. $map[] = ['create_at', '<', date('Y-m-d H:i:s', strtotime('-3 days'))];
  66. [$total, $count] = [$this->app->db->name('ShopOrder')->where($map)->count(), 0];
  67. foreach ($this->app->db->name('ShopOrder')->where($map)->cursor() as $item) {
  68. $this->queue->message($total, ++$count, "开始清理已取消的订单 {$item['order_no']}");
  69. $this->app->db->name('ShopOrder')->where(['order_no' => $item['order_no']])->delete();
  70. $this->app->db->name('ShopOrderItem')->where(['order_no' => $item['order_no']])->delete();
  71. $this->queue->message($total, $count, "完成清理已取消的订单 {$item['order_no']}", 1);
  72. }
  73. } catch (\Exception $exception) {
  74. $this->queue->error($exception->getMessage());
  75. }
  76. }
  77. }