SubmitController.class.php 16.4 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
<?php
/**
 * Created by PhpStorm.
 * User: liyifei2012it
 * Date: 16/9/18
 * Reader: zhoutao 2017-06-13 10:26:15
 * Reconstruction: zhoutao 2017-06-22 19:09:28
 * Time: 11:52
 */

namespace Api\Controller\Invite;

use Com\Cookie;
use Common\Common\Cache;
use Common\Common\Department;
use Common\Common\Job;
use Common\Common\Msg;
use Common\Common\User;
use Common\Model\AttrModel;
use Common\Model\InviteSettingModel;
use Common\Model\InviteUserModel;
use Common\Service\AttrService;
use Common\Service\InviteLinkService;
use Common\Service\InviteSettingService;
use Common\Service\InviteUserRightService;
use Common\Service\InviteUserService;
use Common\Service\UserService;
use Think\Log;
use VcySDK\Config;

/**
 * @property AttrService attrServ
 * @property User userServ
 * @property InviteUserService inviteUserServ
 */
class SubmitController extends CheckUserController
{

    // 用户信息(手机号|邮箱|微信号)已存在
    const MEM_INFO_EXIST = 1;

    // 邀请链接表
    protected $inviteLinkServ = null;
    // 属性表
    protected $attrServ = null;
    // 人员
    protected $userServ = null;
    // 人员邀请
    protected $inviteUserServ = null;

    // 邀请设置数据
    protected $setting = [];
    // 邀请链接数据
    protected $inviteLink = [];
    // 提交的数据
    protected $form = [];
    // 邀请人
    protected $invitor = [];

    public function before_action($action = '')
    {
        // 获取设置数据
        $settingService = new InviteSettingService();
        $this->setting = $settingService->getSetting();
        // 获取邀请链接数据
        $inviteLinkService = new InviteLinkService();
        $this->inviteLink = $inviteLinkService->get(I('post.link_id', '', 'trim'));
        $this->inviteLink['default_data'] = unserialize($this->inviteLink['default_data']);
        if (empty($this->inviteLink)) {
            E('_ERR_INVITE_DATA_IS_NULL');
        }
        // 提交的表单数据
        $this->form = I('post.form');
        // 验证邮箱合法性
        if (!empty($this->form['memEmail']) &&
            false === filter_var($this->form['memEmail'], FILTER_VALIDATE_EMAIL)) {
            E(L('_ERR_ILLEGAL_PARAM', ['name' => '邮箱']));
        }
        // 人员属性表
        $this->attrServ = new AttrService();
        // 人员表
        $this->userServ = new User();
        // 人员邀请表
        $this->inviteUserServ = new InviteUserService();

        return parent::before_action($action);
    }

    /**
     * 【通讯录】提交表单接口(被邀请人填写的表单信息)
     * @author liyifei
     * Reconstruction: zhoutao 2017-06-23 15:22:03
     */
    public function Index_post()
    {
        // 是否已经被接受
        $this->isAccepted();
        // 检查邀请链接是否可用
        $this->_checkLinkId($this->inviteLink['link_id']);
        // 获取邀请人填写的数据
        $this->getInviteData();
        // 获取邀请人数据
        $this->invitor = $this->userServ->getByUid($this->inviteLink['invite_uid'], true);
        // 邀请人不存在或已被删除
        if (!$this->invitor || !$this->userServ->isNormal($this->invitor)) {
            E('_ERR_INVITER_NOT_FOUND');
        }

        // 判断邀请默认数据
        $this->_checkDefaultData($this->inviteLink['default_data']);
        // 格式化表单数据,将field_name设置为key
        $this->form = array_combine_by_key($this->form, 'field_name');
        // 获得属性列表,然后比较表单数据,检查数据是否完整
        $attrList = $this->attrServ->getAttrList(true, [AttrModel::ATTR_TYPE_SPECIAL, AttrModel::ATTR_TYPE_LEADER]);
        if (!$this->inviteUserServ->checkInviteData($this->form, $attrList)) {
            E('_ERR_FORM_CHECK_FAIL');
        }
        // 验证手机号,微信号,邮箱是否已存在
        $this->checkMemInfoSingle();

        // 根据审批类型判断是否要写入
        $is_write = $this->checkWithApproveType();
        // 写入数据
        $this->insertData($is_write);

        // 接口返回数据
        $this->returnResult();

        return true;
    }

