ServiceTimer.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Components\Helpers;
  4. use App\Http\Controllers\ServiceController;
  5. use App\Http\Models\Order;
  6. use App\Http\Models\User;
  7. use App\Http\Models\UserLabel;
  8. use DB;
  9. use Exception;
  10. use Illuminate\Console\Command;
  11. use Log;
  12. class ServiceTimer extends Command
  13. {
  14. protected $signature = 'serviceTimer';
  15. protected $description = '服务计时器';
  16. public function __construct()
  17. {
  18. parent::__construct();
  19. }
  20. public function handle()
  21. {
  22. $jobStartTime = microtime(TRUE);
  23. // 扣减用户到期商品的流量
  24. $this->decGoodsTraffic();
  25. $jobEndTime = microtime(TRUE);
  26. $jobUsedTime = round(($jobEndTime-$jobStartTime), 4);
  27. Log::info('---【'.$this->description.'】完成---,耗时'.$jobUsedTime.'秒');
  28. }
  29. // 扣减用户到期商品的流量
  30. private function decGoodsTraffic()
  31. {
  32. //获取失效的套餐
  33. $orderList = Order::query()->with(['goods'])->whereStatus(2)->whereIsExpire(0)->whereHas('goods', function($q){ $q->whereType(2); })->where('expire_at', '<=', date('Y-m-d H:i:s'))->get();
  34. if($orderList->isNotEmpty()){
  35. try{
  36. DB::beginTransaction();
  37. foreach($orderList as $order){
  38. // 过期本订单
  39. Order::query()->whereOid($order->oid)->update(['is_expire' => 1]);
  40. // 过期生效中的加油包
  41. Order::query()
  42. ->with(['goods'])
  43. ->whereUserId($order->user_id)
  44. ->whereStatus(2)
  45. ->whereIsExpire(0)
  46. ->whereHas('goods', function($q){
  47. $q->whereType(1);
  48. })->update(['is_expire' => 1]);
  49. if(empty($order->user) || empty($order->goods)){
  50. continue;
  51. }
  52. // 清理全部流量
  53. Helpers::addUserTrafficModifyLog($order->user_id, $order->oid, $order->user->transfer_enable, 0, '[定时任务]用户所购商品到期,扣减商品对应的流量');
  54. User::query()->whereId($order->user_id)->update(['u' => 0, 'd' => 0, 'transfer_enable' => 0, 'reset_time' => NULL]);
  55. // 删除对应用户的所有标签
  56. UserLabel::query()->whereUserId($order->user_id)->delete();
  57. // 检查该订单对应用户是否有预支付套餐
  58. $prepaidOrder = Order::query()->whereUserId($order->user_id)->whereStatus(3)->orderBy('oid', 'asc')->first();
  59. if($prepaidOrder){
  60. (new ServiceController)->activePrepaidOrder($prepaidOrder->oid);
  61. }
  62. }
  63. DB::commit();
  64. }catch(Exception $e){
  65. Log::error($this->description.':'.$e);
  66. DB::rollBack();
  67. }
  68. }
  69. }
  70. }