Compare commits

...

9 Commits

3
.gitignore vendored

@ -1 +1,4 @@
/runtime/ /runtime/
.env
.idea
.Ds_Store

8
.idea/.gitignore vendored

@ -1,8 +0,0 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

@ -1,56 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/spec" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/tests" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/vendor/topthink/think-installer" />
<excludeFolder url="file://$MODULE_DIR$/vendor/topthink/think-sae" />
<excludeFolder url="file://$MODULE_DIR$/vendor/pclzip/pclzip" />
<excludeFolder url="file://$MODULE_DIR$/vendor/topthink/think-worker" />
<excludeFolder url="file://$MODULE_DIR$/vendor/phpexcel/PHPExcel" />
<excludeFolder url="file://$MODULE_DIR$/vendor/topthink/think-image" />
<excludeFolder url="file://$MODULE_DIR$/vendor/topthink/think-mongo" />
<excludeFolder url="file://$MODULE_DIR$/vendor/phpspec/prophecy" />
<excludeFolder url="file://$MODULE_DIR$/vendor/composer" />
<excludeFolder url="file://$MODULE_DIR$/vendor/zendframework/zend-escaper" />
<excludeFolder url="file://$MODULE_DIR$/vendor/sebastian/recursion-context" />
<excludeFolder url="file://$MODULE_DIR$/vendor/sebastian/diff" />
<excludeFolder url="file://$MODULE_DIR$/vendor/sebastian/global-state" />
<excludeFolder url="file://$MODULE_DIR$/vendor/sebastian/comparator" />
<excludeFolder url="file://$MODULE_DIR$/vendor/sebastian/environment" />
<excludeFolder url="file://$MODULE_DIR$/vendor/sebastian/exporter" />
<excludeFolder url="file://$MODULE_DIR$/vendor/sebastian/version" />
<excludeFolder url="file://$MODULE_DIR$/vendor/phpdocumentor/reflection-docblock" />
<excludeFolder url="file://$MODULE_DIR$/vendor/phpdocumentor/type-resolver" />
<excludeFolder url="file://$MODULE_DIR$/vendor/phpdocumentor/reflection-common" />
<excludeFolder url="file://$MODULE_DIR$/vendor/doctrine/instantiator" />
<excludeFolder url="file://$MODULE_DIR$/vendor/phpoffice/phpspreadsheet" />
<excludeFolder url="file://$MODULE_DIR$/vendor/webmozart/assert" />
<excludeFolder url="file://$MODULE_DIR$/vendor/symfony/polyfill-mbstring" />
<excludeFolder url="file://$MODULE_DIR$/vendor/phpoffice/phpword" />
<excludeFolder url="file://$MODULE_DIR$/vendor/symfony/yaml" />
<excludeFolder url="file://$MODULE_DIR$/vendor/phpoffice/common" />
<excludeFolder url="file://$MODULE_DIR$/vendor/symfony/dom-crawler" />
<excludeFolder url="file://$MODULE_DIR$/vendor/phpoffice/phpexcel" />
<excludeFolder url="file://$MODULE_DIR$/vendor/symfony/polyfill-ctype" />
<excludeFolder url="file://$MODULE_DIR$/vendor/workerman/workerman" />
<excludeFolder url="file://$MODULE_DIR$/vendor/psr/simple-cache" />
<excludeFolder url="file://$MODULE_DIR$/vendor/phpunit/php-timer" />
<excludeFolder url="file://$MODULE_DIR$/vendor/phpunit/php-file-iterator" />
<excludeFolder url="file://$MODULE_DIR$/vendor/phpunit/php-text-template" />
<excludeFolder url="file://$MODULE_DIR$/vendor/phpunit/phpunit" />
<excludeFolder url="file://$MODULE_DIR$/vendor/topthink/think-testing" />
<excludeFolder url="file://$MODULE_DIR$/vendor/markbaker/matrix" />
<excludeFolder url="file://$MODULE_DIR$/vendor/phpunit/phpunit-mock-objects" />
<excludeFolder url="file://$MODULE_DIR$/vendor/topthink/think-helper" />
<excludeFolder url="file://$MODULE_DIR$/vendor/markbaker/complex" />
<excludeFolder url="file://$MODULE_DIR$/vendor/phpunit/php-code-coverage" />
<excludeFolder url="file://$MODULE_DIR$/vendor/topthink/think-queue" />
<excludeFolder url="file://$MODULE_DIR$/vendor/phpunit/php-token-stream" />
<excludeFolder url="file://$MODULE_DIR$/vendor/topthink/think-migration" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

@ -1,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/crm_php.iml" filepath="$PROJECT_DIR$/.idea/crm_php.iml" />
</modules>
</component>
</project>

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

@ -1 +0,0 @@
open_basedir=/www/wwwroot/72crm/:/tmp/

@ -0,0 +1,66 @@
<?php
namespace app\common\wework\api;
use think\Cache;
class Api {
/**
* @var object 对象实例
*/
protected static $instance;
protected static $baseUrl = 'https://qyapi.weixin.qq.com/cgi-bin/';
protected static $getAccessToken = 'gettoken';
protected static $contactInfo = 'externalcontact/get';
protected $corpId = '';
protected $corpSecret = '';
protected $accessToken = '';
function __construct($corpId, $corpSecret)
{
$this->corpId = $corpId;
$this->corpSecret = $corpSecret;
}
/**
* 获取客户详情
* @param $externalUserId
* @return mixed
*/
function contactInfo($externalUserId) {
return $this->get(self::$contactInfo, [
'access_token' => $this->getAccessToken(),
'external_userid' => $externalUserId
]);
}
/**
* 获取accessToken
* @return false|mixed
*/
protected function getAccessToken() {
if ($this->accessToken == '') {
$this->accessToken = Cache::get('accessToken:' . $this->corpId);
if ($this->accessToken == '') {
$result = $this->get(self::$getAccessToken, [
'corpid' => $this->corpId,
'corpsecret' => $this->corpSecret
]);
if (isset($result['access_token']) && $result['access_token']) {
Cache::set('accessToken:' . $this->corpId, $result['access_token'],$result['expires_in']-60);
$this->accessToken = $result['access_token'];
}
}
}
return $this->accessToken;
}
protected function get($action, $data) {
return json_decode(Curl::get(self::$baseUrl . $action,null,$data), true);
}
}

@ -0,0 +1,110 @@
<?php
namespace app\common\wework\api;
class Curl
{
/**
*curl post请求
* @param $url
* @param null $header
* @param null $data
* @param bool $isHeader
* @return mixed
*/
public static function post($url, $header = null, $data = null, $isHeader = false)
{
return self::curl('post', $url, $header, $data, $isHeader);
}
/**
*curl put请求
* @param $url
* @param null $header
* @param null $data
* @param bool $isHeader
* @return mixed
* @return bool|string
*/
public static function put($url, $header = null, $data = null, $isHeader = false)
{
return self::curl('put', $url, $header, $data, $isHeader);
}
/**
*curl get请求
* @param $url
* @param null $header
* @param null $data
* @param bool $isHeader
* @return mixed
*/
public static function get($url, $header = null, $data = null, $isHeader = false)
{
if ($data) {
if (is_array($data)) {
$data = http_build_query($data);
}
if (strpos($url, '?') === false) {
$url = $url . '?' . $data;
} else {
$url = $url . '&' . $data;
}
}
return self::curl('get', $url, $header, null, $isHeader);
}
/**
*curl请求
* @param $method
* @param $url
* @param null $header
* @param null $data
* @param bool $isHeader
* @return mixed
*/
public static function curl($method, $url, $header = null, $data = null, $isHeader = false)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
if ($header) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
if (stripos($url, "https://") !== FALSE) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
}
if ($data) {
if (is_array($data)) {
$sets = array();
foreach ($data as $key => $val) {
$sets[] = $key . '=' . urlencode($val);
}
$data = implode('&', $sets);
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
$method = strtolower($method);
if ('post' == $method) {
curl_setopt($ch, CURLOPT_POST, true);
} elseif ('put' == $method) {
//curl_setopt($ch,CURLOPT_PUT,true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
}
// curl_setopt($ch, CURLOPT_PROXY, "socks5://127.0.0.1:18080");
//获取头部信息
if ($isHeader) {
curl_setopt($ch, CURLOPT_HEADER, 1);
}
$output = curl_exec($ch);
if ($output === false) {
var_dump(curl_error($ch));
}
curl_close($ch);
return $output;
}
}

@ -0,0 +1,35 @@
<?php
namespace app\common\wework\callback;
/**
* error code 说明.
* <ul>
* <li>-40001: 签名验证错误</li>
* <li>-40002: xml解析失败</li>
* <li>-40003: sha加密生成签名失败</li>
* <li>-40004: encodingAesKey 非法</li>
* <li>-40005: corpid 校验错误</li>
* <li>-40006: aes 加密失败</li>
* <li>-40007: aes 解密失败</li>
* <li>-40008: 解密后得到的buffer非法</li>
* <li>-40009: base64加密失败</li>
* <li>-40010: base64解密失败</li>
* <li>-40011: 生成xml失败</li>
* </ul>
*/
class ErrorCode
{
public static $OK = 0;
public static $ValidateSignatureError = -40001;
public static $ParseXmlError = -40002;
public static $ComputeSignatureError = -40003;
public static $IllegalAesKey = -40004;
public static $ValidateCorpidError = -40005;
public static $EncryptAESError = -40006;
public static $DecryptAESError = -40007;
public static $IllegalBuffer = -40008;
public static $EncodeBase64Error = -40009;
public static $DecodeBase64Error = -40010;
public static $GenReturnXmlError = -40011;
}
?>

@ -0,0 +1,51 @@
<?php
namespace app\common\wework\callback;
/**
* PKCS7Encoder class
*
* 提供基于PKCS7算法的加解密接口.
*/
class PKCS7Encoder
{
public static $block_size = 32;
/**
* 对需要加密的明文进行填充补位
* @param $text 需要进行填充补位操作的明文
* @return 补齐明文字符串
*/
function encode($text)
{
$block_size = PKCS7Encoder::$block_size;
$text_length = strlen($text);
//计算需要填充的位数
$amount_to_pad = PKCS7Encoder::$block_size - ($text_length % PKCS7Encoder::$block_size);
if ($amount_to_pad == 0) {
$amount_to_pad = PKCS7Encoder::block_size;
}
//获得补位所用的字符
$pad_chr = chr($amount_to_pad);
$tmp = "";
for ($index = 0; $index < $amount_to_pad; $index++) {
$tmp .= $pad_chr;
}
return $text . $tmp;
}
/**
* 对解密后的明文进行补位删除
* @param decrypted 解密后的明文
* @return 删除填充补位后的明文
*/
function decode($text)
{
$pad = ord(substr($text, -1));
if ($pad < 1 || $pad > PKCS7Encoder::$block_size) {
$pad = 0;
}
return substr($text, 0, (strlen($text) - $pad));
}
}

@ -0,0 +1,110 @@
<?php
namespace app\common\wework\callback;
/**
* Prpcrypt class
*
* 提供接收和推送给公众平台消息的加解密接口.
*/
class Prpcrypt
{
public $key = null;
public $iv = null;
/**
* Prpcrypt constructor.
* @param $k
*/
public function __construct($k)
{
$this->key = base64_decode($k . '=');
$this->iv = substr($this->key, 0, 16);
}
/**
* 加密
*
* @param $text
* @param $receiveId
* @return array
*/
public function encrypt($text, $receiveId)
{
try {
//拼接
$text = $this->getRandomStr() . pack('N', strlen($text)) . $text . $receiveId;
//添加PKCS#7填充
$pkc_encoder = new PKCS7Encoder;
$text = $pkc_encoder->encode($text);
//加密
if (function_exists('openssl_encrypt')) {
$encrypted = openssl_encrypt($text, 'AES-256-CBC', $this->key, OPENSSL_ZERO_PADDING, $this->iv);
} else {
$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $this->key, base64_decode($text), MCRYPT_MODE_CBC, $this->iv);
}
return array(ErrorCode::$OK, $encrypted);
} catch (Exception $e) {
print $e;
return array(MyErrorCode::$EncryptAESError, null);
}
}
/**
* 解密
*
* @param $encrypted
* @param $receiveId
* @return array
*/
public function decrypt($encrypted, $receiveId)
{
try {
//解密
if (function_exists('openssl_decrypt')) {
$decrypted = openssl_decrypt($encrypted, 'AES-256-CBC', $this->key, OPENSSL_ZERO_PADDING, $this->iv);
} else {
$decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $this->key, base64_decode($encrypted), MCRYPT_MODE_CBC, $this->iv);
}
} catch (Exception $e) {
return array(ErrorCode::$DecryptAESError, null);
}
try {
//删除PKCS#7填充
$pkc_encoder = new PKCS7Encoder;
$result = $pkc_encoder->decode($decrypted);
if (strlen($result) < 16) {
return array();
}
//拆分
$content = substr($result, 16, strlen($result));
$len_list = unpack('N', substr($content, 0, 4));
$xml_len = $len_list[1];
$xml_content = substr($content, 4, $xml_len);
$from_receiveId = substr($content, $xml_len + 4);
} catch (Exception $e) {
print $e;
return array(ErrorCode::$IllegalBuffer, null);
}
if ($from_receiveId != $receiveId) {
return array(ErrorCode::$ValidateCorpidError, null);
}
return array(0, $xml_content);
}
/**
* 生成随机字符串
*
* @return string
*/
private function getRandomStr()
{
$str = '';
$str_pol = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyl';
$max = strlen($str_pol) - 1;
for ($i = 0; $i < 16; $i++) {
$str .= $str_pol[mt_rand(0, $max)];
}
return $str;
}
}

@ -0,0 +1,34 @@
<?php
namespace app\common\wework\callback;
/**
* SHA1 class
*
* 计算公众平台的消息签名接口.
*/
class SHA1
{
/**
* 用SHA1算法生成安全签名
* @param string $token 票据
* @param string $timestamp 时间戳
* @param string $nonce 随机字符串
* @param string $encrypt 密文消息
*/
public function getSHA1($token, $timestamp, $nonce, $encrypt_msg)
{
//排序
try {
$array = array($encrypt_msg, $token, $timestamp, $nonce);
sort($array, SORT_STRING);
$str = implode($array);
return array(ErrorCode::$OK, sha1($str));
} catch (Exception $e) {
print $e . "\n";
return array(ErrorCode::$ComputeSignatureError, null);
}
}
}

