StatisticsPayRepository.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. <?php
  2. /**
  3. * 支付统计仓库.
  4. *
  5. * @author nj
  6. * @date 2021-07-23 10:34
  7. */
  8. namespace App\Repositories\Statistics;
  9. use App\Models\Mysql\AgentAttrsDayModel;
  10. use App\Models\Mysql\AgentAttrsModel;
  11. use App\Models\Mysql\AgentModel;
  12. use App\Repositories\AgentRepository;
  13. use App\Repositories\CommissionLogRepository;
  14. use Carbon\Carbon;
  15. use App\Models\Mongo\PayLogsModel;
  16. use Jenssegers\Mongodb\Eloquent\Model;
  17. use DB;
  18. class StatisticsPayRepository
  19. {
  20. /**
  21. * @var null|AgentRepository
  22. */
  23. protected $agentRepo = null;
  24. /**
  25. * @var null|CommissionLogRepository
  26. */
  27. protected $commissionLogRepo = null;
  28. /**
  29. * 计算某一个天的值
  30. * @param string $computeType 计算类型,count=总计数量;money=总计金额
  31. * @param mixed $date 日期.
  32. * @param array $conditions 查询条件.
  33. * @return int|mixed
  34. */
  35. public function computeOneDay($computeType, $date, array $conditions = [])
  36. {
  37. $computeType = strtolower($computeType);
  38. $channelUid = isset($conditions['channel_uid']) ? $conditions['channel_uid'] : null;
  39. $momAppUid = isset($conditions['mom_app_uid']) ? $conditions['mom_app_uid'] : null;
  40. $agentUid = isset($conditions['agent_uid']) ? $conditions['agent_uid'] : null;
  41. $deviceType = data_get($conditions, 'device_type', '');
  42. $payChannel = data_get($conditions, 'pay_channel', null);
  43. $transactionNo = data_get($conditions, 'transaction_no', null);
  44. $payStatus = data_get($conditions, 'pay_status', null);
  45. $isDeduction = data_get($conditions, 'is_deduction', null);
  46. $dayStartObj = Carbon::parse($date)->startOfDay();
  47. $dayEndObj = Carbon::parse($date)->endOfDay();
  48. $model = new PayLogsModel();
  49. if (!is_null($channelUid)) {
  50. $model = $model->where(['channel_uid' => $channelUid]);
  51. }
  52. if (!is_null($momAppUid)) {
  53. $model = $model->where(['mom_app_uid' => $momAppUid]);
  54. }
  55. if (!is_null($agentUid)) {
  56. $model = $model->where(['agent_uid' => $agentUid]);
  57. }
  58. if (!empty($deviceType)) {
  59. $model = $model->where(['device_type' => $deviceType]);
  60. }
  61. if (!is_null($isDeduction)) {
  62. $model = $model->where(['is_deduction' => $isDeduction]);
  63. }
  64. if (!is_null($payChannel)) {
  65. $model = $model->where(['pay_channel' => $payChannel]);
  66. }
  67. if (!is_null($transactionNo)) {
  68. $model = $model->where(['transaction_no' => $transactionNo]);
  69. }
  70. if (!is_null($payStatus)) {
  71. $model = $model->where(['pay_status' => $payStatus]);
  72. }
  73. // 日期查询放最后.
  74. $t1 = $dayStartObj;
  75. $t2 = $dayEndObj;
  76. $model = $model->whereBetween('created_at', [$t1, $t2]);
  77. $result = 0;
  78. if ($computeType == 'money') {
  79. $result = $model->sum('real_amount');
  80. } else {
  81. $result = $model->count();
  82. }
  83. return $result;
  84. }
  85. /**
  86. * 计算时间段内的值
  87. * @param string $computeType 计算类型,count=总计数量;money=总计金额
  88. * @param mixed $startDate 日期.
  89. * @param mixed $endDate 日期.
  90. * @param array $conditions 查询条件.
  91. * @return int|mixed
  92. */
  93. public function computeSomeDays($computeType, $startDate, $endDate = null, array $conditions = [])
  94. {
  95. $computeType = strtolower($computeType);
  96. $channelUid = isset($conditions['channel_uid']) ? $conditions['channel_uid'] : null;
  97. $momAppUid = isset($conditions['mom_app_uid']) ? $conditions['mom_app_uid'] : null;
  98. $agentUid = isset($conditions['agent_uid']) ? $conditions['agent_uid'] : null;
  99. $deviceType = data_get($conditions, 'device_type', '');
  100. $payChannel = data_get($conditions, 'pay_channel', null);
  101. $transactionNo = data_get($conditions, 'transaction_no', null);
  102. $payStatus = data_get($conditions, 'pay_status', null);
  103. $isDeduction = data_get($conditions, 'is_deduction', null);
  104. $startDateObj = Carbon::parse($startDate);
  105. $startYmd = $startDateObj->toDateString();
  106. $startDayObj = (clone $startDateObj)->startOfDay();
  107. $endDateObj = null;
  108. $endDayObj = null;
  109. $endYmd = '';
  110. if (!empty($endDate)) {
  111. $endDateObj = Carbon::parse($endDate);
  112. $endYmd = $endDateObj->toDateString();
  113. $endDayObj = (clone $endDateObj)->endOfDay();
  114. if ($startDateObj > $endDateObj) {
  115. // 时间溢出.
  116. return 0;
  117. }
  118. }
  119. $model = new PayLogsModel();
  120. if (!is_null($channelUid)) {
  121. $model = $model->where(['channel_uid' => $channelUid]);
  122. }
  123. if (!is_null($momAppUid)) {
  124. $model = $model->where(['mom_app_uid' => $momAppUid]);
  125. }
  126. if (!is_null($agentUid)) {
  127. $model = $model->where(['agent_uid' => $agentUid]);
  128. }
  129. if (!empty($deviceType)) {
  130. $model = $model->where(['device_type' => $deviceType]);
  131. }
  132. if (!is_null($isDeduction)) {
  133. $model = $model->where(['is_deduction' => $isDeduction]);
  134. }
  135. if (!is_null($payChannel)) {
  136. $model = $model->where(['pay_channel' => $payChannel]);
  137. }
  138. if (!is_null($transactionNo)) {
  139. $model = $model->where(['transaction_no' => $transactionNo]);
  140. }
  141. if (!is_null($payStatus)) {
  142. $model = $model->where(['pay_status' => $payStatus]);
  143. }
  144. // 日期查询放最后.
  145. if (!empty($endDate)) {
  146. if ($endYmd != $startYmd) {
  147. $model = $model->whereNested(function (Model $query) use ($startDayObj, $endDayObj) {
  148. $t1 = $startDayObj;
  149. $t2 = $endDayObj;
  150. $query->whereBetween('created_at', [$t1, $t2]);
  151. });
  152. } else {
  153. $tmpEndDayObj = (clone $startDayObj)->endOfDay();
  154. $t1 = $startDayObj;
  155. $t2 = $tmpEndDayObj;
  156. $model = $model->whereBetween('created_at', [$t1, $t2]);
  157. }
  158. } else {
  159. $t = $startDayObj;
  160. $model = $model->where('created_at', '>=', $t);
  161. }
  162. $result = 0;
  163. if ($computeType == 'money') {
  164. $result = $model->sum('real_amount');
  165. } else {
  166. $result = $model->count();
  167. }
  168. return $result;
  169. }
  170. /**
  171. * 记录每层代理提成日志.
  172. * @param string $logId mongo支付日志_id
  173. * @return bool
  174. * @throws \KZ2\Laravel\Repositories\Exceptions\RepositoryException
  175. */
  176. public function recordCommissionOneDayByRoot($logId)
  177. {
  178. $logObj = PayLogsModel::where(['_id' => $logId, 'is_deduction' => 0])->first();
  179. if (empty($logObj->_id)) {
  180. return false;
  181. }
  182. if ($logObj->order_status != 1 || $logObj->pay_status != 1) {
  183. // 没有成功的订单不处理.
  184. return false;
  185. }
  186. $createdAt = $logObj->created_at;
  187. $date = Carbon::parse($createdAt)->toDateString();
  188. $orderAmount = $logObj->order_amount;
  189. $agentUid = $logObj->agent_uid;
  190. /**
  191. * @var $agentRepo AgentRepository;
  192. */
  193. $agentRepo = app(AgentRepository::class);
  194. $rootAgent = $agentRepo->makeModel()->query()->where(['uid' => $agentUid])->first();
  195. if (empty($rootAgent)) {
  196. return false;
  197. }
  198. self::loopParentCommission($logObj, $rootAgent->uid, $rootAgent->commission_ratio);
  199. return true;
  200. }
  201. /**
  202. * 递归循环上级记录.
  203. * @param $logObj
  204. * @param string $agentParentUid
  205. * @param int $diffRatio
  206. * @return false
  207. * @throws \KZ2\Laravel\Repositories\Exceptions\RepositoryException
  208. */
  209. private function loopParentCommission($logObj, $agentParentUid = '', $diffRatio = 0)
  210. {
  211. if ($logObj->is_deduction != 0) {
  212. // 如果是标记为扣量的订单,不给代理分,算官方的.
  213. return false;
  214. }
  215. if (empty($agentParentUid)) {
  216. return false;
  217. }
  218. $createdAt = $logObj->created_at;
  219. $date = Carbon::parse($createdAt)->toDateString();
  220. $parentAgent = $this->getAgentRepo()
  221. ->makeModel()
  222. ->query()
  223. ->where(['uid' => $agentParentUid])
  224. ->first(['id', 'uid', 'commission_ratio', 'commission_diff_ratio', 'parent_uid']);
  225. if (!empty($parentAgent)) {
  226. $commissionMoney = floatval(number_format($logObj->order_amount * ($diffRatio / 100), 2)); // 当前渠道的当前用户用commission_ratio计算
  227. $setarr = [
  228. 'date' => $date,
  229. 'channel_uid' => $logObj->channel_uid,
  230. 'root_agent_uid' => $logObj->agent_uid,
  231. 'agent_uid' => $agentParentUid,
  232. 'mom_app_uid' => $logObj->mom_app_uid,
  233. 'order_sn' => $logObj->order_sn,
  234. 'order_amount' => $logObj->order_amount,
  235. 'commission_money' => $commissionMoney,
  236. 'commission_curr_ratio' => $diffRatio,
  237. ];
  238. $parentLogObj = $this->getCommissionLogRepo()->create($setarr);
  239. return self::loopParentCommission($logObj, $parentAgent->parent_uid, $parentAgent->commission_diff_ratio);
  240. } else {
  241. return false;
  242. }
  243. }
  244. /**
  245. * 根据根用户订单增量更新代理属性一次性(不把下级的累加进来)
  246. * @param $logId
  247. * @param array $oldLog
  248. * @return false
  249. */
  250. public function updateAgentAttrsOnceByRootOrder($logId, $oldLog = [])
  251. {
  252. $logObj = PayLogsModel::where(['_id' => $logId])->first();
  253. if (empty($logObj->_id)) {
  254. return false;
  255. }
  256. $agentUid = $logObj->agent_uid;
  257. if (empty($agentUid)) {
  258. // 没有渠道,不叠加属性.
  259. return false;
  260. }
  261. $result = false;
  262. $originAgent = AgentModel::query()->where(['uid' => $agentUid])->first();
  263. DB::beginTransaction();
  264. try {
  265. // 加悲观锁,因为2个仓库可能同时更新表, 临时取消悲观锁.
  266. $agent = AgentAttrsModel::where(['agent_uid' => $agentUid])->firstOrFail();
  267. // 表没有commission_ratio,commission_diff_ratio,重新赋值.
  268. $todayDate = Carbon::now()->toDateString();
  269. $logDateYmd = Carbon::parse($logObj->created_at)->toDateString();
  270. $isNewToday = false;
  271. if ((empty($agent->td_date) || $agent->td_date != $todayDate) && $todayDate == $logDateYmd) {
  272. $isNewToday = true;
  273. $agent->td_date = $todayDate;
  274. }
  275. $agent = self::updateCommonAttrsFields($originAgent, $agent, $logObj, $oldLog, false);
  276. if ($agent->td_date == $todayDate && $todayDate == $logDateYmd) {
  277. // 更新td字段开头的.
  278. $agent = self::updateCommonAttrsFields($originAgent, $agent, $logObj, $oldLog, true, $isNewToday);
  279. }
  280. $result = $agent->save();
  281. if ($result) {
  282. // 对day表进行处理.
  283. $dayAttrsObj = AgentAttrsDayModel::whereDate('td_date', $logDateYmd)->where(['agent_uid' => $agentUid])->first();
  284. if (empty($dayAttrsObj)) {
  285. $setarr = [
  286. 'agent_uid' => $agentUid,
  287. 'td_date' => $logDateYmd,
  288. 'is_used' => 0,
  289. ];
  290. $dayAttrsObj = AgentAttrsDayModel::create($setarr);
  291. }
  292. $dayAttrsObj = self::updateCommonAttrsFields($originAgent, $dayAttrsObj, $logObj, $oldLog, true, false);
  293. // $fields = $agent->getCommonOrderSubffixFields();
  294. // foreach ($fields as $field) {
  295. // $tdFieldName = 'td_'. $field;
  296. // $dayAttrsObj->{$tdFieldName} = $agent->{$tdFieldName}; // 重新给day表赋值
  297. // }
  298. $dayAttrsObj->save();
  299. }
  300. DB::commit();
  301. } catch (\Exception $e) {
  302. DB::rollBack();
  303. logger('[error][StatisticsPayRepository][updateAgentAttrsOnceByRootOrder]', ['msg' => $e->getMessage(), 'log_id' => $logId, 'agent_uid' => $agentUid, 'detail' => $e->getTrace()]);
  304. }
  305. return $result;
  306. }
  307. /**
  308. * 更新订单公共字段.
  309. * @param mixed $originAgent 代理原始主表数据.
  310. * @param AgentAttrsModel $agent
  311. * @param PayLogsModel $logObj
  312. * @param array $oldLog
  313. * @param false $isForToday
  314. * @param false $isNewToday
  315. * @return mixed
  316. */
  317. private function updateCommonAttrsFields($originAgent, $agent, $logObj, $oldLog = [], $isForToday = false, $isNewToday = false)
  318. {
  319. $fields = $agent->getCommonOrderSubffixFields();
  320. foreach ($fields as $field) {
  321. ${$field} = $isForToday ? 'td_' . $field : $field;
  322. if ($isNewToday) {
  323. // 重制今日字段数据属性.
  324. $agent->{${$field}} = 0;
  325. }
  326. }
  327. if (empty($oldLog['pay_status'])) {
  328. // 新订单
  329. $agent->{$order_total} = $agent->{$order_total} + 1;
  330. $agent->{$order_money} += $logObj->real_amount;
  331. if ($logObj->device_type == 'A') {
  332. $agent->{$android_total} = $agent->{$android_total} + 1;
  333. $agent->{$android_money} += $logObj->real_amount;
  334. } elseif ($logObj->device_type == 'I') {
  335. $agent->{$ios_total} = $agent->{$ios_total} + 1;
  336. $agent->{$ios_money} += $logObj->real_amount;
  337. } elseif ($logObj->device_type == 'H') {
  338. $agent->{$h5_total} = $agent->{$h5_total} + 1;
  339. $agent->{$h5_money} += $logObj->real_amount;
  340. }
  341. if ($logObj->pay_status == 1) {
  342. $agent->{$order_success} = $agent->{$order_success} + 1;
  343. $agent->{$order_success_money} += $logObj->real_amount;
  344. if ($logObj->device_type == 'A') {
  345. $agent->{$android_success} = $agent->{$android_success} + 1;
  346. $agent->{$android_success_money} += $logObj->real_amount;
  347. } elseif ($logObj->device_type == 'I') {
  348. $agent->{$ios_success} = $agent->{$ios_success} + 1;
  349. $agent->{$ios_success_money} += $logObj->real_amount;
  350. } elseif ($logObj->device_type == 'H') {
  351. $agent->{$h5_success} = $agent->{$h5_success} + 1;
  352. $agent->{$h5_success_money} += $logObj->real_amount;
  353. }
  354. } elseif ($logObj->pay_status == 2) {
  355. $agent->{$order_failed} = $agent->{$order_failed} + 1;
  356. if ($logObj->device_type == 'A') {
  357. $agent->{$android_failed} = $agent->{$android_failed} + 1;
  358. } elseif ($logObj->device_type == 'I') {
  359. $agent->{$ios_failed} = $agent->{$ios_failed} + 1;
  360. } elseif ($logObj->device_type == 'H') {
  361. $agent->{$h5_failed} = $agent->{$h5_failed} + 1;
  362. }
  363. }
  364. if ($logObj->is_deduction == 1) {
  365. // 此订单没被扣量,就记录.
  366. $agent->{$deduction_total} = $agent->{$deduction_total} + 1;
  367. $agent->{$deduction_money} += $logObj->real_amount;
  368. if ($logObj->pay_status == 1) {
  369. $agent->{$deduction_success} = $agent->{$deduction_success} + 1;
  370. $agent->{$deduction_success_money} += $logObj->real_amount;
  371. } elseif ($logObj->pay_status == 2) {
  372. $agent->{$deduction_failed} = $agent->{$deduction_failed} + 1;
  373. }
  374. } else {
  375. if ($logObj->pay_status == 1) {
  376. $countCommissionMoney = floatval(number_format($logObj->real_amount * ($originAgent->commission_ratio / 100), 2)); // 当前渠道的当前用户用commission_ratio计算
  377. $agent->{$commission_money} += $countCommissionMoney;
  378. }
  379. }
  380. } else {
  381. // 更新老订单
  382. if ($oldLog['pay_status'] != $logObj->pay_status) {
  383. // 支付状态前后变化, 才执行更新.
  384. if ($logObj->pay_status == 1) {
  385. // 成功订单
  386. $agent->{$order_success} = $agent->{$order_success} + 1;
  387. $agent->{$order_success_money} += $logObj->real_amount;
  388. if ($logObj->device_type == 'A') {
  389. $agent->{$android_success} = $agent->{$android_success} + 1;
  390. $agent->{$android_success_money} += $logObj->real_amount;
  391. } elseif ($logObj->device_type == 'I') {
  392. $agent->{$ios_success} = $agent->{$ios_success} + 1;
  393. $agent->{$ios_success_money} += $logObj->real_amount;
  394. } elseif ($logObj->device_type == 'H') {
  395. $agent->{$h5_success} = $agent->{$h5_success} + 1;
  396. $agent->{$h5_success_money} += $logObj->real_amount;
  397. }
  398. } elseif ($logObj->pay_status == 2) {
  399. // 失败订单
  400. $agent->{$order_failed} = $agent->{$order_failed} + 1;
  401. if ($logObj->device_type == 'A') {
  402. $agent->{$android_failed} = $agent->{$android_failed} + 1;
  403. } elseif ($logObj->device_type == 'I') {
  404. $agent->{$ios_failed} = $agent->{$ios_failed} + 1;
  405. } elseif ($logObj->device_type == 'H') {
  406. $agent->{$h5_failed} = $agent->{$h5_failed} + 1;
  407. }
  408. }
  409. if ($logObj->is_deduction == 1) {
  410. // 订单被扣量,就记录.
  411. if ($logObj->pay_status == 1) {
  412. $agent->{$deduction_success} = $agent->{$deduction_success} + 1;
  413. $agent->{$deduction_success_money} += $logObj->real_amount;
  414. } elseif ($logObj->pay_status == 2) {
  415. $agent->{$deduction_failed} = $agent->{$deduction_failed} + 1;
  416. }
  417. } else {
  418. if ($logObj->pay_status == 1) {
  419. $countCommissionMoney = floatval(number_format($logObj->real_amount * ($originAgent->commission_ratio / 100), 2)); // 当前渠道的当前用户用commission_ratio计算
  420. $agent->{$commission_money} += $countCommissionMoney;
  421. }
  422. }
  423. }
  424. }
  425. return $agent;
  426. }
  427. /**
  428. * @return AgentRepository|\Illuminate\Contracts\Foundation\Application|mixed|null
  429. */
  430. private function getAgentRepo()
  431. {
  432. if (!$this->agentRepo instanceof AgentRepository) {
  433. $this->agentRepo = app(AgentRepository::class);
  434. }
  435. return $this->agentRepo;
  436. }
  437. /**
  438. * @return CommissionLogRepository|\Illuminate\Contracts\Foundation\Application|mixed|null
  439. */
  440. private function getCommissionLogRepo()
  441. {
  442. if (!$this->commissionLogRepo instanceof CommissionLogRepository) {
  443. $this->commissionLogRepo = app(CommissionLogRepository::class);
  444. }
  445. return $this->commissionLogRepo;
  446. }
  447. }