InviteUserService.class.php 20.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
<?php
/**
 * Created by PhpStorm.
 * User: Slok
 * Date: 16/9/29
 * Time: 20:44
 */

namespace Common\Service;

use Common\Common\Constant;
use Common\Common\Cache;
use Common\Common\ShortUrl;
use Common\Common\Sms;
use Common\Common\User;
use Common\Model\AttrModel;
use Common\Model\InviteUserModel;
use Think\Log;
use VcySDK\Mail;
use VcySDK\Service;

class InviteUserService extends AbstractService
{
    /**
     * 审批状态,等待审批
     */
    const CHECK_STATUS_WAIT = 1;

    /**
     * 审批状态,审批通过
     */
    const CHECK_STATUS_PASS = 2;

    /**
     * 审批状态,审批驳回
     */
    const CHECK_STATUS_FAIL = 3;

    /**
     * 列表类型,我的邀请列表
     */
    const MY_INVITE_LIST = 1;

    /**
     * 列表类型,我的审核列表
     */
    const MY_CHECK_LIST = 2;

    /**
     * 用户是否已关注,是
     */
    const USER_IS_FOLLOW_TRUE = 1;

    /**
     * 用户是否已关注,否
     */
    const USER_IS_FOLLOW_FALSE = 0;

    /**
     * 是否已通知邀请人,是
     */
    const INVITER_IS_NOTICE_TRUE = 1;

    /**
     * 是否已通知邀请人,否
     */
    const INVITER_IS_NOTICE_FALSE = 0;

    // 构造方法
    public function __construct()
    {

        parent::__construct();
        $this->_d = new InviteUserModel();
    }

    /**
     * 根据表单数据中的手机号、微信号、邮箱获取邀请数据
     * @author zhonglei
     * @param array $form
     * @param bool  $ignoreRefuse 忽略拒绝
     * @return array
     */
    public function getInviteUser($form, $ignoreRefuse = false)
    {

        $dict = ['memMobile' => 'mobile', 'memWeixin' => 'weixin', 'memEmail' => 'email'];
        $data = [];

        foreach ($dict as $k => $v) {
            if (isset($form[$k]['attr_value']) && $form[$k]['attr_value']) {
                $data[$v] = $form[$k]['attr_value'];
            }
        }

        return $this->_d->getByAccount($data, $ignoreRefuse);
    }

    /**
     * 发送审核结果通知
     * @author zhonglei
     * @param array $inviteData   邀请数据
     * @param int   $check_status 审核结果
     * @param string $reason      拒绝理由
     * @return void
     */
    public function sendNotice($inviteData, $check_status, $reason = '')
    {

        // 获取企业信息
        $ep = Cache::instance()->get(
            'Common.EnterpriseDetail',
            '',
            ['expire' => cfg('ENTERPRISE_DETAIL_CACHE_EXPIRE')]
        );

        // 发送短信
        if ($inviteData['mobile']) {
            // 获取短连接
            $longUrl = oaUrl('Frontend/Index/InviteSuccess/Index', ['invite_id' => $inviteData['invite_id']]);
            $url = ShortUrl::create($longUrl);

            $smsContent = [
                self::CHECK_STATUS_PASS => [
                    'templateId' => Sms::SMS_TMP_ID_INVITE_SUCCESS,
                    'message' => json_encode([
                        'enterprise_name' => $ep['epName'],
                        'url' => $url
                    ])
                ],
                self::CHECK_STATUS_FAIL => [
                    'templateId' => Sms::SMS_TMP_ID_INVITE_FAILED,
                    'message' => json_encode([
                        'enterprise_name' => $ep['epName'],
                        'reason' => $reason
                    ])
                ]
            ];

            // 成功的情况 发送短链 超出长度 分两次发
            $sms = &Sms::instance();
            $sms->send(
                $inviteData['mobile'],
                $smsContent[$check_status]['message'],
                '',
                '',
                Sms::CHANNEL_SENDCLOUD,
                $smsContent[$check_status]['templateId']
            );
        }

        // 发送邮件
        if ($inviteData['email']) {
            $userServ = new User();
            $inviter = $userServ->getByUid($inviteData['invite_uid']);

            $tplnames = [
                self::CHECK_STATUS_PASS => 'yq_apply_to_join_enterprise_succeed',
                self::CHECK_STATUS_FAIL => 'yq_apply_to_join_enterprise_failed',
            ];

            $subjects = [
                self::CHECK_STATUS_PASS => '申请加入' . $ep['epName'] . '成功',
                self::CHECK_STATUS_FAIL => '申请加入' . $ep['epName'] . '失败',
            ];

            $params = [
                '%qy_name%' => $ep['epName'],
                '%reason%' => $reason,
                '%inviter%' => $inviter['memUsername'],
                '%qrcode%' => $ep['corpWxqrcode'],
                '%date%' => rgmdate(NOW_TIME, 'Y-m-d'),
            ];

            $mailSdk = new Mail(Service::instance());
            $mailSdk->sendTemplateMail([
                'mcTplName' => $tplnames[$check_status],
                'mcEmails' => [$inviteData['email']],
                'mcSubject' => $subjects[$check_status],
                'mcVars' => $params,
            ]);
        }
    }