@ -0,0 +1,178 @@
<?php
namespace app\common\wework\callback;
/**
* 企业微信回调消息加解密示例代码.
*
* @copyright Copyright (c) 1998-2014 Tencent Inc.
*/
class WXBizMsgCrypt
{
private $m_sToken;
private $m_sEncodingAesKey;
private $m_sReceiveId;
/**
* 构造函数
* @param $token string 开发者设置的token
* @param $encodingAesKey string 开发者设置的EncodingAESKey
* @param $receiveId string, 不同应用场景传不同的id
*/
public function __construct($token, $encodingAesKey, $receiveId)
{
$this->m_sToken = $token;
$this->m_sEncodingAesKey = $encodingAesKey;
$this->m_sReceiveId = $receiveId;
}
/*
*验证URL
*@param sMsgSignature: 签名串对应URL参数的msg_signature
*@param sTimeStamp: 时间戳对应URL参数的timestamp
*@param sNonce: 随机串对应URL参数的nonce
*@param sEchoStr: 随机串对应URL参数的echostr
*@param sReplyEchoStr: 解密之后的echostr当return返回0时有效
*@return成功0失败返回对应的错误码
*/
public function VerifyURL($sMsgSignature, $sTimeStamp, $sNonce, $sEchoStr, &$sReplyEchoStr)
{
if (strlen($this->m_sEncodingAesKey) != 43) {
return ErrorCode::$IllegalAesKey;
}
$pc = new Prpcrypt($this->m_sEncodingAesKey);
//verify msg_signature
$sha1 = new SHA1();
$array = $sha1->getSHA1($this->m_sToken, $sTimeStamp, $sNonce, $sEchoStr);
$ret = $array[0];
if ($ret != 0) {
return $ret;
}
$signature = $array[1];
if ($signature != $sMsgSignature) {
return ErrorCode::$ValidateSignatureError;
}
$result = $pc->decrypt($sEchoStr, $this->m_sReceiveId);
if ($result[0] != 0) {
return $result[0];
}
$sReplyEchoStr = $result[1];
return ErrorCode::$OK;
}
/**
* 将公众平台回复用户的消息加密打包.
* <ol>
* <li>对要发送的消息进行AES-CBC加密</li>
* <li>生成安全签名</li>
* <li>将消息密文和安全签名打包成xml格式</li>
* </ol>
*
* @param $replyMsg string 公众平台待回复用户的消息xml格式的字符串
* @param $timeStamp string 时间戳可以自己生成也可以用URL参数的timestamp
* @param $nonce string 随机串可以自己生成也可以用URL参数的nonce
* @param &$encryptMsg string 加密后的可以直接回复用户的密文包括msg_signature, timestamp, nonce, encrypt的xml格式的字符串,
* 当return返回0时有效
*
* @return int 成功0失败返回对应的错误码
*/
public function EncryptMsg($sReplyMsg, $sTimeStamp, $sNonce, &$sEncryptMsg)
{
$pc = new Prpcrypt($this->m_sEncodingAesKey);
//加密
$array = $pc->encrypt($sReplyMsg, $this->m_sReceiveId);
$ret = $array[0];
if ($ret != 0) {
return $ret;
}
if ($sTimeStamp == null) {
$sTimeStamp = time();
}
$encrypt = $array[1];
//生成安全签名
$sha1 = new SHA1;
$array = $sha1->getSHA1($this->m_sToken, $sTimeStamp, $sNonce, $encrypt);
$ret = $array[0];
if ($ret != 0) {
return $ret;
}
$signature = $array[1];
//生成发送的xml
$xmlparse = new XMLParse;
$sEncryptMsg = $xmlparse->generate($encrypt, $signature, $sTimeStamp, $sNonce);
return ErrorCode::$OK;
}
/**
* 检验消息的真实性,并且获取解密后的明文.
* <ol>
* <li>利用收到的密文生成安全签名,进行签名验证</li>
* <li>若验证通过则提取xml中的加密消息</li>
* <li>对消息进行解密</li>
* </ol>
*
* @param $msgSignature string 签名串对应URL参数的msg_signature
* @param $timestamp string 时间戳 对应URL参数的timestamp
* @param $nonce string 随机串对应URL参数的nonce
* @param $postData string 密文对应POST请求的数据
* @param &$msg string 解密后的原文当return返回0时有效
*
* @return int 成功0失败返回对应的错误码
*/
public function DecryptMsg($sMsgSignature, $sTimeStamp = null, $sNonce, $sPostData, &$sMsg)
{
if (strlen($this->m_sEncodingAesKey) != 43) {
return ErrorCode::$IllegalAesKey;
}
$pc = new Prpcrypt($this->m_sEncodingAesKey);
//提取密文
$xmlparse = new XMLParse;
$array = $xmlparse->extract($sPostData);
$ret = $array[0];
if ($ret != 0) {
return $ret;
}
if ($sTimeStamp == null) {
$sTimeStamp = time();
}
$encrypt = $array[1];
//验证安全签名
$sha1 = new SHA1;
$array = $sha1->getSHA1($this->m_sToken, $sTimeStamp, $sNonce, $encrypt);
$ret = $array[0];
if ($ret != 0) {
return $ret;
}
$signature = $array[1];
if ($signature != $sMsgSignature) {
return ErrorCode::$ValidateSignatureError;
}
$result = $pc->decrypt($encrypt, $this->m_sReceiveId);
if ($result[0] != 0) {
return $result[0];
}
$sMsg = $result[1];
return ErrorCode::$OK;
}
}

@ -0,0 +1,61 @@
<?php
namespace app\common\wework\callback;
/**
* XMLParse class
*
* 提供提取消息格式中的密文及生成回复消息格式的接口.
*/
class XMLParse
{
/**
* 提取出xml数据包中的加密消息
* @param string $xmltext 待提取的xml字符串
* @return string 提取出的加密消息字符串
*/
public function extract($xmltext)
{
try {
$xml = new \DOMDocument();
$xml->loadXML($xmltext);
$array_e = $xml->getElementsByTagName('Encrypt');
$encrypt = $array_e->item(0)->nodeValue;
return array(0, $encrypt);
} catch (Exception $e) {
print $e . "\n";
return array(ErrorCode::$ParseXmlError, null);
}
}
/**
* 生成xml消息
* @param string $encrypt 加密后的消息密文
* @param string $signature 安全签名
* @param string $timestamp 时间戳
* @param string $nonce 随机字符串
*/
public function generate($encrypt, $signature, $timestamp, $nonce)
{
$format = "<xml>
<Encrypt><![CDATA[%s]]></Encrypt>
<MsgSignature><![CDATA[%s]]></MsgSignature>
<TimeStamp>%s</TimeStamp>
<Nonce><![CDATA[%s]]></Nonce>
</xml>";
return sprintf($format, $encrypt, $signature, $timestamp, $nonce);
}
}
//
// Test
/*
$sPostData = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><AgentID><![CDATA[toAgentID]]></AgentID><Encrypt><![CDATA[msg_encrypt]]></Encrypt></xml>";
$xmlparse = new XMLParse;
$array = $xmlparse->extract($sPostData);
var_dump($array);
*/
?>

@ -0,0 +1,86 @@
<?php
// +----------------------------------------------------------------------
// | Description: CRM工作台
// +----------------------------------------------------------------------
// | Author: Michael_xu | gengxiaoxu@5kcrm.com
// +----------------------------------------------------------------------
namespace app\crm\controller;
use app\common\wework\api\Api;
use app\common\wework\callback\WXBizMsgCrypt;
use think\Controller;
use think\Log;
use think\Request;
class Callback extends Controller
{
public function index()
{
$wxcpt = new WXBizMsgCrypt(config('wework.token'), config('wework.encodingAesKey'), config('wework.corpId'));
if (Request::instance()->isPost()) {
$sReqMsgSig = Request::instance()->get('msg_signature');
$sReqTimeStamp = Request::instance()->get('timestamp');
$sReqNonce = Request::instance()->get('nonce');
$sReqData =Request::instance()->getContent();
$sMsg = ""; // 解析之后的明文
$errCode = $wxcpt->DecryptMsg($sReqMsgSig, $sReqTimeStamp, $sReqNonce, $sReqData, $sMsg);
if ($errCode == 0) {
// 解密成功sMsg即为xml格式的明文
$simpleXMLElement = simplexml_load_string($sMsg,'SimpleXMLElement', LIBXML_NOCDATA);
switch ($simpleXMLElement->Event->__toString()) {
case 'change_external_contact':
$api = new Api(config('wework.corpId'), config('wework.corpSecret'));
$contactInfo = $api->contactInfo('wm9nLQEAAA6lshIXRN5xdd1iZjqevSyA');
foreach ($contactInfo['follow_user'] as $contactUserInfo) {
if ($contactUserInfo['userid'] == $simpleXMLElement->UserID->__toString()) {
$customerInfo = model('Customer')->where('name', $contactUserInfo['remark_corp_name'])->find();
if ($customerInfo) {
$contactsInfo = model('Contacts')->where([
'name' => $contactUserInfo['remark'],
'customer_id' => $customerInfo['customer_id']
])->find();
if (!$contactsInfo) {
$param = [
'business_id' => null,
'create_user_id' => 1,
'owner_user_id' => 1,
'customer_id' => $customerInfo['customer_id'],
'name' => $contactUserInfo['remark'],
'mobile' => $contactUserInfo['remark_mobiles'][0],
];
if (model('Contacts')->createData($param)) {
Log::record('联系人添加成功');
} else {
Log::record('联系人添加失败');
}
}
}
}
}
break;
}
} else {
print("ERR: " . $errCode . "\n\n");
}
} else {
$sVerifyMsgSig = Request::instance()->get('msg_signature');
$sVerifyTimeStamp = Request::instance()->get('timestamp');
$sVerifyNonce = Request::instance()->get('nonce');
$sVerifyEchoStr = Request::instance()->get('echostr');
// 需要返回的明文
$sEchoStr = "";
$errCode = $wxcpt->VerifyURL($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $sVerifyEchoStr, $sEchoStr);
if ($errCode == 0) {
echo ($sEchoStr);
// 验证URL成功将sEchoStr返回
// HttpUtils.SetResponce($sEchoStr);
} else {
print("ERR: " . $errCode . "\n\n");
}
}
}
}

