CpSubscribeMonthStatisticData.php 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. namespace App\Console\Commands\ContentManage;
  3. use Illuminate\Console\Command;
  4. use Illuminate\Support\Facades\DB;
  5. use Modules\Common\Support\Trace\TraceContext;
  6. use Modules\ContentManage\Services\CpManage\BookSettlement;
  7. class CpSubscribeMonthStatisticData extends Command
  8. {
  9. /**
  10. * The name and signature of the console command.
  11. *
  12. * @var string
  13. */
  14. protected $signature = 'ContentManage:CpSubscribeMonthStatisticData {--month= : 被统计的月份}';
  15. /**
  16. * The console command description.
  17. *
  18. * @var string
  19. */
  20. protected $description = 'cp订阅数据月统计';
  21. /**
  22. * Execute the console command.
  23. */
  24. public function handle(): void
  25. {
  26. $month = $this->option('month');
  27. if(!$month){
  28. $this->error('month necessary');
  29. }
  30. $cpNames = DB::table('cps')
  31. ->select('cp_name')
  32. ->get()->pluck('cp_name');
  33. $datas = DB::table('cp_subscribe_statistic_data')
  34. ->where([
  35. 'month' => $month
  36. ])->select(
  37. DB::raw('count(distinct bid) as book_num'),
  38. 'cp_name'
  39. )->groupBy('cp_name')
  40. ->get()->keyBy('cp_name');
  41. $insertDatas = [];
  42. $now = date('Y-m-d H:i:s');
  43. foreach ($cpNames as $cpName) {
  44. $bookFinalAmounts = [];
  45. $bids = DB::table('cp_subscribe_statistic_data')
  46. ->where(['cp_name' => $cpName, 'month' => $month])
  47. ->distinct()
  48. ->select('bid')
  49. ->get()->pluck('bid');
  50. $finalAmount = 0;
  51. DB::table('cp_book_month_final_amounts')
  52. ->where(['cp_name' => $cpName, 'month' => $month])
  53. ->update(['is_enabled' => 0, 'updated_at' => $now]);
  54. foreach ($bids as $bid) {
  55. $service = new BookSettlement($bid, $month);
  56. $service->traceContext = TraceContext::newFromParent(app(TraceContext::class)->getTraceInfo());
  57. $bookFinalAmountDetails = $service->detail();
  58. $monthFinalAmount = array_sum($bookFinalAmountDetails);
  59. $finalAmount += $monthFinalAmount;
  60. $bookFinalAmounts[] = [
  61. 'bid' => $bid,
  62. 'cp_name' => $cpName,
  63. 'month' => $month,
  64. 'final_amount' => $monthFinalAmount,
  65. 'created_at' => $now,
  66. 'updated_at' => $now,
  67. ];
  68. }
  69. DB::table('cp_book_month_final_amounts')
  70. ->insert($bookFinalAmounts);
  71. $insertDatas[] = [
  72. 'book_num' => $datas->get($cpName)->book_num ?? 0, 'final_amount' => $finalAmount,
  73. 'cp_name' => $cpName, 'month' => $month, 'created_at' => $now, 'updated_at' => $now,
  74. ];
  75. }
  76. DB::table('cp_subscribe_month_statistic_data')
  77. ->insert($insertDatas);
  78. }
  79. }