    /**
     * 检查是否有等待审核的邀请人员
     * @author tony
     * @return bool
     */
    public function haveInviteUserWait()
    {

        $count = $this->_d->count_by_conds(['check_status' => InviteUserService::CHECK_STATUS_WAIT]);

        return $count > 0;
    }

    /**
     * 检查邀请表单数据
     * @author tony
     * @param array $form     表单数据
     * @param array $attrList 属性数据
     * @return bool
     */
    public function checkInviteData($form, $attrList)
    {

        // 遍历表单设置,检查必填项
        foreach ($attrList as $fieldSetting) {
            // 跳过非必填项(跳过直属上级,不给被邀请人选择直属上级的权限)
            if ($fieldSetting['is_required'] == AttrModel::ATTR_IS_REQUIRED_FALSE || $fieldSetting['type'] == AttrModel::ATTR_TYPE_LEADER) {
                continue;
            }

            $is_exist = false;
            // 检查必填项是否存在,且值不能为空
            if (isset($form[$fieldSetting['field_name']])) {
                $attr_value = $form[$fieldSetting['field_name']]['attr_value'];
                if (is_array($attr_value)) {
                    $is_exist = !empty($attr_value);
                } else {
                    $is_exist = strlen(trim($attr_value)) > 0;
                }
            }
            if (!$is_exist) {
                E('1009:' . $fieldSetting['attr_name'] . '不能为空');
            }
        }

        return true;
    }

    /**
     * 搜索邀请信息邀请ID列表
     * @param array  $condition
     * @param mixed  $page_option
     * @param array  $order_option
     * @param string $field
     * @return array|bool
     */
    public function listByRight($condition, $page_option = null, $order_option = array(), $field = '*')
    {

        try {
            return $this->_d->listByRight($condition, $page_option, $order_option, $field);
        } catch (\Exception $e) {
            E($e->getCode() . ":" . $e->getMessage());

            return false;
        }
    }


    /**
     * 删除手机号,微信号,邮箱关联的邀请记录
     * @param $mobileArr
     * @param $weixinArr
     * @param $emailArr
     * @return bool
     */
    public function delInviteUserRecord($mobileArr = [], $weixinArr = [], $emailArr = []) {

        if (count($mobileArr) == 0) {
            E("_ERR_WHERE_MOBILE_NOT_EMPTY");
        }

        return $this->_d->delInviteUserRecord([
            'mobile' => implode(",", $this->formatWhereParams($mobileArr)),
            'weixin' => count($weixinArr) > 0 ? implode(",", $this->formatWhereParams($weixinArr)) : "",
            'email' => count($emailArr) > 0 ? implode(",", $this->formatWhereParams($emailArr)) : ""
        ]);
    }

    /**
     * 格式化SQL条件
     * @param $arr
     * @return mixed
     */
    private function formatWhereParams($arr)
    {
        foreach ($arr as $key => &$item) {

            if (empty($item)) {
                unset($arr[$key]);
                continue;
            }

            $item = "'" . $item . "'";
        }

        return $arr;
    }