    /**
     * 处理返回值
     */
    protected function returnResult()
    {
        $ep = Cache::instance()->get(
            'Common.EnterpriseDetail',
            '',
            ['expire' => cfg('ENTERPRISE_DETAIL_CACHE_EXPIRE')]
        );

        $this->_result = [
            'is_check' => $this->setting['type'] == InviteSettingService::INVITE_TYPE_NEED_CHECK ? 1 : 0,
            'qrcode' => $ep['corpWxqrcode'],
            'invite_type' => $this->inviteLink['type']
        ];

        return true;
    }

    /**
     * 写入数据
     * @param $is_write
     * @return bool
     */
    protected function insertData($is_write)
    {
        // 写入岗位
        $this->insertJob();
        // 不写入, 在这里就结束了
        if (!$is_write) {
            return true;
        }

        // 写入邀请数据
        list($insertData, $invite_id) = $this->insertInviteData();
        // 新增权限对应关系
        $inviteUserRightService = new InviteUserRightService();
        $rights = [[
                'invite_id' => $invite_id,
                'udtid' => $this->invitor['memUid']
            ], [
                'invite_id' => $invite_id,
                'udtid' => $this->inviteLink['default_data']['department']['dpId']
            ]];
        $inviteUserRightService->insert_all($rights);

        // 发送审批消息
        if ($this->setting['type'] == InviteSettingService::INVITE_TYPE_NEED_CHECK) {
            $this->sendApproveMsg($insertData);
        }

        return true;
    }

    /**
     * 验证是否已经被接受
     * @return bool
     */
    protected function isAccepted()
    {
        // 如果已经接受了邀请
        $user = array();
        if ($this->_hasAcceptAndWrite($user, $this->inviteLink['link_id'])) {
            // 已通过审核
            if (InviteUserModel::CHECK_STATUS_PASS == $user['check_status']) {
                E('_ERR_IS_ENTERPRISE_INTERNAL_STAFF');
            } elseif (InviteUserModel::CHECK_STATUS_REJECT == $user['check_status']) {
                E('_ERR_APPLICATION_HAS_BEEN_REJECTED');
            } else {
                E('_ERR_PLEASE_DO_NOT_RESUBMIT');
            }
        }

        return true;
    }

    /**
     * 获取邀请人填写的数据
     * @return bool
     */
    protected function getInviteData()
    {
        foreach ($this->inviteLink['default_data'] as $_field => $_data) {
            if ('job' == $_field) {
                $this->form[] = array(
                    'type' => 1,
                    'field_name' => 'memJob',
                    'attr_name' => '岗位',
                    'attr_value' => $_data,
                    'option' => ''
                );
            } elseif ('role' == $_field) {
                $this->form[] = array(
                    'type' => 1,
                    'field_name' => 'memRole',
                    'attr_name' => '角色',
                    'attr_value' => $_data,
                    'option' => ''
                );
            } elseif ('department' == $_field) {
                $this->form[] = array(
                    'type' => 1,
                    'field_name' => 'dpIdList',
                    'attr_name' => '组织',
                    'attr_value' => $_data['dpId'],
                    'option' => ''
                );
            }
        }
        if (empty($this->form)) {
            E('_ERR_PARAM_IS_NULL');
        }

        return true;
    }

    /**
     * 验证手机号,微信号,邮箱是否已存在
     * @return bool
     */
    protected function checkMemInfoSingle()
    {
        $isExist = $this->userServ->checkMemInfoSingle(
            $this->form['memMobile']['attr_value'],
            $this->form['memEmail']['attr_value'],
            $this->form['memWeixin']['attr_value']);
        if ($isExist['memMobile'] == self::MEM_INFO_EXIST) {
            E(L('_ERR_PARAM_EXISTED', ['name' => '手机号码']));
        } else if ($isExist['memWeixin'] == self::MEM_INFO_EXIST) {
            E(L('_ERR_PARAM_EXISTED', ['name' => '微信号']));
        } else if ($isExist['memEmail'] == self::MEM_INFO_EXIST) {
            E(L('_ERR_PARAM_EXISTED', ['name' => '邮箱']));
        }

        return true;
    }