@ -28,7 +28,7 @@ class Message extends ApiCommon
{ {
$action = [ $action = [
'permission' => [], 'permission' => [],
'allow' => [ 'allow' => [
'num', 'num',
'todayleads', 'todayleads',
'todaycustomer', 'todaycustomer',
@ -45,19 +45,19 @@ class Message extends ApiCommon
'alldeal' 'alldeal'
] ]
]; ];
Hook::listen('check_auth',$action); Hook::listen('check_auth', $action);
$request = Request::instance(); $request = Request::instance();
$a = strtolower($request->action()); $a = strtolower($request->action());
if (!in_array($a, $action['permission'])) { if (!in_array($a, $action['permission'])) {
parent::_initialize(); parent::_initialize();
} }
} }
/** /**
* 系统通知 * 系统通知
* *
* @author Michael_xu
* @return * @return
* @author Michael_xu
*/ */
public function index() public function index()
{ {
@ -69,7 +69,7 @@ class Message extends ApiCommon
$data = $messageModel->getDataList($param); $data = $messageModel->getDataList($param);
return resultArray(['data' => $data]); return resultArray(['data' => $data]);
} }
/** /**
* 消息数 * 消息数
* *
@ -83,19 +83,19 @@ class Message extends ApiCommon
$configData = $configDataModel->getData(); $configData = $configDataModel->getData();
$data = []; $data = [];
# 今日需联系线索 # 今日需联系线索
$todayLeadsTime = cache('todayLeadsTime'.$userInfo['id']); $todayLeadsTime = cache('todayLeadsTime' . $userInfo['id']);
$todayLeadsCount = cache('todayLeadsCount'.$userInfo['id']); $todayLeadsCount = cache('todayLeadsCount' . $userInfo['id']);
if (time() <= $todayLeadsTime) { if (time() <= $todayLeadsTime) {
$data['todayLeads'] = (int)$todayLeadsCount; $data['todayLeads'] = (int)$todayLeadsCount;
} else { } else {
$todayLeads = $this->todayLeads(true); $todayLeads = $this->todayLeads(true);
$data['todayLeads'] = $todayLeads['dataCount'] ? : 0; $data['todayLeads'] = $todayLeads['dataCount'] ?: 0;
cache('todayLeadsCount'.$userInfo['id'], $data['todayLeads']); cache('todayLeadsCount' . $userInfo['id'], $data['todayLeads']);
cache('todayLeadsTime'.$userInfo['id'], time() ); cache('todayLeadsTime' . $userInfo['id'], time());
} }
# 今日需联系客户 # 今日需联系客户
$todayCustomerTime = cache('todayCustomerTime'.$userInfo['id']); $todayCustomerTime = cache('todayCustomerTime' . $userInfo['id']);
$todayCustomerCount = cache('todayCustomerCount'.$userInfo['id']); $todayCustomerCount = cache('todayCustomerCount' . $userInfo['id']);
if (time() <= $todayCustomerTime) { if (time() <= $todayCustomerTime) {
$data['todayCustomer'] = (int)$todayCustomerCount; $data['todayCustomer'] = (int)$todayCustomerCount;
} else { } else {
@ -105,128 +105,154 @@ class Message extends ApiCommon
cache('todayCustomerTime'.$userInfo['id'], time() ); cache('todayCustomerTime'.$userInfo['id'], time() );
} }
# 今日需联系商机 # 今日需联系商机
$todayBusinessTime = cache('todayBusinessTime'.$userInfo['id']); $todayBusinessTime = cache('todayBusinessTime' . $userInfo['id']);
$todayBusinessCount = cache('todayBusinessCount'.$userInfo['id']); $todayBusinessCount = cache('todayBusinessCount' . $userInfo['id']);
if (time() <= $todayBusinessTime) { if (time() <= $todayBusinessTime) {
$data['todayBusiness'] = (int)$todayBusinessCount; $data['todayBusiness'] = (int)$todayBusinessCount;
} else { } else {
$todayBusiness = $this->todayBusiness(true); $todayBusiness = $this->todayBusiness(true);
$data['todayBusiness'] = $todayBusiness['dataCount'] ? : 0; $data['todayBusiness'] = $todayBusiness['dataCount'] ?: 0;
cache('todayBusinessCount'.$userInfo['id'], $data['todayBusiness']); cache('todayBusinessCount' . $userInfo['id'], $data['todayBusiness']);
cache('todayBusinessTime'.$userInfo['id'], time() ); cache('todayBusinessTime' . $userInfo['id'], time());
} }
# 分配给我的线索 # 分配给我的线索
$followLeadsTime = cache('followLeadsTime'.$userInfo['id']); $followLeadsTime = cache('followLeadsTime' . $userInfo['id']);
$followLeadsCount = cache('followLeadsCount'.$userInfo['id']); $followLeadsCount = cache('followLeadsCount' . $userInfo['id']);
if (time() <= $followLeadsTime) { if (time() <= $followLeadsTime) {
$data['followLeads'] = (int)$followLeadsCount; $data['followLeads'] = (int)$followLeadsCount;
} else { } else {
$followLeads = $this->followLeads(true); $followLeads = $this->followLeads(true);
$data['followLeads'] = $followLeads['dataCount'] ? : 0; $data['followLeads'] = $followLeads['dataCount'] ?: 0;
cache('followLeadsCount'.$userInfo['id'], $data['followLeads']); cache('followLeadsCount' . $userInfo['id'], $data['followLeads']);
cache('followLeadsTime'.$userInfo['id'], time() ); cache('followLeadsTime' . $userInfo['id'], time());
} }
# 分配给我的客户 # 分配给我的客户
$followCustomerTime = cache('followCustomerTime'.$userInfo['id']); $followCustomerTime = cache('followCustomerTime' . $userInfo['id']);
$followCustomerCount = cache('followCustomerCount'.$userInfo['id']); $followCustomerCount = cache('followCustomerCount' . $userInfo['id']);
if (time() <= $followCustomerTime) { if (time() <= $followCustomerTime) {
$data['followCustomer'] = (int)$followCustomerCount; $data['followCustomer'] = (int)$followCustomerCount;
} else { } else {
$followCustomer = $this->followCustomer(true); $followCustomer = $this->followCustomer(true);
$data['followCustomer'] = $followCustomer['dataCount'] ? : 0; $data['followCustomer'] = $followCustomer['dataCount'] ?: 0;
cache('followCustomerCount'.$userInfo['id'], $data['followCustomer']); cache('followCustomerCount' . $userInfo['id'], $data['followCustomer']);
cache('followCustomerTime'.$userInfo['id'], time() ); cache('followCustomerTime' . $userInfo['id'], time());
} }
# 待审核合同 # 待审核合同
$checkContractTime = cache('checkContractTime'.$userInfo['id']); $checkContractTime = cache('checkContractTime' . $userInfo['id']);
$checkContractCount = cache('checkContractCount'.$userInfo['id']); $checkContractCount = cache('checkContractCount' . $userInfo['id']);
if (time() <= $checkContractTime) { if (time() <= $checkContractTime) {
$data['checkContract'] = (int)$checkContractCount; $data['checkContract'] = (int)$checkContractCount;
} else { } else {
$checkContract = $this->checkContract(true); $checkContract = $this->checkContract(true);
$data['checkContract'] = $checkContract['dataCount'] ? : 0; $data['checkContract'] = $checkContract['dataCount'] ?: 0;
cache('checkContractCount'.$userInfo['id'], $data['checkContract']); cache('checkContractCount' . $userInfo['id'], $data['checkContract']);
cache('checkContractTime'.$userInfo['id'], time() ); cache('checkContractTime' . $userInfo['id'], time());
} }
# 待审核回款 # 待审核回款
$checkReceivablesTime = cache('checkReceivablesTime'.$userInfo['id']); $checkReceivablesTime = cache('checkReceivablesTime' . $userInfo['id']);
$checkReceivablesCount = cache('checkReceivablesCount'.$userInfo['id']); $checkReceivablesCount = cache('checkReceivablesCount' . $userInfo['id']);
if (time() <= $checkReceivablesTime) { if (time() <= $checkReceivablesTime) {
$data['checkReceivables'] = (int)$checkReceivablesCount; $data['checkReceivables'] = (int)$checkReceivablesCount;
} else { } else {
$checkReceivables = $this->checkReceivables(true); $checkReceivables = $this->checkReceivables(true);
$data['checkReceivables'] = $checkReceivables['dataCount'] ? : 0; $data['checkReceivables'] = $checkReceivables['dataCount'] ?: 0;
cache('checkReceivablesCount'.$userInfo['id'], $data['checkReceivables']); cache('checkReceivablesCount' . $userInfo['id'], $data['checkReceivables']);
cache('checkReceivablesTime'.$userInfo['id'], time() ); cache('checkReceivablesTime' . $userInfo['id'], time());
} }
# 待审核发票 # 待审核发票
$checkInvoiceTime = cache('checkInvoiceTime'.$userInfo['id']); $checkInvoiceTime = cache('checkInvoiceTime' . $userInfo['id']);
$checkInvoiceCount = cache('checkInvoiceCount'.$userInfo['id']); $checkInvoiceCount = cache('checkInvoiceCount' . $userInfo['id']);
if (time() <= $checkInvoiceTime) { if (time() <= $checkInvoiceTime) {
$data['checkInvoice'] = (int)$checkInvoiceCount; $data['checkInvoice'] = (int)$checkInvoiceCount;
} else { } else {
$checkInvoice = $this->checkInvoice(true); $checkInvoice = $this->checkInvoice(true);
$data['checkInvoice'] = $checkInvoice['dataCount'] ? : 0; $data['checkInvoice'] = $checkInvoice['dataCount'] ?: 0;
cache('checkInvoiceCount' . $userInfo['id'], $data['checkInvoice']);
cache('checkInvoiceTime' . $userInfo['id'], time());
}
# 待审核商机
$checkBusinessTime = cache('checkBusinessTime' . $userInfo['id']);
$checkBusinessCount = cache('checkBusinessCount' . $userInfo['id']);
if (time() <= $checkBusinessTime) {
$data['checkBusiness'] = (int)$checkBusinessCount;
cache('checkInvoiceCount'.$userInfo['id'], $data['checkInvoice']); } else {
cache('checkInvoiceTime'.$userInfo['id'], time() ); $checkBusiness = $this->checkBusiness(true);
$data['checkBusiness'] = $checkBusiness['dataCount'] ?: 0;
cache('checkBusinessCount' . $userInfo['id'], $data['checkBusiness']);
cache('checkBusinessTime' . $userInfo['id'], time());
} }
# 待回款提醒 # 待回款提醒
$remindReceivablesPlanTime = cache('remindReceivablesPlanTime'.$userInfo['id']); $remindReceivablesPlanTime = cache('remindReceivablesPlanTime' . $userInfo['id']);
$remindReceivablesPlanCount = cache('remindReceivablesPlanCount'.$userInfo['id']); $remindReceivablesPlanCount = cache('remindReceivablesPlanCount' . $userInfo['id']);
if (time() <= $remindReceivablesPlanTime) { if (time() <= $remindReceivablesPlanTime) {
$data['remindReceivablesPlan'] = (int)$remindReceivablesPlanCount; $data['remindReceivablesPlan'] = (int)$remindReceivablesPlanCount;
} else { } else {
$remindReceivablesPlan = $this->remindReceivablesPlan(true); $remindReceivablesPlan = $this->remindReceivablesPlan(true);
$data['remindReceivablesPlan'] = $remindReceivablesPlan['dataCount'] ? : 0; $data['remindReceivablesPlan'] = $remindReceivablesPlan['dataCount'] ?: 0;
cache('remindReceivablesPlanCount'.$userInfo['id'], $data['remindReceivablesPlan']); cache('remindReceivablesPlanCount' . $userInfo['id'], $data['remindReceivablesPlan']);
cache('remindReceivablesPlanTime'.$userInfo['id'], time() ); cache('remindReceivablesPlanTime' . $userInfo['id'], time());
} }
if ($configData['visit_config'] == 1) { if ($configData['visit_config'] == 1) {
# 待回访合同 # 待回访合同
$visitContractTime = cache('visitContractTime'.$userInfo['id']); $visitContractTime = cache('visitContractTime' . $userInfo['id']);
$visitContractCount = cache('visitContractCount'.$userInfo['id']); $visitContractCount = cache('visitContractCount' . $userInfo['id']);
if (time() <= $visitContractTime) { if (time() <= $visitContractTime) {
$data['returnVisitRemind'] = (int)$visitContractCount; $data['returnVisitRemind'] = (int)$visitContractCount;
} else { } else {
$visitContract = $this->visitContract(true); $visitContract = $this->visitContract(true);
$data['returnVisitRemind'] = $visitContract['dataCount'] ? : 0; $data['returnVisitRemind'] = $visitContract['dataCount'] ?: 0;
cache('visitContractCount'.$userInfo['id'], $data['returnVisitRemind']); cache('visitContractCount' . $userInfo['id'], $data['returnVisitRemind']);
cache('visitContractTime'.$userInfo['id'], time() ); cache('visitContractTime' . $userInfo['id'], time());
} }
} }
# 即将到期合同 # 即将到期合同
if ($configData['contract_config'] == 1) { if ($configData['contract_config'] == 1) {
$endContractTime = cache('endContractTime'.$userInfo['id']); $endContractTime = cache('endContractTime' . $userInfo['id']);
$endContractCount = cache('endContractCount'.$userInfo['id']); $endContractCount = cache('endContractCount' . $userInfo['id']);
if (time() <= $endContractTime) { if (time() <= $endContractTime) {
$data['endContract'] = (int)$endContractCount; $data['endContract'] = (int)$endContractCount;
} else { } else {
$endContract = $this->endContract(true); $endContract = $this->endContract(true);
$data['endContract'] = $endContract['dataCount'] ? : 0; $data['endContract'] = $endContract['dataCount'] ?: 0;
cache('endContractCount'.$userInfo['id'], $data['endContract']); cache('endContractCount' . $userInfo['id'], $data['endContract']);
cache('endContractTime'.$userInfo['id'], time() ); cache('endContractTime' . $userInfo['id'], time());
} }
} }
# 新增商机
$newBusinessTime = cache('newBusinessTime' . $userInfo['id']);
$newBusinessCount = cache('newBusinessCount' . $userInfo['id']);
if (time() <= $newBusinessTime) {
$data['newBusiness'] = (int)$newBusinessCount;
} else {
$newBusiness = $this->newBusiness(true);
$data['newBusiness'] = $newBusiness['dataCount'] ?: 0;
cache('newBusinessCount' . $userInfo['id'], $data['newBusiness']);
cache('newBusinessTime' . $userInfo['id'], time());
}
# 待进入公海提醒 # 待进入公海提醒
$pool = db('crm_customer_pool')->where(['status' => 1, 'remind_conf' => 1])->count(); $pool = db('crm_customer_pool')->where(['status' => 1, 'remind_conf' => 1])->count();
if (!empty($pool)) { if (!empty($pool)) {
$remindCustomerTime = cache('remindCustomerTime'.$userInfo['id']); $remindCustomerTime = cache('remindCustomerTime' . $userInfo['id']);
$remindCustomerCount = cache('remindCustomerCount'.$userInfo['id']); $remindCustomerCount = cache('remindCustomerCount' . $userInfo['id']);
if (time() <= $remindCustomerTime) { if (time() <= $remindCustomerTime) {
$data['putInPoolRemind'] = (int)$remindCustomerCount; $data['putInPoolRemind'] = (int)$remindCustomerCount;
} else { } else {
$remindCustomer = $this->remindCustomer(true); $remindCustomer = $this->remindCustomer(true);
$data['putInPoolRemind'] = !empty($remindCustomer['dataCount']) ? $remindCustomer['dataCount'] : 0; $data['putInPoolRemind'] = !empty($remindCustomer['dataCount']) ? $remindCustomer['dataCount'] : 0;
cache('remindCustomerCount'.$userInfo['id'], $data['putInPoolRemind']); cache('remindCustomerCount' . $userInfo['id'], $data['putInPoolRemind']);
cache('remindCustomerTime'.$userInfo['id'], time() ); cache('remindCustomerTime' . $userInfo['id'], time());
} }
} }
return resultArray(['data' => $data]); return resultArray(['data' => $data]);
} }
/** /**
* 今日需联系线索 * 今日需联系线索
* *
@ -235,21 +261,21 @@ class Message extends ApiCommon
*/ */
public function todayLeads($getCount = false) public function todayLeads($getCount = false)
{ {
$param = $this->param; $param = $this->param;
$userId = $this->userInfo['id']; $userId = $this->userInfo['id'];
$types = $param['types']; $types = $param['types'];
unset($param['types']); unset($param['types']);
$param['user_id'] = $userId; $param['user_id'] = $userId;
if ($getCount == true) $param['getCount'] = 1; if ($getCount == true) $param['getCount'] = 1;
$messageLogic= new MessageLogic(); $messageLogic = new MessageLogic();
$data = $messageLogic->todayLeads($param); $data = $messageLogic->todayLeads($param);
if ($types == 'list') return resultArray(['data' => $data]); if ($types == 'list') return resultArray(['data' => $data]);
return $data; return $data;
} }
/** /**
* 今日需联系客户 * 今日需联系客户
* *
@ -266,14 +292,14 @@ class Message extends ApiCommon
} }
unset($param['types']); unset($param['types']);
$param['user_id'] = $userId; $param['user_id'] = $userId;
$messageLogic= new MessageLogic(); $messageLogic = new MessageLogic();
$data = $messageLogic->remindCustomer($param); $data = $messageLogic->remindCustomer($param);
if ($types == 'list') { if ($types == 'list') {
return resultArray(['data' => $data]); return resultArray(['data' => $data]);
} }
return $data; return $data;
} }
/** /**
* 今日需联系商机 * 今日需联系商机
* *
@ -285,24 +311,24 @@ class Message extends ApiCommon
*/ */
public function todayBusiness($getCount = false) public function todayBusiness($getCount = false)
{ {
$param = $this->param; $param = $this->param;
$userId = $this->userInfo['id']; $userId = $this->userInfo['id'];
$types = $param['types']; $types = $param['types'];
unset($param['types']); unset($param['types']);
if ($getCount == true) $param['getCount'] = 1; if ($getCount == true) $param['getCount'] = 1;
$messageLogic= new MessageLogic(); $messageLogic = new MessageLogic();
$param['user_id'] = $userId; $param['user_id'] = $userId;
$data = $messageLogic->todayBusiness($param); $data = $messageLogic->todayBusiness($param);
if ($types == 'list') return resultArray(['data' => $data]); if ($types == 'list') return resultArray(['data' => $data]);
return $data; return $data;
} }
/** /**
* 分配给我的线索 * 分配给我的线索
* @author Michael_xu
* @return * @return
* @author Michael_xu
*/ */
public function followLeads($getCount = false) public function followLeads($getCount = false)
{ {
@ -312,18 +338,18 @@ class Message extends ApiCommon
unset($param['types']); unset($param['types']);
if ($getCount == true) $param['getCount'] = 1; if ($getCount == true) $param['getCount'] = 1;
$param['user_id'] = $userInfo['id']; $param['user_id'] = $userInfo['id'];
$messageLogic=new MessageLogic(); $messageLogic = new MessageLogic();
$data = $messageLogic->followLeads($param); $data = $messageLogic->followLeads($param);
if ($types == 'list') { if ($types == 'list') {
return resultArray(['data' => $data]); return resultArray(['data' => $data]);
} }
return $data; return $data;
} }
/** /**
* 分配给我的客户 * 分配给我的客户
* @author Michael_xu
* @return * @return
* @author Michael_xu
*/ */
public function followCustomer($getCount = false) public function followCustomer($getCount = false)
{ {
@ -334,7 +360,7 @@ class Message extends ApiCommon
$param['getCount'] = 1; $param['getCount'] = 1;
} }
unset($param['types']); unset($param['types']);
$messageLogic=new MessageLogic(); $messageLogic = new MessageLogic();
$param['user_id'] = $userInfo['id']; $param['user_id'] = $userInfo['id'];
$data = $messageLogic->followCustomer($param); $data = $messageLogic->followCustomer($param);
if ($types == 'list') { if ($types == 'list') {
@ -342,7 +368,7 @@ class Message extends ApiCommon
} }
return $data; return $data;
} }
/** /**
* 待审核合同 * 待审核合同
* *
@ -358,7 +384,7 @@ class Message extends ApiCommon
if ($getCount == true) { if ($getCount == true) {
$param['getCount'] = 1; $param['getCount'] = 1;
} }
$messageLogic=new MessageLogic(); $messageLogic = new MessageLogic();
$param['user_id'] = $userInfo['id']; $param['user_id'] = $userInfo['id'];
$data = $messageLogic->checkContract($param); $data = $messageLogic->checkContract($param);
if ($types == 'list') { if ($types == 'list') {
@ -366,11 +392,11 @@ class Message extends ApiCommon
} }
return $data; return $data;
} }
/** /**
* 待审核回款 * 待审核回款
* @author Michael_xu
* @return * @return
* @author Michael_xu
*/ */
public function checkReceivables($getCount = false) public function checkReceivables($getCount = false)
{ {
@ -379,7 +405,7 @@ class Message extends ApiCommon
$types = $param['types']; $types = $param['types'];
unset($param['types']); unset($param['types']);
if ($getCount == true) $param['getCount'] = 1; if ($getCount == true) $param['getCount'] = 1;
$messageLogic=new MessageLogic(); $messageLogic = new MessageLogic();
$param['user_id'] = $userInfo['id']; $param['user_id'] = $userInfo['id'];
$data = $messageLogic->checkReceivables($param); $data = $messageLogic->checkReceivables($param);
if ($types == 'list') { if ($types == 'list') {
@ -387,7 +413,7 @@ class Message extends ApiCommon
} }
return $data; return $data;
} }
/** /**
* 待审核发票 * 待审核发票
* *
@ -397,40 +423,63 @@ class Message extends ApiCommon
*/ */
public function checkInvoice($getCount = false) public function checkInvoice($getCount = false)
{ {
$param = $this->param; $param = $this->param;
$userId = $this->userInfo['id']; $userId = $this->userInfo['id'];
$types = $param['types']; $types = $param['types'];
if ($getCount == true) $param['getCount'] = 1; if ($getCount == true) $param['getCount'] = 1;
# 清除与模型无关的数据 # 清除与模型无关的数据
unset($param['types']); unset($param['types']);
$param['user_id'] = $userId; $param['user_id'] = $userId;
$messageLogic=new MessageLogic(); $messageLogic = new MessageLogic();
$data = $messageLogic->checkInvoice($param); $data = $messageLogic->checkInvoice($param);
if ($types == 'list') return resultArray(['data' => $data]);
return $data;
}
/**
* 待审核商机
*
* @return array|\think\response\Json
* @throws \think\exception\DbException
*/
public function checkBusiness($getCount = false)
{
$param = $this->param;
$userId = $this->userInfo['id'];
$types = $param['types'];
if ($getCount == true) $param['getCount'] = 1;
# 清除与模型无关的数据
unset($param['types']);
$param['user_id'] = $userId;
$messageLogic = new MessageLogic();
$data = $messageLogic->checkBusiness($param);
if ($types == 'list') return resultArray(['data' => $data]); if ($types == 'list') return resultArray(['data' => $data]);
return $data; return $data;
} }
/** /**
* 待回款提醒 * 待回款提醒
* @author Michael_xu
* @return * @return
* @author Michael_xu
*/ */
public function remindReceivablesPlan($getCount = false) public function remindReceivablesPlan($getCount = false)
{ {
$param = $this->param; $param = $this->param;
$userInfo = $this->userInfo; $userInfo = $this->userInfo;
$types = $param['types']; $types = $param['types'];
$type = $param['type'] ? : 1; $type = $param['type'] ?: 1;
$isSub = $param['isSub'] ? : ''; $isSub = $param['isSub'] ?: '';
unset($param['types']); unset($param['types']);
unset($param['type']); unset($param['type']);
unset($param['isSub']); unset($param['isSub']);
$receivablesPlanModel = model('ReceivablesPlan'); $receivablesPlanModel = model('ReceivablesPlan');
if ($getCount == true) $param['getCount'] = 1; if ($getCount == true) $param['getCount'] = 1;
$param['owner_user_id'] = $userInfo['id']; $param['owner_user_id'] = $userInfo['id'];
if ($isSub) { if ($isSub) {
$param['owner_user_id'] = ['in', getSubUserId(false)]; $param['owner_user_id'] = ['in', getSubUserId(false)];
@ -460,19 +509,19 @@ class Message extends ApiCommon
} }
return $data; return $data;
} }
/** /**
* 即将到期合同 * 即将到期合同
* @author Michael_xu
* @return * @return
* @author Michael_xu
*/ */
public function endContract($getCount = false) public function endContract($getCount = false)
{ {
$param = $this->param; $param = $this->param;
$userInfo = $this->userInfo; $userInfo = $this->userInfo;
$types = $param['types']; $types = $param['types'];
$type = $param['type'] ? : 1; $type = $param['type'] ?: 1;
$isSub = $param['isSub'] ? : ''; $isSub = $param['isSub'] ?: '';
if ($getCount == true) $param['getCount'] = 1; if ($getCount == true) $param['getCount'] = 1;
unset($param['types']); unset($param['types']);
unset($param['type']); unset($param['type']);
@ -480,19 +529,21 @@ class Message extends ApiCommon
$contractModel = model('Contract'); $contractModel = model('Contract');
$configModel = new \app\crm\model\ConfigData(); $configModel = new \app\crm\model\ConfigData();
$configInfo = $configModel->getData(); $configInfo = $configModel->getData();
$expireDay = $configInfo['contract_day'] ? : '7'; $expireDay = $configInfo['contract_day'] ?: '7';
// 合同到期不提醒 // 合同到期不提醒
if (empty($configInfo['contract_config'])) return resultArray(['data' => []]); if (empty($configInfo['contract_config'])) return resultArray(['data' => []]);
$param['owner_user_id'] = $userInfo['id']; $param['owner_user_id'] = $userInfo['id'];
if ($isSub) { if ($isSub) {
$param['owner_user_id'] = array('in',getSubUserId(false)); $param['owner_user_id'] = array('in', getSubUserId(false));
} }
switch ($type) { switch ($type) {
case '1' : case '1' :
$param['end_time'] = array('between',array(date('Y-m-d',time()),date('Y-m-d',time()+86400*$expireDay))); $param['end_time'] = array('between', array(date('Y-m-d', time()), date('Y-m-d', time() + 86400 * $expireDay)));
$param['expire_remind'] = 0; $param['expire_remind'] = 0;
break; break;
case '2' : $param['end_time'] = array('lt',date('Y-m-d',time())); break; case '2' :
$param['end_time'] = array('lt', date('Y-m-d', time()));
break;
} }
$data = $contractModel->getDataList($param); $data = $contractModel->getDataList($param);
// p($contractModel->getLastSql()); // p($contractModel->getLastSql());
@ -501,41 +552,70 @@ class Message extends ApiCommon
} }
return $data; return $data;
} }
/** /**
* 待进入客户池 * 新增商机
* @return
* @author Michael_xu * @author Michael_xu
*/
public function newBusiness($getCount = false)
{
$param = $this->param;
$userInfo = $this->userInfo;
$types = $param['types'];
$type = $param['type'] ?: 1;
$isSub = $param['isSub'] ?: '';
if ($getCount == true) $param['getCount'] = 1;
unset($param['types']);
unset($param['type']);
unset($param['isSub']);
$businessModel = model('Business');
$param['owner_user_id'] = $userInfo['id'];
if ($isSub) {
$param['owner_user_id'] = array('in', getSubUserId(false));
}
$data = $businessModel->getDataList($param);
// p($contractModel->getLastSql());
if ($types == 'list') {
return resultArray(['data' => $data]);
}
return $data;
}
/**
* 待进入客户池
* @return * @return
* @author Michael_xu
*/ */
public function remindCustomer($getCount = false) public function remindCustomer($getCount = false)
{ {
$customerModel = model('Customer'); $customerModel = model('Customer');
$param = $this->param; $param = $this->param;
$userInfo = $this->userInfo; $userInfo = $this->userInfo;
$types = $param['types']; $types = $param['types'];
$isSub = $param['isSub'] ? : ''; $isSub = $param['isSub'] ?: '';
if ($getCount == true) $param['getCount'] = 1; if ($getCount == true) $param['getCount'] = 1;
unset($param['types']); unset($param['types']);
unset($param['type']); unset($param['type']);
unset($param['isSub']); unset($param['isSub']);
unset($param['deal_status']); unset($param['deal_status']);
unset($param['owner_user_id']); unset($param['owner_user_id']);
# 负责人 # 负责人
$param['owner_user_id'] = !empty($isSub) ? ['in', getSubUserId(false, 0, $userInfo['id'])] : $userInfo['id']; $param['owner_user_id'] = !empty($isSub) ? ['in', getSubUserId(false, 0, $userInfo['id'])] : $userInfo['id'];
# 是否提醒 # 是否提醒
$data = []; $data = [];
$remind = db('crm_customer_pool')->where(['status' => 1, 'remind_conf' => 1])->count(); $remind = db('crm_customer_pool')->where(['status' => 1, 'remind_conf' => 1])->count();
if (!empty($remind)) { if (!empty($remind)) {
$whereData = $param ? : []; $whereData = $param ?: [];
$whereData['is_remind'] = 1; $whereData['is_remind'] = 1;
$whereData['user_id'] = $userInfo['id']; $whereData['user_id'] = $userInfo['id'];
$whereData['pool_remain'] = 0; $whereData['pool_remain'] = 0;
$whereData['scene_id'] = db('admin_scene')->where(['types' => 'crm_customer','bydata' => 'me'])->value('scene_id'); $whereData['scene_id'] = db('admin_scene')->where(['types' => 'crm_customer', 'bydata' => 'me'])->value('scene_id');
if ($isSub) { if ($isSub) {
$whereData['scene_id'] = db('admin_scene')->where(['types' => 'crm_customer','bydata' => 'sub'])->value('scene_id'); $whereData['scene_id'] = db('admin_scene')->where(['types' => 'crm_customer', 'bydata' => 'sub'])->value('scene_id');
} }
$data = $customerModel->getDataList($whereData); $data = $customerModel->getDataList($whereData);
} }
@ -544,7 +624,7 @@ class Message extends ApiCommon
} }
return $data; return $data;
} }
/** /**
* 待回访合同 * 待回访合同
* *
@ -556,30 +636,30 @@ class Message extends ApiCommon
*/ */
public function visitContract($getCount = false) public function visitContract($getCount = false)
{ {
$param = $this->param; $param = $this->param;
$userId = $this->userInfo['id']; $userId = $this->userInfo['id'];
$isSub = !empty($param['isSub']) ? $param['isSub'] : 0; $isSub = !empty($param['isSub']) ? $param['isSub'] : 0;
$types = !empty($param['types']) ? $param['types'] : ''; $types = !empty($param['types']) ? $param['types'] : '';
if ($getCount == true) $param['getCount'] = 1; if ($getCount == true) $param['getCount'] = 1;
unset($param['isSub']); unset($param['isSub']);
unset($param['types']); unset($param['types']);
$param['is_visit'] = 0; # 未回访 $param['is_visit'] = 0; # 未回访
$param['check_status'] = 2; # 审核通过 $param['check_status'] = 2; # 审核通过
$contractModel = new \app\crm\model\Contract(); $contractModel = new \app\crm\model\Contract();
# 负责人 # 负责人
$param['owner_user_id'] = !empty($isSub) ? ['in', getSubUserId(false)] : $userId; $param['owner_user_id'] = !empty($isSub) ? ['in', getSubUserId(false)] : $userId;
$param['user_id'] = $userId; $param['user_id'] = $userId;
$data = $contractModel->getDataList($param); $data = $contractModel->getDataList($param);
if ($types == 'list') return resultArray(['data' => $data]); if ($types == 'list') return resultArray(['data' => $data]);
return $data; return $data;
} }
/** /**
* 全部标记已处理 * 全部标记已处理
* *
@ -589,16 +669,16 @@ class Message extends ApiCommon
*/ */
public function allDeal() public function allDeal()
{ {
$type = $this->param['type']; $type = $this->param['type'];
$typeId = !empty($this->param['type_id']) ? $this->param['type_id'] : ''; $typeId = !empty($this->param['type_id']) ? $this->param['type_id'] : '';
$isSub = !empty($this->param['isSub']) ? $this->param['isSub'] : 0; $isSub = !empty($this->param['isSub']) ? $this->param['isSub'] : 0;
$userId = $this->userInfo['id']; $userId = $this->userInfo['id'];
if (empty($type)) return resultArray(['error' => '缺少模块类型参数']); if (empty($type)) return resultArray(['error' => '缺少模块类型参数']);
# 获得今日开始和结束时间戳 # 获得今日开始和结束时间戳
$todayTime = getTimeByType('today'); $todayTime = getTimeByType('today');
# 处理今日需联系线索、客户、商机 # 处理今日需联系线索、客户、商机
if (in_array($type, ['todayLeads', 'todayCustomer', 'todayBusiness'])) { if (in_array($type, ['todayLeads', 'todayCustomer', 'todayBusiness'])) {
# 负责人 # 负责人
@ -607,14 +687,14 @@ class Message extends ApiCommon
$where['next_time'] = ['between', [$todayTime[0], $todayTime[1]]]; $where['next_time'] = ['between', [$todayTime[0], $todayTime[1]]];
# 是否已处理(联系) # 是否已处理(联系)
$where['is_dealt'] = 0; $where['is_dealt'] = 0;
# 线索 # 线索
if ($type == 'todayLeads') { if ($type == 'todayLeads') {
$leadsId = !empty($typeId) ? $typeId : Db::name('crm_leads')->where($where)->column('leads_id'); $leadsId = !empty($typeId) ? $typeId : Db::name('crm_leads')->where($where)->column('leads_id');
Db::name('crm_leads')->whereIn('leads_id', $leadsId)->update([ Db::name('crm_leads')->whereIn('leads_id', $leadsId)->update([
'last_time' => time(), 'last_time' => time(),
'is_dealt' => 1, 'is_dealt' => 1,
'follow' => '已跟进' 'follow' => '已跟进'
]); ]);
} }
# 客户 # 客户
@ -622,8 +702,8 @@ class Message extends ApiCommon
$customerId = !empty($typeId) ? $typeId : Db::name('crm_customer')->where($where)->column('customer_id'); $customerId = !empty($typeId) ? $typeId : Db::name('crm_customer')->where($where)->column('customer_id');
Db::name('crm_customer')->whereIn('customer_id', $customerId)->update([ Db::name('crm_customer')->whereIn('customer_id', $customerId)->update([
'last_time' => time(), 'last_time' => time(),
'is_dealt' => 1, 'is_dealt' => 1,
'follow' => '已跟进' 'follow' => '已跟进'
]); ]);
} }
# 商机 # 商机
@ -631,17 +711,17 @@ class Message extends ApiCommon
$businessId = !empty($typeId) ? $typeId : Db::name('crm_business')->where($where)->column('business_id'); $businessId = !empty($typeId) ? $typeId : Db::name('crm_business')->where($where)->column('business_id');
Db::name('crm_business')->whereIn('business_id', $businessId)->update([ Db::name('crm_business')->whereIn('business_id', $businessId)->update([
'last_time' => time(), 'last_time' => time(),
'is_dealt' => 1 'is_dealt' => 1
]); ]);
} }
} }
# 处理分配给我的线索、客户 # 处理分配给我的线索、客户
if (in_array($type, ['followLeads', 'followCustomer'])) { if (in_array($type, ['followLeads', 'followCustomer'])) {
$where['owner_user_id'] = $userId; $where['owner_user_id'] = $userId;
$where['follow'] = [['neq','已跟进'], null, 'or']; $where['follow'] = [['neq', '已跟进'], null, 'or'];
$where['is_allocation'] = 1; $where['is_allocation'] = 1;
# 线索 # 线索
if ($type == 'followLeads') { if ($type == 'followLeads') {
$leadsId = !empty($typeId) ? $typeId : Db::name('crm_leads')->where($where)->column('leads_id'); $leadsId = !empty($typeId) ? $typeId : Db::name('crm_leads')->where($where)->column('leads_id');
@ -653,12 +733,12 @@ class Message extends ApiCommon
Db::name('crm_customer')->whereIn('customer_id', $customerId)->update(['follow' => '已跟进']); Db::name('crm_customer')->whereIn('customer_id', $customerId)->update(['follow' => '已跟进']);
} }
} }
# 处理待审核合同、回款、发票 # 处理待审核合同、回款、发票
if (in_array($type, ['checkContract', 'checkReceivables', 'checkInvoice'])) { if (in_array($type, ['checkContract', 'checkReceivables', 'checkInvoice'])) {
$where['check_status'] = ['lt','2']; $where['check_status'] = ['lt', '2'];
$where['check_user_id'] = ['like',',%' . $userId . '%,']; $where['check_user_id'] = ['like', ',%' . $userId . '%,'];
# 合同 # 合同
if ($type == 'checkContract') { if ($type == 'checkContract') {
$contractId = !empty($typeId) ? $typeId : Db::name('crm_contract')->where($where)->column('contract_id'); $contractId = !empty($typeId) ? $typeId : Db::name('crm_contract')->where($where)->column('contract_id');
@ -674,33 +754,33 @@ class Message extends ApiCommon
$invoiceId = !empty($typeId) ? $typeId : Db::name('crm_invoice')->where($where)->column('invoice_id'); $invoiceId = !empty($typeId) ? $typeId : Db::name('crm_invoice')->where($where)->column('invoice_id');
db('crm_dealt_relation')->where('user_id', $userId)->where('types', 'crm_invoice')->whereIn('types_id', $invoiceId)->delete(); db('crm_dealt_relation')->where('user_id', $userId)->where('types', 'crm_invoice')->whereIn('types_id', $invoiceId)->delete();
} }
} }
# 处理到期合同 # 处理到期合同
if ($type == 'endContract') { if ($type == 'endContract') {
$configModel = new \app\crm\model\ConfigData(); $configModel = new \app\crm\model\ConfigData();
$configInfo = $configModel->getData(); $configInfo = $configModel->getData();
$expireDay = $configInfo['contract_day'] ? : '7'; $expireDay = $configInfo['contract_day'] ?: '7';
$where['owner_user_id'] = $userId; $where['owner_user_id'] = $userId;
$where['end_time'] = ['between', [date('Y-m-d',time()), date('Y-m-d',time()+86400*$expireDay)]]; $where['end_time'] = ['between', [date('Y-m-d', time()), date('Y-m-d', time() + 86400 * $expireDay)]];
$where['expire_remind'] = 1; $where['expire_remind'] = 1;
$contractId = !empty($typeId) ? $typeId : Db::name('crm_contract')->where($where)->column('contract_id'); $contractId = !empty($typeId) ? $typeId : Db::name('crm_contract')->where($where)->column('contract_id');
Db::name('crm_contract')->whereIn('contract_id', $contractId)->update(['expire_remind' => 0]); Db::name('crm_contract')->whereIn('contract_id', $contractId)->update(['expire_remind' => 0]);
} }
# 处理待回访合同 # 处理待回访合同
if ($type == 'returnVisitRemind') { if ($type == 'returnVisitRemind') {
$where['owner_user_id'] = !empty($isSub) ? ['in', getSubUserId(false)] : $userId; # 负责人 $where['owner_user_id'] = !empty($isSub) ? ['in', getSubUserId(false)] : $userId; # 负责人
$where['is_visit'] = 0; # 未回访 $where['is_visit'] = 0; # 未回访
$where['check_status'] = 2; # 审核通过 $where['check_status'] = 2; # 审核通过
$contractId = !empty($typeId) ? $typeId : Db::name('crm_contract')->where($where)->column('contract_id'); $contractId = !empty($typeId) ? $typeId : Db::name('crm_contract')->where($where)->column('contract_id');
Db::name('crm_contract')->whereIn('contract_id', $contractId)->update(['is_visit' => 1]); Db::name('crm_contract')->whereIn('contract_id', $contractId)->update(['is_visit' => 1]);
} }
# 处理待进入公海 # 处理待进入公海
if ($type == 'putInPoolRemind') { if ($type == 'putInPoolRemind') {
if (!empty($typeId)) { if (!empty($typeId)) {
@ -713,66 +793,67 @@ class Message extends ApiCommon
$whereData['is_remind'] = 1; $whereData['is_remind'] = 1;
$whereData['user_id'] = $userId; $whereData['user_id'] = $userId;
$whereData['pool_remain'] = 0; $whereData['pool_remain'] = 0;
$whereData['scene_id'] = db('admin_scene')->where(['types' => 'crm_customer','bydata' => empty($isSub) ? 'me' : 'sub'])->value('scene_id'); $whereData['scene_id'] = db('admin_scene')->where(['types' => 'crm_customer', 'bydata' => empty($isSub) ? 'me' : 'sub'])->value('scene_id');
$whereData['owner_user_id'] = !empty($isSub) ? ['in', getSubUserId(false, 0, $userId)] : $userId; $whereData['owner_user_id'] = !empty($isSub) ? ['in', getSubUserId(false, 0, $userId)] : $userId;
$poolCustomers = (new \app\crm\model\Customer())->getDataList($whereData); $poolCustomers = (new \app\crm\model\Customer())->getDataList($whereData);
$ids = []; $ids = [];
foreach ($poolCustomers['list'] AS $key => $value) { foreach ($poolCustomers['list'] as $key => $value) {
if (!empty($value['customer_id'])) $ids[] = $value['customer_id']; if (!empty($value['customer_id'])) $ids[] = $value['customer_id'];
} }
if (!empty($ids)) Db::name('crm_customer')->whereIn('customer_id', $ids)->update(['pool_remain' => 1]); if (!empty($ids)) Db::name('crm_customer')->whereIn('customer_id', $ids)->update(['pool_remain' => 1]);
} }
} }
} }
# 带回款提醒 # 带回款提醒
if ($type == 'remindReceivablesPlan') { if ($type == 'remindReceivablesPlan') {
$planId = []; $planId = [];
if (!empty($typeId)) { if (!empty($typeId)) {
$planId = $typeId; $planId = $typeId;
} else { } else {
$param['owner_user_id'] = $isSub ? ['in',getSubUserId(false)] : $userId; $param['owner_user_id'] = $isSub ? ['in', getSubUserId(false)] : $userId;
$param['receivables_id'] = 0; $param['receivables_id'] = 0;
$param['check_status'] = ['lt', 2]; $param['check_status'] = ['lt', 2];
$param['remind_date'] = ['elt', date('Y-m-d',time())]; $param['remind_date'] = ['elt', date('Y-m-d', time())];
$param['return_date'] = ['egt', date('Y-m-d',time())]; $param['return_date'] = ['egt', date('Y-m-d', time())];
$param['types'] = 1; $param['types'] = 1;
$param['page'] = 1; $param['page'] = 1;
$param['limit'] = 1000; $param['limit'] = 1000;
$receivablesPlanModel = model('ReceivablesPlan'); $receivablesPlanModel = model('ReceivablesPlan');
$data = $receivablesPlanModel->getDataList($param); $data = $receivablesPlanModel->getDataList($param);
foreach ($data['list'] AS $key => $value) { foreach ($data['list'] as $key => $value) {
$planId[] = $value['plan_id']; $planId[] = $value['plan_id'];
} }
} }
if (!empty($planId)) db('crm_receivables_plan')->whereIn('plan_id', $planId)->update(['is_dealt' => 1]); if (!empty($planId)) db('crm_receivables_plan')->whereIn('plan_id', $planId)->update(['is_dealt' => 1]);
} }
cache::rm('todayLeadsCount'.$userId); cache::rm('todayLeadsCount' . $userId);
cache::rm('todayCustomerCount'.$userId); cache::rm('todayCustomerCount' . $userId);
cache::rm('todayBusinessCount'.$userId); cache::rm('todayBusinessCount' . $userId);
cache::rm('followLeadsCount'.$userId); cache::rm('followLeadsCount' . $userId);
cache::rm('followCustomerCount'.$userId); cache::rm('followCustomerCount' . $userId);
cache::rm('checkContractCount'.$userId); cache::rm('checkContractCount' . $userId);
cache::rm('checkReceivablesCount'.$userId); cache::rm('checkReceivablesCount' . $userId);
cache::rm('checkInvoiceCount'.$userId); cache::rm('checkInvoiceCount' . $userId);
cache::rm('remindReceivablesPlanCount'.$userId); cache::rm('remindReceivablesPlanCount' . $userId);
cache::rm('visitContractCount'.$userId); cache::rm('visitContractCount' . $userId);
cache::rm('endContractCount'.$userId); cache::rm('endContractCount' . $userId);
cache::rm('remindCustomerCount'.$userId); cache::rm('remindCustomerCount' . $userId);
cache::rm('todayLeadsTime'.$userId); cache::rm('todayLeadsTime' . $userId);
cache::rm('todayCustomerTime'.$userId); cache::rm('todayCustomerTime' . $userId);
cache::rm('todayBusinessTime'.$userId); cache::rm('todayBusinessTime' . $userId);
cache::rm('followLeadsTime'.$userId); cache::rm('followLeadsTime' . $userId);
cache::rm('followCustomerTime'.$userId); cache::rm('followCustomerTime' . $userId);
cache::rm('checkContractTime'.$userId); cache::rm('checkContractTime' . $userId);
cache::rm('checkReceivablesTime'.$userId); cache::rm('checkReceivablesTime' . $userId);
cache::rm('checkInvoiceTime'.$userId); cache::rm('checkInvoiceTime' . $userId);
cache::rm('remindReceivablesPlanTime'.$userId); cache::rm('checkBusinessTime' . $userId);
cache::rm('visitContractTime'.$userId); cache::rm('remindReceivablesPlanTime' . $userId);
cache::rm('endContractTime'.$userId); cache::rm('visitContractTime' . $userId);
cache::rm('remindCustomerTime'.$userId); cache::rm('endContractTime' . $userId);
cache::rm('remindCustomerTime' . $userId);
return resultArray(['data' => '操作成功!']); return resultArray(['data' => '操作成功!']);
} }
} }