    /**
     * 根据条件获取邀请列表
     * @param $conds
     * @param $pageOption
     * @param $orderOption
     * @return array|bool
     */
    public function listInviteUserByParams($conds, $pageOption, $orderOption) {
        return $this->_d->listInviteUserByParams($conds, $pageOption, $orderOption);
    }


    /**
     * 批量审批被邀请加入的员工
     * @param $inviteIds
     * @param $checkStatus
     * @param $rejectDesc
     * @param $checkUser
     * @return int
     */
    public function batchApprovalInvitee($inviteIds, $checkStatus, $rejectDesc, $checkUser) {

        $inviteUserRecords = $this->_d->list_by_conds([
            'invite_id' => $inviteIds
        ]);

        // 审批驳回
        if ($checkStatus == InviteUserService::CHECK_STATUS_FAIL) {
            return $this->rejectHandle($checkStatus, $rejectDesc, $checkUser, $inviteUserRecords);
        } else {
            return $this->agreeHandle($checkStatus, $checkUser, $inviteUserRecords);
        }
    }


    /**
     * 封装新增用户数据
     * 以UC接口参数字段为键,拼接用户信息
     * @param $fillInForm
     * @param $attrs
     * @param $inviteUserInfo
     * @return array
     */
    private function formatInsertData($fillInForm, $attrs, $inviteUserInfo)
    {
        // 所在组织
        $insertData = [
            'dpIdList' => (array)$fillInForm['dpIdList']['attr_value']
        ];

        foreach ($attrs as $attr) {
            $insertData[$attr['field_name']] = $this->getAttrValue($fillInForm, $attr);
        }

        $insertData['memJoinType'] = InviteUserModel::USER_INVITE_JOIN;
        $insertData['memJoinInviter'] = $inviteUserInfo['memUsername'];

        return $insertData;
    }

    /**
     * 获取属性值
     * @param $form
     * @param $attr
     * @return mixed
     */
    private function getAttrValue($form, $attr)
    {
        // 属性类型是多选或者图片
        $isCheckBoxOrPictureType = in_array($form[$attr['field_name']]['type'], [
            AttrModel::ATTR_TYPE_CHECKBOX,
            AttrModel::ATTR_TYPE_PICTURE,
        ]);

        // 属性值不为空功
        $attrValueNotEmpty = !empty($form[$attr['field_name']]['attr_value']);

        if ($isCheckBoxOrPictureType && $attrValueNotEmpty) {
            return serialize($form[$attr['field_name']]['attr_value']);
        } else {
            return $form[$attr['field_name']]['attr_value'];
        }
    }

    /**
     * 驳回处理
     * @param $checkStatus
     * @param $rejectDesc
     * @param $checkUser
     * @param $inviteUserRecords
     * @return int
     */
    private function rejectHandle($checkStatus, $rejectDesc, $checkUser, $inviteUserRecords)
    {
        $errorTotal = 0;

        // 修改审批人UID、审批状态、审批时间、审批人类型
        $updateData = [
            'check_uid' => $checkUser['eaId'],
            'check_status' => $checkStatus,
            'check_time' => MILLI_TIME,
            'check_type' => InviteUserModel::CHECK_TYPE_ADMIN,
            'reason' => $rejectDesc
        ];

        // 更新审批结果
        foreach ($inviteUserRecords as $inviteData) {

            // 待审核的数据才处理
            if ($inviteData['check_status'] != InviteUserModel::CHECK_STATUS_WAIT) {
                continue;
            }

            $this->_d->start_trans();

            try {
                $this->_d->update($inviteData['invite_id'], $updateData);
                $this->_d->commit();

                // 发送消息异常, 不影响主流程
                try {
                    $this->sendNotice($inviteData, $checkStatus, $rejectDesc);
                } catch (\Exception $e) {
                    Log::record("邀请人员-管理员审批发送审批驳回通知异常: " . $e->getMessage());
                }

            } catch (\Exception $e) {
                Log::record("管理后台审批邀请加入员工异常: " . $e->getMessage(), Log::ERR);
                $this->_d->rollback();

                // 记录失败次数
                $errorTotal += 1;
            }
        }

        return $errorTotal;
    }

