UpdateBikesProfitCommand.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Models\Bike;
  4. use App\Models\Order;
  5. use App\Models\OrderRent;
  6. use App\Utils\RedisKeys;
  7. use Carbon\Carbon;
  8. use Illuminate\Console\Command;
  9. use Illuminate\Support\Facades\DB;
  10. use Illuminate\Support\Facades\Log;
  11. class UpdateBikesProfitCommand extends Command
  12. {
  13. /**
  14. * The name and signature of the console command.
  15. *
  16. * @var string
  17. */
  18. protected $signature = 'update:bikes_profit';
  19. /**
  20. * The console command description.
  21. *
  22. * @var string
  23. */
  24. protected $description = '更新车辆总收益 截止到昨天24:00';
  25. /**
  26. * Create a new command instance.
  27. *
  28. * @return void
  29. */
  30. public function __construct()
  31. {
  32. parent::__construct();
  33. }
  34. /**
  35. * Execute the console command.
  36. *
  37. * @return mixed
  38. */
  39. public function handle()
  40. {
  41. $today = Carbon::today();
  42. $yesterday = Carbon::yesterday();
  43. $lock = $this->makeUpdateBikesProfitLock($yesterday);
  44. if($lock){
  45. //
  46. $order = Order::query()->where('status', Order::STATUS_COMPLETE_ORDER)
  47. ->with(['bikes'])
  48. ->where('pay_time', '>', $yesterday)
  49. ->where('pay_time', '<', $today)
  50. ->groupBy(['bike_id'])
  51. ->select('bike_id', DB::raw('sum(pay_money) as total_sum'))
  52. ->orderByDesc('total_sum')
  53. ->get();
  54. if(!empty($order)){
  55. foreach ($order as $v){
  56. Bike::query()->where('id',$v->bike_id)->increment('total_money',$v->total_sum);
  57. }
  58. }
  59. $order_rent = OrderRent::query()->where('status', OrderRent::STATUS_COMPLETE_ORDER)
  60. ->with(['bikes'])
  61. ->where('pay_time', '>', $yesterday)
  62. ->where('pay_time', '<', $today)
  63. ->groupBy(['bike_id'])
  64. ->select('bike_id', DB::raw('sum(order_total_money) as total_sum'))
  65. ->orderByDesc('total_sum')
  66. ->get();
  67. if(!empty($order_rent)){
  68. foreach ($order_rent as $v){
  69. Bike::query()->where('id',$v->bike_id)->increment('total_money',$v->total_sum);
  70. }
  71. }
  72. }else{
  73. Log::error('已执行过更新昨日车辆总收益');
  74. }
  75. }
  76. public function makeUpdateBikesProfitLock($yesterday)
  77. {
  78. $key = sprintf(RedisKeys::LOCK_EVERYDAY_UPDATE_BIKES_PROFIT_DAY, $yesterday);
  79. $res = app()->redis->incr($key);
  80. app()->redis->Expire($key, RedisKeys::LOCK_EVERYDAY_UPDATE_BIKES_PROFIT_DAY_EXPRIRE);
  81. return $res > 1 ? false : true;
  82. }
  83. }