OrderClean.php 2.9 KB

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