    /**
     * 同意处理
     * @param $checkStatus
     * @param $checkUser
     * @param $inviteUserRecords
     * @return int
     */
    private function agreeHandle($checkStatus, $checkUser, $inviteUserRecords)
    {
        $errorTotal = 0;

        // 邀请人uids
        $inviteUserIds = array_column($inviteUserRecords, "invite_uid");

        // 邀请人信息
        $inviteUsers = User::instance()->listByUid($inviteUserIds);

        // 邀请属性配置
        $attrService = new AttrService();
        $attrs = $attrService->getAttrList(true, [AttrModel::ATTR_TYPE_SPECIAL, AttrModel::ATTR_TYPE_LEADER]);

        $userServ = new UserService();
        foreach ($inviteUserRecords as $inviteData) {

            // 格式化用户填写的邀请表单数据
            $fillInForm = unserialize($inviteData['form']);

            // 将field_name设置为key
            $fillInForm = array_combine_by_key($fillInForm, 'field_name');

            // 封装需要新增的用户数据
            $insertData = $this->formatInsertData($fillInForm, $attrs, $inviteUsers[$inviteData['invite_id']]);

            try {

                // 调用UC新增员工
                $addUserResult = $userServ->saveUser('', $insertData);

                // 修改审批人UID、审批状态、审批时间、审批人类型
                $updateData = [
                    'check_uid' => $checkUser['eaId'],
                    'check_status' => $checkStatus,
                    'check_time' => MILLI_TIME,
                    'check_type' => InviteUserModel::CHECK_TYPE_ADMIN,
                    'uid' => $addUserResult['memUid']
                ];

                $this->_d->update($inviteData['invite_id'], $updateData);

                // 发送消息异常, 不影响主流程
                try {
                    $this->sendNotice($inviteData, $checkStatus);
                } catch (\Exception $e) {
                    Log::record("邀请人员-管理员审批发送审批通过通知异常: " . $e->getMessage());
                }

            } catch (\Exception $e) {
                Log::record("管理后台审批邀请加入员工异常: " . $e->getMessage(), Log::ERR);

                // 记录失败次数
                $errorTotal += 1;
            }

        }

        clear_cache();

        return $errorTotal;
    }