    /**
     * 根据审批类型判断是否要写入
     * @return bool
     */
    protected function checkWithApproveType()
    {
        $invite = $this->inviteUserServ->getInviteUser($this->form, true);
        $user = $this->userServ->getByUid($invite['uid'], true);

        $is_write = true;

        // 邀请类型为不需要审批
        $inviteTypeNoCheck = $this->setting['type'] == InviteSettingService::INVITE_TYPE_NO_CHECK;
        // 审批状态 待审批
        $inviteCheckStatusWait = $invite['check_status'] == InviteUserService::CHECK_STATUS_WAIT;
        // 审批状态 通过
        $inviteCheckStatusPass = $invite['check_status'] == InviteUserService::CHECK_STATUS_PASS;
        // 人员未被删除
        $userExist = $user['memStatus'] != User::STATUS_DELETED;

        // 直接邀请 && 邀请数据 && uid已存在 && 用户未被删除,无需记录新的邀请数据
        if ($inviteTypeNoCheck && $invite && $invite['uid'] && $userExist) {
            $is_write = false;
        // 审批邀请,且邀请数据已存在
        } elseif ($invite) {
            // 等待审批,无需记录新的邀请数据
            if ($inviteCheckStatusWait) {
                // 再判断邀请表手机号,微信号,邮箱是否已存在
                if ($invite['mobile'] == $this->form['memMobile']['attr_value']) {
                    E(L('_ERR_PARAM_EXISTED', ['name' => '手机号码']));
                } elseif ($invite['weixin'] == $this->form['memWeixin']['attr_value']) {
                    E(L('_ERR_PARAM_EXISTED', ['name' => '微信号']));
                } elseif ($invite['email'] == $this->form['memEmail']['attr_value']) {
                    E(L('_ERR_PARAM_EXISTED', ['name' => '邮箱']));
                }
                $is_write = false;
                // 审批通过
            } elseif ($inviteCheckStatusPass && $invite['uid'] && $userExist) {
                // 用户未被删除,无需记录新的邀请数据
                $is_write = false;
            }
        }

        return $is_write;
    }

    /**
     * 写入岗位
     */
    protected function insertJob()
    {
        // 如果没有岗位则写入
        try {
            if (!empty($this->form['memJob'])) {
                $jobName = $this->form['memJob']['attr_value'];
                $jobServ = new Job();
                $jobData = $jobServ->getByName($jobName);
                if (empty($jobData)) {
                    $jobServ->addJob(['jobName' => $this->form['memJob']['attr_value']]);
                }
            }
        } catch (\Exception $e) {
            // 不影响主流程
            Log::record("提交邀请时,新增岗位异常:", var_export($e, true));
        }

        return true;
    }

    /**
     * 获取表单字段数据
     * @return string
     */
    protected function getFromAttrValue($attrField)
    {
        return isset($this->form[$attrField]['attr_value']) ? $this->form[$attrField]['attr_value'] : '';
    }

    /**
     * 写入邀请数据
     * @return array
     */
    protected function insertInviteData()
    {
        // 初始化邀请数据
        $insertData = [
            'link_id' => $this->inviteLink['link_id'],
            'invite_uid' => $this->invitor['memUid'],
            'udpid' => $this->invitor['memUid'] . ',' . $this->inviteLink['default_data']['department']['dpId'],
            'wx_openid' => Cookie::instance()->getx('wx_openid'),
            'uid' => '',
            'username' => $this->getFromAttrValue('memUsername'),
            'weixin' => $this->getFromAttrValue('memWeixin'),
            'mobile' => $this->getFromAttrValue('memMobile'),
            'email' => $this->getFromAttrValue('memEmail'),
            'form' => serialize(array_values($this->form)),
            'type' => intval($this->setting['type']),
            'check_status' => $this->setting['type'] == InviteSettingService::INVITE_TYPE_NO_CHECK ?
                InviteUserService::CHECK_STATUS_PASS : InviteUserService::CHECK_STATUS_WAIT,
            'dp_id' => $this->inviteLink['default_data']['department']['dpId'],
            'job_name' => empty($this->inviteLink['default_data']['job']) ?
                '' : $this->inviteLink['default_data']['job'],
            'role_name' => empty($this->inviteLink['default_data']['role']) ?
                '' : $this->inviteLink['default_data']['role']
        ];

        // 直接邀请,将用户数据写入UC
        if ($this->setting['type'] == InviteSettingService::INVITE_TYPE_NO_CHECK) {
            // 审批人为邀请人
            $insertData['check_uid'] = $this->invitor['memUid'];
            $insertData['check_time'] = MILLI_TIME;
            $this->addUser($insertData);
        }

        $invite_id = $this->inviteUserServ->insert($insertData);
        // 邀请数据写入失败
        if (!$invite_id) {
            E('_ERR_INSERT_INVITE_FAIL');
        }

        return array($insertData, $invite_id);
    }

