PlatformOrderCrontabController.php 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. /**
  3. * 平台订单 定时任务
  4. */
  5. namespace console\controllers;
  6. use common\enums\OrderStatusEnum;
  7. use common\enums\StatusEnum;
  8. use common\models\platform\PlatformOrder;
  9. use common\models\platform\PlatformOrderStatisticsDay;
  10. use yii\console\Controller;
  11. use yii\console\ExitCode;
  12. class PlatformOrderCrontabController extends Controller
  13. {
  14. /**
  15. * 取消订单
  16. * 0 20 0 * * * *
  17. * @Author: lun
  18. * @DateTime: 2021/11/17 0017 20:38
  19. * @Copyright: copyright (c) 2021 广东七件事集团
  20. * @return int
  21. */
  22. public function actionCancelOrder(){
  23. try {
  24. $time = time();
  25. $where[] = ['=', 'order_status', StatusEnum::DISABLED];
  26. $where[] = ['<=', 'expire_time', $time];
  27. $select = "id,order_id,pay_money,source_table";
  28. $params = ['where' => $where, 'select' => $select];
  29. // 查询已过期的订单列表
  30. $list = PlatformOrder::lists($params);
  31. $tables = $poids = [];
  32. $total_pay_money = 0;// 取消的总订单金额
  33. $total_order_num = count($list);// 取消的总订单总数
  34. // 获取不同表需要更新的订单id
  35. foreach ($list as $item) {
  36. $tables[$item['source_table']][] = $item['order_id'];
  37. $poids[] = $item['id'];
  38. $total_pay_money += $item['pay_money'];
  39. }
  40. if (!empty($tables)) {
  41. $trans = \Yii::$app->db->beginTransaction();
  42. try {
  43. // 修改平台订单的订单状态
  44. \Yii::$app->db->createCommand()->update(PlatformOrder::tableName(), ['order_status' => (OrderStatusEnum::REPEAL)], 'id in('. implode(',', $poids) .')')->execute();
  45. // 循环订单数据
  46. foreach ($tables as $table => $oids) {
  47. // 批量修改过期订单
  48. \Yii::$app->db->createCommand()->update($table, [
  49. 'order_status' => OrderStatusEnum::REPEAL,
  50. 'close_time' => $time,
  51. ], 'id in('. implode(',', $oids) .')')->execute();
  52. }
  53. // 修改订单统计
  54. $res = PlatformOrderStatisticsDay::setData([
  55. 'cancel_order_num' => $total_order_num,
  56. 'cancel_order_money' => $total_pay_money,
  57. 'cancel_goods_num' => $total_order_num,
  58. ]);
  59. if ($res == false) throw new \Exception(PlatformOrderStatisticsDay::getStaticError());
  60. $trans->commit();
  61. } catch (\Exception $e) {
  62. $trans->rollBack();
  63. throw new \Exception($e->getMessage());
  64. }
  65. }
  66. echo '操作成功';
  67. return ExitCode::OK;
  68. } catch (\Exception $e) {
  69. echo $e->getMessage();
  70. $this->stderr('平台订单Error: ' . ExitCode::getReason(ExitCode::UNSPECIFIED_ERROR));
  71. return ExitCode::UNSPECIFIED_ERROR;
  72. }
  73. }
  74. }