    /**
     * 校验并格式化要修改的邀请人员信息
     * @author liyifei
     * @param array $form 新提交的表单信息
     * @param array $old_form 原邀请人员信息
     * @return array
     */
    public function formatInviteData($form, $old_form)
    {
        // 仅校验"姓名"、手机""、"组织"、"性别"四个必填属性是否存在
        $keys = ['memUsername', 'dpIdList', 'memMobile', 'memGender'];
        $fields = array_column($form, 'field_name');
        if (array_diff($keys, $fields)) {
            E('_ERR_PARAM_FORMAT_LOSE');
        }

        // 不可重复的属性值(手机、邮箱、微信)
        $form = array_combine_by_key($form, 'field_name');
        $userServ = new User();
        $isExist = $userServ->checkMemInfoSingle(
            $form['memMobile']['attr_value'],
            $form['memEmail']['attr_value'],
            $form['memWeixin']['attr_value']);

        // 对比新老表单数据:属性是否有变化
        $is_change = false;
        $old_form = array_combine_by_key($old_form, 'field_name');
        $old_fields = array_column($old_form, 'field_name');
        if (array_diff($old_fields, $fields)) {
            $is_change = true;
        }

        // 校验参数值、与老数据对比
        $data = [];
        $check_field_name = ['memUsername', 'memMobile', 'memWeixin', 'memEmail', 'dpIdList', 'memJob', 'memRole'];

        foreach ($form as $attr) {
            $field_name = $attr['field_name'];
            $attr_value = $attr['attr_value'];

            switch ($field_name) {
                case 'memUsername':
                    // 校验"姓名"有效性
                    $name_len = mb_strlen($attr_value);
                    if ($name_len > 50 || $name_len == 0) {
                        E(L('_ERR_ILLEGAL_PARAM', ['name' => '姓名']));
                    }

                    // 与原表单数据对比
                    if (isset($old_form[$field_name]) && $old_form[$field_name]['attr_value'] != $attr_value) {
                        $data['username'] = $attr_value;
                    }
                    break;

                case 'memMobile':
                    // 校验"手机号码"唯一性
                    if (!$attr_value || $isExist['memMobile'] == Constant::MEM_INFO_EXIST) {
                        E(L('_ERR_PARAM_EXISTED', ['name' => '手机号码']));
                    }

                    // "手机号"不可编辑
                    if ($attr_value != $old_form[$field_name]['attr_value']) {
                        E(L('_ERR_PARAM_NOT_ALLOW_EDIT', ['name' => '手机号码']));
                    }

                    // 与原表单数据对比
                    if (isset($old_form[$field_name]) && $old_form[$field_name]['attr_value'] != $attr_value) {
                        $data['mobile'] = $attr_value;
                    }
                    break;

                case 'memWeixin':
                    // 校验"微信号"唯一性
                    if ($attr_value && $isExist['memWeixin'] == Constant::MEM_INFO_EXIST) {
                        E(L('_ERR_PARAM_EXISTED', ['name' => '微信号']));
                    }

                    // 与原表单数据对比
                    if (isset($old_form[$field_name]) && $old_form[$field_name]['attr_value'] != $attr_value) {
                        $data['weixin'] = $attr_value;
                    }
                    break;

                case 'memEmail':
                    // 校验"邮箱"有效性
                    if ($attr_value && false === filter_var($attr_value, FILTER_VALIDATE_EMAIL)) {
                        E(L('_ERR_ILLEGAL_PARAM', ['name' => '邮箱']));
                    }

                    // 校验"邮箱"唯一性
                    if ($isExist['memEmail'] == Constant::MEM_INFO_EXIST) {
                        E(L('_ERR_PARAM_EXISTED', ['name' => '邮箱']));
                    }

                    // 与原表单数据对比
                    if (isset($old_form[$field_name]) && $old_form[$field_name]['attr_value'] != $attr_value) {
                        $data['email'] = $attr_value;
                    }
                    break;

                case 'dpIdList':
                    // 与原表单数据对比
                    if (isset($old_form[$field_name]) && $old_form[$field_name]['attr_value'] != $attr_value) {
                        $data['dp_id'] = $attr_value;
                    }
                    break;

                case 'memJob':
                    // 与原表单数据对比
                    if (isset($old_form[$field_name]) && $old_form[$field_name]['attr_value'] != $attr_value) {
                        $data['job_name'] = $attr_value;
                    }
                    break;

                case 'memRole':
                    // 与原表单数据对比
                    if (isset($old_form[$field_name]) && $old_form[$field_name]['attr_value'] != $attr_value) {
                        $data['role_name'] = $attr_value;
                    }
                    break;
            }

            // 以上固定属性有改动时,即说明form有改动;若无改动,则继续对比剩余的属性值;
            if ($is_change == false) {
                if (!empty($data)) {
                    $is_change = true;

                } else {
                    foreach ($old_form as $old_field_name => $old_attr) {
                        // 跳过已对比过的属性
                        if (in_array($old_field_name, $check_field_name)) {
                            continue;
                        }

                        // 对比剩余属性值,是否有变化
                        if ($field_name == $old_field_name) {

                            // 属性类型为"多选类型"时,属性值需特殊对比
                            if ($old_attr['type'] == Constant::ATTR_TYPE_CHECKBOX) {
                                if (serialize($old_attr['attr_value']) != serialize($attr_value)) {
                                    $is_change = true;
                                    break;
                                }

                            } else {
                                if ($old_attr['attr_value'] != $attr_value) {
                                    $is_change = true;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }

        // 新老表单数据有变化
        if ($is_change) {
            $data['form'] = serialize($form);
        }

        return $data;
    }
}