| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407 |
- <?php
- /**
- * 用途:分销用户统计(xhDistributionUser)
- * 谁用:hdApp 客户详情-分销板块
- */
- namespace bizHd\distribution\classes;
- use bizHd\base\classes\BaseClass;
- use bizHd\custom\classes\CustomClass;
- use common\components\dateUtil;
- use Yii;
- use yii\db\Query;
- class DistributionUserClass extends BaseClass
- {
- public static $baseFile = '\bizHd\distribution\models\DistributionUser';
- /**
- * 获取客户分销统计(无记录返回默认 0)
- * @param int $shopId 门店ID
- * @param int $customId 客户 xhCustom.id
- * @return array
- * @throws \Exception
- */
- public static function getUserStat($shopId, $customId)
- {
- $customId = (int)$customId;
- if ($customId <= 0) {
- throw new \Exception('客户ID无效');
- }
- $row = self::getByCondition(['shopId' => (int)$shopId, 'id' => $customId]);
- if (empty($row)) {
- return self::defaultStat($customId);
- }
- return [
- 'customId' => $customId,
- 'totalCommission' => $row['totalCommission'],
- 'inviteCount' => (int)$row['inviteCount'],
- 'orderCount' => (int)$row['orderCount'],
- 'pendingCommission' => $row['pendingCommission'],
- 'settledCommission' => $row['settledCommission'],
- ];
- }
- /**
- * 商城 C 端我的分红汇总
- * @param int $shopId
- * @param int $customId
- * @return array
- * @throws \Exception
- */
- public static function getMallMyStat($shopId, $customId)
- {
- $stat = self::getUserStat($shopId, $customId);
- $row = self::getByCondition(['shopId' => (int)$shopId, 'id' => (int)$customId]);
- $stat['availDeposit'] = round((float)(!empty($row) ? ($row['availDeposit'] ?? 0) : 0), 2);
- $period = dateUtil::formatTime('thisMonth', '', '');
- $monthCommission = 0;
- if (!empty($period['startTime']) && !empty($period['endTime'])) {
- $monthCommission = (float)(new Query())
- ->from('xhDistributionFlow')
- ->where([
- 'shopId' => (int)$shopId,
- 'xhCustomId' => (int)$customId,
- 'flowType' => 1,
- ])
- ->andWhere(['between', 'flowTime', $period['startTime'], $period['endTime']])
- ->sum('amount');
- }
- $stat['monthCommission'] = round($monthCommission, 2);
- return $stat;
- }
- /**
- * 无分销记录时的默认统计
- */
- protected static function defaultStat($customId)
- {
- return [
- 'customId' => (int)$customId,
- 'totalCommission' => '0.00',
- 'inviteCount' => 0,
- 'orderCount' => 0,
- 'pendingCommission' => '0.00',
- 'settledCommission' => '0.00',
- 'availDeposit' => '0.00',
- 'monthCommission' => '0.00',
- ];
- }
- /**
- * 拉新客户列表(xhDistributionUser + xhCustom)
- * 条件:du.inviterId = 当前分销员;绑定时间取 inviteTime
- * @param int $shopId
- * @param int $inviterId 邀请人 xhCustom.id
- * @return array
- * @throws \Exception
- */
- public static function getInviteList($shopId, $inviterId)
- {
- $shopId = (int)$shopId;
- $inviterId = (int)$inviterId;
- if ($inviterId <= 0) {
- throw new \Exception('客户ID无效');
- }
- $get = Yii::$app->request->get();
- $keyword = isset($get['keyword']) ? trim($get['keyword']) : '';
- $sortField = isset($get['sortField']) ? trim($get['sortField']) : 'inviteTime';
- $sortOrder = isset($get['sortOrder']) && strtolower($get['sortOrder']) === 'asc' ? 'ASC' : 'DESC';
- $page = isset($get['page']) ? max(1, (int)$get['page']) : 1;
- $pageSize = isset($get['pageSize']) && (int)$get['pageSize'] > 0
- ? (int)$get['pageSize']
- : (int)Yii::$app->params['pageSize'];
- $query = (new Query())
- ->from(['du' => 'xhDistributionUser'])
- ->leftJoin(['c' => 'xhCustom'], 'c.id = du.id')
- ->where(['du.shopId' => $shopId, 'du.inviterId' => $inviterId])
- ->select([
- 'du.id',
- 'du.inviteTime',
- 'du.upOrderCount',
- 'du.upCommissionAmount',
- 'c.name',
- 'c.mobile',
- 'c.avatar',
- ]);
- if ($keyword !== '') {
- $query->andWhere([
- 'or',
- ['like', 'c.name', $keyword],
- ['like', 'c.mobile', $keyword],
- ]);
- }
- // 排序:贡献字段取 up*(本人下单给上级的贡献)
- $orderMap = [
- 'inviteTime' => 'du.inviteTime',
- 'commission' => 'du.upCommissionAmount',
- 'orderCount' => 'du.upOrderCount',
- ];
- $orderColumn = isset($orderMap[$sortField]) ? $orderMap[$sortField] : 'du.inviteTime';
- $query->orderBy([$orderColumn => $sortOrder === 'ASC' ? SORT_ASC : SORT_DESC, 'du.id' => SORT_DESC]);
- $total = (int)(clone $query)->count('*', Yii::$app->db);
- $totalPage = $pageSize > 0 ? (int)ceil($total / $pageSize) : 0;
- $rows = $query->offset(($page - 1) * $pageSize)->limit($pageSize)->all(Yii::$app->db);
- $customRows = [];
- foreach ($rows as $row) {
- $customRows[] = [
- 'id' => (int)$row['id'],
- 'name' => $row['name'] ?: '',
- 'mobile' => $row['mobile'] ?: '',
- 'avatar' => $row['avatar'] ?: '',
- ];
- }
- $avatarMap = [];
- if (!empty($customRows)) {
- foreach (CustomClass::groupBaseInfo($customRows) as $customItem) {
- $avatarMap[(int)$customItem['id']] = $customItem;
- }
- }
- $list = [];
- foreach ($rows as $row) {
- $custom = $avatarMap[(int)$row['id']] ?? [];
- $bindTime = $row['inviteTime'];
- $list[] = [
- 'customId' => (int)$row['id'],
- 'name' => $custom['name'] ?? ($row['name'] ?: ''),
- 'mobile' => $custom['mobile'] ?? ($row['mobile'] ?: ''),
- 'smallAvatar' => $custom['smallAvatar'] ?? '',
- 'bindTime' => $bindTime,
- 'bindDays' => self::calcBindDays($bindTime),
- 'bindDaysText' => self::buildBindDaysText($bindTime),
- 'contribCommission' => round((float)$row['upCommissionAmount'], 2),
- 'contribOrderCount' => (int)$row['upOrderCount'],
- ];
- }
- return [
- 'list' => $list,
- 'totalPage' => $totalPage,
- 'moreData' => $page < $totalPage ? 1 : 0,
- ];
- }
- /**
- * 门店获佣人数明细(报表跳转)
- * @param int $shopId
- * @return array
- */
- public static function getShopDistList($shopId)
- {
- $shopId = (int)$shopId;
- $get = Yii::$app->request->get();
- $keyword = isset($get['keyword']) ? trim($get['keyword']) : '';
- $page = isset($get['page']) ? max(1, (int)$get['page']) : 1;
- $pageSize = isset($get['pageSize']) && (int)$get['pageSize'] > 0
- ? (int)$get['pageSize']
- : (int)Yii::$app->params['pageSize'];
- $period = self::buildReportPeriod($get);
- $orderQuery = (new Query())
- ->from('xhDistributionOrder')
- ->where(['shopId' => $shopId])
- ->andWhere(['>', 'distId', 0]);
- if ($period) {
- $orderQuery->andWhere(['between', 'orderTime', $period[0], $period[1]]);
- }
- if ($keyword !== '') {
- $orderQuery->innerJoin(['c' => 'xhCustom'], 'c.id = xhDistributionOrder.distId')
- ->andWhere([
- 'or',
- ['like', 'c.name', $keyword],
- ['like', 'c.mobile', $keyword],
- ]);
- }
- $subQuery = (clone $orderQuery)
- ->select([
- 'distId',
- 'orderCount' => 'COUNT(*)',
- 'commissionAmount' => 'SUM(commissionAmount)',
- 'distName' => 'MAX(distName)',
- ])
- ->groupBy('distId');
- $total = (int)(new Query())->from(['t' => $subQuery])->count('*', Yii::$app->db);
- $totalPage = $pageSize > 0 ? (int)ceil($total / $pageSize) : 0;
- $rows = (new Query())
- ->from(['t' => $subQuery])
- ->orderBy(['commissionAmount' => SORT_DESC, 'distId' => SORT_DESC])
- ->offset(($page - 1) * $pageSize)
- ->limit($pageSize)
- ->all(Yii::$app->db);
- $distIds = [];
- foreach ($rows as $row) {
- $distIds[] = (int)$row['distId'];
- }
- $avatarMap = [];
- if (!empty($distIds)) {
- // groupBaseInfo 仅处理头像,需先 getCustomByIds 拉取 name/mobile
- foreach (CustomClass::getCustomByIds($distIds) as $customItem) {
- $avatarMap[(int)$customItem['id']] = $customItem;
- }
- }
- $list = [];
- foreach ($rows as $row) {
- $distId = (int)$row['distId'];
- $custom = $avatarMap[$distId] ?? [];
- $list[] = [
- 'customId' => $distId,
- 'name' => $custom['name'] ?? ($row['distName'] ?? ''),
- 'mobile' => $custom['mobile'] ?? '',
- 'smallAvatar' => $custom['smallAvatar'] ?? '',
- 'orderCount' => (int)$row['orderCount'],
- 'commissionAmount' => round((float)$row['commissionAmount'], 2),
- ];
- }
- return [
- 'list' => $list,
- 'totalPage' => $totalPage,
- 'moreData' => $page < $totalPage ? 1 : 0,
- ];
- }
- /**
- * 门店拉新明细(报表跳转)
- * @param int $shopId
- * @return array
- */
- public static function getShopInviteList($shopId)
- {
- $shopId = (int)$shopId;
- $get = Yii::$app->request->get();
- $keyword = isset($get['keyword']) ? trim($get['keyword']) : '';
- $page = isset($get['page']) ? max(1, (int)$get['page']) : 1;
- $pageSize = isset($get['pageSize']) && (int)$get['pageSize'] > 0
- ? (int)$get['pageSize']
- : (int)Yii::$app->params['pageSize'];
- $period = self::buildReportPeriod($get);
- $query = (new Query())
- ->from(['du' => 'xhDistributionUser'])
- ->leftJoin(['c' => 'xhCustom'], 'c.id = du.id')
- ->leftJoin(['inv' => 'xhCustom'], 'inv.id = du.inviterId')
- ->where(['du.shopId' => $shopId])
- ->andWhere(['>', 'du.inviterId', 0])
- ->select([
- 'du.id',
- 'du.inviterId',
- 'du.inviteTime',
- 'du.upOrderCount',
- 'du.upCommissionAmount',
- 'c.name',
- 'c.mobile',
- 'c.avatar',
- 'inv.name AS inviterName',
- 'inv.mobile AS inviterMobile',
- ]);
- if ($period) {
- $query->andWhere(['between', 'du.inviteTime', $period[0], $period[1]]);
- }
- if ($keyword !== '') {
- $query->andWhere([
- 'or',
- ['like', 'c.name', $keyword],
- ['like', 'c.mobile', $keyword],
- ['like', 'inv.name', $keyword],
- ]);
- }
- $total = (int)(clone $query)->count('*', Yii::$app->db);
- $totalPage = $pageSize > 0 ? (int)ceil($total / $pageSize) : 0;
- $rows = $query
- ->orderBy(['du.inviteTime' => SORT_DESC, 'du.id' => SORT_DESC])
- ->offset(($page - 1) * $pageSize)
- ->limit($pageSize)
- ->all(Yii::$app->db);
- $customRows = [];
- foreach ($rows as $row) {
- $customRows[] = [
- 'id' => (int)$row['id'],
- 'name' => $row['name'] ?: '',
- 'mobile' => $row['mobile'] ?: '',
- 'avatar' => $row['avatar'] ?: '',
- ];
- }
- $avatarMap = [];
- if (!empty($customRows)) {
- foreach (CustomClass::groupBaseInfo($customRows) as $customItem) {
- $avatarMap[(int)$customItem['id']] = $customItem;
- }
- }
- $list = [];
- foreach ($rows as $row) {
- $custom = $avatarMap[(int)$row['id']] ?? [];
- $bindTime = $row['inviteTime'];
- $list[] = [
- 'customId' => (int)$row['id'],
- 'inviterId' => (int)$row['inviterId'],
- 'inviterName' => $row['inviterName'] ?: '',
- 'inviterMobile' => $row['inviterMobile'] ?: '',
- 'name' => $custom['name'] ?? ($row['name'] ?: ''),
- 'mobile' => $custom['mobile'] ?? ($row['mobile'] ?: ''),
- 'smallAvatar' => $custom['smallAvatar'] ?? '',
- 'bindTime' => $bindTime,
- 'bindDaysText' => self::buildBindDaysText($bindTime),
- 'contribCommission' => round((float)$row['upCommissionAmount'], 2),
- 'contribOrderCount' => (int)$row['upOrderCount'],
- ];
- }
- return [
- 'list' => $list,
- 'totalPage' => $totalPage,
- 'moreData' => $page < $totalPage ? 1 : 0,
- ];
- }
- /** 报表页时间范围 */
- protected static function buildReportPeriod($get)
- {
- $searchTime = isset($get['searchTime']) ? trim($get['searchTime']) : 'today';
- $startTime = isset($get['startTime']) ? trim($get['startTime']) : '';
- $endTime = isset($get['endTime']) ? trim($get['endTime']) : '';
- $period = dateUtil::formatTime($searchTime, $startTime, $endTime);
- if (empty($period['startTime']) || empty($period['endTime'])) {
- return null;
- }
- return [$period['startTime'], $period['endTime']];
- }
- /** 计算绑定天数 */
- protected static function calcBindDays($bindTime)
- {
- if (empty($bindTime) || $bindTime === '0000-00-00 00:00:00') {
- return 0;
- }
- $time = strtotime($bindTime);
- if ($time <= 0) {
- return 0;
- }
- return max(0, (int)floor((time() - $time) / 86400));
- }
- /** 绑定天数文案 */
- protected static function buildBindDaysText($bindTime)
- {
- $days = self::calcBindDays($bindTime);
- return '已绑定' . $days . '天';
- }
- }
|