DistributionUserClass.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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. * 无分销记录时的默认统计
  71. */
  72. protected static function defaultStat($customId)
  73. {
  74. return [
  75. 'customId' => (int)$customId,
  76. 'totalCommission' => '0.00',
  77. 'inviteCount' => 0,
  78. 'orderCount' => 0,
  79. 'pendingCommission' => '0.00',
  80. 'settledCommission' => '0.00',
  81. 'availDeposit' => '0.00',
  82. 'monthCommission' => '0.00',
  83. ];
  84. }
  85. /**
  86. * 拉新客户列表(xhDistributionUser + xhCustom)
  87. * 条件:du.inviterId = 当前分销员;绑定时间取 inviteTime
  88. * @param int $shopId
  89. * @param int $inviterId 邀请人 xhCustom.id
  90. * @return array
  91. * @throws \Exception
  92. */
  93. public static function getInviteList($shopId, $inviterId)
  94. {
  95. $shopId = (int)$shopId;
  96. $inviterId = (int)$inviterId;
  97. if ($inviterId <= 0) {
  98. throw new \Exception('客户ID无效');
  99. }
  100. $get = Yii::$app->request->get();
  101. $keyword = isset($get['keyword']) ? trim($get['keyword']) : '';
  102. $sortField = isset($get['sortField']) ? trim($get['sortField']) : 'inviteTime';
  103. $sortOrder = isset($get['sortOrder']) && strtolower($get['sortOrder']) === 'asc' ? 'ASC' : 'DESC';
  104. $page = isset($get['page']) ? max(1, (int)$get['page']) : 1;
  105. $pageSize = isset($get['pageSize']) && (int)$get['pageSize'] > 0
  106. ? (int)$get['pageSize']
  107. : (int)Yii::$app->params['pageSize'];
  108. $query = (new Query())
  109. ->from(['du' => 'xhDistributionUser'])
  110. ->leftJoin(['c' => 'xhCustom'], 'c.id = du.id')
  111. ->where(['du.shopId' => $shopId, 'du.inviterId' => $inviterId])
  112. ->select([
  113. 'du.id',
  114. 'du.inviteTime',
  115. 'du.upOrderCount',
  116. 'du.upCommissionAmount',
  117. 'c.name',
  118. 'c.mobile',
  119. 'c.avatar',
  120. ]);
  121. if ($keyword !== '') {
  122. $query->andWhere([
  123. 'or',
  124. ['like', 'c.name', $keyword],
  125. ['like', 'c.mobile', $keyword],
  126. ]);
  127. }
  128. // 排序:贡献字段取 up*(本人下单给上级的贡献)
  129. $orderMap = [
  130. 'inviteTime' => 'du.inviteTime',
  131. 'commission' => 'du.upCommissionAmount',
  132. 'orderCount' => 'du.upOrderCount',
  133. ];
  134. $orderColumn = isset($orderMap[$sortField]) ? $orderMap[$sortField] : 'du.inviteTime';
  135. $query->orderBy([$orderColumn => $sortOrder === 'ASC' ? SORT_ASC : SORT_DESC, 'du.id' => SORT_DESC]);
  136. $total = (int)(clone $query)->count('*', Yii::$app->db);
  137. $totalPage = $pageSize > 0 ? (int)ceil($total / $pageSize) : 0;
  138. $rows = $query->offset(($page - 1) * $pageSize)->limit($pageSize)->all(Yii::$app->db);
  139. $customRows = [];
  140. foreach ($rows as $row) {
  141. $customRows[] = [
  142. 'id' => (int)$row['id'],
  143. 'name' => $row['name'] ?: '',
  144. 'mobile' => $row['mobile'] ?: '',
  145. 'avatar' => $row['avatar'] ?: '',
  146. ];
  147. }
  148. $avatarMap = [];
  149. if (!empty($customRows)) {
  150. foreach (CustomClass::groupBaseInfo($customRows) as $customItem) {
  151. $avatarMap[(int)$customItem['id']] = $customItem;
  152. }
  153. }
  154. $list = [];
  155. foreach ($rows as $row) {
  156. $custom = $avatarMap[(int)$row['id']] ?? [];
  157. $bindTime = $row['inviteTime'];
  158. $list[] = [
  159. 'customId' => (int)$row['id'],
  160. 'name' => $custom['name'] ?? ($row['name'] ?: ''),
  161. 'mobile' => $custom['mobile'] ?? ($row['mobile'] ?: ''),
  162. 'smallAvatar' => $custom['smallAvatar'] ?? '',
  163. 'bindTime' => $bindTime,
  164. 'bindDays' => self::calcBindDays($bindTime),
  165. 'bindDaysText' => self::buildBindDaysText($bindTime),
  166. 'contribCommission' => round((float)$row['upCommissionAmount'], 2),
  167. 'contribOrderCount' => (int)$row['upOrderCount'],
  168. ];
  169. }
  170. return [
  171. 'list' => $list,
  172. 'totalPage' => $totalPage,
  173. 'moreData' => $page < $totalPage ? 1 : 0,
  174. ];
  175. }
  176. /**
  177. * 门店获佣人数明细(报表跳转)
  178. * @param int $shopId
  179. * @return array
  180. */
  181. public static function getShopDistList($shopId)
  182. {
  183. $shopId = (int)$shopId;
  184. $get = Yii::$app->request->get();
  185. $keyword = isset($get['keyword']) ? trim($get['keyword']) : '';
  186. $page = isset($get['page']) ? max(1, (int)$get['page']) : 1;
  187. $pageSize = isset($get['pageSize']) && (int)$get['pageSize'] > 0
  188. ? (int)$get['pageSize']
  189. : (int)Yii::$app->params['pageSize'];
  190. $period = self::buildReportPeriod($get);
  191. $orderQuery = (new Query())
  192. ->from('xhDistributionOrder')
  193. ->where(['shopId' => $shopId])
  194. ->andWhere(['>', 'distId', 0]);
  195. if ($period) {
  196. $orderQuery->andWhere(['between', 'orderTime', $period[0], $period[1]]);
  197. }
  198. if ($keyword !== '') {
  199. $orderQuery->innerJoin(['c' => 'xhCustom'], 'c.id = xhDistributionOrder.distId')
  200. ->andWhere([
  201. 'or',
  202. ['like', 'c.name', $keyword],
  203. ['like', 'c.mobile', $keyword],
  204. ]);
  205. }
  206. $subQuery = (clone $orderQuery)
  207. ->select([
  208. 'distId',
  209. 'orderCount' => 'COUNT(*)',
  210. 'commissionAmount' => 'SUM(commissionAmount)',
  211. 'distName' => 'MAX(distName)',
  212. ])
  213. ->groupBy('distId');
  214. $total = (int)(new Query())->from(['t' => $subQuery])->count('*', Yii::$app->db);
  215. $totalPage = $pageSize > 0 ? (int)ceil($total / $pageSize) : 0;
  216. $rows = (new Query())
  217. ->from(['t' => $subQuery])
  218. ->orderBy(['commissionAmount' => SORT_DESC, 'distId' => SORT_DESC])
  219. ->offset(($page - 1) * $pageSize)
  220. ->limit($pageSize)
  221. ->all(Yii::$app->db);
  222. $distIds = [];
  223. foreach ($rows as $row) {
  224. $distIds[] = (int)$row['distId'];
  225. }
  226. $avatarMap = [];
  227. if (!empty($distIds)) {
  228. // groupBaseInfo 仅处理头像,需先 getCustomByIds 拉取 name/mobile
  229. foreach (CustomClass::getCustomByIds($distIds) as $customItem) {
  230. $avatarMap[(int)$customItem['id']] = $customItem;
  231. }
  232. }
  233. $list = [];
  234. foreach ($rows as $row) {
  235. $distId = (int)$row['distId'];
  236. $custom = $avatarMap[$distId] ?? [];
  237. $list[] = [
  238. 'customId' => $distId,
  239. 'name' => $custom['name'] ?? ($row['distName'] ?? ''),
  240. 'mobile' => $custom['mobile'] ?? '',
  241. 'smallAvatar' => $custom['smallAvatar'] ?? '',
  242. 'orderCount' => (int)$row['orderCount'],
  243. 'commissionAmount' => round((float)$row['commissionAmount'], 2),
  244. ];
  245. }
  246. return [
  247. 'list' => $list,
  248. 'totalPage' => $totalPage,
  249. 'moreData' => $page < $totalPage ? 1 : 0,
  250. ];
  251. }
  252. /**
  253. * 门店拉新明细(报表跳转)
  254. * @param int $shopId
  255. * @return array
  256. */
  257. public static function getShopInviteList($shopId)
  258. {
  259. $shopId = (int)$shopId;
  260. $get = Yii::$app->request->get();
  261. $keyword = isset($get['keyword']) ? trim($get['keyword']) : '';
  262. $page = isset($get['page']) ? max(1, (int)$get['page']) : 1;
  263. $pageSize = isset($get['pageSize']) && (int)$get['pageSize'] > 0
  264. ? (int)$get['pageSize']
  265. : (int)Yii::$app->params['pageSize'];
  266. $period = self::buildReportPeriod($get);
  267. $query = (new Query())
  268. ->from(['du' => 'xhDistributionUser'])
  269. ->leftJoin(['c' => 'xhCustom'], 'c.id = du.id')
  270. ->leftJoin(['inv' => 'xhCustom'], 'inv.id = du.inviterId')
  271. ->where(['du.shopId' => $shopId])
  272. ->andWhere(['>', 'du.inviterId', 0])
  273. ->select([
  274. 'du.id',
  275. 'du.inviterId',
  276. 'du.inviteTime',
  277. 'du.upOrderCount',
  278. 'du.upCommissionAmount',
  279. 'c.name',
  280. 'c.mobile',
  281. 'c.avatar',
  282. 'inv.name AS inviterName',
  283. 'inv.mobile AS inviterMobile',
  284. ]);
  285. if ($period) {
  286. $query->andWhere(['between', 'du.inviteTime', $period[0], $period[1]]);
  287. }
  288. if ($keyword !== '') {
  289. $query->andWhere([
  290. 'or',
  291. ['like', 'c.name', $keyword],
  292. ['like', 'c.mobile', $keyword],
  293. ['like', 'inv.name', $keyword],
  294. ]);
  295. }
  296. $total = (int)(clone $query)->count('*', Yii::$app->db);
  297. $totalPage = $pageSize > 0 ? (int)ceil($total / $pageSize) : 0;
  298. $rows = $query
  299. ->orderBy(['du.inviteTime' => SORT_DESC, 'du.id' => SORT_DESC])
  300. ->offset(($page - 1) * $pageSize)
  301. ->limit($pageSize)
  302. ->all(Yii::$app->db);
  303. $customRows = [];
  304. foreach ($rows as $row) {
  305. $customRows[] = [
  306. 'id' => (int)$row['id'],
  307. 'name' => $row['name'] ?: '',
  308. 'mobile' => $row['mobile'] ?: '',
  309. 'avatar' => $row['avatar'] ?: '',
  310. ];
  311. }
  312. $avatarMap = [];
  313. if (!empty($customRows)) {
  314. foreach (CustomClass::groupBaseInfo($customRows) as $customItem) {
  315. $avatarMap[(int)$customItem['id']] = $customItem;
  316. }
  317. }
  318. $list = [];
  319. foreach ($rows as $row) {
  320. $custom = $avatarMap[(int)$row['id']] ?? [];
  321. $bindTime = $row['inviteTime'];
  322. $list[] = [
  323. 'customId' => (int)$row['id'],
  324. 'inviterId' => (int)$row['inviterId'],
  325. 'inviterName' => $row['inviterName'] ?: '',
  326. 'inviterMobile' => $row['inviterMobile'] ?: '',
  327. 'name' => $custom['name'] ?? ($row['name'] ?: ''),
  328. 'mobile' => $custom['mobile'] ?? ($row['mobile'] ?: ''),
  329. 'smallAvatar' => $custom['smallAvatar'] ?? '',
  330. 'bindTime' => $bindTime,
  331. 'bindDaysText' => self::buildBindDaysText($bindTime),
  332. 'contribCommission' => round((float)$row['upCommissionAmount'], 2),
  333. 'contribOrderCount' => (int)$row['upOrderCount'],
  334. ];
  335. }
  336. return [
  337. 'list' => $list,
  338. 'totalPage' => $totalPage,
  339. 'moreData' => $page < $totalPage ? 1 : 0,
  340. ];
  341. }
  342. /** 报表页时间范围 */
  343. protected static function buildReportPeriod($get)
  344. {
  345. $searchTime = isset($get['searchTime']) ? trim($get['searchTime']) : 'today';
  346. $startTime = isset($get['startTime']) ? trim($get['startTime']) : '';
  347. $endTime = isset($get['endTime']) ? trim($get['endTime']) : '';
  348. $period = dateUtil::formatTime($searchTime, $startTime, $endTime);
  349. if (empty($period['startTime']) || empty($period['endTime'])) {
  350. return null;
  351. }
  352. return [$period['startTime'], $period['endTime']];
  353. }
  354. /** 计算绑定天数 */
  355. protected static function calcBindDays($bindTime)
  356. {
  357. if (empty($bindTime) || $bindTime === '0000-00-00 00:00:00') {
  358. return 0;
  359. }
  360. $time = strtotime($bindTime);
  361. if ($time <= 0) {
  362. return 0;
  363. }
  364. return max(0, (int)floor((time() - $time) / 86400));
  365. }
  366. /** 绑定天数文案 */
  367. protected static function buildBindDaysText($bindTime)
  368. {
  369. $days = self::calcBindDays($bindTime);
  370. return '已绑定' . $days . '天';
  371. }
  372. }