DistributionUserClass.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. <?php
  2. /**
  3. * 用途:分销用户统计(xhDistributionUser)
  4. * 谁用:hdApp 客户详情-分销板块
  5. */
  6. namespace bizHd\distribution\classes;
  7. use bizHd\base\classes\BaseClass;
  8. use bizHd\custom\classes\CustomClass;
  9. use common\components\dateUtil;
  10. use Yii;
  11. use yii\db\Query;
  12. class DistributionUserClass extends BaseClass
  13. {
  14. public static $baseFile = '\bizHd\distribution\models\DistributionUser';
  15. /**
  16. * 获取客户分销统计(无记录返回默认 0)
  17. * @param int $shopId 门店ID
  18. * @param int $customId 客户 xhCustom.id
  19. * @return array
  20. * @throws \Exception
  21. */
  22. public static function getUserStat($shopId, $customId)
  23. {
  24. $customId = (int)$customId;
  25. if ($customId <= 0) {
  26. throw new \Exception('客户ID无效');
  27. }
  28. $row = self::getByCondition(['shopId' => (int)$shopId, 'id' => $customId]);
  29. if (empty($row)) {
  30. return self::defaultStat($customId);
  31. }
  32. return [
  33. 'customId' => $customId,
  34. 'totalCommission' => $row['totalCommission'],
  35. 'inviteCount' => (int)$row['inviteCount'],
  36. 'orderCount' => (int)$row['orderCount'],
  37. 'pendingCommission' => $row['pendingCommission'],
  38. 'settledCommission' => $row['settledCommission'],
  39. ];
  40. }
  41. /**
  42. * 商城 C 端我的分红汇总
  43. * @param int $shopId
  44. * @param int $customId
  45. * @return array
  46. * @throws \Exception
  47. */
  48. public static function getMallMyStat($shopId, $customId)
  49. {
  50. $stat = self::getUserStat($shopId, $customId);
  51. $row = self::getByCondition(['shopId' => (int)$shopId, 'id' => (int)$customId]);
  52. $stat['availDeposit'] = round((float)(!empty($row) ? ($row['availDeposit'] ?? 0) : 0), 2);
  53. $period = dateUtil::formatTime('thisMonth', '', '');
  54. $monthCommission = 0;
  55. if (!empty($period['startTime']) && !empty($period['endTime'])) {
  56. $monthCommission = (float)(new Query())
  57. ->from('xhDistributionFlow')
  58. ->where([
  59. 'shopId' => (int)$shopId,
  60. 'xhCustomId' => (int)$customId,
  61. 'flowType' => 1,
  62. ])
  63. ->andWhere(['between', 'flowTime', $period['startTime'], $period['endTime']])
  64. ->sum('amount');
  65. }
  66. $stat['monthCommission'] = round($monthCommission, 2);
  67. return $stat;
  68. }
  69. /**
  70. * 新建 xhCustom 时初始化 xhDistributionUser
  71. * 规则:customId 无记录则创建;有邀请人则写 inviterId、inviteTime,并给邀请人 inviteCount +1;已有记录则不操作
  72. * @param int $shopId 门店 ID
  73. * @param int $inviteeCustomId 被邀请人 xhCustom.id
  74. * @param int $inviterCustomId 邀请人 xhCustom.id,0 表示无邀请人
  75. * @return int 0未操作 1已创建且完成邀请绑定
  76. * @throws \Throwable
  77. */
  78. public static function bindInviteOnRegister($shopId, $inviteeCustomId, $inviterCustomId = 0)
  79. {
  80. $shopId = (int)$shopId;
  81. $inviteeCustomId = (int)$inviteeCustomId;
  82. $inviterCustomId = (int)$inviterCustomId;
  83. if ($shopId <= 0 || $inviteeCustomId <= 0) {
  84. return 0;
  85. }
  86. // 按 customId 查是否已有分销记录,有则不做任何操作
  87. $inviteeRow = self::getByCondition(['customId' => $inviteeCustomId]);
  88. if (!empty($inviteeRow)) {
  89. return 0;
  90. }
  91. // 校验邀请人(无效则仍创建被邀请人记录,但不绑定)
  92. $canBindInviter = false;
  93. if ($inviterCustomId > 0 && $inviterCustomId !== $inviteeCustomId) {
  94. $inviter = CustomClass::getById($inviterCustomId, true);
  95. if (!empty($inviter) && (int)$inviter->shopId === $shopId) {
  96. $canBindInviter = true;
  97. }
  98. }
  99. $createData = [
  100. 'id' => $inviteeCustomId,
  101. 'customId' => $inviteeCustomId,
  102. 'shopId' => $shopId,
  103. ];
  104. if ($canBindInviter) {
  105. $createData['inviterId'] = $inviterCustomId;
  106. $createData['inviteTime'] = date('Y-m-d H:i:s');
  107. }
  108. $transaction = Yii::$app->db->beginTransaction();
  109. try {
  110. try {
  111. self::add($createData, true);
  112. } catch (\yii\db\IntegrityException $e) {
  113. // 并发下记录已被创建,不做任何操作
  114. if (strpos($e->getMessage(), 'Duplicate entry') !== false) {
  115. $transaction->rollBack();
  116. return 0;
  117. }
  118. throw $e;
  119. }
  120. // 绑定邀请人成功后,邀请人拉新数量 +1
  121. if ($canBindInviter) {
  122. $inviterRow = self::getByCondition(['customId' => $inviterCustomId]);
  123. if (empty($inviterRow)) {
  124. self::add([
  125. 'id' => $inviterCustomId,
  126. 'customId' => $inviterCustomId,
  127. 'shopId' => $shopId,
  128. 'inviteCount' => 1,
  129. ], true);
  130. } else {
  131. static::$baseFile::updateAllCounters(
  132. ['inviteCount' => 1],
  133. ['customId' => $inviterCustomId]
  134. );
  135. }
  136. }
  137. $transaction->commit();
  138. return $canBindInviter ? 1 : 0;
  139. } catch (\Throwable $e) {
  140. $transaction->rollBack();
  141. throw $e;
  142. }
  143. }
  144. /**
  145. * 无分销记录时的默认统计
  146. */
  147. protected static function defaultStat($customId)
  148. {
  149. return [
  150. 'customId' => (int)$customId,
  151. 'totalCommission' => '0.00',
  152. 'inviteCount' => 0,
  153. 'orderCount' => 0,
  154. 'pendingCommission' => '0.00',
  155. 'settledCommission' => '0.00',
  156. 'availDeposit' => '0.00',
  157. 'monthCommission' => '0.00',
  158. ];
  159. }
  160. /**
  161. * 拉新客户列表(xhDistributionUser + xhCustom)
  162. * 条件:du.inviterId = 当前分销员;绑定时间取 inviteTime
  163. * @param int $shopId
  164. * @param int $inviterId 邀请人 xhCustom.id
  165. * @return array
  166. * @throws \Exception
  167. */
  168. public static function getInviteList($shopId, $inviterId)
  169. {
  170. $shopId = (int)$shopId;
  171. $inviterId = (int)$inviterId;
  172. if ($inviterId <= 0) {
  173. throw new \Exception('客户ID无效');
  174. }
  175. $get = Yii::$app->request->get();
  176. $keyword = isset($get['keyword']) ? trim($get['keyword']) : '';
  177. $sortField = isset($get['sortField']) ? trim($get['sortField']) : 'inviteTime';
  178. $sortOrder = isset($get['sortOrder']) && strtolower($get['sortOrder']) === 'asc' ? 'ASC' : 'DESC';
  179. $page = isset($get['page']) ? max(1, (int)$get['page']) : 1;
  180. $pageSize = isset($get['pageSize']) && (int)$get['pageSize'] > 0
  181. ? (int)$get['pageSize']
  182. : (int)Yii::$app->params['pageSize'];
  183. $query = (new Query())
  184. ->from(['du' => 'xhDistributionUser'])
  185. ->leftJoin(['c' => 'xhCustom'], 'c.id = du.id')
  186. ->where(['du.shopId' => $shopId, 'du.inviterId' => $inviterId])
  187. ->select([
  188. 'du.id',
  189. 'du.inviteTime',
  190. 'du.upOrderCount',
  191. 'du.upCommissionAmount',
  192. 'c.name',
  193. 'c.mobile',
  194. 'c.avatar',
  195. ]);
  196. if ($keyword !== '') {
  197. $query->andWhere([
  198. 'or',
  199. ['like', 'c.name', $keyword],
  200. ['like', 'c.mobile', $keyword],
  201. ]);
  202. }
  203. // 排序:贡献字段取 up*(本人下单给上级的贡献)
  204. $orderMap = [
  205. 'inviteTime' => 'du.inviteTime',
  206. 'commission' => 'du.upCommissionAmount',
  207. 'orderCount' => 'du.upOrderCount',
  208. ];
  209. $orderColumn = isset($orderMap[$sortField]) ? $orderMap[$sortField] : 'du.inviteTime';
  210. $query->orderBy([$orderColumn => $sortOrder === 'ASC' ? SORT_ASC : SORT_DESC, 'du.id' => SORT_DESC]);
  211. $total = (int)(clone $query)->count('*', Yii::$app->db);
  212. $totalPage = $pageSize > 0 ? (int)ceil($total / $pageSize) : 0;
  213. $rows = $query->offset(($page - 1) * $pageSize)->limit($pageSize)->all(Yii::$app->db);
  214. $customRows = [];
  215. foreach ($rows as $row) {
  216. $customRows[] = [
  217. 'id' => (int)$row['id'],
  218. 'name' => $row['name'] ?: '',
  219. 'mobile' => $row['mobile'] ?: '',
  220. 'avatar' => $row['avatar'] ?: '',
  221. ];
  222. }
  223. $avatarMap = [];
  224. if (!empty($customRows)) {
  225. foreach (CustomClass::groupBaseInfo($customRows) as $customItem) {
  226. $avatarMap[(int)$customItem['id']] = $customItem;
  227. }
  228. }
  229. $list = [];
  230. foreach ($rows as $row) {
  231. $custom = $avatarMap[(int)$row['id']] ?? [];
  232. $bindTime = $row['inviteTime'];
  233. $list[] = [
  234. 'customId' => (int)$row['id'],
  235. 'name' => $custom['name'] ?? ($row['name'] ?: ''),
  236. 'mobile' => $custom['mobile'] ?? ($row['mobile'] ?: ''),
  237. 'smallAvatar' => $custom['smallAvatar'] ?? '',
  238. 'bindTime' => $bindTime,
  239. 'bindDays' => self::calcBindDays($bindTime),
  240. 'bindDaysText' => self::buildBindDaysText($bindTime),
  241. 'contribCommission' => round((float)$row['upCommissionAmount'], 2),
  242. 'contribOrderCount' => (int)$row['upOrderCount'],
  243. ];
  244. }
  245. return [
  246. 'list' => $list,
  247. 'totalPage' => $totalPage,
  248. 'moreData' => $page < $totalPage ? 1 : 0,
  249. ];
  250. }
  251. /**
  252. * 门店获佣人数明细(报表跳转)
  253. * @param int $shopId
  254. * @return array
  255. */
  256. public static function getShopDistList($shopId)
  257. {
  258. $shopId = (int)$shopId;
  259. $get = Yii::$app->request->get();
  260. $keyword = isset($get['keyword']) ? trim($get['keyword']) : '';
  261. $page = isset($get['page']) ? max(1, (int)$get['page']) : 1;
  262. $pageSize = isset($get['pageSize']) && (int)$get['pageSize'] > 0
  263. ? (int)$get['pageSize']
  264. : (int)Yii::$app->params['pageSize'];
  265. $period = self::buildReportPeriod($get);
  266. $orderQuery = (new Query())
  267. ->from('xhDistributionOrder')
  268. ->where(['shopId' => $shopId])
  269. ->andWhere(['>', 'distId', 0]);
  270. if ($period) {
  271. $orderQuery->andWhere(['between', 'orderTime', $period[0], $period[1]]);
  272. }
  273. if ($keyword !== '') {
  274. $orderQuery->innerJoin(['c' => 'xhCustom'], 'c.id = xhDistributionOrder.distId')
  275. ->andWhere([
  276. 'or',
  277. ['like', 'c.name', $keyword],
  278. ['like', 'c.mobile', $keyword],
  279. ]);
  280. }
  281. $subQuery = (clone $orderQuery)
  282. ->select([
  283. 'distId',
  284. 'orderCount' => 'COUNT(*)',
  285. 'commissionAmount' => 'SUM(commissionAmount)',
  286. 'distName' => 'MAX(distName)',
  287. ])
  288. ->groupBy('distId');
  289. $total = (int)(new Query())->from(['t' => $subQuery])->count('*', Yii::$app->db);
  290. $totalPage = $pageSize > 0 ? (int)ceil($total / $pageSize) : 0;
  291. $rows = (new Query())
  292. ->from(['t' => $subQuery])
  293. ->orderBy(['commissionAmount' => SORT_DESC, 'distId' => SORT_DESC])
  294. ->offset(($page - 1) * $pageSize)
  295. ->limit($pageSize)
  296. ->all(Yii::$app->db);
  297. $distIds = [];
  298. foreach ($rows as $row) {
  299. $distIds[] = (int)$row['distId'];
  300. }
  301. $avatarMap = [];
  302. if (!empty($distIds)) {
  303. // groupBaseInfo 仅处理头像,需先 getCustomByIds 拉取 name/mobile
  304. foreach (CustomClass::getCustomByIds($distIds) as $customItem) {
  305. $avatarMap[(int)$customItem['id']] = $customItem;
  306. }
  307. }
  308. $list = [];
  309. foreach ($rows as $row) {
  310. $distId = (int)$row['distId'];
  311. $custom = $avatarMap[$distId] ?? [];
  312. $list[] = [
  313. 'customId' => $distId,
  314. 'name' => $custom['name'] ?? ($row['distName'] ?? ''),
  315. 'mobile' => $custom['mobile'] ?? '',
  316. 'smallAvatar' => $custom['smallAvatar'] ?? '',
  317. 'orderCount' => (int)$row['orderCount'],
  318. 'commissionAmount' => round((float)$row['commissionAmount'], 2),
  319. ];
  320. }
  321. return [
  322. 'list' => $list,
  323. 'totalPage' => $totalPage,
  324. 'moreData' => $page < $totalPage ? 1 : 0,
  325. ];
  326. }
  327. /**
  328. * 门店拉新明细(报表跳转)
  329. * @param int $shopId
  330. * @return array
  331. */
  332. public static function getShopInviteList($shopId)
  333. {
  334. $shopId = (int)$shopId;
  335. $get = Yii::$app->request->get();
  336. $keyword = isset($get['keyword']) ? trim($get['keyword']) : '';
  337. $page = isset($get['page']) ? max(1, (int)$get['page']) : 1;
  338. $pageSize = isset($get['pageSize']) && (int)$get['pageSize'] > 0
  339. ? (int)$get['pageSize']
  340. : (int)Yii::$app->params['pageSize'];
  341. $period = self::buildReportPeriod($get);
  342. $query = (new Query())
  343. ->from(['du' => 'xhDistributionUser'])
  344. ->leftJoin(['c' => 'xhCustom'], 'c.id = du.id')
  345. ->leftJoin(['inv' => 'xhCustom'], 'inv.id = du.inviterId')
  346. ->where(['du.shopId' => $shopId])
  347. ->andWhere(['>', 'du.inviterId', 0])
  348. ->select([
  349. 'du.id',
  350. 'du.inviterId',
  351. 'du.inviteTime',
  352. 'du.upOrderCount',
  353. 'du.upCommissionAmount',
  354. 'c.name',
  355. 'c.mobile',
  356. 'c.avatar',
  357. 'inv.name AS inviterName',
  358. 'inv.mobile AS inviterMobile',
  359. ]);
  360. if ($period) {
  361. $query->andWhere(['between', 'du.inviteTime', $period[0], $period[1]]);
  362. }
  363. if ($keyword !== '') {
  364. $query->andWhere([
  365. 'or',
  366. ['like', 'c.name', $keyword],
  367. ['like', 'c.mobile', $keyword],
  368. ['like', 'inv.name', $keyword],
  369. ]);
  370. }
  371. $total = (int)(clone $query)->count('*', Yii::$app->db);
  372. $totalPage = $pageSize > 0 ? (int)ceil($total / $pageSize) : 0;
  373. $rows = $query
  374. ->orderBy(['du.inviteTime' => SORT_DESC, 'du.id' => SORT_DESC])
  375. ->offset(($page - 1) * $pageSize)
  376. ->limit($pageSize)
  377. ->all(Yii::$app->db);
  378. $customRows = [];
  379. foreach ($rows as $row) {
  380. $customRows[] = [
  381. 'id' => (int)$row['id'],
  382. 'name' => $row['name'] ?: '',
  383. 'mobile' => $row['mobile'] ?: '',
  384. 'avatar' => $row['avatar'] ?: '',
  385. ];
  386. }
  387. $avatarMap = [];
  388. if (!empty($customRows)) {
  389. foreach (CustomClass::groupBaseInfo($customRows) as $customItem) {
  390. $avatarMap[(int)$customItem['id']] = $customItem;
  391. }
  392. }
  393. $list = [];
  394. foreach ($rows as $row) {
  395. $custom = $avatarMap[(int)$row['id']] ?? [];
  396. $bindTime = $row['inviteTime'];
  397. $list[] = [
  398. 'customId' => (int)$row['id'],
  399. 'inviterId' => (int)$row['inviterId'],
  400. 'inviterName' => $row['inviterName'] ?: '',
  401. 'inviterMobile' => $row['inviterMobile'] ?: '',
  402. 'name' => $custom['name'] ?? ($row['name'] ?: ''),
  403. 'mobile' => $custom['mobile'] ?? ($row['mobile'] ?: ''),
  404. 'smallAvatar' => $custom['smallAvatar'] ?? '',
  405. 'bindTime' => $bindTime,
  406. 'bindDaysText' => self::buildBindDaysText($bindTime),
  407. 'contribCommission' => round((float)$row['upCommissionAmount'], 2),
  408. 'contribOrderCount' => (int)$row['upOrderCount'],
  409. ];
  410. }
  411. return [
  412. 'list' => $list,
  413. 'totalPage' => $totalPage,
  414. 'moreData' => $page < $totalPage ? 1 : 0,
  415. ];
  416. }
  417. /** 报表页时间范围 */
  418. protected static function buildReportPeriod($get)
  419. {
  420. $searchTime = isset($get['searchTime']) ? trim($get['searchTime']) : 'today';
  421. $startTime = isset($get['startTime']) ? trim($get['startTime']) : '';
  422. $endTime = isset($get['endTime']) ? trim($get['endTime']) : '';
  423. $period = dateUtil::formatTime($searchTime, $startTime, $endTime);
  424. if (empty($period['startTime']) || empty($period['endTime'])) {
  425. return null;
  426. }
  427. return [$period['startTime'], $period['endTime']];
  428. }
  429. /** 计算绑定天数 */
  430. protected static function calcBindDays($bindTime)
  431. {
  432. if (empty($bindTime) || $bindTime === '0000-00-00 00:00:00') {
  433. return 0;
  434. }
  435. $time = strtotime($bindTime);
  436. if ($time <= 0) {
  437. return 0;
  438. }
  439. return max(0, (int)floor((time() - $time) / 86400));
  440. }
  441. /** 绑定天数文案 */
  442. protected static function buildBindDaysText($bindTime)
  443. {
  444. $days = self::calcBindDays($bindTime);
  445. return '已绑定' . $days . '天';
  446. }
  447. }