@ -167,6 +167,25 @@ class MessageLogic extends Common
$data = (new InvoiceLogic())->index($request); $data = (new InvoiceLogic())->index($request);
return $data; return $data;
} }
/**
*待审核商机
*
* @author alvin guogaobo
* @version 1.0 版本号
* @since 2021/5/26 0026 13:35
*/
public function checkBusiness($param){
$type = !empty($param['type']) ? $param['type'] : 1;
$isSub = 1;
unset($param['type']);
$businessModel = model('Business');
$request = $this->whereCheck($param, $type,$isSub);
$request['isMessage'] = true;
$data = $businessModel->getDataList($request);
return $data;
}
/** /**
* 审批查询条件 * 审批查询条件
* @param $param * @param $param

@ -49,6 +49,7 @@ class Business extends Common
$businessTypeId = $request['typesId']; // 针对mobile $businessTypeId = $request['typesId']; // 针对mobile
$businessStatusId = $request['statusId']; // 针对mobile $businessStatusId = $request['statusId']; // 针对mobile
$overdue = $request['overdue']; // 待办事项下需联系商机(逾期) $overdue = $request['overdue']; // 待办事项下需联系商机(逾期)
$isMessage = !empty($request['isMessage']);
unset($request['scene_id']); unset($request['scene_id']);
unset($request['search']); unset($request['search']);
unset($request['user_id']); unset($request['user_id']);
@ -60,6 +61,7 @@ class Business extends Common
unset($request['typesId']); unset($request['typesId']);
unset($request['statusId']); unset($request['statusId']);
unset($request['overdue']); unset($request['overdue']);
unset($request['isMessage']);
$request = $this->fmtRequest($request); $request = $this->fmtRequest($request);
$requestMap = $request['map'] ?: []; $requestMap = $request['map'] ?: [];
$sceneModel = new \app\admin\model\Scene(); $sceneModel = new \app\admin\model\Scene();
@ -80,28 +82,28 @@ class Business extends Common
} }
if (isset($requestMap['type_id'])) { if (isset($requestMap['type_id'])) {
$requestMap['type_id']['value'] = $requestMap['type_id']['type_id']; $requestMap['type_id']['value'] = $requestMap['type_id']['type_id'];
if(in_array($requestMap['type_id']['status_id'],[1,2,3])){ if (in_array($requestMap['type_id']['status_id'], [1, 2, 3])) {
$requestMap['is_end']=$requestMap['type_id']['status_id']; $requestMap['is_end'] = $requestMap['type_id']['status_id'];
}else{ } else {
if ($requestMap['type_id']['status_id']) $requestMap['status_id']['value'] = $requestMap['type_id']['status_id']; if ($requestMap['type_id']['status_id']) $requestMap['status_id']['value'] = $requestMap['type_id']['status_id'];
$requestMap['is_end']=0; $requestMap['is_end'] = 0;
} }
} }
if ($sceneMap['type_id']) { if ($sceneMap['type_id']) {
$requestMap['type_id']['value'] = $sceneMap['type_id']['type_id']; $requestMap['type_id']['value'] = $sceneMap['type_id']['type_id'];
if(in_array($sceneMap['type_id']['status_id'],[1,2,3])){ if (in_array($sceneMap['type_id']['status_id'], [1, 2, 3])) {
$sceneMap['is_end']=$sceneMap['type_id']['status_id']; $sceneMap['is_end'] = $sceneMap['type_id']['status_id'];
}else{ } else {
if ($sceneMap['type_id']['status_id']) $requestMap['status_id']['value'] = $sceneMap['type_id']['status_id']; if ($sceneMap['type_id']['status_id']) $requestMap['status_id']['value'] = $sceneMap['type_id']['status_id'];
$sceneMap['is_end']=0; $sceneMap['is_end'] = 0;
} }
unset($sceneMap['type_id']); unset($sceneMap['type_id']);
} }
$partMap = []; $partMap = [];
$teamMap=$requestMap['team_id']; $teamMap = $requestMap['team_id'];
//团队成员 高级筛选 //团队成员 高级筛选
if($teamMap){ if ($teamMap) {
$partMap= advancedQueryFormatForTeam($teamMap,'business',''); $partMap = advancedQueryFormatForTeam($teamMap, 'business', '');
unset($requestMap['team_id']); unset($requestMap['team_id']);
$map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap; $map = $requestMap ? array_merge($sceneMap, $requestMap) : $sceneMap;
} else { } else {
@ -110,22 +112,23 @@ class Business extends Common
//高级筛选 //高级筛选
$map = advancedQuery($map, 'crm', 'business', 'index'); $map = advancedQuery($map, 'crm', 'business', 'index');
$authMap = []; $authMap = [];
$a = 'index'; $a = 'index';
if ($is_excel) $a = 'excelExport'; if ($is_excel) $a = 'excelExport';
$auth_user_ids = $userModel->getUserByPer('crm', 'business', $a); $auth_user_ids = $userModel->getUserByPer('crm', 'business', $a);
if (isset($map['business.owner_user_id'])) { if (isset($map['business.owner_user_id'])) {
if (!is_array($map['business.owner_user_id'][1])) { if (!is_array($map['business.owner_user_id'][1])) {
$map['business.owner_user_id'][1] = [$map['business.owner_user_id'][1]]; $map['business.owner_user_id'][1] = [$map['business.owner_user_id'][1]];
} }
if (in_array($map['business.owner_user_id'][0], ['neq', 'notin'])) { if (in_array($map['business.owner_user_id'][0], ['neq', 'notin'])) {
$auth_user_ids = array_diff($auth_user_ids, $map['business.owner_user_id'][1]) ?: []; //取差集 $auth_user_ids = array_diff($auth_user_ids, $map['business.owner_user_id'][1]) ?: []; //取差集
} else {
$auth_user_ids = array_intersect($map['business.owner_user_id'][1], $auth_user_ids) ?: []; //取交集
}
unset($map['business.owner_user_id']);
$auth_user_ids = array_merge(array_unique(array_filter($auth_user_ids))) ?: ['-1'];
$authMap['business.owner_user_id'] = array('in', $auth_user_ids);
} else { } else {
$auth_user_ids = array_intersect($map['business.owner_user_id'][1], $auth_user_ids) ?: []; //取交集
}
unset($map['business.owner_user_id']);
$auth_user_ids = array_merge(array_unique(array_filter($auth_user_ids))) ?: ['-1'];
$authMap['business.owner_user_id'] = array('in', $auth_user_ids);
} else {
if (!$isMessage) {
$authMapData = []; $authMapData = [];
$authMapData['auth_user_ids'] = $auth_user_ids; $authMapData['auth_user_ids'] = $auth_user_ids;
$authMapData['user_id'] = $user_id; $authMapData['user_id'] = $user_id;
@ -135,6 +138,7 @@ class Business extends Common
->whereOr('business.rw_user_id', array('like', '%,' . $authMapData['user_id'] . ',%')); ->whereOr('business.rw_user_id', array('like', '%,' . $authMapData['user_id'] . ',%'));
}; };
} }
}
//联系人商机 //联系人商机
if ($contacts_id) { if ($contacts_id) {
@ -167,22 +171,22 @@ class Business extends Common
} else { } else {
$order = 'business.update_time desc'; $order = 'business.update_time desc';
} }
# 商机组和商机状态搜索 # 商机组和商机状态搜索
if (!empty($businessTypeId)) $map['business.type_id'] = ['eq', $businessTypeId]; if (!empty($businessTypeId)) $map['business.type_id'] = ['eq', $businessTypeId];
if (!empty($businessStatusId)) { if (!empty($businessStatusId)) {
if(preg_match("/^[1-9][0-9]*$/" ,$businessStatusId)){ if (preg_match("/^[1-9][0-9]*$/", $businessStatusId)) {
$map['is_end']=0; $map['is_end'] = 0;
$map['business.status_id'] = ['eq', $businessStatusId]; $map['business.status_id'] = ['eq', $businessStatusId];
}else{ } else {
$map['is_end']=abs($businessStatusId); $map['is_end'] = abs($businessStatusId);
} }
} }
// 待办事项下需联系商机(逾期) // 待办事项下需联系商机(逾期)
$overdueWhere = ''; $overdueWhere = '';
if (!empty($overdue)) { if (!empty($overdue)) {
$overdueWhere = "(FROM_UNIXTIME(`business`.`last_time`,'%Y-%m-%d') < FROM_UNIXTIME(`business`.`next_time`,'%Y-%m-%d') OR (ISNULL(`business`.`last_time`) AND `business`.`next_time` < ".time()."))"; $overdueWhere = "(FROM_UNIXTIME(`business`.`last_time`,'%Y-%m-%d') < FROM_UNIXTIME(`business`.`next_time`,'%Y-%m-%d') OR (ISNULL(`business`.`last_time`) AND `business`.`next_time` < " . time() . "))";
} }
$readAuthIds = $userModel->getUserByPer('crm', 'business', 'read'); $readAuthIds = $userModel->getUserByPer('crm', 'business', 'read');
@ -215,7 +219,7 @@ class Business extends Common
# 扩展数据 # 扩展数据
$extraData = []; $extraData = [];
$list=getFieldData($list,'crm_business',$user_id); $list = getFieldData($list, 'crm_business', $user_id);
foreach ($list as $k => $v) { foreach ($list as $k => $v) {
$list[$k]['customer_id_info']['customer_id'] = $v['customer_id']; $list[$k]['customer_id_info']['customer_id'] = $v['customer_id'];
$list[$k]['customer_id_info']['name'] = $v['customer_name']; $list[$k]['customer_id_info']['name'] = $v['customer_name'];
@ -310,31 +314,31 @@ class Business extends Common
// 处理日期date类型 // 处理日期date类型
$dateField = $fieldModel->getFieldByFormType('crm_business', 'date'); $dateField = $fieldModel->getFieldByFormType('crm_business', 'date');
if (!empty($dateField)) { if (!empty($dateField)) {
foreach ($param AS $key => $value) { foreach ($param as $key => $value) {
if (in_array($key, $dateField) && empty($value)) $param[$key] = null; if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
} }
} }
// 处理手写签名类型 // 处理手写签名类型
$handwritingField = $fieldModel->getFieldByFormType('crm_business', 'handwriting_sign'); $handwritingField = $fieldModel->getFieldByFormType('crm_business', 'handwriting_sign');
if (!empty($handwritingField)) { if (!empty($handwritingField)) {
foreach ($param AS $key => $value) { foreach ($param as $key => $value) {
if (in_array($key, $handwritingField)) { if (in_array($key, $handwritingField)) {
$param[$key] = !empty($value['file_id']) ? $value['file_id'] : ''; $param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
} }
} }
} }
// 处理地址、定位、日期区间、明细表格类型字段 // 处理地址、定位、日期区间、明细表格类型字段
$positionField = $fieldModel->getFieldByFormType($this->name, 'position'); $positionField = $fieldModel->getFieldByFormType($this->name, 'position');
$locationField = $fieldModel->getFieldByFormType($this->name, 'location'); $locationField = $fieldModel->getFieldByFormType($this->name, 'location');
$dateIntervalField = $fieldModel->getFieldByFormType($this->name, 'date_interval'); $dateIntervalField = $fieldModel->getFieldByFormType($this->name, 'date_interval');
$detailTableField = $fieldModel->getFieldByFormType($this->name, 'detail_table'); $detailTableField = $fieldModel->getFieldByFormType($this->name, 'detail_table');
foreach ($param AS $key => $value) { foreach ($param as $key => $value) {
// 处理地址类型字段数据 // 处理地址类型字段数据
if (in_array($key, $positionField)) { if (in_array($key, $positionField)) {
if (!empty($value)) { if (!empty($value)) {
$businessData[] = [ $businessData[] = [
'field' => $key, 'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK), 'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time() 'create_time' => time()
]; ];
$positionNames = array_column($value, 'name'); $positionNames = array_column($value, 'name');
@ -347,8 +351,8 @@ class Business extends Common
if (in_array($key, $locationField)) { if (in_array($key, $locationField)) {
if (!empty($value)) { if (!empty($value)) {
$businessData[] = [ $businessData[] = [
'field' => $key, 'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK), 'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time() 'create_time' => time()
]; ];
$param[$key] = $value['address']; $param[$key] = $value['address'];
@ -360,8 +364,8 @@ class Business extends Common
if (in_array($key, $dateIntervalField)) { if (in_array($key, $dateIntervalField)) {
if (!empty($value)) { if (!empty($value)) {
$businessData[] = [ $businessData[] = [
'field' => $key, 'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK), 'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time() 'create_time' => time()
]; ];
$param[$key] = implode('_', $value); $param[$key] = implode('_', $value);
@ -373,8 +377,8 @@ class Business extends Common
if (in_array($key, $detailTableField)) { if (in_array($key, $detailTableField)) {
if (!empty($value)) { if (!empty($value)) {
$businessData[] = [ $businessData[] = [
'field' => $key, 'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK), 'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time() 'create_time' => time()
]; ];
$param[$key] = $key; $param[$key] = $key;
@ -391,7 +395,7 @@ class Business extends Common
$param['discount_rate'] = $param['discount_rate'] ?: '0.00'; $param['discount_rate'] = $param['discount_rate'] ?: '0.00';
if ($this->data($param)->allowField(true)->save()) { if ($this->data($param)->allowField(true)->save()) {
updateActionLog($param['create_user_id'], 'crm_business', $this->business_id, '', '', '创建了商机'); updateActionLog($param['create_user_id'], 'crm_business', $this->business_id, '', '', '创建了商机');
RecordActionLog($param['create_user_id'],'crm_business','save',$param['name'],'','','新增了商机'.$param['name']); RecordActionLog($param['create_user_id'], 'crm_business', 'save', $param['name'], '', '', '新增了商机' . $param['name']);
$business_id = $this->business_id; $business_id = $this->business_id;
$data['business_id'] = $business_id; $data['business_id'] = $business_id;
if ($param['product']) { if ($param['product']) {
@ -480,31 +484,31 @@ class Business extends Common
// 处理日期date类型 // 处理日期date类型
$dateField = $fieldModel->getFieldByFormType('crm_business', 'date'); $dateField = $fieldModel->getFieldByFormType('crm_business', 'date');
if (!empty($dateField)) { if (!empty($dateField)) {
foreach ($param AS $key => $value) { foreach ($param as $key => $value) {
if (in_array($key, $dateField) && empty($value)) $param[$key] = null; if (in_array($key, $dateField) && empty($value)) $param[$key] = null;
} }
} }
// 处理手写签名类型 // 处理手写签名类型
$handwritingField = $fieldModel->getFieldByFormType('crm_business', 'handwriting_sign'); $handwritingField = $fieldModel->getFieldByFormType('crm_business', 'handwriting_sign');
if (!empty($handwritingField)) { if (!empty($handwritingField)) {
foreach ($param AS $key => $value) { foreach ($param as $key => $value) {
if (in_array($key, $handwritingField)) { if (in_array($key, $handwritingField)) {
$param[$key] = !empty($value['file_id']) ? $value['file_id'] : ''; $param[$key] = !empty($value['file_id']) ? $value['file_id'] : '';
} }
} }
} }
// 处理地址、定位、日期区间、明细表格类型字段 // 处理地址、定位、日期区间、明细表格类型字段
$positionField = $fieldModel->getFieldByFormType($this->name, 'position'); $positionField = $fieldModel->getFieldByFormType($this->name, 'position');
$locationField = $fieldModel->getFieldByFormType($this->name, 'location'); $locationField = $fieldModel->getFieldByFormType($this->name, 'location');
$dateIntervalField = $fieldModel->getFieldByFormType($this->name, 'date_interval'); $dateIntervalField = $fieldModel->getFieldByFormType($this->name, 'date_interval');
$detailTableField = $fieldModel->getFieldByFormType($this->name, 'detail_table'); $detailTableField = $fieldModel->getFieldByFormType($this->name, 'detail_table');
foreach ($param AS $key => $value) { foreach ($param as $key => $value) {
// 处理地址类型字段数据 // 处理地址类型字段数据
if (in_array($key, $positionField)) { if (in_array($key, $positionField)) {
if (!empty($value)) { if (!empty($value)) {
$businessData[] = [ $businessData[] = [
'field' => $key, 'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK), 'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time() 'create_time' => time()
]; ];
$positionNames = array_column($value, 'name'); $positionNames = array_column($value, 'name');
@ -517,8 +521,8 @@ class Business extends Common
if (in_array($key, $locationField)) { if (in_array($key, $locationField)) {
if (!empty($value)) { if (!empty($value)) {
$businessData[] = [ $businessData[] = [
'field' => $key, 'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK), 'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time() 'create_time' => time()
]; ];
$param[$key] = $value['address']; $param[$key] = $value['address'];
@ -530,8 +534,8 @@ class Business extends Common
if (in_array($key, $dateIntervalField)) { if (in_array($key, $dateIntervalField)) {
if (!empty($value)) { if (!empty($value)) {
$businessData[] = [ $businessData[] = [
'field' => $key, 'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK), 'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time() 'create_time' => time()
]; ];
$param[$key] = implode('_', $value); $param[$key] = implode('_', $value);
@ -543,8 +547,8 @@ class Business extends Common
if (in_array($key, $detailTableField)) { if (in_array($key, $detailTableField)) {
if (!empty($value)) { if (!empty($value)) {
$businessData[] = [ $businessData[] = [
'field' => $key, 'field' => $key,
'content' => json_encode($value, JSON_NUMERIC_CHECK), 'content' => json_encode($value, JSON_NUMERIC_CHECK),
'create_time' => time() 'create_time' => time()
]; ];
$param[$key] = $key; $param[$key] = $key;
@ -572,7 +576,7 @@ class Business extends Common
$resProduct = $productModel->createObject('crm_business', $param, $business_id); $resProduct = $productModel->createObject('crm_business', $param, $business_id);
//修改记录 //修改记录
updateActionLog($param['user_id'], 'crm_business', $business_id, $dataInfo, $param); updateActionLog($param['user_id'], 'crm_business', $business_id, $dataInfo, $param);
RecordActionLog($param['user_id'], 'crm_business', 'update',$dataInfo['name'], $dataInfo, $param); RecordActionLog($param['user_id'], 'crm_business', 'update', $dataInfo['name'], $dataInfo, $param);
// 添加商机扩展数据 // 添加商机扩展数据
db('crm_business_data')->where('business_id', $business_id)->delete(); db('crm_business_data')->where('business_id', $business_id)->delete();
array_walk($businessData, function (&$val) use ($business_id) { array_walk($businessData, function (&$val) use ($business_id) {
@ -598,38 +602,38 @@ class Business extends Common
* @throws \think\db\exception\ModelNotFoundException * @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException * @throws \think\exception\DbException
*/ */
public function getDataById($id = '', $userId = 0,$model='') public function getDataById($id = '', $userId = 0, $model = '')
{ {
$dataInfo = db('crm_business')->where('business_id', $id)->find(); $dataInfo = db('crm_business')->where('business_id', $id)->find();
if (!$dataInfo) { if (!$dataInfo) {
$this->error = '暂无此数据'; $this->error = '暂无此数据';
return false; return false;
} }
if(empty($model) && $model!='update'){ if (empty($model) && $model != 'update') {
$grantData = getFieldGrantData($userId); $grantData = getFieldGrantData($userId);
foreach ($grantData['crm_business'] as $key => $value) { foreach ($grantData['crm_business'] as $key => $value) {
foreach ($value as $ke => $va) { foreach ($value as $ke => $va) {
if($va['maskType']!=0){ if ($va['maskType'] != 0) {
$fieldGrant[$ke]['maskType'] = $va['maskType']; $fieldGrant[$ke]['maskType'] = $va['maskType'];
$fieldGrant[$ke]['form_type'] = $va['form_type']; $fieldGrant[$ke]['form_type'] = $va['form_type'];
$fieldGrant[$ke]['field'] = $va['field']; $fieldGrant[$ke]['field'] = $va['field'];
} }
} }
} }
foreach ($fieldGrant AS $key => $val){ foreach ($fieldGrant as $key => $val) {
//掩码相关类型字段 //掩码相关类型字段
if ($val['maskType']!=0 && $val['form_type'] == 'mobile') { if ($val['maskType'] != 0 && $val['form_type'] == 'mobile') {
$pattern = "/(1[3458]{1}[0-9])[0-9]{4}([0-9]{4})/i"; $pattern = "/(1[3458]{1}[0-9])[0-9]{4}([0-9]{4})/i";
$rs = preg_replace($pattern, "$1****$2", $dataInfo[$val['field']]); $rs = preg_replace($pattern, "$1****$2", $dataInfo[$val['field']]);
$dataInfo[$val['field']] = !empty($dataInfo[$val['field']]) ? (string)$rs : null; $dataInfo[$val['field']] = !empty($dataInfo[$val['field']]) ? (string)$rs : null;
} elseif ($val['maskType']!=0 && $val['form_type'] == 'email') { } elseif ($val['maskType'] != 0 && $val['form_type'] == 'email') {
$email_array = explode("@", $dataInfo[$val['field']]); $email_array = explode("@", $dataInfo[$val['field']]);
$prevfix = (strlen($email_array[0]) < 4) ? "" : substr($dataInfo[$val['field']], 0, 2); // $prevfix = (strlen($email_array[0]) < 4) ? "" : substr($dataInfo[$val['field']], 0, 2); //
$str = preg_replace('/([\d\w+_-]{0,100})@/', "***@", $dataInfo[$val['field']], -1, $count); $str = preg_replace('/([\d\w+_-]{0,100})@/', "***@", $dataInfo[$val['field']], -1, $count);
$rs = $prevfix . $str; $rs = $prevfix . $str;
$dataInfo[$val['field']] = !empty($dataInfo[$val['field']]) ?$rs: null; $dataInfo[$val['field']] = !empty($dataInfo[$val['field']]) ? $rs : null;
} elseif ($val['maskType']!=0 && in_array($val['form_type'],['position','floatnumber'])) { } elseif ($val['maskType'] != 0 && in_array($val['form_type'], ['position', 'floatnumber'])) {
$dataInfo[$val['field']] = !empty($dataInfo[$val['field']]) ? (string)substr_replace($dataInfo[$val['field']], '*****',0,strlen($dataInfo[$val['field']])) : null; $dataInfo[$val['field']] = !empty($dataInfo[$val['field']]) ? (string)substr_replace($dataInfo[$val['field']], '*****', 0, strlen($dataInfo[$val['field']])) : null;
} }
} }
} }
@ -654,8 +658,8 @@ class Business extends Common
foreach ($datetimeField as $key => $val) { foreach ($datetimeField as $key => $val) {
$dataInfo[$val] = !empty($dataInfo[$val]) ? date('Y-m-d H:i:s', $dataInfo[$val]) : null; $dataInfo[$val] = !empty($dataInfo[$val]) ? date('Y-m-d H:i:s', $dataInfo[$val]) : null;
} }
if($dataInfo['is_end']!=1){ if ($dataInfo['is_end'] != 1) {
$dataInfo['statusRemark']=db('crm_business_log')->where(['business_id'=>$id,'is_end'=>$dataInfo['is_end']])->value('remark'); $dataInfo['statusRemark'] = db('crm_business_log')->where(['business_id' => $id, 'is_end' => $dataInfo['is_end']])->value('remark');
} }
$dataInfo['next_time'] = !empty($dataInfo['next_time']) ? date('Y-m-d H:i:s', $dataInfo['next_time']) : null; $dataInfo['next_time'] = !empty($dataInfo['next_time']) ? date('Y-m-d H:i:s', $dataInfo['next_time']) : null;
$dataInfo['create_time'] = !empty($dataInfo['create_time']) ? date('Y-m-d H:i:s', $dataInfo['create_time']) : null; $dataInfo['create_time'] = !empty($dataInfo['create_time']) ? date('Y-m-d H:i:s', $dataInfo['create_time']) : null;
@ -665,7 +669,7 @@ class Business extends Common
if (!empty($userId)) { if (!empty($userId)) {
$grantData = getFieldGrantData($userId); $grantData = getFieldGrantData($userId);
$userLevel = isSuperAdministrators($userId); $userLevel = isSuperAdministrators($userId);
foreach ($dataInfo AS $key => $value) { foreach ($dataInfo as $key => $value) {
if (!$userLevel && !empty($grantData['crm_business'])) { if (!$userLevel && !empty($grantData['crm_business'])) {
$status = getFieldGrantStatus($key, $grantData['crm_business']); $status = getFieldGrantStatus($key, $grantData['crm_business']);
@ -712,7 +716,7 @@ class Business extends Common
$map['create_time'] = $where['create_time']; $map['create_time'] = $where['create_time'];
$map['owner_user_id'] = ['in', $userIds]; $map['owner_user_id'] = ['in', $userIds];
$map['type_id'] = $type_id; $map['type_id'] = $type_id;
$sql_a = CrmBusinessModel::field([ $sql_a = CrmBusinessModel::field([
'SUM(CASE WHEN is_end = 1 THEN money ELSE 0 END) AS sum_ying', 'SUM(CASE WHEN is_end = 1 THEN money ELSE 0 END) AS sum_ying',
'SUM(CASE WHEN is_end = 2 THEN money ELSE 0 END) AS sum_shu', 'SUM(CASE WHEN is_end = 2 THEN money ELSE 0 END) AS sum_shu',
@ -728,7 +732,7 @@ class Business extends Common
"status_id", "status_id",
'COUNT(*)' => 'count', 'COUNT(*)' => 'count',
'SUM(`money`)' => 'sum', 'SUM(`money`)' => 'sum',
'type_id' // 'type_id'
]) ])
->where($where) ->where($where)
->whereNotIn('is_end', '3') ->whereNotIn('is_end', '3')
@ -737,7 +741,7 @@ class Business extends Common
->select(); ->select();
$res = queryCache($sql, 200); $res = queryCache($sql, 200);
$res = array_column($res, null, 'status_id'); $res = array_column($res, null, 'status_id');
$sum_money = 0; $sum_money = 0;
$count = 0; # 商机数总和 $count = 0; # 商机数总和
$moneyCount = 0; # 金额总和 $moneyCount = 0; # 金额总和
@ -745,22 +749,22 @@ class Business extends Common
$v['count'] = $res[$v['status_id']]['count'] ?: 0; $v['count'] = $res[$v['status_id']]['count'] ?: 0;
$v['money'] = $res[$v['status_id']]['sum'] ?: 0; $v['money'] = $res[$v['status_id']]['sum'] ?: 0;
$v['status_name'] = $v['name']; $v['status_name'] = $v['name'];
$statusList[$k] = $v; $statusList[$k] = $v;
$sum_money += $v['money']; $sum_money += $v['money'];
$moneyCount += $v['money']; $moneyCount += $v['money'];
$count += $v['count']; $count += $v['count'];
} }
$data['list'] = $statusList; $data['list'] = $statusList;
$data['sum_ying'] = $res_a[0]['sum_ying'] ?: 0; $data['sum_ying'] = $res_a[0]['sum_ying'] ?: 0;
$data['sum_shu'] = $res_a[0]['sum_shu'] ?: 0; $data['sum_shu'] = $res_a[0]['sum_shu'] ?: 0;
$data['count_ying']=$res_a[0]['count_ying']?:0; $data['count_ying'] = $res_a[0]['count_ying'] ?: 0;
$data['count_shu']=$res_a[0]['count_shu']?:0; $data['count_shu'] = $res_a[0]['count_shu'] ?: 0;
$data['sum_money'] = $sum_money ?: 0; $data['sum_money'] = $sum_money ?: 0;
$data['total'] = ['name' => '合计', 'money_count' => $moneyCount, 'count' => $count]; $data['total'] = ['name' => '合计', 'money_count' => $moneyCount, 'count' => $count];
return $data ?: []; return $data ?: [];
} }
@ -899,12 +903,12 @@ class Business extends Common
public function getSystemInfo($id) public function getSystemInfo($id)
{ {
# 商机 # 商机
$business = Db::name('crm_business')->field(['create_user_id' ,'owner_user_id', 'create_time', 'update_time', 'last_time'])->where('business_id', $id)->find(); $business = Db::name('crm_business')->field(['create_user_id', 'owner_user_id', 'create_time', 'update_time', 'last_time'])->where('business_id', $id)->find();
# 创建人 # 创建人
$realname = Db::name('admin_user')->where('id', $business['create_user_id'])->value('realname'); $realname = Db::name('admin_user')->where('id', $business['create_user_id'])->value('realname');
# zjf 20210726 # zjf 20210726
$userModel = new \app\admin\model\User(); $userModel = new \app\admin\model\User();
$ownerUserInfo = $userModel->getUserById($business['owner_user_id']); $ownerUserInfo = $userModel->getUserById($business['owner_user_id']);
# 负责人部门 # 负责人部门
$ownerStructureName = $ownerUserInfo['structure_name']; $ownerStructureName = $ownerUserInfo['structure_name'];

@ -313,13 +313,13 @@ class Contacts extends Common
$businessId = $param['business_id']; $businessId = $param['business_id'];
unset($param['business_id']); unset($param['business_id']);
$fieldModel = new \app\admin\model\Field(); $fieldModel = new \app\admin\model\Field();
// 数据验证 // 数据验证
$validateResult = $this->fieldDataValidate($param, $this->name, $param['create_user_id']); // $validateResult = $this->fieldDataValidate($param, $this->name, $param['create_user_id']);
if (!empty($validateResult)) { // if (!empty($validateResult)) {
$this->error = $validateResult; // $this->error = $validateResult;
return false; // return false;
} // }
# 处理客户首要联系人 # 处理客户首要联系人
$primaryStatus = Db::name('crm_contacts')->where('customer_id', $param['customer_id'])->value('contacts_id'); $primaryStatus = Db::name('crm_contacts')->where('customer_id', $param['customer_id'])->value('contacts_id');

@ -4,6 +4,8 @@
// +---------------------------------------------------------------------- // +----------------------------------------------------------------------
// | Author: // | Author:
// +---------------------------------------------------------------------- // +----------------------------------------------------------------------
use think\Env;
error_reporting(E_ERROR | E_WARNING | E_PARSE); error_reporting(E_ERROR | E_WARNING | E_PARSE);
return [ return [
@ -183,7 +185,7 @@ return [
// 驱动方式 // 驱动方式
'type' => 'redis', 'type' => 'redis',
// 连接地址 // 连接地址
'host' => '127.0.0.1', 'host' => Env::get('cache_host','127.0.0.1'),
// 端口 // 端口
'port' => 6379, 'port' => 6379,
// 密码 // 密码
@ -271,5 +273,12 @@ return [
// 商机状态组列表缓存时间(秒) // 商机状态组列表缓存时间(秒)
'business_status_cache_time' => 1800, 'business_status_cache_time' => 1800,
'wework' => [
'corpId' => Env::get('wework_corpId',''),
'corpSecret' => Env::get('wework_corpSecret',''),
'token' => Env::get('wework_token',''),
'encodingAesKey' => Env::get('wework_encodingAesKey',''),
],
'public_key' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkqKFcAQtIp4rlkB5LOMnViyVY/hhA6x0R9ftwtEXsAFu4hBZrm9txdEvxSrDCUsx3Zwv/gdimeOzTtfSKffdoE/DwllNP9Zu6nsr2kGRgPrRwjtlO+j2FOM0b9UY1SQ/bWE+a9oQL2jL9xMSbtX1xG/+HcMo1bT+pa6FNQzs3egmvMt75/jaxINPSraj4kgNFawSBk7qDBEqDYiQwtPTuaNW1YZIs++/gZHsCRgGs/JrAbxNpl7+v/+Z503I3I2rs/8eUM5d16NXR8M7vtobUDCTIiQOgRahO8WMadgFlwavyVCYhy/TBXyj5RUfWaS26LrEN3vkj4TjoJu5m9LQ5QIDAQAB', 'public_key' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkqKFcAQtIp4rlkB5LOMnViyVY/hhA6x0R9ftwtEXsAFu4hBZrm9txdEvxSrDCUsx3Zwv/gdimeOzTtfSKffdoE/DwllNP9Zu6nsr2kGRgPrRwjtlO+j2FOM0b9UY1SQ/bWE+a9oQL2jL9xMSbtX1xG/+HcMo1bT+pa6FNQzs3egmvMt75/jaxINPSraj4kgNFawSBk7qDBEqDYiQwtPTuaNW1YZIs++/gZHsCRgGs/JrAbxNpl7+v/+Z503I3I2rs/8eUM5d16NXR8M7vtobUDCTIiQOgRahO8WMadgFlwavyVCYhy/TBXyj5RUfWaS26LrEN3vkj4TjoJu5m9LQ5QIDAQAB',
]; ];

@ -5,11 +5,11 @@ return [
// 服务器地址 // 服务器地址
'hostname' => '127.0.0.1', 'hostname' => '127.0.0.1',
// 数据库名 // 数据库名
'database' => 'test_com', 'database' => 'wkcrm',
// 用户名 // 用户名
'username' => 'test_com', 'username' => 'root',
// 密码 // 密码
'password' => 'YNKdaMS2XBHKcAh7', 'password' => '123123',
// 端口 // 端口
'hostport' => '3306', 'hostport' => '3306',
// 连接dsn // 连接dsn

@ -189,6 +189,8 @@ return [
'crm/business/count' => ['crm/business/count', ['method' => 'POST']], 'crm/business/count' => ['crm/business/count', ['method' => 'POST']],
// 【商机】菜单数量 // 【商机】菜单数量
'crm/business/setPrimary' => ['crm/business/setPrimary', ['method' => 'POST']], 'crm/business/setPrimary' => ['crm/business/setPrimary', ['method' => 'POST']],
// 【商机】审批
'crm/business/check' => ['crm/business/check', ['method' => 'POST']],
// 【合同】列表 // 【合同】列表
'crm/contract/index' => ['crm/contract/index', ['method' => 'POST']], 'crm/contract/index' => ['crm/contract/index', ['method' => 'POST']],
@ -301,8 +303,8 @@ return [
'crm/invoice/resetInvoiceStatus' => ['crm/invoice/resetInvoiceStatus', ['method' => 'POST']], 'crm/invoice/resetInvoiceStatus' => ['crm/invoice/resetInvoiceStatus', ['method' => 'POST']],
// 【发票】导出 // 【发票】导出
'crm/invoice/excelExport' => ['crm/invoice/excelExport', ['method' => 'POST']], 'crm/invoice/excelExport' => ['crm/invoice/excelExport', ['method' => 'POST']],
// 【发票-开户行】列表 // 【发票-开户行】列表
'crm/invoiceInfo/index' => ['crm/invoiceInfo/index', ['method' => 'POST']], 'crm/invoiceInfo/index' => ['crm/invoiceInfo/index', ['method' => 'POST']],
// 【发票-开户行】详情 // 【发票-开户行】详情
@ -386,7 +388,7 @@ return [
'crm/index/autoNumberStatus' => ['crm/index/autoNumberStatus', ['method' => 'POST']], 'crm/index/autoNumberStatus' => ['crm/index/autoNumberStatus', ['method' => 'POST']],
// 【商机阶段列表】 // 【商机阶段列表】
'crm/index/businessList' => ['crm/index/businessList', ['method' => 'POST']], 'crm/index/businessList' => ['crm/index/businessList', ['method' => 'POST']],
// 【获取仪表盘布局】 // 【获取仪表盘布局】
'crm/index/dashboard' => ['crm/index/dashboard', ['method' => 'POST']], 'crm/index/dashboard' => ['crm/index/dashboard', ['method' => 'POST']],
// 【修改仪表盘布局】 // 【修改仪表盘布局】
@ -394,20 +396,22 @@ return [
// 【待办事项】今日需联系 // 【待办事项】今日需联系
'crm/message/todayLeads' => ['crm/message/todayLeads', ['method' => 'POST']], 'crm/message/todayLeads' => ['crm/message/todayLeads', ['method' => 'POST']],
'crm/message/todayCustomer' => ['crm/message/todayCustomer', ['method' => 'POST']], 'crm/message/todayCustomer' => ['crm/message/todayCustomer', ['method' => 'POST']],
'crm/message/todayBusiness' => ['crm/message/todayBusiness', ['method' => 'POST']], 'crm/message/todayBusiness' => ['crm/message/todayBusiness', ['method' => 'POST']],
'crm/message/num' => ['crm/message/num', ['method' => 'POST']], 'crm/message/num' => ['crm/message/num', ['method' => 'POST']],
'crm/message/followLeads' => ['crm/message/followLeads', ['method' => 'POST']], 'crm/message/followLeads' => ['crm/message/followLeads', ['method' => 'POST']],
'crm/message/followCustomer' => ['crm/message/followCustomer', ['method' => 'POST']], 'crm/message/followCustomer' => ['crm/message/followCustomer', ['method' => 'POST']],
'crm/message/checkContract' => ['crm/message/checkContract', ['method' => 'POST']], 'crm/message/checkContract' => ['crm/message/checkContract', ['method' => 'POST']],
'crm/message/checkReceivables' => ['crm/message/checkReceivables', ['method' => 'POST']], 'crm/message/checkReceivables' => ['crm/message/checkReceivables', ['method' => 'POST']],
'crm/message/remindReceivablesPlan' => ['crm/message/remindReceivablesPlan', ['method' => 'POST']], 'crm/message/remindReceivablesPlan' => ['crm/message/remindReceivablesPlan', ['method' => 'POST']],
'crm/message/endContract' => ['crm/message/endContract', ['method' => 'POST']], 'crm/message/endContract' => ['crm/message/endContract', ['method' => 'POST']],
'crm/message/remindCustomer' => ['crm/message/remindCustomer', ['method' => 'POST']], 'crm/message/remindCustomer' => ['crm/message/remindCustomer', ['method' => 'POST']],
'crm/message/checkInvoice' => ['crm/message/checkInvoice', ['method' => 'POST']], 'crm/message/checkInvoice' => ['crm/message/checkInvoice', ['method' => 'POST']],
'crm/message/visitContract' => ['crm/message/visitContract', ['method' => 'POST']], 'crm/message/checkBusiness' => ['crm/message/checkBusiness', ['method' => 'POST']],
'crm/message/allDeal' => ['crm/message/allDeal', ['method' => 'POST']], 'crm/message/newBusiness' => ['crm/message/newBusiness', ['method' => 'POST']],
'crm/message/visitContract' => ['crm/message/visitContract', ['method' => 'POST']],
'crm/message/allDeal' => ['crm/message/allDeal', ['method' => 'POST']],
// 【客户】标记跟进 // 【客户】标记跟进
'crm/customer/setFollow' => ['crm/customer/setFollow', ['method' => 'POST']], 'crm/customer/setFollow' => ['crm/customer/setFollow', ['method' => 'POST']],
@ -481,14 +485,14 @@ return [
'crm/preview/previewPdf' => ['crm/preview/previewPdf', ['method' => 'POST']], 'crm/preview/previewPdf' => ['crm/preview/previewPdf', ['method' => 'POST']],
//【打印】下载打印文件 //【打印】下载打印文件
'crm/printing/down' => ['crm/printing/down', ['method' => 'POST']], 'crm/printing/down' => ['crm/printing/down', ['method' => 'POST']],
//跟进记录导入模板 //跟进记录导入模板
'crm/activity/excelDownload' => ['crm/activity/excelDownload', ['method' => 'POST']], 'crm/activity/excelDownload' => ['crm/activity/excelDownload', ['method' => 'POST']],
//跟进记录导入 //跟进记录导入
'crm/activity/excelImport' => ['crm/activity/excelImport', ['method' => 'POST']], 'crm/activity/excelImport' => ['crm/activity/excelImport', ['method' => 'POST']],
//跟进记录导出 //跟进记录导出
'crm/activity/excelExport' => ['crm/activity/excelExport', ['method' => 'POST']], 'crm/activity/excelExport' => ['crm/activity/excelExport', ['method' => 'POST']],
//市场活动列表 //市场活动列表
'crm/market/index' => ['crm/market/index', ['method' => 'POST']], 'crm/market/index' => ['crm/market/index', ['method' => 'POST']],
//市场活动添加 //市场活动添加
@ -517,11 +521,15 @@ return [
'crm/market/marketGetField' => ['crm/market/marketGetField', ['method' => 'POST']], 'crm/market/marketGetField' => ['crm/market/marketGetField', ['method' => 'POST']],
//【通用】快捷编辑 //【通用】快捷编辑
'crm/common/quickEdit' => ['crm/common/quickEdit', ['method' => 'POST']], 'crm/common/quickEdit' => ['crm/common/quickEdit', ['method' => 'POST']],
//手机导航列表 //手机导航列表
'crm/setting/appMenuConfig' => ['crm/setting/appMenuConfig', ['method' => 'POST']], 'crm/setting/appMenuConfig' => ['crm/setting/appMenuConfig', ['method' => 'POST']],
//办公数量 //办公数量
'crm/setting/oaNumber' => ['crm/setting/oaNumber', ['method' => 'POST']], 'crm/setting/oaNumber' => ['crm/setting/oaNumber', ['method' => 'POST']],
// 企业微信回调
'crm/callback/index' => ['crm/callback/index', ['method' => 'POST|GET']],
// MISS路由 // MISS路由
'__miss__' => 'admin/base/miss', '__miss__' => 'admin/base/miss',
]; ];

Loading…
Cancel
Save