| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466 |
- <?php
- namespace addons\WechatVideoShop\common\service;
- use addons\WechatVideoShop\common\enums\WechatVideoShopEnums;
- use addons\WechatVideoShop\common\expand\sdk\weixin\src\model\sharer\SharerListModel;
- use addons\WechatVideoShop\common\expand\sdk\weixin\src\model\sharer\SharerUnbindModel;
- use addons\WechatVideoShop\common\expand\sdk\weixin\src\request\sharer\SharerListRequest;
- use addons\WechatVideoShop\common\expand\sdk\weixin\src\request\sharer\SharerUnbindRequest;
- use addons\WechatVideoShop\common\helper\WechatRequestHelper;
- use addons\WechatVideoShop\common\logic\ConditionUpgradeLogic;
- use addons\WechatVideoShop\common\logic\SyncSharerLogic;
- use addons\WechatVideoShop\common\models\WechatVideoShop;
- use addons\WechatVideoShop\common\models\WechatVideoShopLevel;
- use addons\WechatVideoShop\common\models\WechatVideoShopOrder;
- use addons\WechatVideoShop\common\models\WechatVideoShopSharer;
- use common\enums\AddonsEnum;
- use common\enums\RabbitMqEnum;
- use common\enums\StatusEnum;
- use common\helpers\FormatHelper;
- use common\models\order\Order;
- use common\models\user\User;
- use common\models\user\UserInfo;
- class SharerService extends AbstractService
- {
- /**
- * 分销员
- * @param int $mall_id
- * @param array $params
- * @return array|false|mixed|string|void
- */
- public function page(int $mall_id, array $params)
- {
- $where = [
- ['mall_id' => $mall_id],
- ['status' => StatusEnum::ENABLED]
- ];
- if (!empty($params['shop_id'])) {
- $where[] = ['shop_id' => $params['shop_id']];
- }
- if (!empty($params['level'])) {
- $where[] = ['level' => $params['level']];
- }
- if (!empty($params['member'])) {
- $uids = User::find()
- ->where(['mall_id' => $mall_id])
- ->andWhere(['or', ['like', 'username', $params['member']], ['like', 'mobile', $params['member']], ['like', 'nickname', $params['member']]])
- ->select('id')->column();
- if (empty($uids)) return [];
- $where[] = ['user_id' => $uids];
- }
- if (!empty($params['status'])) {
- if ($params['status'] == 1) { // 100已绑定,1未绑定
- $where[] = ['user_id' => 0];
- } else {
- $where[] = ['>', 'user_id', 0];
- }
- }
- // 邀请时间
- if (!empty($params['invite_start_date'])) $where[] = ['>=', 'invite_at', strtotime($params['invite_start_date'])];
- if (!empty($params['invite_end_date'])) $where[] = ['<=', 'invite_at', strtotime($params['invite_end_date'])];
- // 绑定时间
- if (!empty($params['bind_start_date'])) $where[] = ['>=', 'bind_at', strtotime($params['bind_start_date'])];
- if (!empty($params['bind_end_date'])) $where[] = ['<=', 'bind_at', strtotime($params['bind_end_date'])];
- $ret = WechatVideoShopSharer::listPage([
- 'where' => $where,
- 'limit' => $params['limit'] ?? 10,
- 'page' => $params['page'] ?? 1,
- 'order' => 'id desc',
- 'with' => ['user', 'shop' => function($query) {
- $query->select('id, name');
- }]
- ]);
- if (!empty(WechatVideoShop::getStaticError())) return WechatVideoShop::getStaticError();
- return $ret;
- }
- /**
- * 废弃
- * @param int $mall_id
- * @param array $params
- * @return array|string
- * @throws \Exception
- */
- public function index(int $mall_id, array $params)
- {
- $request = new SharerListRequest($this->config);
- $shareModel = new SharerListModel();
- $shareModel->page = intval($params['page'] ?? 1);
- $shareModel->page_size = intval($params['limit'] ?? 10);
- $shareModel->sharer_type = intval($params['sharer_type'] ?? 1);
- $resp = WechatRequestHelper::accessTokenAndToArray($request, $shareModel);
- if (!empty($resp['sharer_info_list'])) {
- $openIds = array_column($resp['sharer_info_list'], "openid");
- // 获取用户
- $users = $this->getSharerByOpenIds($mall_id, $openIds);
- $flag = $this->checkBind($mall_id, $users, $resp['sharer_info_list'], $openIds, $params['shop_id']);
- if (is_string($flag)) return $flag;
- if ($flag === true) { // 需要重载
- $users = $this->getSharerByOpenIds($mall_id, $openIds);
- }
- foreach ($resp['sharer_info_list'] as &$item) {
- $item['sharer'] = $users[$item['openid']] ?? null;
- }
- return $resp['sharer_info_list'];
- }
- return [];
- }
- /**
- * @param int $mall_id
- * @param array $openIds
- * @return false|mixed|string
- */
- protected function getSharerByOpenIds(int $mall_id, array $openIds)
- {
- $users = WechatVideoShopSharer::lists([
- 'where' => [
- ['mall_id' => $mall_id],
- ['openid' => $openIds],
- ['status' => StatusEnum::ENABLED],
- ],
- 'with' => ['user' => function($query) {
- $query->select('id, username, nickname, avatar_url, mobile');
- }, 'shop'],
- 'index' => 'openid'
- ]);
- if (!empty(WechatVideoShopSharer::getStaticError())) return WechatVideoShopSharer::getStaticError();
- return $users;
- }
- /**
- * 检测是否需要绑定
- * @param int $mall_id
- * @param array $users
- * @param array $sharers
- * @param array $openIds
- * @param int $shop_id
- * @return bool|string
- */
- protected function checkBind(int $mall_id, array $users, array $sharers, array $openIds, int $shop_id)
- {
- throw new \Exception("废弃方法");
- $tmp_sharers = [];
- foreach ($sharers as $sharer) {
- $tmp_sharers[$sharer['openid']] = $sharer;
- }
- // 判断是否有绑定过
- $userInfos = UserInfo::lists([
- 'where' => [
- ['mall_id' => $mall_id],
- ['openid' => $openIds],
- ['status' => StatusEnum::ENABLED]
- ],
- 'index' => 'openid'
- ]);
- $ret = false;
- if (!empty($userInfos)) {
- // 需要绑定用户
- foreach ($userInfos as $openid => $userInfo) {
- if (empty($users[$openid])) {
- $data = $tmp_sharers[$openid];
- $data['user_id'] = $userInfo['user_id'];
- $data['shop_id'] = $shop_id;
- // 执行绑定
- $flag = $this->bind($mall_id, $data, false);
- if (is_string($flag)) return $flag;
- $ret = true;
- }
- }
- }
- return $ret;
- }
- /**
- * 绑定
- * @param int $mall_id
- * @param array $params
- * @param bool $bind_user_info
- * @return true|string
- */
- public function bind(int $mall_id, array $params, bool $bind_user_info = true)
- {
- $sharer = WechatVideoShopSharer::getOne([
- ['mall_id' => $mall_id],
- ['openid' => $params['openid']],
- ['id' => $params['id']]
- ]);
- if (empty($sharer)) return '分销员不存在';
- if (!empty($sharer->user_id)) return '当前用户已绑定分销员';
- $t = \Yii::$app->db->beginTransaction();
- try {
- $sharer->user_id = $params['user_id'];
- $sharer->bind_at = time();
- if (!$sharer->save()) throw new \Exception($sharer->getErrorMessage());
- // 有可能已经存在
- if ($bind_user_info) {
- // 用户那边需要加数据
- UserInfo::setData([
- 'openid' => $params['openid'],
- 'unionid' => $params['unionid'],
- 'platform' => User::PLATFORM_WECHAT_VIDEO_SHOP,
- 'mall_id' => $mall_id,
- 'user_id' => $params['user_id']
- ]);
- if (!empty(UserInfo::getStaticError())) throw new \Exception(UserInfo::getStaticError());
- }
- // 触发升级
- $cond_upgrade = new ConditionUpgradeLogic();
- $cond_upgrade->execute(AddonsEnum::ADDONS_NAME_WECHAT_VIDEO_SHOP,
- (new WechatVideoShopSharer()), (new WechatVideoShopLevel()), [
- 'id' => 0,
- 'user_id' => $params['user_id'],
- 'mall_id' => $this->config['mall_id']
- ]);
- $t->commit();
- } catch (\Exception $e) {
- $t->rollBack();
- return $e->getMessage();
- }
- return true;
- }
- /**
- * 解绑
- * @param int $mall_id
- * @param array $params
- * @return string|true
- */
- public function unbind(int $mall_id, array $params)
- {
- try {
- $config = (new ShopService())->getShop($params['shop_id']);
- // 请求微信端
- $sharerRequest = new SharerUnbindRequest($config);
- $sharerModel = new SharerUnbindModel();
- $sharerModel->openid_list = [
- $params['openid']
- ];
- WechatRequestHelper::accessTokenAndToArray($sharerRequest, $sharerModel);
- $sharer = WechatVideoShopSharer::getOne([
- ['mall_id' => $mall_id],
- ['openid' => $params['openid']]
- ]);
- // 删除分销员
- if (!empty($sharer)) {
- $t = \Yii::$app->db->beginTransaction();
- $sharer->status = StatusEnum::DELETE;
- if (!$sharer->save()) throw new \Exception($sharer->getErrorMessage());
- $userInfo = UserInfo::getOne([
- ['mall_id' => $mall_id],
- ['openid' => $params['openid']]
- ]);
- if (!empty($userInfo)) {
- $userInfo->status = StatusEnum::DELETE;
- if (!$userInfo->save()) throw new \Exception($userInfo->getErrorMessage());
- }
- $t->commit();
- }
- } catch (\Exception $e) {
- if (!empty($t)) $t->rollBack();
- return $e->getMessage();
- }
- return true;
- }
- /**
- * 同步分销员
- * @param array $params
- * @return bool 如果返回false则跳过循环,否则继续下一页
- * @throws \Exception
- */
- public function sync(array $params): bool
- {
- $request = new SharerListRequest($this->config);
- $shareModel = new SharerListModel();
- $shareModel->page = intval($params['page'] ?? 1);
- $shareModel->page_size = intval($params['limit'] ?? 10);
- $shareModel->sharer_type = intval($params['sharer_type'] ?? 1);
- $resp = WechatRequestHelper::accessTokenAndToArray($request, $shareModel);
- // 写入
- if (!empty($resp['sharer_info_list'])) {
- $openIds = array_column($resp['sharer_info_list'], "openid");
- $unionids = array_column($resp['sharer_info_list'], "unionid", "openid");
- $local_sharers = WechatVideoShopSharer::find()
- ->where(['shop_id' => $this->shop_id])
- ->andWhere(['mall_id' => $this->mall_id])
- ->andWhere(['status' => StatusEnum::ENABLED])
- ->andWhere(['openid' => $openIds])->select('openid')->column();
- if (count($local_sharers) != count($resp['sharer_info_list'])) {
- // 所以需要处理
- foreach ($resp['sharer_info_list'] as $item) {
- if (!empty(!in_array($item['openid'], $local_sharers))) {
- if (!empty($unionids[$item['openid']])) { // 查找用户
- $userInfo = UserInfo::getOne([
- ['mall_id' => $this->mall_id],
- ['unionid' => $unionids[$item['openid']]]
- ]);
- if (!empty($userInfo)) {
- UserInfo::setData([
- 'openid' => $item['openid'],
- 'unionid' => $item['unionid'],
- 'platform' => User::PLATFORM_WECHAT_VIDEO_SHOP,
- 'mall_id' => $this->mall_id,
- 'user_id' => $userInfo->user_id
- ]);
- if (!empty(UserInfo::getStaticError())) throw new \Exception(UserInfo::getStaticError());
- }
- }
- // 这个需要写入
- $sharerModel = new WechatVideoShopSharer();
- $sharerModel->mall_id = $this->config['mall_id'];
- $sharerModel->shop_id = $this->shop_id;
- $sharerModel->openid = $item['openid'];
- $sharerModel->unionid = $item['unionid'];
- $sharerModel->invite_at = $item['bind_time'];
- $sharerModel->sharer_type = $item['sharer_type'];
- $sharerModel->nickname = $item['nickname'];
- $sharerModel->user_id = !empty($userInfo) ? $userInfo->user_id : 0; // 绑定用户
- $sharerModel->bind_at = $sharerModel->user_id > 0 ? time() : 0; // 绑定时间
- if (!$sharerModel->save()) {
- \Yii::error(__METHOD__ . " 同步分销员失败 " . $sharerModel->getErrorMessage());
- }
- // 触发条件升级
- if (!empty($sharerModel->user_id)) {
- $cond_upgrade = new ConditionUpgradeLogic();
- $cond_upgrade->execute(AddonsEnum::ADDONS_NAME_WECHAT_VIDEO_SHOP,
- (new WechatVideoShopSharer()), (new WechatVideoShopLevel()), [
- 'id' => 0,
- 'user_id' => $sharerModel->user_id,
- 'mall_id' => $this->config['mall_id']
- ]);
- }
- }
- }
- return true;
- } else {
- WechatVideoShopSharer::updateAll(['status' => StatusEnum::ENABLED], ['and', ['shop_id' => $this->shop_id],
- ['mall_id' => $this->config['mall_id']], ['in', 'openid', $openIds]]);
- }
- }
- return false;
- }
- /**
- * 异步同步
- * @return void
- * @throws \Exception
- */
- public function async()
- {
- \Yii::$app->services->rabbitMq->push(RabbitMqEnum::EXCHANGE_TASK, RabbitMqEnum::TASK_QUEUE,
- [], SyncSharerLogic::class, 'sharer');
- }
- /**
- * 客户列表
- * @param int $mall_id
- * @param array $params
- * @return array|false|mixed|string|null
- */
- public function customerList(int $mall_id, array $params)
- {
- $where = [
- ['mall_id' => $mall_id],
- ['status' => StatusEnum::ENABLED],
- ['parent_id' => $params['parent_id']]
- ];
- if (!empty($params['user_id'])) {
- $where[] = ['user_id' => $params['user_id']];
- } else if (!empty($params['keyword'])) {
- $uids = User::find()->where(['mall_id' => $mall_id])
- ->andWhere(['or', ['like', 'nickname', $params['keyword']], ['like', 'mobile', $params['keyword']]])
- ->select('id')->column();
- if (empty($uids)) return [];
- $where[] = ['user_id' => $uids];
- }
- if (!empty($params['start_date'])) $where[] = ['>=', 'created_at', strtotime($params['start_date'])];
- if (!empty($params['end_date'])) $where[] = ['<=', 'created_at', strtotime($params['end_date'])];
- $ret = WechatVideoShopOrder::listPage([
- 'where' => $where,
- 'limit' => $params['limit'] ?? 10,
- 'order' => 'id desc',
- 'group' => 'user_id',
- 'with' => ['user' => function($query) {
- $query->select('id, nickname, username, mobile, created_at, avatar_url');
- }]
- ]);
- if (!empty(WechatVideoShopOrder::getStaticError())) return WechatVideoShopOrder::getStaticError();
- if (!empty($ret['list'])) {
- $uids = array_column($ret['list'], 'user_id');
- // 订单数量,支付金额
- $cnt = Order::find()->where(['mall_id' => $mall_id])
- ->andWhere(['pay_status' => StatusEnum::ENABLED])
- ->andWhere(['user_id' => $uids])
- ->andWhere(['order_source' => WechatVideoShopEnums::ADDONS_NAME])
- ->select('COUNT(*) as cnt, user_id')->groupBy('user_id')->asArray()->all();
- $amount = Order::find()->where(['mall_id' => $mall_id])
- ->andWhere(['pay_status' => StatusEnum::ENABLED])
- ->andWhere(['user_id' => $uids])
- ->andWhere(['order_source' => WechatVideoShopEnums::ADDONS_NAME])
- ->select('SUM(pay_money) as amount, user_id')->groupBy('user_id')->asArray()->all();
- $cnt_map = array_column($cnt, 'cnt', 'user_id');
- $amount_map = array_column($amount, 'amount', 'user_id');
- foreach ($ret['list'] as &$item) {
- $item['order_num'] = $cnt_map[$item['user_id']] ?? 0;
- $item['pay_amount'] = $amount_map[$item['user_id']] ?? 0;
- }
- }
- return $ret;
- }
- }
|