    /**
     * 添加人员
     * @param $insertData
     * @return bool
     */
    protected function addUser(&$insertData)
    {
        // 获取部门ID
        $dpIds = $this->setting['departments'] ?
            $this->setting['departments'] : array_column($this->invitor['dpName'], 'dpId');
        $data = ['dpIdList' => $dpIds];

        // 处理人员属性字段
        $attrs = $this->attrServ->getAttrList(true, [AttrModel::ATTR_TYPE_SPECIAL, AttrModel::ATTR_TYPE_LEADER]);
        $serializeAttr = [
            AttrModel::ATTR_TYPE_CHECKBOX,
            AttrModel::ATTR_TYPE_PICTURE,
        ];
        foreach ($attrs as $attr) {
            // 提交表单字段数据
            $formAttr = $this->form[$attr['field_name']];
            // checkbox 和 图片特殊处理
            if (in_array($formAttr['type'], $serializeAttr) && !empty($formAttr['attr_value'])) {
                $data[$attr['field_name']] = serialize($formAttr['attr_value']);
            } else {
                $data[$attr['field_name']] = $formAttr['attr_value'];
            }
        }

        // 调用验证接口,验证参数传值是否符合规范
        $errors = $this->attrServ->checkValue($data, 'is_required');
        if (!empty($errors)) {
            E($errors[0]);
        }

        $userService = new UserService();
        $data['memJoinInviter'] = $this->invitor['memUsername'];
        $data['memJoinType'] = InviteUserModel::USER_INVITE_JOIN;
        $result = $userService->saveUser('', $data);
        $insertData['uid'] = $result['memUid'];

        return true;
    }

    /**
     * 发送消息
     * @param $insertData
     */
    protected function sendApproveMsg($insertData)
    {
        // 开启邀请人审批
        $checkUids = [];
        if (InviteSettingModel::TYPE_DIRECT == (InviteSettingModel::TYPE_DIRECT & $this->setting['check_type'])) {
            $checkUids[] = $this->inviteLink['invite_uid'];
        }
        // 开启组织负责人审批
        $dpId = $this->inviteLink['default_data']['department']['dpId'];
        $department = Department::instance()->getById($dpId);
        if ((InviteSettingModel::TYPE_APPROVAL == (InviteSettingModel::TYPE_APPROVAL & $this->setting['check_type'])) && !empty($department['dpLead'])) {
            $checkUids[] = $department['dpLead'];
        }
        $text = "申请人:{$insertData['username']}";
        $inviteUser = User::instance()->getByUid($this->invitor['memUid']);
        if (!empty($inviteUser)) {
            $text .= "\n邀请人:{$inviteUser['memUsername']}";
        }
        $text .= "\n申请时间:" . rgmdate(NOW_TIME, 'Y-m-d H:i');
        // 发送消息
        if (!empty($checkUids)) {
            // 消息发至管理助手
            $app = Config::instance()->config['pluginIdentifier'];
            Config::instance()->setConfig(['pluginIdentifier' => 'yuanquan']);

            $msgService = new Msg();
            $msgService->sendNews($checkUids, '', '', [
                [
                    'title' => "【审核通知】您有一个同事加入待审核",
                    'description' => $text,
                    'url' => oaUrl('Frontend/Index/InviteList'),
                ]
            ]);

            // 改回应用标识
            Config::instance()->setConfig(['pluginIdentifier' => $app]);
        }
    }
}