作者 郭文星

123

正在显示 59 个修改的文件 包含 6528 行增加0 行删除
{"files":["application\\admin\\controller\\wechat\\Autoreply.php","application\\admin\\controller\\wechat\\Config.php","application\\admin\\controller\\wechat\\Menu.php","application\\admin\\controller\\wechat\\Response.php","application\\admin\\lang\\zh-cn\\wechat\\autoreply.php","application\\admin\\lang\\zh-cn\\wechat\\config.php","application\\admin\\lang\\zh-cn\\wechat\\response.php","application\\admin\\model\\WechatAutoreply.php","application\\admin\\model\\WechatCaptcha.php","application\\admin\\model\\WechatConfig.php","application\\admin\\model\\WechatContext.php","application\\admin\\model\\WechatResponse.php","application\\admin\\view\\wechat\\autoreply\\add.html","application\\admin\\view\\wechat\\autoreply\\edit.html","application\\admin\\view\\wechat\\autoreply\\index.html","application\\admin\\view\\wechat\\config\\add.html","application\\admin\\view\\wechat\\config\\edit.html","application\\admin\\view\\wechat\\config\\index.html","application\\admin\\view\\wechat\\menu\\index.html","application\\admin\\view\\wechat\\response\\add.html","application\\admin\\view\\wechat\\response\\edit.html","application\\admin\\view\\wechat\\response\\index.html","application\\admin\\view\\wechat\\response\\select.html","public\\assets\\js\\backend\\wechat\\autoreply.js","public\\assets\\js\\backend\\wechat\\config.js","public\\assets\\js\\backend\\wechat\\menu.js","public\\assets\\js\\backend\\wechat\\response.js","public\\assets\\addons\\wechat\\css\\menu.css","public\\assets\\addons\\wechat\\images\\mobile_footer_bg.png","public\\assets\\addons\\wechat\\images\\mobile_header_bg.png","public\\assets\\addons\\wechat\\images\\mobile_index.png","public\\assets\\addons\\wechat\\images\\weixin_icon.png"],"license":"regular","licenseto":"56052","licensekey":"z43Dir5MYRb7LdKm 5dY2yLiHBuRzRCkDrrhR3w==","domains":[],"licensecodes":[],"validations":[],"menus":["wechat","wechat\/autoreply","wechat\/autoreply\/index","wechat\/autoreply\/add","wechat\/autoreply\/edit","wechat\/autoreply\/del","wechat\/autoreply\/multi","wechat\/config","wechat\/config\/index","wechat\/config\/add","wechat\/config\/edit","wechat\/config\/del","wechat\/config\/multi","wechat\/menu","wechat\/menu\/index","wechat\/menu\/add","wechat\/menu\/edit","wechat\/menu\/del","wechat\/menu\/remote","wechat\/menu\/sync","wechat\/menu\/multi","wechat\/response","wechat\/response\/index","wechat\/response\/add","wechat\/response\/edit","wechat\/response\/del","wechat\/response\/select","wechat\/response\/multi"]}
\ No newline at end of file
... ...
<?php
namespace addons\wechat;
use app\common\library\Menu;
use think\Addons;
/**
* 微信插件
*/
class Wechat extends Addons
{
/**
* 插件安装方法
* @return bool
*/
public function install()
{
$menu = [
[
'name' => 'wechat',
'title' => '微信管理',
'icon' => 'fa fa-wechat',
'sublist' => [
[
'name' => 'wechat/autoreply',
'title' => '自动回复管理',
'icon' => 'fa fa-reply-all',
'sublist' => [
['name' => 'wechat/autoreply/index', 'title' => '查看'],
['name' => 'wechat/autoreply/add', 'title' => '添加'],
['name' => 'wechat/autoreply/edit', 'title' => '修改'],
['name' => 'wechat/autoreply/del', 'title' => '删除'],
['name' => 'wechat/autoreply/multi', 'title' => '批量更新'],
]
],
[
'name' => 'wechat/config',
'title' => '配置管理',
'icon' => 'fa fa-cog',
'sublist' => [
['name' => 'wechat/config/index', 'title' => '查看'],
['name' => 'wechat/config/add', 'title' => '添加'],
['name' => 'wechat/config/edit', 'title' => '修改'],
['name' => 'wechat/config/del', 'title' => '删除'],
['name' => 'wechat/config/multi', 'title' => '批量更新'],
]
],
[
'name' => 'wechat/menu',
'title' => '菜单管理',
'icon' => 'fa fa-list',
'sublist' => [
['name' => 'wechat/menu/index', 'title' => '查看'],
['name' => 'wechat/menu/add', 'title' => '添加'],
['name' => 'wechat/menu/edit', 'title' => '修改'],
['name' => 'wechat/menu/del', 'title' => '删除'],
['name' => 'wechat/menu/remote', 'title' => '加载远程菜单'],
['name' => 'wechat/menu/sync', 'title' => '同步'],
['name' => 'wechat/menu/multi', 'title' => '批量更新'],
]
],
[
'name' => 'wechat/response',
'title' => '资源管理',
'icon' => 'fa fa-list-alt',
'sublist' => [
['name' => 'wechat/response/index', 'title' => '查看'],
['name' => 'wechat/response/add', 'title' => '添加'],
['name' => 'wechat/response/edit', 'title' => '修改'],
['name' => 'wechat/response/del', 'title' => '删除'],
['name' => 'wechat/response/select', 'title' => '选择'],
['name' => 'wechat/response/multi', 'title' => '批量更新'],
]
]
]
]
];
Menu::create($menu);
return true;
}
/**
* 插件卸载方法
* @return bool
*/
public function uninstall()
{
Menu::delete('wechat');
return true;
}
/**
* 插件启用方法
*/
public function enable()
{
Menu::enable('wechat');
}
/**
* 插件禁用方法
*/
public function disable()
{
Menu::disable('wechat');
}
}
... ...
<?php
return [
[
'name' => 'app_id',
'title' => 'app_id',
'type' => 'string',
'content' => [],
'value' => 'wxb7dd0c03865a94e0',
'rule' => 'required',
'msg' => '',
'tip' => '',
'ok' => '',
'extend' => '',
],
[
'name' => 'secret',
'title' => 'secret',
'type' => 'string',
'content' => [],
'value' => '6af75a6fb8211da45631630e34769f82',
'rule' => 'required',
'msg' => '',
'tip' => '',
'ok' => '',
'extend' => '',
],
[
'name' => 'token',
'title' => 'token',
'type' => 'string',
'content' => [],
'value' => 'Fdc2022666fdC',
'rule' => 'required',
'msg' => '',
'tip' => '',
'ok' => '',
'extend' => '',
],
[
'name' => 'aes_key',
'title' => 'aes_key',
'type' => 'string',
'content' => [],
'value' => 'vfVRWaOmV7B19NqjE6zPBHaBTEDgv71plzhEGr8SxiQ',
'rule' => 'required',
'msg' => '',
'tip' => '',
'ok' => '',
'extend' => '',
],
[
'name' => 'debug',
'title' => '调试模式',
'type' => 'radio',
'content' => [
'否',
'是',
],
'value' => '1',
'rule' => 'required',
'msg' => '',
'tip' => '',
'ok' => '',
'extend' => '',
],
[
'name' => 'log_level',
'title' => '日志记录等级',
'type' => 'select',
'content' => [
'debug' => 'debug',
'info' => 'info',
'notice' => 'notice',
'warning' => 'warning',
'error' => 'error',
'critical' => 'critical',
'alert' => 'alert',
'emergency' => 'emergency',
],
'value' => 'info',
'rule' => 'required',
'msg' => '',
'tip' => '生产环境日志记录等级',
'ok' => '',
'extend' => '',
],
[
'name' => 'oauth_callback',
'title' => '登录回调',
'type' => 'string',
'content' => [],
'value' => 'https://fdc.xp.yn.cn/',
'rule' => 'required',
'msg' => '',
'tip' => '',
'ok' => '',
'extend' => '',
],
];
... ...
<?php
namespace addons\wechat\controller;
use addons\wechat\library\Wechat;
use addons\wechat\model\WechatCaptcha;
use fast\Http;
/**
* 微信验证码验证接口
*/
class Captcha extends \think\addons\Controller
{
/**
* 验证码检测接口
*/
public function check()
{
$captcha = $this->request->post("captcha");
$event = $this->request->post("event");
$result = WechatCaptcha::check($captcha, $event);
if ($result) {
$this->success("验证码正确");
} else {
$this->error("验证码错误");
}
}
/**
* 验证码发送接口
*/
public function send()
{
$ip = $this->request->ip();
$event = $this->request->post("event");
if (!$event) {
$this->error("参数错误");
}
$captch = WechatCaptcha::where('ip', $ip)
->where('event', $event)
->whereTime('createtime', '-2 minutes')
->find();
if ($captch) {
$this->error("获取频繁,请稍后重试");
}
$token = Wechat::getAccessToken();
if (!$token) {
$this->error("发送失败,请稍后重试");
}
$url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={$token}";
$params = [
'expire_seconds' => 120,
'action_name' => 'QR_STR_SCENE',
'action_info' => [
'scene' => [
'scene_str' => "captcha_" . $event . "_" . $ip,
]
],
];
//获取验证码
$result = Http::sendRequest($url, json_encode($params));
if ($result['ret']) {
$msg = (array)json_decode($result['msg'], true);
if (isset($msg['ticket']) && isset($msg['url'])) {
$this->success("", null, ['image' => "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" . urlencode($msg['ticket']), 'url' => $msg['url']]);
}
}
$this->error("获取失败!请稍后重试");
}
}
... ...
<?php
namespace addons\wechat\controller;
use addons\wechat\library\Config;
use addons\wechat\model\WechatAutoreply;
use addons\wechat\model\WechatCaptcha;
use addons\wechat\model\WechatContext;
use addons\wechat\model\WechatResponse;
use addons\wechat\model\WechatConfig;
use app\common\library\Menu;
use EasyWeChat\Factory;
use addons\wechat\library\Wechat as WechatService;
use addons\wechat\library\Config as ConfigService;
use think\Log;
use think\Db;
use fast\Date;
use fast\Random;
use fast\Http;
use addons\third\model\Third;
use think\Session;
/**
* 微信接口
*/
class Index extends \think\addons\Controller
{
public $app = null;
public function _initialize()
{
parent::_initialize();
$this->app = Factory::officialAccount(Config::load());
}
/**
*
*/
public function index()
{
$menu = [
[
'name' => 'wechat',
'title' => '微信管理',
'icon' => 'fa fa-wechat',
'sublist' => [
[
'name' => 'wechat/autoreply',
'title' => '自动回复管理',
'icon' => 'fa fa-reply-all',
'sublist' => [
['name' => 'wechat/autoreply/index', 'title' => '查看'],
['name' => 'wechat/autoreply/add', 'title' => '添加'],
['name' => 'wechat/autoreply/edit', 'title' => '修改'],
['name' => 'wechat/autoreply/del', 'title' => '删除'],
['name' => 'wechat/autoreply/multi', 'title' => '批量更新'],
]
],
[
'name' => 'wechat/config',
'title' => '配置管理',
'icon' => 'fa fa-cog',
'sublist' => [
['name' => 'wechat/config/index', 'title' => '查看'],
['name' => 'wechat/config/add', 'title' => '添加'],
['name' => 'wechat/config/edit', 'title' => '修改'],
['name' => 'wechat/config/del', 'title' => '删除'],
['name' => 'wechat/config/multi', 'title' => '批量更新'],
]
],
[
'name' => 'wechat/menu',
'title' => '菜单管理',
'icon' => 'fa fa-list',
'sublist' => [
['name' => 'wechat/menu/index', 'title' => '查看'],
['name' => 'wechat/menu/add', 'title' => '添加'],
['name' => 'wechat/menu/edit', 'title' => '修改'],
['name' => 'wechat/menu/del', 'title' => '删除'],
['name' => 'wechat/menu/remote', 'title' => '加载远程菜单'],
['name' => 'wechat/menu/sync', 'title' => '同步'],
['name' => 'wechat/menu/multi', 'title' => '批量更新'],
]
],
[
'name' => 'wechat/response',
'title' => '资源管理',
'icon' => 'fa fa-list-alt',
'sublist' => [
['name' => 'wechat/response/index', 'title' => '查看'],
['name' => 'wechat/response/add', 'title' => '添加'],
['name' => 'wechat/response/edit', 'title' => '修改'],
['name' => 'wechat/response/del', 'title' => '删除'],
['name' => 'wechat/response/select', 'title' => '选择'],
['name' => 'wechat/response/multi', 'title' => '批量更新'],
]
]
]
]
];
Menu::create($menu);
return true;
}
/**
* 微信API对接接口
*/
public function api()
{
$this->app->server->push(function ($message) {
$wechatService = new WechatService;
$matches = null;
$openid = $message['FromUserName'];
$to_openid = $message['ToUserName'];
//file_put_contents("pcl_wct.log", date("Y-m-d H:i:s") . "1-::" . json_encode($message, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
$unknownMessage = WechatConfig::getValue('default.unknown.message');
$unknownMessage = $unknownMessage ? $unknownMessage : "";
switch ($message['MsgType']) {
case 'event': //事件消息
$event = $message['Event'];
$eventkey = $message['EventKey'] ? $message['EventKey'] : $message['Event'];
//验证码消息
if (in_array($event, ['subscribe', 'SCAN']) && preg_match("/^captcha_([a-zA-Z0-9]+)_([0-9\.]+)/", $eventkey, $matches)) {
return WechatCaptcha::send($openid, $matches[1], $matches[2]);
}
switch ($event) {
case 'subscribe'://添加关注
$subscribeMessage = WechatConfig::getValue('default.subscribe.message');
//$subscribeMessage = $subscribeMessage ? $subscribeMessage : "欢迎关注惠蒙房地产交易综合服务大厅!";
$subscribeMessage = '欢迎关注蒙自市房地产交易综合服务大厅,<a data-miniprogram-appid="wx0a5edd82c146e6f4" data-miniprogram-path="pages/home/mine1/mine1" href="https://fdc.xp.yn.cn" data-miniprogram-type="text">点击链接注册成为物业经理</a>';
//获得access_token
$getAccessToken = $this->getAccessToken();
//获得用户信息
$params = [];
$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $getAccessToken . "&openid=" . $openid . "&lang=zh_CN";
$userInfo = Http::sendRequest($url, $params, 'GET');
//根据UnionID判断用户是否已注册
$u_info_data = json_decode($userInfo['msg'], true);
$ucks = Db::name('wct_user')
->where(['unionid' => $u_info_data['unionid']])
->find();
if (empty($ucks)) {
$useradd['unionid'] = $u_info_data['unionid'];
$useradd['wx_openid'] = $openid;
$useradd['loginip'] = request()->ip();
$useradd['createtime'] = time();
Db::name('wct_user')->insertGetId($useradd);
}
file_put_contents("pcl_wct.log", date("Y-m-d H:i:s") . "::3-" . json_encode($userInfo['msg'], JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
return $subscribeMessage;
case 'unsubscribe'://取消关注
return '';
case 'LOCATION'://获取地理位置
return '';
case 'VIEW': //跳转链接,eventkey为链接
return '';
case 'SCAN': //扫码
return '';
default:
break;
}
$wechatResponse = WechatResponse::where(["eventkey" => $eventkey, 'status' => 'normal'])->find();
if ($wechatResponse) {
$responseContent = (array)json_decode($wechatResponse['content'], true);
$wechatContext = WechatContext::where(['openid' => $openid])->order('id', 'desc')->find();
$data = ['eventkey' => $eventkey, 'command' => '', 'refreshtime' => time(), 'openid' => $openid];
if ($wechatContext) {
$wechatContext->save($data);
} else {
$wechatContext = WechatContext::create($data, true);
}
$result = $wechatService->response($this, $openid, '', $responseContent, $wechatContext);
if ($result) {
return $result;
}
}
return $unknownMessage;
case 'text': //文字消息
case 'image': //图片消息
case 'voice': //语音消息
case 'video': //视频消息
case 'location': //坐标消息
case 'link': //链接消息
default: //其它消息
//自动回复处理
if ($message['MsgType'] == 'text') {
$autoreply = null;
$autoreplyList = WechatAutoreply::where('status', 'normal')->cache(true)->order('weigh DESC,id DESC')->select();
foreach ($autoreplyList as $index => $item) {
//完全匹配和正则匹配
if ($item['text'] == $message['Content'] || (in_array(mb_substr($item['text'], 0, 1), ['#', '~', '/']) && preg_match($item['text'], $message['Content'], $matches))) {
$autoreply = $item;
break;
}
}
if ($autoreply) {
$wechatResponse = WechatResponse::where(["eventkey" => $autoreply['eventkey'], 'status' => 'normal'])->find();
if ($wechatResponse) {
$responseContent = (array)json_decode($wechatResponse['content'], true);
$wechatContext = WechatContext::where(['openid' => $openid])->order('id', 'desc')->find();
$result = $wechatService->response($this, $openid, $message['Content'], $responseContent, $wechatContext, $matches);
if ($result) {
return $result;
}
}
}
}
return $unknownMessage;
}
return ""; //SUCCESS
});
$response = $this->app->server->serve();
//file_put_contents("pcl_wct.log", date("Y-m-d H:i:s") . "::4-" . json_encode($response, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
// 将响应输出
$response->send();
return;
}
/**
* 登录回调
*/
public function callback()
{
}
/**
* 支付回调
*/
public function notify()
{
Log::record(file_get_contents('php://input'), "notify");
$response = $this->app->handlePaidNotify(function ($message, $fail) {
// 你的逻辑
return true;
// 或者错误消息
$fail('Order not exists.');
});
$response->send();
return;
}
/**
* 获取Token
*/
public static function getAccessToken()
{
$token = Session::get('wechat_access_token');
if (!$token) {
$config = get_addon_config('wechat');
$params = [
'grant_type' => 'client_credential',
'appid' => $config['app_id'],
'secret' => $config['secret'],
];
$url = "https://api.weixin.qq.com/cgi-bin/token";
$result = Http::sendRequest($url, $params, 'GET');
if ($result['ret']) {
$msg = (array)json_decode($result['msg'], true);
if (isset($msg['access_token'])) {
$token = $msg['access_token'];
Session::set('wechat_access_token', $token, $msg['expires_in'] - 1);
}
}
}
return $token;
}
/**
* 根据Openid获取用户信息
* @param string $openid 微信OpenID
* @return User|null
*/
public static function getUserByOpenid($openid)
{
$third = Third::where('platform', 'wechat')->where('openid', $openid)->find();
if ($third && $third->user_id) {
return User::get($third->user_id);
}
return null;
}
}
... ...
name = wechat
title = 微信管理
intro = 在线管理微信公众号插件
author = FastAdmin
website = https://www.fastadmin.net
version = 1.2.0
state = 1
url = /addons/wechat
license = regular
licenseto = 56052
... ...
CREATE TABLE IF NOT EXISTS `__PREFIX__wechat_autoreply` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`title` varchar(100) NOT NULL DEFAULT '' COMMENT '标题',
`text` varchar(100) NOT NULL DEFAULT '' COMMENT '触发文本',
`eventkey` varchar(50) NOT NULL DEFAULT '' COMMENT '响应事件',
`remark` varchar(255) NOT NULL DEFAULT '' COMMENT '备注',
`weigh` int(10) NOT NULL DEFAULT '0' COMMENT '权重',
`createtime` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '添加时间',
`updatetime` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '更新时间',
`status` varchar(30) NOT NULL DEFAULT '' COMMENT '状态',
PRIMARY KEY (`id`),
KEY `eventkey` (`eventkey`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COMMENT='微信自动回复表';
BEGIN;
INSERT INTO `__PREFIX__wechat_autoreply`(`id`, `title`, `text`, `eventkey`, `remark`, `weigh`, `createtime`, `updatetime`, `status`) VALUES (1, '输入hello', 'hello', '58c7d908c4570', '', 1, 1493366855, 1493366855, 'normal');
INSERT INTO `__PREFIX__wechat_autoreply`(`id`, `title`, `text`, `eventkey`, `remark`, `weigh`, `createtime`, `updatetime`, `status`) VALUES (2, '输入你好', '你好', '58fdfaa9e1965', '', 2, 1493704976, 1493704976, 'normal');
COMMIT;
CREATE TABLE IF NOT EXISTS `__PREFIX__wechat_captcha` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`event` varchar(100) DEFAULT '' COMMENT '事件',
`openid` varchar(255) DEFAULT NULL COMMENT '用户openid',
`context` varchar(20) DEFAULT NULL COMMENT '上下文',
`code` varchar(30) DEFAULT NULL COMMENT '验证码',
`times` int(10) unsigned DEFAULT '0' COMMENT '验证次数',
`ip` varchar(50) DEFAULT '' COMMENT 'IP',
`createtime` int(10) DEFAULT NULL COMMENT '创建时间',
PRIMARY KEY (`id`),
KEY `ip` (`ip`,`event`) USING BTREE,
KEY `openid` (`openid`(191),`event`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='微信公众号验证码';
CREATE TABLE IF NOT EXISTS `__PREFIX__wechat_config` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL DEFAULT '' COMMENT '配置名称',
`title` varchar(50) NOT NULL DEFAULT '' COMMENT '配置标题',
`value` text NOT NULL COMMENT '配置值',
`createtime` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '创建时间',
`updatetime` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '更新时间',
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COMMENT='微信配置表';
BEGIN;
INSERT INTO `__PREFIX__wechat_config` VALUES ('1', 'menu', '微信菜单', '[{\"name\":\"FastAdmin\",\"sub_button\":[{\"name\":\"官网\",\"type\":\"view\",\"url\":\"http:\\/\\/www.fastadmin.net\"},{\"name\":\"在线演示\",\"type\":\"click\",\"key\":\"\"},{\"name\":\"文档\",\"type\":\"view\",\"url\":\"http:\\/\\/doc.fastadmin.net\"}]},{\"name\":\"在线客服\",\"type\":\"click\",\"key\":\"58cb852984970\"},{\"name\":\"关于我们\",\"type\":\"click\",\"key\":\"58bf944aa0777\"}]', '1497398820', '1500538185'), ('2', 'service', '客服配置', '{\"onlinetime\":\"09:00-18:00\",\"offlinemsg\":\"请在工作时间联系客服!\",\"nosessionmsg\":\"当前没有客服在线!请稍后重试!\",\"waitformsg\":\"请问有什么可以帮到您?\"}', '1497429674', '1497429674'), ('3', 'signin', '连续登录配置', '{\"s1\":\"100\",\"s2\":\"200\",\"s3\":\"300\",\"sn\":\"500\"}', '1497429711', '1497429711');
COMMIT;
CREATE TABLE IF NOT EXISTS `__PREFIX__wechat_context` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`openid` varchar(64) NOT NULL DEFAULT '',
`type` varchar(30) NOT NULL DEFAULT '' COMMENT '类型',
`eventkey` varchar(64) NOT NULL DEFAULT '',
`command` varchar(64) NOT NULL DEFAULT '',
`message` varchar(255) NOT NULL DEFAULT '' COMMENT '内容',
`refreshtime` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '最后刷新时间',
`createtime` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '创建时间',
`updatetime` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '更新时间',
PRIMARY KEY (`id`),
KEY `openid` (`openid`,`eventkey`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='微信上下文表';
CREATE TABLE IF NOT EXISTS `__PREFIX__wechat_response` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`title` varchar(100) NOT NULL DEFAULT '' COMMENT '资源名',
`eventkey` varchar(128) NOT NULL DEFAULT '' COMMENT '事件',
`type` enum('text','image','news','voice','video','music','link','app') NOT NULL DEFAULT 'text' COMMENT '类型',
`content` text NOT NULL COMMENT '内容',
`remark` varchar(255) NOT NULL DEFAULT '' COMMENT '备注',
`createtime` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '创建时间',
`updatetime` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '更新时间',
`status` varchar(30) NOT NULL DEFAULT '' COMMENT '状态',
PRIMARY KEY (`id`),
UNIQUE KEY `eventkey` (`eventkey`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COMMENT='微信资源表';
BEGIN;
INSERT INTO `__PREFIX__wechat_response` VALUES ('1', '签到送积分', '58adaf7876aab', 'app', '{\"app\":\"signin\"}', '', '1487777656', '1487777656', 'normal'), ('2', '关于我们', '58bf944aa0777', 'app', '{\"app\":\"page\",\"id\":\"1\"}', '', '1488950346', '1488950346', 'normal'), ('3', '自动回复1', '58c7d908c4570', 'text', '{\"content\":\"world\"}', '', '1489492232', '1489492232', 'normal'), ('5', '自动回复2', '58fdfaa9e1965', 'text', '{\"content\":\"我是FastAdmin!\"}', '', '1493039785', '1493039785', 'normal');
COMMIT;
... ...
<?php
namespace addons\wechat\library;
/**
* 微信配置类
*/
class Config
{
public static function load()
{
$config = get_addon_config('wechat');
return [
/**
* 账号基本信息,请从微信公众平台/开放平台获取
*/
'app_id' => $config['app_id'], // AppID
'secret' => $config['secret'], // AppSecret
'token' => $config['token'], // Token
'aes_key' => $config['aes_key'], // EncodingAESKey,安全模式下请一定要填写!!!
/**
* 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名
* 使用自定义类名时,构造函数将会接收一个 `EasyWeChat\Kernel\Http\Response` 实例
*/
'response_type' => 'array',
/**
* 日志配置
*
* level: 日志级别, 可选为:debug/info/notice/warning/error/critical/alert/emergency
* path:日志文件位置(绝对路径!!!),要求可写权限
*/
'log' => [
'default' => 'dev', // 默认使用的 channel,生产环境可以改为下面的 prod
'channels' => [
// 测试环境
'dev' => [
'driver' => 'single',
'path' => ROOT_PATH . '/runtime/log/easywechat.log',
'level' => 'debug',
],
// 生产环境
'prod' => [
'driver' => 'daily',
'path' => ROOT_PATH . '/runtime/log/easywechat.log',
'level' => $config['log_level'],
],
],
],
/**
* 接口请求相关配置,超时时间等,具体可用参数请参考:
* http://docs.guzzlephp.org/en/stable/request-config.html
*
* - retries: 重试次数,默认 1,指定当 http 请求失败时重试的次数。
* - retry_delay: 重试延迟间隔(单位:ms),默认 500
* - log_template: 指定 HTTP 日志模板,请参考:https://github.com/guzzle/guzzle/blob/master/src/MessageFormatter.php
*/
'http' => [
'max_retries' => 1,
'retry_delay' => 500,
'timeout' => 5.0,
// 'base_uri' => 'https://api.weixin.qq.com/', // 如果你在国外想要覆盖默认的 url 的时候才使用,根据不同的模块配置不同的 uri
],
/**
* OAuth 配置
*
* scopes:公众平台(snsapi_userinfo / snsapi_base),开放平台:snsapi_login
* callback:OAuth授权完成后的回调页地址
*/
'oauth' => [
'scopes' => ['snsapi_userinfo'],
'callback' => $config['oauth_callback'],
],
];
}
}
... ...
<?php
namespace addons\wechat\library;
use addons\signin\model\Signin;
use addons\third\model\Third;
use app\common\model\User;
use EasyWeChat\Kernel\Messages\News;
use EasyWeChat\Kernel\Messages\NewsItem;
use fast\Date;
use fast\Http;
use fast\Random;
use think\Session;
use think\Config;
/**
* 微信服务类
*/
class Wechat
{
public static function appConfig()
{
return array(
'signin' => array(
'name' => '签到送积分',
'config' => array()
),
'blog' => array(
'name' => '关联博客',
'config' => array(
array(
'type' => 'text',
'caption' => '日志ID',
'field' => 'post_id',
'rule' => '',
'extend' => 'class="form-control selectpage" data-source="blog/post/index" data-field="title"',
'options' => '',
),
array(
'type' => 'radio',
'caption' => '开启搜索日志',
'field' => 'searchpost',
'rule' => '',
'extend' => '',
'options' => [
'1' => '是',
'0' => '否',
],
),
array(
'type' => 'text',
'caption' => '正则搜索匹配索引',
'field' => 'searchregexindex',
'rule' => '',
'defaultvalue' => '1',
'extend' => '',
'options' => [],
)
)
),
'cms' => array(
'name' => '关联CMS',
'config' => array(
array(
'type' => 'text',
'caption' => '文章ID',
'field' => 'archives_id',
'rule' => '',
'extend' => 'class="form-control selectpage" data-source="cms/archives/index" data-field="title"',
'options' => ''
),
array(
'type' => 'text',
'caption' => '单页ID',
'field' => 'page_id',
'rule' => '',
'extend' => 'class="form-control selectpage" data-source="cms/page/index" data-field="title"',
'options' => ''
),
array(
'type' => 'text',
'caption' => '专题ID',
'field' => 'special_id',
'rule' => '',
'extend' => 'class="form-control selectpage" data-source="cms/special/index" data-field="title"',
'options' => ''
),
array(
'type' => 'radio',
'caption' => '开启搜索文章',
'field' => 'searcharchives',
'rule' => '',
'extend' => '',
'options' => [
'1' => '是',
'0' => '否',
],
),
array(
'type' => 'radio',
'caption' => '开启搜索单页',
'field' => 'searchpage',
'rule' => '',
'extend' => '',
'options' => [
'1' => '是',
'0' => '否',
],
),
array(
'type' => 'radio',
'caption' => '开启搜索专题',
'field' => 'searchspecial',
'rule' => '',
'extend' => '',
'options' => [
'1' => '是',
'0' => '否',
],
),
array(
'type' => 'text',
'caption' => '正则搜索匹配索引',
'field' => 'searchregexindex',
'rule' => '',
'defaultvalue' => '1',
'extend' => '',
'options' => [],
)
)
),
'ask' => array(
'name' => '关联问答',
'config' => array(
array(
'type' => 'text',
'caption' => '问题ID',
'field' => 'question_id',
'extend' => 'class="form-control selectpage" data-source="ask/question/index" data-field="title"',
'options' => ''
),
array(
'type' => 'text',
'caption' => '文章ID',
'field' => 'article_id',
'extend' => 'class="form-control selectpage" data-source="ask/article/index" data-field="title"',
'options' => ''
),
array(
'type' => 'radio',
'caption' => '开启搜索问题',
'field' => 'searchquestion',
'rule' => '',
'extend' => '',
'options' => [
'1' => '是',
'0' => '否',
],
),
array(
'type' => 'radio',
'caption' => '开启搜索文章',
'field' => 'searcharticle',
'rule' => '',
'extend' => '',
'options' => [
'1' => '是',
'0' => '否',
],
),
array(
'type' => 'text',
'caption' => '正则搜索匹配索引',
'field' => 'searchregexindex',
'rule' => '',
'defaultvalue' => '1',
'extend' => '',
'options' => [],
)
)
),
'vote' => array(
'name' => '关联投票',
'config' => array(
array(
'type' => 'text',
'caption' => '投票主题ID',
'field' => 'subject_id',
'extend' => 'class="form-control selectpage" data-source="vote/subject/index" data-field="title"',
'rule' => '',
'options' => ''
),
array(
'type' => 'text',
'caption' => '参赛人员ID',
'field' => 'player_id',
'rule' => '',
'extend' => 'class="form-control selectpage" data-source="vote/player/index" data-field="nickname"',
'options' => ''
),
array(
'type' => 'radio',
'caption' => '开启搜索主题',
'field' => 'searchsubject',
'rule' => '',
'extend' => '',
'options' => [
'1' => '是',
'0' => '否',
],
),
array(
'type' => 'radio',
'caption' => '开启搜索参赛人员',
'field' => 'searchplayer',
'rule' => '',
'extend' => '',
'options' => [
'1' => '是',
'0' => '否',
],
),
array(
'type' => 'text',
'caption' => '正则搜索匹配索引',
'field' => 'searchregexindex',
'rule' => '',
'defaultvalue' => '1',
'extend' => '',
'options' => [],
)
)
),
);
}
/**
* 应用交互
* @return array|bool|mixed|string
*/
public function response($obj, $openid, $message, $content, $context, $matches = null)
{
$response = false;
if (isset($content['app'])) {
$entry = null;
$keyword = isset($content['searchregexindex']) && $content['searchregexindex'] > -1 && $matches && isset($matches[$content['searchregexindex']])
? $matches[$content['searchregexindex']] : $message;
switch ($content['app']) {
case 'signin':
$signinInfo = get_addon_info('signin');
if (!$signinInfo || !$signinInfo['state']) {
return "请先在后台管理安装并启用《会员签到》插件";
}
$thirdInfo = get_addon_info('third');
if (!$thirdInfo || !$thirdInfo['state']) {
return "请先在后台管理安装并启用《第三方登录》插件";
}
$user = self::getUserByOpenid($openid);
if (!$user) {
return "请先在会员中心绑定微信登录,<a href='" . addon_url('third/index/connect', [':platform' => 'wechat'], true, true) . "'>点击这里绑定</a>";
}
$config = get_addon_config('signin');
$signdata = $config['signinscore'];
$lastdata = Signin::where('user_id', $user->id)->order('id', 'desc')->find();
$successions = $lastdata && $lastdata['createtime'] > Date::unixtime('day', -1) ? $lastdata['successions'] : 0;
$signin = Signin::where('user_id', $user->id)->whereTime('createtime', 'today')->find();
if ($signin) {
return '今天已签到,请明天再来!';
} else {
$successions++;
Signin::create(['user_id' => $user->id, 'successions' => $successions, 'createtime' => time()]);
$score = isset($signdata['s' . $successions]) ? $signdata['s' . $successions] : $signdata['sn'];
$user->setInc('score', $score);
User::score($score, $user->id, "连续签到{$successions}天");
return '签到成功!连续签到' . $successions . '天!获得' . $score . '积分,';
}
break;
case 'blog':
$blogInfo = get_addon_info('blog');
if (!$blogInfo || !$blogInfo['state']) {
return "请先在后台管理安装并启用《简单博客》插件";
}
$entry = \addons\blog\model\Post::get($content['post_id']);
if ($entry) {
$entry['image'] = $entry['thumb'];
}
if (!$entry && $content['searchpost']) {
$entry = \addons\blog\model\Post::where("title|description", 'like', "%{$keyword}%")->where('status', 'normal')->find();
}
if (!$entry) {
return "未搜索到任何匹配信息$keyword" . json_encode($matches);
}
break;
case 'cms':
$cmsInfo = get_addon_info('cms');
if (!$cmsInfo || !$cmsInfo['state']) {
return "请先在后台管理安装并启用《CMS内容管理系统》插件";
}
if (isset($content['archives_id']) && $content['archives_id']) {
$entry = \addons\cms\model\Archives::get($content['archives_id']);
} elseif (isset($content['page_id']) && $content['page_id']) {
$entry = \addons\cms\model\Page::get($content['page_id']);
} elseif (isset($content['special_id']) && $content['special_id']) {
$entry = \addons\cms\model\Special::get($content['special_id']);
}
if (!$entry && $content['searcharchives']) {
$entry = \addons\cms\model\Archives::where("title|description", 'like', "%{$keyword}%")->where('status', 'normal')->find();
}
if (!$entry && $content['searchpage']) {
$entry = \addons\cms\model\Page::where("title|description", 'like', "%{$keyword}%")->where('status', 'normal')->find();
}
if (!$entry && $content['searchspecial']) {
$entry = \addons\cms\model\Special::where("title|description", 'like', "%{$keyword}%")->where('status', 'normal')->find();
}
if (!$entry) {
return "未搜索到任何匹配信息";
}
break;
case 'ask':
$blogInfo = get_addon_info('ask');
if (!$blogInfo || !$blogInfo['state']) {
return "请先在后台管理安装并启用《知识付费问答》插件";
}
if (isset($content['question_id']) && $content['question_id']) {
$entry = \addons\ask\model\Question::get($content['question_id']);
} elseif (isset($content['article_id']) && $content['article_id']) {
$entry = \addons\ask\model\Article::get($content['article_id']);
}
if (!$entry && $content['searchquestion']) {
$entry = \addons\ask\model\Question::where("title", 'like', "%{$keyword}%")->where('status', 'normal')->find();
}
if (!$entry && $content['searcharticle']) {
$entry = \addons\ask\model\Article::where("title|description", 'like', "%{$keyword}%")->where('status', 'normal')->find();
}
if (!$entry) {
return "未搜索到任何匹配信息";
}
break;
case 'vote':
$blogInfo = get_addon_info('vote');
if (!$blogInfo || !$blogInfo['state']) {
return "请先在后台管理安装并启用《在线投票系统》插件";
}
if (isset($content['subject_id']) && $content['subject_id']) {
$entry = \addons\vote\model\Subject::all($content['subject_id']);
} elseif (isset($content['player_id']) && $content['player_id']) {
$entry = \addons\vote\model\Player::all($content['player_id']);
}
if (!$entry && $content['searchsubject']) {
$entry = \addons\vote\model\Subject::where("title|description", 'like', "%{$keyword}%")->where('status', 'normal')->find();
}
if (!$entry && $content['searchplayer']) {
$entry = \addons\vote\model\Player::where("nickname", 'like', "%{$keyword}%")->where('status', 'normal')->find();
}
if (!$entry) {
return "未搜索到任何匹配信息";
}
break;
default:
break;
}
if (isset($entry) && $entry) {
$items = [
new NewsItem([
'title' => isset($entry['title']) ? $entry['title'] : (isset($entry['nickname']) ? $entry['nickname'] : ''),
'description' => isset($entry['description']) ? $entry['description'] : '',
'url' => $entry['fullurl'],
'image' => cdnurl($entry['image'], true),
]),
];
$news = new News($items);
$response[] = $news;
}
} else {
$response = isset($content['content']) ? $content['content'] : $response;
}
return $response;
}
/**
* 获取Token
*/
public static function getAccessToken()
{
$token = Session::get('wechat_access_token');
if (!$token) {
$config = get_addon_config('wechat');
$params = [
'grant_type' => 'client_credential',
'appid' => $config['app_id'],
'secret' => $config['secret'],
];
$url = "https://api.weixin.qq.com/cgi-bin/token";
$result = Http::sendRequest($url, $params, 'GET');
if ($result['ret']) {
$msg = (array)json_decode($result['msg'], true);
if (isset($msg['access_token'])) {
$token = $msg['access_token'];
Session::set('wechat_access_token', $token, $msg['expires_in'] - 1);
}
}
}
return $token;
}
/**
* 根据Openid获取用户信息
* @param string $openid 微信OpenID
* @return User|null
*/
public static function getUserByOpenid($openid)
{
$third = Third::where('platform', 'wechat')->where('openid', $openid)->find();
if ($third && $third->user_id) {
return User::get($third->user_id);
}
return null;
}
}
... ...
<?php
namespace addons\wechat\model;
use think\Model;
class WechatAutoreply extends Model
{
// 自动写入时间戳字段
protected $autoWriteTimestamp = 'int';
// 定义时间戳字段名
protected $createTime = 'createtime';
protected $updateTime = 'updatetime';
}
... ...
<?php
namespace addons\wechat\model;
use fast\Random;
use think\Model;
class WechatCaptcha extends Model
{
// 表名
protected $name = 'wechat_captcha';
// 自动写入时间戳字段
protected $autoWriteTimestamp = 'int';
// 定义时间戳字段名
protected $createTime = 'createtime';
protected $updateTime = '';
// 追加属性
protected $append = [
];
/**
* 发送验证码
* @param $openid string 用户OpenID
* @param $event string 事件
* @param $ip string IP地址
* @return string
*/
public static function send($openid, $event, $ip)
{
$captcha = self::where(['openid' => $openid, 'event' => $event])->whereTime('createtime', '-2 minutes')->find();
if ($captcha) {
return "验证码发送速度过快,请稍后重试";
}
$code = Random::alnum(4);
$data = [
'event' => $event,
'openid' => $openid,
'code' => $code,
'ip' => $ip,
];
self::create($data);
return "你的验证码是:{$code},2分钟内输入有效";
}
/**
* 检测验证码
* @param $code string 验证码
* @param $event string 事件
* @param $ip string IP
* @return bool
*/
public static function check($code, $event, $ip = null)
{
$ip = is_null($ip) ? request()->ip() : $ip;
$captcha = self::where(['ip' => $ip, 'event' => $event])->whereTime('createtime', '-2 minutes')->find();
if ($captcha && $captcha->code == $code && $captcha->times < 10) {
$captcha->setInc("times");
return true;
}
//验证大于10次或超时
if ($captcha && ($captcha->times >= 10 || time() - $captcha->createtime > 120)) {
$captcha->delete();
}
return false;
}
}
... ...
<?php
namespace addons\wechat\model;
use think\Model;
class WechatConfig extends Model
{
// 表名,不含前缀
public $name = 'wechat_config';
// 自动写入时间戳字段
protected $autoWriteTimestamp = 'int';
// 定义时间戳字段名
protected $createTime = 'createtime';
protected $updateTime = 'updatetime';
// 追加属性
protected $append = [
];
/**
* 读取指定配置名称的值
* @param string $name
* @return string
*/
public static function getValue($name)
{
$item = self::get(['name' => $name]);
return $item ? $item->value : '';
}
}
... ...
<?php
namespace addons\wechat\model;
use think\Model;
class WechatContext extends Model
{
// 自动写入时间戳字段
protected $autoWriteTimestamp = 'int';
// 定义时间戳字段名
protected $createTime = 'createtime';
protected $updateTime = 'updatetime';
}
... ...
<?php
namespace addons\wechat\model;
use think\Model;
class WechatResponse extends Model
{
// 自动写入时间戳字段
protected $autoWriteTimestamp = 'int';
// 定义时间戳字段名
protected $createTime = 'createtime';
protected $updateTime = 'updatetime';
}
... ...
<?php
namespace app\admin\controller\agent;
use app\common\controller\Backend;
use think\Db;
/**
* 用户信用管理
*
* @icon fa fa-circle-o
*/
class Agentcredit extends Backend
{
/**
* Agentcredit模型对象
* @var \app\admin\model\agent\Agentcredit
*/
protected $model = null;
public function _initialize()
{
parent::_initialize();
$this->model = new \app\admin\model\agent\Agentcredit;
$this->view->assign("acTypeList", $this->model->getAcTypeList());
$this->view->assign("acStuList", $this->model->getAcStuList());
$actype = $this->request->param('actype', 0);//分类
//选择的企业id
$agentListIds = $this->request->param('ids', 0);
if ($actype == 0) {
$ginfo = Db::name('agent_list')
->where(['id' => $agentListIds])
->find();
} else {
$ginfo = [];
}
//门店信息
if ($actype == 1) {
$sinfo = Db::name('agent_shop')
->where(['id' => $agentListIds])
->find();
//门店所属企业信息
$ginfo = Db::name('agent_list')
->where(['id' => $sinfo['agent_list_id']])
->find();
} else {
$sinfo = [];
}
//经纪人信息
if ($actype == 2) {
$jinfo = Db::name('agent_users')
->where(['id' => $agentListIds])
->find();
//所属企业信息
$ginfo = Db::name('agent_list')
->where(['id' => $jinfo['agent_list_id']])
->find();
//所属门店
$sinfo = Db::name('agent_shop')
->where(['id' => $jinfo['agent_shop_id']])
->find();
} else {
$jinfo = [];
}
$this->view->assign("ginfo", $ginfo);
$this->view->assign("sinfo", $sinfo);
$this->view->assign("jinfo", $jinfo);
$this->view->assign('actype', $actype);
}
/**
* 查看
*/
public function index()
{
//当前是否为关联查询
$this->relationSearch = false;
//设置过滤方法
$this->request->filter(['strip_tags', 'trim']);
if ($this->request->isAjax()) {
$actype = $this->request->param('actype', 0);//分类
$ids = $this->request->param('ids', 0);
if ($actype == 0) {
$wh['agent_list_id'] = ['=', $ids];
}
if ($actype == 1) {
$wh['agent_shop_id'] = ['=', $ids];
}
if ($actype == 2) {
$wh['agent_user_id'] = ['=', $ids];
}
//如果发送的来源是Selectpage,则转发到Selectpage
if ($this->request->request('keyField')) {
return $this->selectpage();
}
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$list = $this->model
->where($where)
->where($wh)
->order($sort, $order)
->paginate($limit);
$rows = $list->items();
foreach ($rows as $kk => $vv) {
//关联企业、门店、经纪人信息
$ginfo = Db::name('agent_list')
->where(['id' => $vv['agent_list_id']])
->field('id,agent_name')
->find();
$rows[$kk]['agent_name'] = $ginfo['agent_name'] ? $ginfo['agent_name'] : '-';
$sinfo = Db::name('agent_shop')
->where(['id' => $vv['agent_shop_id']])
->field('id,shop_name')
->find();
$rows[$kk]['shop_name'] = $sinfo['shop_name'] ? $sinfo['shop_name'] : '-';
$jinfo = Db::name('agent_users')
->where(['id' => $vv['agent_user_id']])
->field('id,jjr_name')
->find();
$rows[$kk]['jjr_name'] = $jinfo['jjr_name'] ? $jinfo['jjr_name'] : '-';
}
$result = array("total" => $list->total(), "rows" => $rows);
return json($result);
}
return $this->view->fetch();
}
/**
* 添加
*/
public function add()
{
if ($this->request->isPost()) {
$params = $this->request->post("row/a");
if ($params) {
$params = $this->preExcludeFields($params);
if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
$params[$this->dataLimitField] = $this->auth->id;
}
$result = false;
Db::startTrans();
try {
//是否采用模型验证
if ($this->modelValidate) {
$name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
$this->model->validateFailException(true)->validate($validate);
}
$params['admin'] = $this->auth->id;
//计算之前和之后的信用分数
if ($params['ac_type'] == 0) {
if (empty($params['agent_list_id'])) {
$this->error('请选择企业信息');
}
//企业原信用分
$ginfo = Db::name('agent_list')
->where(['id' => $params['agent_list_id']])
->find();
$params['change_before'] = $ginfo['credit'];
$params['change_after'] = $ginfo['credit'] + $params['change_num'];
}
//门店的
if ($params['ac_type'] == 1) {
if (empty($params['agent_list_id'])) {
$this->error('请选择企业信息');
}
if (empty($params['agent_shop_id'])) {
$this->error('请选择门店信息');
}
//原信用分
$sinfo = Db::name('agent_shop')
->where(['id' => $params['agent_shop_id']])
->find();
$params['change_before'] = $sinfo['credit'];
$params['change_after'] = $sinfo['credit'] + $params['change_num'];
}
//经纪人的
if ($params['ac_type'] == 2) {
if (empty($params['agent_user_id'])) {
$this->error('请选择经纪人信息');
}
//原信用分
$jinfo = Db::name('agent_users')
->where(['id' => $params['agent_user_id']])
->find();
$params['change_before'] = $jinfo['credit'];
$params['change_after'] = $jinfo['credit'] + $params['change_num'];
}
$result = $this->model->allowField(true)->save($params);
//更新企业、门店、经纪人表的信用分数
$agentnum['credit'] = $params['change_after'];
$agentnum['updatetime'] = time();
if ($params['ac_type'] == 0) {
Db::name('agent_list')
->where(['id' => $params['agent_list_id']])
->update($agentnum);
}
if ($params['ac_type'] == 1) {
Db::name('agent_shop')
->where(['id' => $params['agent_shop_id']])
->update($agentnum);
}
if ($params['ac_type'] == 2) {
Db::name('agent_users')
->where(['id' => $params['agent_user_id']])
->update($agentnum);
}
Db::commit();
} catch (ValidateException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (PDOException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($result !== false) {
$this->success();
} else {
$this->error(__('No rows were inserted'));
}
}
$this->error(__('Parameter %s can not be empty', ''));
}
return $this->view->fetch();
}
/**
* 编辑
*/
public function edit($ids = null)
{
$row = $this->model->get($ids);
if (!$row) {
$this->error(__('No Results were found'));
}
$adminIds = $this->getDataLimitAdminIds();
if (is_array($adminIds)) {
if (!in_array($row[$this->dataLimitField], $adminIds)) {
$this->error(__('You have no permission'));
}
}
if ($this->request->isPost()) {
$params = $this->request->post("row/a");
if ($params) {
$params = $this->preExcludeFields($params);
$result = false;
Db::startTrans();
try {
//是否采用模型验证
if ($this->modelValidate) {
$name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
$row->validateFailException(true)->validate($validate);
}
$result = $row->allowField(true)->save($params);
Db::commit();
} catch (ValidateException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (PDOException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($result !== false) {
$this->success();
} else {
$this->error(__('No rows were updated'));
}
}
$this->error(__('Parameter %s can not be empty', ''));
}
$this->view->assign("row", $row);
return $this->view->fetch();
}
}
... ...
<?php
namespace app\admin\controller\agent;
use app\common\controller\Backend;
use think\Db;
use app\api\controller\v1\WxXcxQrcode;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
/**
* 企业管理
*
* @icon fa fa-circle-o
*/
class Agentlist extends Backend
{
protected $noNeedRight = ['index'];
/**
* Agentlist模型对象
* @var \app\admin\model\agent\Agentlist
*/
protected $model = null;
protected $dataLimit = 'auth'; //默认基类中为false,表示不启用,可额外使用auth和personal两个值
protected $dataLimitField = 'admin_id'; //数据关联字段,当前控制器对应的模型表中必须存在该字段
protected $isSup = 0;
public function _initialize()
{
parent::_initialize();
$this->model = new \app\admin\model\agent\Agentlist;
$this->view->assign("agentStuList", $this->model->getAgentStuList());
$this->view->assign("payStuList", $this->model->getPayStuList());
//判断是否是超级管理员
if (in_array($this->auth->id, [1, 2, 26, 32, 37])) {
$this->isSup = 1;
} else {
$this->isSup = 0;
}
$this->view->assign("isSup", $this->isSup);
}
public function import()
{
parent::import();
}
/**
* 查看
*/
public function index()
{
//当前是否为关联查询
$this->relationSearch = true;
//设置过滤方法
$this->request->filter(['strip_tags', 'trim']);
if ($this->request->isAjax()) {
//如果发送的来源是Selectpage,则转发到Selectpage
if ($this->request->request('keyField')) {
return $this->selectpage();
}
list($where, $sort, $order, $offset, $limit) = $this->buildparamsAdm();
$list = $this->model
->with(['user', 'agentcategory'])
->where($where)
->order($sort, $order)
->paginate($limit);
foreach ($list as $row) {
$row->visible(['id', 'user_id', 'agent_name', 'head_image', 'createtime', 'fr_name', 'fr_mobile', 'fzr_name', 'fzr_mobile', 'address', 'latitude', 'longitude', 'add_day', 'yeji', 'year_pays', 'pay_amount', 'card_image', 'cert_images', 'cert_desc', 'agent_content', 'agent_stu', 'start_pay_time', 'end_pay_time', 'pay_stu', 'credit']);
$row->visible(['user', 'agentcategory']);
$row->getRelation('user')->visible(['username', 'nickname']);
$row->getRelation('agentcategory')->visible(['catname']);
}
$result = array("total" => $list->total(), "rows" => $list->items());
return json($result);
}
return $this->view->fetch();
}
/**
* 添加
*/
public function add()
{
if ($this->request->isPost()) {
$params = $this->request->post("row/a");
if ($params) {
$params = $this->preExcludeFields($params);
if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
$params[$this->dataLimitField] = $this->auth->id;
}
$result = false;
Db::startTrans();
try {
//是否采用模型验证
if ($this->modelValidate) {
$name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
$this->model->validateFailException(true)->validate($validate);
}
$result = $this->model->allowField(true)->save($params);
Db::commit();
} catch (ValidateException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (PDOException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($result !== false) {
if ($params['agent_stu'] == "1") {
//审核通过;生成小程序二维码
$qrcode_api = new WxXcxQrcode();
$path = '/pages/home/company/detail?id=' . $this->model->id;
$qrcode = $qrcode_api->qrcode($this->model->id, $path, true);
if (!empty($qrcode)) {
Db::name("agent_list")->where("id", $this->model->id)->update(["qrcode" => $qrcode, 'updatetime' => time()]);
}
}
$this->success();
} else {
$this->error(__('No rows were inserted'));
}
}
$this->error(__('Parameter %s can not be empty', ''));
}
return $this->view->fetch();
}
/**
* 编辑
*/
public function edit($ids = null)
{
$row = $this->model->get($ids);
if (!$row) {
$this->error(__('No Results were found'));
}
$adminIds = $this->getDataLimitAdminIds();
/*if (is_array($adminIds)) {
if (!in_array($row[$this->dataLimitField], $adminIds)) {
$this->error(__('You have no permission'));
}
}*/
if (!in_array($this->auth->id, [1, 2, 26, 32, 37])) {
if (is_array($adminIds)) {
if (!in_array($row[$this->dataLimitField], $adminIds)) {
$this->error(__('You have no permission'));
}
}
}
if ($this->request->isPost()) {
$params = $this->request->post("row/a");
if ($params) {
$params = $this->preExcludeFields($params);
if ($this->isSup == 0) {
$params['agent_stu'] = 0;
}
$result = false;
Db::startTrans();
try {
//是否采用模型验证
if ($this->modelValidate) {
$name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
$row->validateFailException(true)->validate($validate);
}
if ($params['agent_stu'] == "1") {
//审核通过;生成小程序二维码
$qrcode_api = new WxXcxQrcode();
$path = '/pages/home/company/detail?id=' . $row->id;
$params['qrcode'] = $qrcode_api->qrcode($row->id, $path, true);
//用法人手机号创建管理员和角色组
$rr = add_group_and_admin($params['fr_mobile'], $params['agent_name']);
if ($rr['back_falg'] == true) {
//更新admin_id
$params['admin_id'] = $rr['uid'];
}
}
$result = $row->allowField(true)->save($params);
Db::commit();
} catch (ValidateException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (PDOException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($result !== false) {
//推送公众号消息给入驻人
if ($params['agent_stu'] == '1' || $params['agent_stu'] == '2') {
if ($params['agent_stu'] == '1') {
$desctit = "企业入驻审核通过";
$remark = '审核通过';
}
if ($params['agent_stu'] == '2') {
$desctit = "企业入驻审核不通过";
$remark = '不通过原因:' . $params['remark'];
}
//获得入驻人openid
$openid = Db::name('user')
->alias('u')
->join('wct_user wct', 'u.unionid=wct.unionid')
->where(['u.id' => $params['user_id']])
->field('wct.id,wct.wx_openid')
->find();
if (!empty($openid['wx_openid'])) {
//推送公众号模板信息给企业管理人
$this->senWxmsgToAgentUser($desctit, $openid['wx_openid'], $remark);
}
}
$this->success();
} else {
$this->error(__('No rows were updated'));
}
}
$this->error(__('Parameter %s can not be empty', ''));
}
$this->view->assign("row", $row);
return $this->view->fetch();
}
/***
* 公众号推送审核信息给经纪人
*/
private function senWxmsgToAgentUser($titdesc, $wxopenid, $remark)
{
$sendInfo = array(
'first' => array('value' => urlencode($titdesc), 'color' => "#743A3A"),
'keyword1' => array('value' => urlencode(date('Y-m-d H:i:s', time())), 'color' => '#173177'),
'keyword2' => array('value' => urlencode('企业入驻'), 'color' => '#173177'),
'remark' => array('value' => urlencode($remark), 'color' => '#173177'),
);
if ($wxopenid) {
$config = get_addon_config('wechat');
$tourl = 'https://fdc.xp.yn.cn/h5/';
$ywt_appid = 'wx9f73637c6b8f2c47';
$pagepath = 'pages/home/index';
$res = sendAstuWxMsgToAgent($sendInfo, $wxopenid, $tourl, $config['app_id'], $config['secret'], $ywt_appid, $pagepath);
//file_put_contents("pcl_wct_send.log", date("Y-m-d H:i:s") . "1-2-" . json_encode($res, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
}
}
/**
* 删除
*/
public function del($ids = "")
{
if (!$this->request->isPost()) {
$this->error(__("Invalid parameters"));
}
$ids = $ids ? $ids : $this->request->post("ids");
if ($ids) {
$pk = $this->model->getPk();
$adminIds = $this->getDataLimitAdminIds();
if (is_array($adminIds)) {
$this->model->where($this->dataLimitField, 'in', [1, 2, 26, 32, 37]);
}
$list = Db::name('agent_list')->where($pk, 'in', $ids)->select();
$count = 0;
Db::startTrans();
try {
foreach ($list as $k => $v) {
//获得企业下门店信息
$shoplist = Db::name('agent_shop')
->where(['agent_list_id' => $v['id']])
->select();
$list[$k]['shop_list'] = $shoplist;
//先生成数据日志
$logs['admin_id'] = $this->auth->id;
$logs['type'] = 'del';
$logs['tablename'] = 'agent_list';
$logs['content'] = json_encode($list[$k], JSON_UNESCAPED_UNICODE);
$logs['createtime'] = time();
Db::name('agent_admin_dologs')->insertGetId($logs);
//禁用企业后台管理员账号
if ($v['admin_id'] > 2 && $v['admin_id'] != $this->auth->id) {
$adminadm['status'] = 'hidden';
$adminadm['updatetime'] = time();
Db::name('admin')
->where(['id' => $v['admin_id']])
->update($adminadm);
}
if ($shoplist) {
//删除企业的门店信息
Db::name('agent_shop')
->where(['agent_list_id' => $v['id']])
->delete();
}
//删除企业信息
$count = Db::name('agent_list')->where(['id' => $v['id']])->delete();
}
Db::commit();
} catch (PDOException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($count) {
$this->success();
} else {
$this->error(__('No rows were deleted'));
}
}
$this->error(__('Parameter %s can not be empty', 'ids'));
}
}
... ...
<?php
namespace app\admin\controller\agent;
use app\common\controller\Backend;
use think\Db;
use app\api\controller\v1\WxXcxQrcode;
/**
* 企业门店管理
*
* @icon fa fa-circle-o
*/
class Agentshop extends Backend
{
protected $noNeedRight = ['index'];
/**
* Agentshop模型对象
* @var \app\admin\model\agent\Agentshop
*/
protected $model = null;
protected $dataLimit = 'auth';
protected $dataLimitField = 'admin_id';
public function _initialize()
{
parent::_initialize();
$this->model = new \app\admin\model\agent\Agentshop;
$this->view->assign("agentStuList", $this->model->getAgentStuList());
$this->view->assign("payStuList", $this->model->getPayStuList());
//选择的企业id
$agentListIds = $this->request->param('ids', 0);
$ginfo = Db::name('agent_list')
->where(['id' => $agentListIds])
->find();
$this->view->assign("ginfo", $ginfo);
//判断是否是超级管理员
if (in_array($this->auth->id, [1, 2, 26, 32, 37])) {
$isSup = 1;
} else {
$isSup = 0;
}
$this->view->assign("isSup", $isSup);
}
public function import()
{
parent::import();
}
/**
* 查看
*/
public function index()
{
//当前是否为关联查询
$this->relationSearch = true;
//设置过滤方法
$this->request->filter(['strip_tags', 'trim']);
if ($this->request->isAjax()) {
$ids = $this->request->param('ids');
//如果发送的来源是Selectpage,则转发到Selectpage
if ($this->request->request('keyField')) {
return $this->selectpage();
}
list($where, $sort, $order, $offset, $limit) = $this->buildparamsAdm();
$list = $this->model
->with(['agentlist'])
->where(['agent_list_id' => $ids])
->where($where)
->order($sort, $order)
->paginate($limit);
foreach ($list as $row) {
$row->visible(['id', 'agent_list_id', 'shop_name', 'head_image', 'createtime', 'updatetime', 'shop_fr_name', 'shop_fr_mobile', 'shop_fzr_name', 'shop_fzr_mobile', 'address', 'latitude', 'longitude', 'add_day', 'card_image', 'cert_images', 'cert_desc', 'agent_content', 'agent_stu', 'credit']);
$row->visible(['agentlist']);
$row->getRelation('agentlist')->visible(['agent_name']);
}
$result = array("total" => $list->total(), "rows" => $list->items());
return json($result);
}
return $this->view->fetch();
}
/**
* 添加
*/
public function add()
{
if ($this->request->isPost()) {
$params = $this->request->post("row/a");
if ($params) {
$params = $this->preExcludeFields($params);
$params['admin_id'] = agent_list_admin_id($params['agent_list_id']);
if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
$params[$this->dataLimitField] = $this->auth->id;
}
$result = false;
Db::startTrans();
try {
//是否采用模型验证
if ($this->modelValidate) {
$name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
$this->model->validateFailException(true)->validate($validate);
}
$result = $this->model->allowField(true)->save($params);
Db::commit();
} catch (ValidateException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (PDOException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($result !== false) {
if ($params['agent_stu'] == "1") {
//审核通过;生成小程序二维码
$qrcode_api = new WxXcxQrcode();
$path = '/pages/home/company/storeDetail?id=' . $this->model->id;
$qrcode = $qrcode_api->qrcode($this->model->id, $path, true);
if (!empty($qrcode)) {
Db::name("agent_shop")->where("id", $this->model->id)->update(["qrcode" => $qrcode, 'updatetime' => time()]);
}
}
$this->success();
} else {
$this->error(__('No rows were inserted'));
}
}
$this->error(__('Parameter %s can not be empty', ''));
}
return $this->view->fetch();
}
/**
* 编辑
*/
public function edit($ids = null)
{
$row = $this->model->get($ids);
if (!$row) {
$this->error(__('No Results were found'));
}
$adminIds = $this->getDataLimitAdminIds();
/*if (is_array($adminIds)) {
if (!in_array($row[$this->dataLimitField], $adminIds)) {
$this->error(__('You have no permission'));
}
}*/
if (!in_array($this->auth->id, [1, 2, 26, 32, 37])) {
if (is_array($adminIds)) {
if (!in_array($row[$this->dataLimitField], $adminIds)) {
$this->error(__('You have no permission'));
}
}
}
if ($this->request->isPost()) {
$params = $this->request->post("row/a");
if ($params) {
$params = $this->preExcludeFields($params);
$params['admin_id'] = agent_list_admin_id($params['agent_list_id']);
$result = false;
Db::startTrans();
try {
//是否采用模型验证
if ($this->modelValidate) {
$name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
$row->validateFailException(true)->validate($validate);
}
if ($params['agent_stu'] == "1") {
//审核通过;生成小程序二维码
$qrcode_api = new WxXcxQrcode();
$path = '/pages/home/company/storeDetail?id=' . $row->id;
$params['qrcode'] = $qrcode_api->qrcode($row->id, $path, true);
}
$result = $row->allowField(true)->save($params);
Db::commit();
} catch (ValidateException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (PDOException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($result !== false) {
$this->success();
} else {
$this->error(__('No rows were updated'));
}
}
$this->error(__('Parameter %s can not be empty', ''));
}
$this->view->assign("row", $row);
return $this->view->fetch();
}
/**
* 删除
*/
public function del($ids = "")
{
if (!$this->request->isPost()) {
$this->error(__("Invalid parameters"));
}
$ids = $ids ? $ids : $this->request->post("ids");
if ($ids) {
$pk = $this->model->getPk();
$adminIds = $this->getDataLimitAdminIds();
if (is_array($adminIds)) {
$this->model->where($this->dataLimitField, 'in', [1, 2, 26, 32, 37]);
}
$list = $this->model->where($pk, 'in', $ids)->select();
$count = 0;
Db::startTrans();
try {
foreach ($list as $k => $v) {
$count += $v->delete();
}
Db::commit();
} catch (PDOException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($count) {
$this->success();
} else {
$this->error(__('No rows were deleted'));
}
}
$this->error(__('Parameter %s can not be empty', 'ids'));
}
}
... ...
<?php
namespace app\admin\controller\agent;
use app\common\controller\Backend;
use think\Db;
use app\api\controller\v1\WxXcxQrcode;
use PhpOffice\PhpSpreadsheet\Helper\Sample;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
/**
* 经纪人管理
*
* @icon fa fa-circle-o
*/
class Agentusers extends Backend
{
/**
* Agentusers模型对象
* @var \app\admin\model\agent\Agentusers
*/
protected $model = null;
protected $dataLimit = 'auth';
protected $dataLimitField = 'admin_id';
protected $relationSearch = true;
protected $searchFields = 'id,jjr_name,agentlist,jjr_mobile';
protected $selectpageFields = "id,jjr_name,agentlist,jjr_mobile";
protected $issupAdm;
public function _initialize()
{
parent::_initialize();
$this->model = new \app\admin\model\agent\Agentusers;
$this->view->assign("jjrTypeList", $this->model->getJjrTypeList());
$this->view->assign("jjrAgentStuList", $this->model->getJjrAgentStuList());
$this->view->assign("jjrPayStuList", $this->model->getJjrPayStuList());
$this->view->assign("getIndustry", $this->model->getIndustry());
//判断是否是超级管理员
if (in_array($this->auth->id, [1, 2, 26, 32, 37])) {
$isSup = 1;
} else {
$isSup = 0;
}
$this->issupAdm = $isSup;
$this->view->assign("isSup", $isSup);
}
/**
* 查看
*/
public function index()
{
//当前是否为关联查询
$this->relationSearch = true;
//设置过滤方法
$this->request->filter(['strip_tags', 'trim']);
if ($this->request->isAjax()) {
//如果发送的来源是Selectpage,则转发到Selectpage
if ($this->request->request('keyField')) {
return $this->selectpage();
}
list($where, $sort, $order, $offset, $limit) = $this->buildparamsAdm();
if ($this->issupAdm == 1) {
$list = $this->model
->with(['agentusercat', 'agentusereducat', 'agentlist', 'user', 'agentshoplist'])
->where($where)
->order($sort, $order)
->paginate($limit);
} else {
$list = $this->model
->with(['agentusercat', 'agentusereducat', 'agentlist', 'user', 'agentshoplist'])
->where($where)
->order($sort, $order)
->paginate($limit);
}
foreach ($list as $row) {
$row->visible(['id', 'user_id', 'jjr_sex', 'agent_shop_id', 'agent_list_id', 'jjr_type', 'user_cat_id', 'user_educat_id', 'jjr_name', 'jjr_image', 'createtime', 'updatetime', 'jjr_mobile', 'home_address', 'now_address', 'idcard', 'idcard_images', 'jjr_content', 'jjr_agent_stu', 'jjr_start_pay_time', 'jjr_end_pay_time', 'jjr_pay_stu', 'credit', 'addstep', 'jjr_type_uptime', 'is_stu_ok', 'is_test_ok', 'userno','industry']);
$row->visible(['agentusercat']);
$row->getRelation('agentusercat')->visible(['catname']);
$row->visible(['agentusereducat']);
$row->getRelation('agentusereducat')->visible(['educat_name']);
$row->visible(['agentlist']);
$row->getRelation('agentlist')->visible(['agent_name']);
$row->visible(['agentshoplist']);
$row->getRelation('agentshoplist')->visible(['shop_name']);
$row->visible(['user']);
$row->getRelation('user')->visible(['username', 'nickname']);
}
$rows = $list->items();
$getIndustry = $this->model->getIndustry();
foreach ($rows as $kk => $vv) {
//身份证处理
$rows[$kk]['idcard'] = tyssl_decode($vv['idcard']);
//判断入驻进度
if ($vv['jjr_pay_stu'] == '0' && $vv['is_stu_ok'] == '0' && $vv['is_test_ok'] == '0') {
$rows[$kk]['addstep'] = '未支付年费';
}
if ($vv['jjr_pay_stu'] == '1' && $vv['is_stu_ok'] == '0' && $vv['is_test_ok'] == '0') {
$rows[$kk]['addstep'] = '已支付年费';
}
/*
if ($vv['jjr_pay_stu'] == '1' && $vv['is_stu_ok'] == '1' && $vv['is_test_ok'] == '0') {
$rows[$kk]['addstep'] = '培训完成,考试中';
}
if ($vv['jjr_pay_stu'] == '1' && $vv['is_stu_ok'] == '1' && $vv['is_test_ok'] == '1' && $vv['jjr_type_uptime'] == 0) {
$rows[$kk]['addstep'] = '考试完成,未选择身份';
}
if ($vv['jjr_pay_stu'] == '1' && $vv['is_stu_ok'] == '1' && $vv['is_test_ok'] == '1' && $vv['jjr_type_uptime'] > 0) {
$rows[$kk]['addstep'] = '已完成';
}
*/
//判断入驻考试是否完成
$testok = getUserGradOk($vv['user_id']);
if ($testok == 1) {
$rows[$kk]['userno'] = '未经考试合格暂无工号';
}
//从事行业处理
$rows[$kk]['industry'] = !empty($vv['industry'])?$getIndustry[$vv['industry']]:'';
}
$result = array("total" => $list->total(), "rows" => $rows);
return json($result);
}
return $this->view->fetch();
}
/**
* 添加
*/
public function add()
{
if ($this->request->isPost()) {
$params = $this->request->post("row/a");
if ($params) {
$params = $this->preExcludeFields($params);
$params['idcard'] = tyssl_encode($params['idcard']);
//经纪人身份
$params['jjr_type_uptime'] = time();
if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
$params[$this->dataLimitField] = $this->auth->id;
}
$result = false;
Db::startTrans();
try {
//是否采用模型验证
if ($this->modelValidate) {
$name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
$this->model->validateFailException(true)->validate($validate);
}
$result = $this->model->allowField(true)->save($params);
Db::commit();
} catch (ValidateException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (PDOException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($result !== false) {
//如果选择了企业,添加经纪人归属
$userup['admin_id'] = 2;
if ($params['jjr_type'] == '1') {
$userup['admin_id'] = agent_list_admin_id($params['agent_list_id']);
}
if ($params['jjr_agent_stu'] == "1") {
//审核通过;生成小程序二维码
$qrcode_api = new WxXcxQrcode();
$path = '/pages/home/broker/broker?id=' . $this->model->id;
$qrcode = $qrcode_api->qrcode($this->model->id, $path, true);
if (!empty($qrcode)) {
$userup['qrcode'] = $qrcode;
}
}
$userup['updatetime'] = time();
Db::name("agent_users")
->where("id", $this->model->id)
->update($userup);
$this->success();
} else {
$this->error(__('No rows were inserted'));
}
}
$this->error(__('Parameter %s can not be empty', ''));
}
return $this->view->fetch();
}
/**
* 编辑
*/
public function edit($ids = null)
{
$row = $this->model->get($ids);
//处理身份证
$row['idcard'] = tyssl_decode($row['idcard']);
if (!$row) {
$this->error(__('No Results were found'));
}
$adminIds = $this->getDataLimitAdminIds();
/*
if (is_array($adminIds)) {
if (!in_array($row[$this->dataLimitField], $adminIds)) {
$this->error(__('You have no permission'));
}
}*/
if (!in_array($this->auth->id, [1, 2, 26, 32, 37])) {
if (is_array($adminIds)) {
if (!in_array($row[$this->dataLimitField], $adminIds)) {
$this->error(__('You have no permission'));
}
}
}
if ($this->request->isPost()) {
$params = $this->request->post("row/a");
if ($params) {
$params = $this->preExcludeFields($params);
$params['idcard'] = tyssl_encode($params['idcard']);
//处理选择为自由经纪人,清空选择的企业
if ($params['jjr_type'] == '0') {
$params['agent_list_id'] = 0;
$params['agent_shop_id'] = 0;
}
//如果选择了企业,添加经纪人归属
if ($params['jjr_type'] == '1') {
$params['admin_id'] = agent_list_admin_id($params['agent_list_id']);
}
//流程改动:上传职业证书的用户审核通过就不需要进行考试等等流程;直接成为经纪人 20230804 陈程
if($params['jjr_agent_stu'] == '1' && !empty($params['vocational_certificate'])){
$time = time();
$params['is_test_time'] = $time; // 完成考试时间
$params['is_test_ok'] = '1'; //完成入驻考试,0否,1是
$params['is_stu_ok'] = '1';//完成培训考试,0否,1是
$parms['is_stu_time']= $time;//完成培训时间
$params['jjr_type_uptime'] = $time; // 经济人信息更新 表示绑定为经济人了
}
$result = false;
Db::startTrans();
try {
//是否采用模型验证
if ($this->modelValidate) {
$name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
$row->validateFailException(true)->validate($validate);
}
if ($params['jjr_agent_stu'] == "1") {
//审核通过;生成小程序二维码
$qrcode_api = new WxXcxQrcode();
$path = '/pages/home/broker/broker?id=' . $row->id;
$params['qrcode'] = $qrcode_api->qrcode($row->id, $path, true);
}
$result = $row->allowField(true)->save($params);
Db::commit();
} catch (ValidateException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (PDOException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($result !== false) {
//公众号消息推送
if ($params['jjr_agent_stu'] == '1' || $params['jjr_agent_stu'] == '2') {
if ($params['jjr_agent_stu'] == '1') {
$desctit = "经纪人入驻已审核通过";
$remark = '审核通过';
}
if ($params['jjr_agent_stu'] == '2') {
$desctit = "经纪人入驻审核不通过";
$remark = '不通过原因:' . $params['remark'];
}
//推送公众号模板信息给经纪人
$this->senWxmsgToAgentUser($desctit, $row->id, $remark);
}
$this->success();
} else {
$this->error(__('No rows were updated'));
}
}
$this->error(__('Parameter %s can not be empty', ''));
}
$this->view->assign("row", $row);
return $this->view->fetch();
}
/***
* 公众号推送审核信息给经纪人
*/
private function senWxmsgToAgentUser($titdesc, $agent_users_id, $remark)
{
$sendInfo = array(
'first' => array('value' => urlencode($titdesc), 'color' => "#743A3A"),
'keyword1' => array('value' => urlencode(date('Y-m-d H:i:s', time())), 'color' => '#173177'),
'keyword2' => array('value' => urlencode('经纪人入驻'), 'color' => '#173177'),
'remark' => array('value' => urlencode($remark), 'color' => '#173177'),
);
$wxopenid = getAgetWxOpenid($agent_users_id);
if ($wxopenid) {
$config = get_addon_config('wechat');
$tourl = 'https://fdc.xp.yn.cn/h5/';
$ywt_appid = 'wx9f73637c6b8f2c47';
$pagepath = 'pages/home/index';
$res = sendAstuWxMsgToAgent($sendInfo, $wxopenid, $tourl, $config['app_id'], $config['secret'], $ywt_appid, $pagepath);
//file_put_contents("pcl_wct_send.log", date("Y-m-d H:i:s") . "1-2-" . json_encode($res, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
}
}
/***
* 导出测试
*/
public function pclexport()
{
//当前是否为关联查询
$this->relationSearch = true;
//设置过滤方法
$this->request->filter(['strip_tags', 'trim']);
if ($this->request->isPost()) {
set_time_limit(0);
ini_set('memory_limit', '2048M');
$search = $this->request->post('search');
$ids = $this->request->post('ids');
//搜索条件
$filter = $this->request->post('filter');
$op = $this->request->post('op');
//导出的字段
$columns = $this->request->post('columns');
//查询条件
$whereIds = $ids == 'all' ? '1=1' : ['agentusers.id' => ['in', explode(',', $ids)]];
$this->request->get(['search' => $search, 'ids' => $ids, 'filter' => $filter, 'op' => $op]);
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
//获得数据列表:全部字段的内容
$list = $this->model
->with(['agentusercat', 'agentusereducat', 'agentlist', 'user', 'agentshoplist'])
->where($where)
->where($whereIds)
->order($sort, $order)
->select();
foreach ($list as $row) {
$row->visible(['id', 'user_id', 'jjr_sex', 'agent_shop_id', 'agent_list_id', 'jjr_type', 'user_cat_id', 'user_educat_id', 'jjr_name', 'jjr_image', 'createtime', 'updatetime', 'jjr_mobile', 'home_address', 'now_address', 'idcard', 'idcard_images', 'jjr_content', 'jjr_agent_stu', 'jjr_start_pay_time', 'jjr_end_pay_time', 'jjr_pay_stu', 'credit', 'addstep', 'jjr_type_uptime', 'is_stu_ok', 'is_test_ok', 'userno']);
$row->visible(['agentusercat']);
$row->getRelation('agentusercat')->visible(['catname']);
$row->visible(['agentusereducat']);
$row->getRelation('agentusereducat')->visible(['educat_name']);
$row->visible(['agentlist']);
$row->getRelation('agentlist')->visible(['agent_name']);
$row->visible(['agentshoplist']);
$row->getRelation('agentshoplist')->visible(['shop_name']);
$row->visible(['user']);
$row->getRelation('user')->visible(['username', 'nickname']);
}
//对象处理成数组
$list = json_encode($list);
$list = json_decode($list, true);
// var_dump($list);
}
}
/**
* 删除
*/
public function del($ids = "")
{
if (!$this->request->isPost()) {
$this->error(__("Invalid parameters"));
}
$ids = $ids ? $ids : $this->request->post("ids");
if ($ids) {
$pk = $this->model->getPk();
$adminIds = $this->getDataLimitAdminIds();
/*if (!is_array($adminIds)) {
$this->model->where($this->dataLimitField, 'in', [1, 2, 26, 32, 37]);
}*/
if (!in_array($this->auth->id, [1, 2, 26, 32, 37])) {
$this->error(__("Invalid parameters"));
}
$list = $this->model->where($pk, 'in', $ids)->select();
$count = 0;
Db::startTrans();
try {
foreach ($list as $k => $v) {
$count += $v->delete();
}
Db::commit();
} catch (PDOException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($count) {
$this->success();
} else {
$this->error(__('No rows were deleted'));
}
}
$this->error(__('Parameter %s can not be empty', 'ids'));
}
}
... ...
<?php
namespace app\admin\controller\agent;
use app\common\controller\Backend;
/**
* 经纪人-从事行业
*
* @icon fa fa-circle-o
*/
class Agentusersindustry extends Backend
{
/**
* Agentusersindustry模型对象
* @var \app\admin\model\agent\Agentusersindustry
*/
protected $model = null;
public function _initialize()
{
parent::_initialize();
$this->model = new \app\admin\model\agent\Agentusersindustry;
$this->view->assign("statusList", $this->model->getStatusList());
}
public function import()
{
parent::import();
}
/**
* 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
* 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
* 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
*/
}
... ...
<?php
namespace app\admin\controller\agent;
use app\common\controller\Backend;
/**
* 用户预约分类管理
*
* @icon fa fa-circle-o
*/
class Appointmentcat extends Backend
{
/**
* Appointmentcat模型对象
* @var \app\admin\model\agent\Appointmentcat
*/
protected $model = null;
public function _initialize()
{
parent::_initialize();
$this->model = new \app\admin\model\agent\Appointmentcat;
$this->view->assign("statusList", $this->model->getStatusList());
}
public function import()
{
parent::import();
}
/**
* 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
* 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
* 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
*/
}
... ...
<?php
namespace app\admin\controller\agent;
use app\common\controller\Backend;
use think\Db;
/**
* 用户预约记录
*
* @icon fa fa-circle-o
*/
class Appointmentlist extends Backend
{
/**
* Appointmentlist模型对象
* @var \app\admin\model\agent\Appointmentlist
*/
protected $model = null;
public function _initialize()
{
parent::_initialize();
$this->model = new \app\admin\model\agent\Appointmentlist;
$this->view->assign("statusList", $this->model->getStatusList());
}
/**
* 查看
*/
public function index()
{
//当前是否为关联查询
$this->relationSearch = true;
//设置过滤方法
$this->request->filter(['strip_tags', 'trim']);
if ($this->request->isAjax()) {
//如果发送的来源是Selectpage,则转发到Selectpage
if ($this->request->request('keyField')) {
return $this->selectpage();
}
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$list = $this->model
->with(['agentuserappointmentcat', 'user'])
->where($where)
->order($sort, $order)
->paginate($limit);
foreach ($list as $row) {
$row->getRelation('agentuserappointmentcat')->visible(['catname']);
$row->getRelation('user')->visible(['id', 'username', 'nickname', 'mobile', 'unionid']);
}
$result = array("total" => $list->total(), "rows" => $list->items());
return json($result);
}
return $this->view->fetch();
}
/**
* 编辑
*/
public function edit($ids = null)
{
$row = $this->model->get($ids);
if (!$row) {
$this->error(__('No Results were found'));
}
$adminIds = $this->getDataLimitAdminIds();
/*if (is_array($adminIds)) {
if (!in_array($row[$this->dataLimitField], $adminIds)) {
$this->error(__('You have no permission'));
}
}*/
if (!in_array($this->auth->id, [1, 2, 26, 32, 37])) {
if (is_array($adminIds)) {
if (!in_array($row[$this->dataLimitField], $adminIds)) {
$this->error(__('You have no permission'));
}
}
}
if ($this->request->isPost()) {
$params = $this->request->post("row/a");
if ($params) {
$params = $this->preExcludeFields($params);
$params['asktimes'] = strtotime($params['asktime']);
$result = false;
Db::startTrans();
try {
//是否采用模型验证
if ($this->modelValidate) {
$name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
$row->validateFailException(true)->validate($validate);
}
$result = $row->allowField(true)->save($params);
Db::commit();
} catch (ValidateException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (PDOException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($result !== false) {
$this->success();
} else {
$this->error(__('No rows were updated'));
}
}
$this->error(__('Parameter %s can not be empty', ''));
}
$this->view->assign("row", $row);
return $this->view->fetch();
}
}
... ...
<?php
namespace app\admin\controller\agent;
use app\common\controller\Backend;
use think\Db;
/**
* 用户投诉分类管理
*
* @icon fa fa-circle-o
*/
class Complaincat extends Backend
{
/**
* Complaincat模型对象
* @var \app\admin\model\agent\Complaincat
*/
protected $model = null;
public function _initialize()
{
parent::_initialize();
$this->model = new \app\admin\model\agent\Complaincat;
$this->view->assign("statusList", $this->model->getStatusList());
}
public function import()
{
parent::import();
}
/**
* 查看
*/
public function index()
{
//当前是否为关联查询
$this->relationSearch = false;
//设置过滤方法
$this->request->filter(['strip_tags', 'trim']);
if ($this->request->isAjax()) {
//如果发送的来源是Selectpage,则转发到Selectpage
if ($this->request->request('keyField')) {
return $this->selectpage();
}
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$list = $this->model
->where($where)
->order($sort, $order)
->paginate($limit);
foreach ($list as $row) {
$row->visible(['id', 'catname', 'createtime', 'weigh', 'status']);
}
$result = array("total" => $list->total(), "rows" => $list->items());
return json($result);
}
return $this->view->fetch();
}
}
... ...
<?php
namespace app\admin\controller\agent;
use app\common\controller\Backend;
use think\Db;
/**
* 用户投诉记录
*
* @icon fa fa-circle-o
*/
class Complainlist extends Backend
{
/**
* Complainlist模型对象
* @var \app\admin\model\agent\Complainlist
*/
protected $model = null;
protected $dataLimit = 'auth';
protected $dataLimitField = 'admin_id';
public function _initialize()
{
parent::_initialize();
$this->model = new \app\admin\model\agent\Complainlist;
$this->view->assign("typeList", $this->model->getTypeList());
$this->view->assign("statusList", $this->model->getStatusList());
//判断是否是超级管理员
if (in_array($this->auth->id, [1, 2])) {
$isSup = 1;
} else {
$isSup = 0;
}
$this->view->assign("isSup", $isSup);
}
public function import()
{
parent::import();
}
/**
* 查看
*/
public function index()
{
//当前是否为关联查询
$this->relationSearch = true;
//设置过滤方法
$this->request->filter(['strip_tags', 'trim']);
if ($this->request->isAjax()) {
//如果发送的来源是Selectpage,则转发到Selectpage
if ($this->request->request('keyField')) {
return $this->selectpage();
}
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$list = $this->model
->with(['agentlist', 'agentshop', 'agentusers', 'complaincat', 'user'])
->where($where)
->order($sort, $order)
->paginate($limit);
foreach ($list as $row) {
$row->visible(['id', 'user_id', 'agent_list_id', 'agent_shop_id', 'agent_user_id', 'type', 'askcat', 'asktit', 'createtime', 'status']);
$row->visible(['agentlist']);
$row->getRelation('agentlist')->visible(['agent_name']);
$row->visible(['agentshop']);
$row->getRelation('agentshop')->visible(['shop_name']);
$row->visible(['agentusers']);
$row->getRelation('agentusers')->visible(['jjr_name']);
$row->visible(['complaincat']);
$row->getRelation('complaincat')->visible(['catname']);
$row->visible(['user']);
$row->getRelation('user')->visible(['nickname']);
}
$result = array("total" => $list->total(), "rows" => $list->items());
return json($result);
}
return $this->view->fetch();
}
/**
* 编辑
*/
public function edit($ids = null)
{
$row = $this->model->get($ids);
if (!$row) {
$this->error(__('No Results were found'));
}
$adminIds = $this->getDataLimitAdminIds();
if (is_array($adminIds)) {
if (!in_array($row[$this->dataLimitField], $adminIds)) {
$this->error(__('You have no permission'));
}
}
if ($this->request->isPost()) {
$params = $this->request->post("row/a");
if ($params) {
$params = $this->preExcludeFields($params);
$result = false;
Db::startTrans();
try {
//是否采用模型验证
if ($this->modelValidate) {
$name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
$row->validateFailException(true)->validate($validate);
}
$result = $row->allowField(true)->save($params);
Db::commit();
} catch (ValidateException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (PDOException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($result !== false) {
//审核通过,生成统计表
if ($params['status'] == '1') {
//判断分类
if ($params['type'] == '1') {
$wh['agent_list_id'] = ['=', $params['agent_list_id']];
$ctall['agent_list_id'] = $params['agent_list_id'];
}
if ($params['type'] == '2') {
$wh['agent_shop_id'] = ['=', $params['agent_shop_id']];
$ctall['agent_shop_id'] = $params['agent_shop_id'];
}
if ($params['type'] == '3') {
$wh['agent_user_id'] = ['=', $params['agent_user_id']];
$ctall['agent_user_id'] = $params['agent_user_id'];
}
$cks = Db::name('agent_user_complain_ctall')
->where($wh)
->find();
$cmpAll = Db::name('agent_user_complain_list')
->where($wh)
->where(['status' => '1'])
->count();
if (empty($cks)) {
//生成统计信息
$ctall['type'] = $params['type'];
$ctall['compall'] = $cmpAll ? $cmpAll : 1;
$ctall['createtime'] = time();
$ctall['admin_id'] = $this->auth->id;
Db::name('agent_user_complain_ctall')->insertGetId($ctall);
} else {
//更新统计信息
$upall['compall'] = $cmpAll;
$upall['updatetime'] = time();
Db::name('agent_user_complain_ctall')
->where($wh)
->update($upall);
}
}
$this->success();
} else {
$this->error(__('No rows were updated'));
}
}
$this->error(__('Parameter %s can not be empty', ''));
}
$this->view->assign("row", $row);
return $this->view->fetch();
}
}
... ...
<?php
namespace app\admin\controller\agent;
use app\common\controller\Backend;
use app\admin\library\Auth;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\common\helper\HttpHelper;
use app\api\controller\v4\notary\Index;
/**
*
*
* @icon fa fa-circle-o
*/
class Order extends Backend
{
/**
* Order模型对象
* @var \app\admin\model\agent\Order
*/
protected $model = null;
protected $dataLimit = 'auth';
protected $dataLimitField = 'admin_id';
public function _initialize()
{
parent::_initialize();
$this->model = new \app\admin\model\agent\Order;
$this->view->assign("statusList", $this->model->getStatusList());
$this->view->assign("userNeedTypeList", $this->model->getUserNeedTypeList());
$this->view->assign("recoveryStateList", $this->model->getRecoveryStateList());
}
/**
* 查看
*/
public function index()
{
//设置过滤方法
$this->request->filter(['strip_tags', 'trim']);
if ($this->request->isAjax()) {
//如果发送的来源是Selectpage,则转发到Selectpage
if ($this->request->request('keyField')) {
return $this->selectpage();
}
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$list = $this->model
->with(['type'])
->where($where)
->order($sort, $order)
->paginate($limit);
$rows = $list->items();
foreach ($rows as $kk => $vv) {
//关联经纪人
if ($vv['agent_users_id'] > 0) {
$agent = Db::name('agent_users')
->where(['id' => $vv['agent_users_id']])
->field('id,jjr_name,jjr_mobile')
->find();
$rows[$kk]['jjr_name'] = $agent['jjr_name'] . '[' . $agent['jjr_mobile'] . ']';
} else {
$rows[$kk]['jjr_name'] = '-';
}
if ($vv['ia_pay'] == '1') {
$rows[$kk]['pay_times'] = setdateTimes($vv['pay_time']);
} else {
$rows[$kk]['pay_times'] = '-';
}
//关联贷款分类
if ($vv['loan_cat_id'] > 0) {
$loncat = Db::name('loan_cat')
->where(['id' => $vv['loan_cat_id']])
->find();
$rows[$kk]['loan_cat'] = $loncat['catname'];
} else {
$rows[$kk]['loan_cat'] = '-';
}
//关联住房性质
if ($vv['house_cat_id'] > 0) {
$housecat = Db::name('house_cat')
->where(['id' => $vv['house_cat_id']])
->find();
$rows[$kk]['house_cat'] = $housecat['catname'];
} else {
$rows[$kk]['house_cat'] = '-';
}
//关联当前推送到公证处状态
$step = Db::name('agent_order_send_logs')
->where(['agent_order_id' => $vv['id']])
->order('id', 'desc')
->find();
if (empty($step)) {
$sendname = '-';
} else {
if ($step['step'] == 1 && $step['send_stu'] == '0') {
$sendname = '用户需求推送失败';
}
if ($step['step'] == 1 && $step['send_stu'] == '1') {
$sendname = '用户需求推送成功';
}
if ($step['step'] == 2 && $step['send_stu'] == '0') {
$sendname = '不动产信息推送失败';
}
if ($step['step'] == 2 && $step['send_stu'] == '1') {
$sendname = '不动产信息推送成功';
}
if ($step['step'] == 3 && $step['send_stu'] == '0') {
$sendname = '查档报告推送失败';
}
if ($step['step'] == 3 && $step['send_stu'] == '1') {
$sendname = '查档报告推送成功';
}
if ($step['step'] == 4 && $step['send_stu'] == '0') {
$sendname = '完税报告推送失败';
}
if ($step['step'] == 4 && $step['send_stu'] == '1') {
$sendname = '完税报告推送成功';
}
if ($step['step'] == 5 && $step['send_stu'] == '0') {
$sendname = '复盘报告推送失败';
}
if ($step['step'] == 5 && $step['send_stu'] == '1') {
$sendname = '复盘报告推送成功';
}
}
$rows[$kk]['sendname'] = $sendname;
$rows[$kk]['types'] = $vv['types'] > '0' ? $vv['types'] : '-';
$rows[$kk]['agent_user'] = $vv['agent_user'] > '0' ? $vv['agent_user'] : '-';
$rows[$kk]['mobile'] = $vv['mobile'] > '0' ? $vv['mobile'] : '-';
$rows[$kk]['content'] = $vv['content'] > '0' ? $vv['content'] : '';
$rows[$kk]['remark'] = $vv['remark'] > '0' ? $vv['remark'] : '';
}
$result = array("total" => $list->total(), "rows" => $rows);
return json($result);
}
return $this->view->fetch();
}
/**
* 添加
*/
public function add()
{
if ($this->request->isPost()) {
$params = $this->request->post("row/a");
if ($params) {
$params = $this->preExcludeFields($params);
$params['order_nunber'] = getOrderSn();
if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
$params[$this->dataLimitField] = $this->auth->id;
}
//判断是否选择了经纪人,选择了经纪人,添加工单所属企业
if ($params['agent_users_id'] > 0) {
$params['admin_id'] = agent_users_admin_id($params['agent_users_id']);
}
//获得企业名称
if ($params['agent_order_type_id'] == '1' && $params['agent_name'] > 0) {
$agent = Db::name('agent_list')
->where(['id' => $params['agent_name']])
->field('id,agent_name')
->find();
$params['agent_name'] = $agent['agent_name'];
}
$result = false;
Db::startTrans();
try {
//是否采用模型验证
if ($this->modelValidate) {
$name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
$this->model->validateFailException(true)->validate($validate);
}
$result = $this->model->allowField(true)->save($params);
Db::commit();
} catch (ValidateException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (PDOException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($result !== false) {
//审核通过并指定了经纪人
if (($params['status'] == '1' || $params['status'] == '3') && $params['agent_users_id'] > 0) {
//获得工单分类名称
$ordertype = Db::name('agent_order_type')
->where(['id' => $params['agent_order_type_id']])
->find();
$jjr_name = Db::name('agent_users')
->where(['id' => $params['agent_users_id']])
->value('jjr_name');
$titdesc = '系统指派工单[' . $ordertype['title'] . ']';
$sendInfo = array(
'first' => array('value' => urlencode($titdesc), 'color' => "#743A3A"),
'keyword1' => array('value' => urlencode($params['order_nunber']), 'color' => '#173177'),
'keyword2' => array('value' => urlencode('已指派,待处理'), 'color' => '#173177'),
'keyword3' => array('value' => urlencode($jjr_name), 'color' => '#173177'),
'remark' => array('value' => urlencode('处理时间:' . date('Y-m-d H:i:s', time())), 'color' => '#173177'),
);
$wxopenid = getAgetWxOpenid($params['agent_users_id']);
if ($wxopenid) {
$config = get_addon_config('wechat');
$tourl = 'https://fdc.xp.yn.cn/h5/';
$ywt_appid = 'wxe1355bcf5af1bea3';
$pagepath = 'pages/home/wait/kind?id=' . $this->model->id . '&type=' . $params['agent_order_type_id'] . '&index=1';
$res = sendWxMsgToAgent($sendInfo, $wxopenid, $tourl, $config['app_id'], $config['secret'], $ywt_appid, $pagepath);
file_put_contents("pcl_wct_send.log", date("Y-m-d H:i:s") . "1-1-" . json_encode($res, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
}
}
$this->success();
} else {
$this->error(__('No rows were inserted'));
}
}
$this->error(__('Parameter %s can not be empty', ''));
}
return $this->view->fetch();
}
/***
* 编辑(old)
*
*/
// public function edit($ids = null)
// {
// $row = $this->model->get($ids);
// $row['types'] = $row['types'] > '0' ? $row['types'] : '';
// $row['agent_user'] = $row['agent_user'] > '0' ? $row['agent_user'] : '';
// $row['mobile'] = $row['mobile'] > '0' ? $row['mobile'] : '';
// $row['content'] = $row['content'] > '0' ? $row['content'] : '';
// $row['remark'] = $row['remark'] > '0' ? $row['remark'] : '';
// if (!$row) {
// $this->error(__('No Results were found'));
// }
// $adminIds = $this->getDataLimitAdminIds();
// if (is_array($adminIds)) {
// if (!in_array($row[$this->dataLimitField], $adminIds)) {
// $this->error(__('You have no permission'));
// }
// }
// if ($this->request->isPost()) {
// $params = $this->request->post("row/a");
// if ($params) {
// $params = $this->preExcludeFields($params);
// //判断是否选择了经纪人,选择了经纪人,添加工单所属企业
// if ($params['agent_users_id'] > 0) {
// $params['admin_id'] = agent_users_admin_id($params['agent_users_id']);
// }
// $result = false;
// Db::startTrans();
// try {
// //是否采用模型验证
// if ($this->modelValidate) {
// $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
// $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
// $row->validateFailException(true)->validate($validate);
// }
// if ($params['status'] == 1 && $params['agent_users_id'] > 0) {
// $params['status'] = 3;
// }
//
// $result = $row->save($params);
// if ($params['status'] == 1) {
// $str = '工单通过审核';
// }
// if ($params['status'] == 2) {
// $str = '工单未通过审核';
// }
// if ($params['status'] == 3) {
// $str = '工单已指派';
// }
// if ($params['status'] == 8) {
// $str = '工单不通过,退款金额原路返回';
// }
//
// Db::name('agent_order_log')->insert([
// 'agent_order_id' => $ids,
// 'admin_id' => $this->auth->id,
// 'content' => $str,
// 'createtime' => time(),
// 'step' => 2,
// 'agent_user_id' => $params['agent_users_id'] ? $params['agent_users_id'] : 0,
// ]);
//
// //判断是否已支付,已支付则退款
// if ($params['status'] == 8 && $row['ia_pay'] == '1') {
// //支付金额
// $paylog = Db::name('workorder_userpay')
// ->where(['work_id' => $row['id'], 'ordersn' => $row['order_nunber']])
// ->find();
// if (!empty($paylog)) {
// //退款处理
// $pay_fee = $paylog['price'];
// $refund_fee = $pay_fee;
// $order_sn = $paylog['ordersn'];
// $pay_type = 'wechat';
// $reason = '工单审核不通过,退回保证金';
// $notifyurl = 'https://fdc.xp.yn.cn/api/index/refundNotifyx';//退款回调地址
// //直接调用退款方法传参即可
// $response = \addons\epay\library\Service::submitRefund($pay_fee, $refund_fee, $order_sn, getRefundSn($paylog['user_id']), $pay_type, $reason, $notifyurl, '', 'miniapp');
// $response = json_encode($response);
// $response = json_decode($response, true);
// file_put_contents("pcl_repay_fdc_v2.log", date("Y-m-d H:i:s") . "::" . json_encode($response, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
// if (!empty($response['return_code'] == 'SUCCESS')) {
// //退款成功,更新退款记录
// $addtime = time();
// $relogs['uptime'] = $addtime;
// $relogs['is_refund'] = 1;
// $relogs['out_refund_no'] = $response['out_refund_no'];
// $relogs['refund_id'] = $response['refund_id'];
// $relogs['refund_fee'] = $response['refund_fee'];
// $relogs['refund_time'] = $addtime;
// $relogs['admin'] = $this->auth->id;
// Db::name('workorder_userpay')
// ->where(['work_id' => $row['id'], 'ordersn' => $row['order_nunber']])
// ->update($relogs);
// //更新工单表
// $order['is_refund'] = 1;
// $order['refund_time'] = $addtime;
// Db::name('agent_order')
// ->where(['id' => $row['id']])
// ->update($order);
// } else {
// $this->error('退款失败');
// }
// }
// }
//
// Db::commit();
// } catch (ValidateException $e) {
// Db::rollback();
// $this->error($e->getMessage());
// } catch (PDOException $e) {
// Db::rollback();
// $this->error($e->getMessage());
// } catch (Exception $e) {
// Db::rollback();
// $this->error($e->getMessage());
// }
// if ($result !== false) {
// //审核通过并指定了经纪人
// if (($params['status'] == '1' || $params['status'] == '3') && $params['agent_users_id'] > 0) {
// //获得工单分类名称
// $ordertype = Db::name('agent_order_type')
// ->where(['id' => $params['agent_order_type_id']])
// ->find();
// $jjr_name = Db::name('agent_users')
// ->where(['id' => $params['agent_users_id']])
// ->value('jjr_name');
// $titdesc = '系统指派工单[' . $ordertype['title'] . ']';
// $sendInfo = array(
// 'first' => array('value' => urlencode($titdesc), 'color' => "#743A3A"),
// 'keyword1' => array('value' => urlencode($row['order_nunber']), 'color' => '#173177'),
// 'keyword2' => array('value' => urlencode('已指派,待处理'), 'color' => '#173177'),
// 'keyword3' => array('value' => urlencode($jjr_name), 'color' => '#173177'),
// 'remark' => array('value' => urlencode('处理时间:' . date('Y-m-d H:i:s', time())), 'color' => '#173177'),
// );
// $wxopenid = getAgetWxOpenid($params['agent_users_id']);
// if ($wxopenid) {
// $config = get_addon_config('wechat');
// $tourl = 'https://fdc.xp.yn.cn/h5/';
// $ywt_appid = 'wxe1355bcf5af1bea3';
// $pagepath = 'pages/home/wait/kind?id=' . $row['id'] . '&type=' . $params['agent_order_type_id'] . '&index=1';
// $res = sendWxMsgToAgent($sendInfo, $wxopenid, $tourl, $config['app_id'], $config['secret'], $ywt_appid, $pagepath);
// file_put_contents("pcl_wct_send.log", date("Y-m-d H:i:s") . "1-2-" . json_encode($res, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
// }
// }
// $this->success();
// } else {
// $this->error(__('No rows were updated'));
// }
// }
// $this->error(__('Parameter %s can not be empty', ''));
// }
// $this->view->assign("row", $row);
// return $this->view->fetch();
// }
/***
* 编辑
*
*/
public function edit($ids = null)
{
$row = $this->model->get($ids);
$row['types'] = $row['types'] > '0' ? $row['types'] : '';
$row['agent_user'] = $row['agent_user'] > '0' ? $row['agent_user'] : '';
$row['mobile'] = $row['mobile'] > '0' ? $row['mobile'] : '';
$row['content'] = $row['content'] > '0' ? $row['content'] : '';
$row['remark'] = $row['remark'] > '0' ? $row['remark'] : '';
//获得推送公证处状态
$step = Db::name('agent_order_send_logs')
->where(['agent_order_id' => $row['id']])
->order('id', 'desc')
->find();
if (!$row) {
$this->error(__('No Results were found'));
}
$adminIds = $this->getDataLimitAdminIds();
if (is_array($adminIds)) {
if (!in_array($row[$this->dataLimitField], $adminIds)) {
$this->error(__('You have no permission'));
}
}
if ($this->request->isPost()) {
$params = $this->request->post("row/a");
if ($params) {
$params = $this->preExcludeFields($params);
//判断是否选择了经纪人,选择了经纪人,添加工单所属企业
if ($params['agent_users_id'] > 0) {
$params['admin_id'] = agent_users_admin_id($params['agent_users_id']);
}
if (isset($params['pclOfficeSendv2'])) {
$pclOfficeSendv2 = $params['pclOfficeSendv2'];
unset($params['pclOfficeSendv2']);
}
if (isset($params['pclOfficeSendv3'])) {
$pclOfficeSendv3 = $params['pclOfficeSendv3'];
unset($params['pclOfficeSendv3']);
}
if (isset($params['pclOfficeSendv4'])) {
$pclOfficeSendv4 = $params['pclOfficeSendv4'];
unset($params['pclOfficeSendv4']);
}
if (isset($params['pclOfficeSendv5'])) {
$pclOfficeSendv5 = $params['pclOfficeSendv5'];
unset($params['pclOfficeSendv5']);
}
$result = false;
Db::startTrans();
try {
//是否采用模型验证
if ($this->modelValidate) {
$name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
$row->validateFailException(true)->validate($validate);
}
$result = $row->save($params);
$statusList = $this->model->getStatusList();
$str = $statusList[$params['status']];
$step_id = 0;
$step = Db::name("agent_order_log")->where("agent_order_id", $ids)->order("step desc,id desc")->value("step");
if ($step) {
$step_id = $step + 1;
}
Db::name('agent_order_log')->insert([
'agent_order_id' => $ids,
'content' => $str,
'user_id' => $row['user_id'],
'createtime' => time(),
'admin_id' => agent_users_admin_id($params['agent_users_id']),
'step' => $step_id,
'write_status' => $params['status'],
'agent_user_id' => $params['agent_users_id'] ? $params['agent_users_id'] : 0,
]);
//判断是否已支付,已支付则退款
// if ($params['status'] == 8 && $row['ia_pay'] == '1') {
// //支付金额
// $paylog = Db::name('workorder_userpay')
// ->where(['work_id' => $row['id'], 'ordersn' => $row['order_nunber']])
// ->find();
// if (!empty($paylog)) {
// //退款处理
// $pay_fee = $paylog['price'];
// $refund_fee = $pay_fee;
// $order_sn = $paylog['ordersn'];
// $pay_type = 'wechat';
// $reason = '工单审核不通过,退回保证金';
// $notifyurl = 'https://fdc.xp.yn.cn/api/index/refundNotifyx';//退款回调地址
// //直接调用退款方法传参即可
// $response = \addons\epay\library\Service::submitRefund($pay_fee, $refund_fee, $order_sn, getRefundSn($paylog['user_id']), $pay_type, $reason, $notifyurl, '', 'miniapp');
// $response = json_encode($response);
// $response = json_decode($response, true);
// file_put_contents("pcl_repay_fdc_v2.log", date("Y-m-d H:i:s") . "::" . json_encode($response, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
// if (!empty($response['return_code'] == 'SUCCESS')) {
// //退款成功,更新退款记录
// $addtime = time();
// $relogs['uptime'] = $addtime;
// $relogs['is_refund'] = 1;
// $relogs['out_refund_no'] = $response['out_refund_no'];
// $relogs['refund_id'] = $response['refund_id'];
// $relogs['refund_fee'] = $response['refund_fee'];
// $relogs['refund_time'] = $addtime;
// $relogs['admin'] = $this->auth->id;
// Db::name('workorder_userpay')
// ->where(['work_id' => $row['id'], 'ordersn' => $row['order_nunber']])
// ->update($relogs);
// //更新工单表
// $order['is_refund'] = 1;
// $order['refund_time'] = $addtime;
// Db::name('agent_order')
// ->where(['id' => $row['id']])
// ->update($order);
// } else {
// $this->error('退款失败');
// }
// }
// }
Db::commit();
} catch (ValidateException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (PDOException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($result !== false) {
//获得工单信息
$orders = Db::name('agent_order')->where(['id' => $row['id']])->find();
$titdesc = $orders['order_nunber'];
if ($params['status'] == '1') {
$titdesc = '工单审核通过';
}
if ($params['status'] == '2') {
$titdesc = '工单审核被拒绝';
}
//第1步 用户需求信息审核成功,调用接口推给公证处
$Office = new Index();
if ($params['status'] == '1') {
$titdesc = '工单审核通过,公证处办理中';
//判断是否推送过了,推送日志表agent_order_send_logs
$cks_send = Db::name('agent_order_send_logs')
->where(['agent_order_id' => $row['id'], 'send_stu' => 1, 'step' => 1])
->find();
if (empty($cks_send)) {
//1获得token
$token = $Office->getOfficeToken();
while (empty($token)) {
$token = $Office->getOfficeToken();
}
//获得推送数据
$sendData = $Office->notifyNewOrder($row['id']);
$url = "https://gz.hxgzc.cn:34443/capitalManage/services/createOrder";
if (!empty($token) && !empty($sendData)) {
$res = HttpHelper::curl($url, 'POST', $sendData, [], $token);
$resArr = json_decode(stripslashes($res), true);
if ($resArr['succeed'] == true) {
$slogs['send_stu'] = 1;
} else {
$slogs['send_stu'] = 0;
}
$slogs['agent_order_id'] = $row['id'];
$slogs['createtime'] = time();
$slogs['step'] = 1;
$slogs['reback_msg'] = $res;
$logs = Db::name('agent_order_send_logs')->insertGetId($slogs);
}
}
}
//2、不动产信息审核通过,推送公证处
if ($pclOfficeSendv2 == 1) {
$titdesc = '不动产信息审核通过,公证处办理中';
//1获得token
$token = $Office->getOfficeToken();
while (empty($token)) {
$token = $Office->getOfficeToken();
}
//获得推送数据
$sendData = $Office->realEstateUpdate($row['id']);
$url = "https://gz.hxgzc.cn:34443/capitalManage/services/realEstateUpdate";
if (!empty($token) && !empty($sendData)) {
$res = HttpHelper::curl($url, 'POST', $sendData, [], $token);
$resArr = json_decode(stripslashes($res), true);
if ($resArr['succeed'] == true) {
$slogs['send_stu'] = 1;
} else {
$slogs['send_stu'] = 0;
}
$slogs['agent_order_id'] = $row['id'];
$slogs['createtime'] = time();
$slogs['step'] = 2;
$slogs['reback_msg'] = $res;
$logs = Db::name('agent_order_send_logs')->insertGetId($slogs);
}
}
//3、推送查档报告
if ($pclOfficeSendv3 == 1) {
$titdesc = '查档报告审核通过,公证处办理中';
//1获得token
$token = $Office->getOfficeToken();
while (empty($token)) {
$token = $Office->getOfficeToken();
}
//获得推送数据
$sendData = $Office->checkReportUpdate($row['id']);
$url = "https://gz.hxgzc.cn:34443/capitalManage/services/checkReportUpdate";
if (!empty($token) && !empty($sendData)) {
$res = HttpHelper::curl($url, 'POST', $sendData, [], $token);
$resArr = json_decode(stripslashes($res), true);
if ($resArr['succeed'] == true) {
$slogs['send_stu'] = 1;
} else {
$slogs['send_stu'] = 0;
}
$slogs['agent_order_id'] = $row['id'];
$slogs['createtime'] = time();
$slogs['step'] = 3;
$slogs['reback_msg'] = $res;
$logs = Db::name('agent_order_send_logs')->insertGetId($slogs);
}
}
//4、推送完税报告
if ($pclOfficeSendv4 == 1) {
$titdesc = '完税报告审核通过,公证处办理中';
//1获得token
$token = $Office->getOfficeToken();
while (empty($token)) {
$token = $Office->getOfficeToken();
}
//获得推送数据
$sendData = $Office->taxPaidReportUpdate($row['id']);
$url = "https://gz.hxgzc.cn:34443/capitalManage/services/taxPaidReportUpdate";
if (!empty($token) && !empty($sendData)) {
$res = HttpHelper::curl($url, 'POST', $sendData, [], $token);
$resArr = json_decode(stripslashes($res), true);
if ($resArr['succeed'] == true) {
$slogs['send_stu'] = 1;
} else {
$slogs['send_stu'] = 0;
}
$slogs['agent_order_id'] = $row['id'];
$slogs['createtime'] = time();
$slogs['step'] = 4;//
$slogs['reback_msg'] = $res;
$logs = Db::name('agent_order_send_logs')->insertGetId($slogs);
}
}
//5、推送复盘报告
if ($pclOfficeSendv5 == 1) {
$titdesc = '复盘信息审核通过,公证处办理中';
//1获得token
$token = $Office->getOfficeToken();
while (empty($token)) {
$token = $Office->getOfficeToken();
}
//获得推送数据
$sendData = $Office->orderMatchReportUpdate($row['id']);
$url = "https://gz.hxgzc.cn:34443/capitalManage/services/orderMatchReportUpdate";
if (!empty($token) && !empty($sendData)) {
$res = HttpHelper::curl($url, 'POST', $sendData, [], $token);
$resArr = json_decode(stripslashes($res), true);
if ($resArr['succeed'] == true) {
$slogs['send_stu'] = 1;
} else {
$slogs['send_stu'] = 0;
}
$slogs['agent_order_id'] = $row['id'];
$slogs['createtime'] = time();
$slogs['step'] = 5;//复盘
$slogs['reback_msg'] = $res;
$logs = Db::name('agent_order_send_logs')->insertGetId($slogs);
}
}
//审核通过并指定了经纪人
// if (($params['status'] == '1' || $params['status'] == '3') && $params['agent_users_id'] > 0) {
// //获得工单分类名称
// $ordertype = Db::name('agent_order_type')
// ->where(['id' => $params['agent_order_type_id']])
// ->find();
// $jjr_name = Db::name('agent_users')
// ->where(['id' => $params['agent_users_id']])
// ->value('jjr_name');
// $titdesc = '系统指派工单[' . $ordertype['title'] . ']';
// $sendInfo = array(
// 'first' => array('value' => urlencode($titdesc), 'color' => "#743A3A"),
// 'keyword1' => array('value' => urlencode($row['order_nunber']), 'color' => '#173177'),
// 'keyword2' => array('value' => urlencode('已指派,待处理'), 'color' => '#173177'),
// 'keyword3' => array('value' => urlencode($jjr_name), 'color' => '#173177'),
// 'remark' => array('value' => urlencode('处理时间:' . date('Y-m-d H:i:s', time())), 'color' => '#173177'),
// );
// $wxopenid = getAgetWxOpenid($params['agent_users_id']);
// if ($wxopenid) {
// $config = get_addon_config('wechat');
// $tourl = 'https://fdc.xp.yn.cn/h5/';
// $ywt_appid = 'wxe1355bcf5af1bea3';
// $pagepath = 'pages/home/wait/kind?id=' . $row['id'] . '&type=' . $params['agent_order_type_id'] . '&index=1';
// $res = sendWxMsgToAgent($sendInfo, $wxopenid, $tourl, $config['app_id'], $config['secret'], $ywt_appid, $pagepath);
// file_put_contents("pcl_wct_send.log", date("Y-m-d H:i:s") . "1-2-" . json_encode($res, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
// }
// }
//推送公众号模板信息给工单管理经纪人
$this->senWxmsgToAgentUser($orders, $titdesc);
$this->success();
} else {
$this->error(__('No rows were updated'));
}
}
$this->error(__('Parameter %s can not be empty', ''));
}
$this->view->assign("row", $row);
$this->view->assign("step", $step);
return $this->view->fetch();
}
/***
* 公众号推送工单信息给经纪人
*/
private function senWxmsgToAgentUser($order, $titdesc)
{
//获得工单分类名称
$ordertype = Db::name('agent_order_type')
->where(['id' => $order['agent_order_type_id']])
->find();
$jjr_name = Db::name('agent_users')
->where(['id' => $order['agent_users_id']])
->value('jjr_name');
$sendInfo = array(
'first' => array('value' => urlencode($titdesc), 'color' => "#743A3A"),
'keyword1' => array('value' => urlencode($order['order_nunber']), 'color' => '#173177'),
'keyword2' => array('value' => urlencode($titdesc), 'color' => '#173177'),
'keyword3' => array('value' => urlencode($jjr_name), 'color' => '#173177'),
'remark' => array('value' => urlencode('处理时间:' . date('Y-m-d H:i:s', time())), 'color' => '#173177'),
);
$wxopenid = getAgetWxOpenid($order['agent_users_id']);
if ($wxopenid) {
$config = get_addon_config('wechat');
$tourl = 'https://fdc.xp.yn.cn/h5/';
$ywt_appid = 'wxe1355bcf5af1bea3';
$pagepath = 'pages/order/order_details?id=' . $order['id'];
$res = sendWxMsgToAgent($sendInfo, $wxopenid, $tourl, $config['app_id'], $config['secret'], $ywt_appid, $pagepath);
//file_put_contents("pcl_wct_send.log", date("Y-m-d H:i:s") . "1-2-" . json_encode($res, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
}
}
/**
* 导入excel数据
*/
public function import()
{
$file = $this->request->request('file');
if (!$file) {
$this->error(__('Parameter %s can not be empty', 'file'));
}
$filePath = ROOT_PATH . DS . 'public' . DS . $file;
if (!is_file($filePath)) {
$this->error(__('No results were found'));
}
if (!is_file($filePath)) {
$this->error('找不到数据文件,请重新上传');
}
//实例化reader
$ext = pathinfo($filePath, PATHINFO_EXTENSION);
if (!in_array($ext, ['xls', 'xlsx'])) {
$this->error('不支持的数据格式');
}
if ($ext === 'xls') {
$reader = new Xls();
} else {
$reader = new Xlsx();
}
//读取EXCEl的内容
$PHPExcel = $reader->load($filePath);
if (!$PHPExcel) {
$this->error('表格内没有数据内容');
}
$currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
$allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
$allRow = $currentSheet->getHighestRow(); //取得一共有多少行
$maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
$fields = [];
//获得表第1行栏目名称
for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
$val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
$fields[] = $val;
}
}
//获得从第2行起内容列表数组
for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
$values = [];
for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
$val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
$values[] = is_null($val) ? '0' : $val;
}
//循环保存数据到数据库
$data['agent_order_type_id'] = $this->getcatIds($values[1]);
$data['order_nunber'] = getOrderSn();
$data['user_name'] = $values[2];
$data['cqr_mobile'] = $values[3];
$data['agent_user'] = $values[4];
$data['mobile'] = $values[5] > '0' ? $values[5] : '';
if ($data['agent_order_type_id'] == 5 && $values[6] > '0') {
$data['loan_cat_id'] = $this->getLoancatIds($values[6]);
} else {
$data['loan_cat_id'] = '';
}
if ($data['agent_order_type_id'] == 1 && $values[7] > '0') {
$data['house_cat_id'] = $this->getHousecatIds($values[7]);
} else {
$data['house_cat_id'] = '';
}
$data['agent_name'] = $values[8] > '0' ? $values[8] : '';
$data['agent_user_name'] = $values[9] > '0' ? $values[9] : '';
$data['agent_mobile'] = $values[10] > '0' ? $values[10] : '';
$data['house_area'] = $values[11] > '0' ? $values[11] : '';
$data['house_price'] = $values[12] > '0' ? $values[12] : '';
$data['content'] = $values[13] > '0' ? $values[13] : '';
$data['remark'] = $values[14] > '0' ? $values[14] : '';
$data['is_import'] = 1;
$data['createtime'] = time();
//判断订单号是否存在
$cks = Db::name('agent_order')
->where(['order_nunber' => $data['order_nunber']])
->find();
if (empty($cks)) {
$rs = Db::name('agent_order')->insertGetId($data);
}
}
$this->success('导入成功');
}
/**
* 配置分类
* 工单分类
*/
protected function getcatIds($data)
{
$wh['title'] = ['=', $data];
$cat = Db::name('agent_order_type')
->where($wh)
->find();
if (empty($cat)) {
$wh2['title'] = ['like', '%' . $data . '%'];
$cat = Db::name('agent_order_type')
->where($wh2)
->find();
}
$cat_id = !empty($cat) ? $cat['id'] : 1;
return $cat_id;
}
/**
* 贷款分类
*
*/
protected function getLoancatIds($data)
{
$wh['catname'] = ['=', $data];
$cat = Db::name('loan_cat')
->where($wh)
->find();
if (empty($cat)) {
$wh2['catname'] = ['like', '%' . $data . '%'];
$cat = Db::name('loan_cat')
->where($wh2)
->find();
}
$cat_id = !empty($cat) ? $cat['id'] : 1;
return $cat_id;
}
/**
* 房子性质分类
*
*/
protected function getHousecatIds($data)
{
$wh['catname'] = ['=', $data];
$cat = Db::name('house_cat')
->where($wh)
->find();
if (empty($cat)) {
$wh2['catname'] = ['like', '%' . $data . '%'];
$cat = Db::name('house_cat')
->where($wh2)
->find();
}
$cat_id = !empty($cat) ? $cat['id'] : 1;
return $cat_id;
}
}
... ...
<?php
namespace app\admin\controller\agent;
use app\common\controller\Backend;
use think\Db;
/**
*
*
* @icon fa fa-circle-o
*/
class Orderlog extends Backend
{
/**
* Orderlog模型对象
* @var \app\admin\model\agent\Orderlog
*/
protected $model = null;
public function _initialize()
{
parent::_initialize();
$this->model = new \app\admin\model\agent\Orderlog;
}
/**
* 查看
*/
public function index()
{
//设置过滤方法
$this->request->filter(['strip_tags', 'trim']);
if ($this->request->isAjax()) {
$appid = $this->request->param('app_id', 0);
if ($appid > 0) {
$wh['agent_order_id'] = ['=', $appid];
} else {
$wh = " 1=1 ";
}
//如果发送的来源是Selectpage,则转发到Selectpage
if ($this->request->request('keyField')) {
return $this->selectpage();
}
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$list = $this->model
->where($where)
->where($wh)
->order('id', 'asc')
->paginate($limit);
$rows = $list->items();
foreach ($rows as $kk => $vv) {
//关联发布人
$oinfo = Db::name('agent_order')
->where(['id' => $vv['agent_order_id']])
->find();
$rows[$kk]['user_name'] = $oinfo['user_name'];
$rows[$kk]['mobile'] = $oinfo['mobile'];
//处理人信息
if ($vv['agent_user_id'] > 0) {
$agent = Db::name('agent_users')
->where(['id' => $vv['agent_user_id']])
->field('id,jjr_name,jjr_mobile')
->find();
$rows[$kk]['jjr_name'] = $agent['jjr_name'] . '[' . $agent['jjr_mobile'] . ']';
} else {
$rows[$kk]['jjr_name'] = '-';
}
}
$result = array("total" => $list->total(), "rows" => $rows);
return json($result);
}
return $this->view->fetch();
}
}
... ...
<?php
namespace app\admin\controller\agent;
use app\common\controller\Backend;
/**
* 工单推送公证处日志
*
* @icon fa fa-circle-o
*/
class Ordersendlog extends Backend
{
/**
* Ordersendlog模型对象
* @var \app\admin\model\agent\Ordersendlog
*/
protected $model = null;
public function _initialize()
{
parent::_initialize();
$this->model = new \app\admin\model\agent\Ordersendlog;
$this->view->assign("sendStuList", $this->model->getSendStuList());
}
public function import()
{
parent::import();
}
/**
* 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
* 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
* 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
*/
}
... ...
<?php
namespace app\admin\controller\agent;
use app\common\controller\Backend;
/**
* 工单分类
*
* @icon fa fa-circle-o
*/
class Ordertype extends Backend
{
/**
* Ordertype模型对象
* @var \app\admin\model\agent\Ordertype
*/
protected $model = null;
public function _initialize()
{
parent::_initialize();
$this->model = new \app\admin\model\agent\Ordertype;
}
/**
* 查看
*/
public function index()
{
//当前是否为关联查询
$this->relationSearch = true;
//设置过滤方法
$this->request->filter(['strip_tags', 'trim']);
if ($this->request->isAjax()) {
//如果发送的来源是Selectpage,则转发到Selectpage
if ($this->request->request('keyField')) {
return $this->selectpage();
}
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$list = $this->model
->where($where)
->where('siteswitch!=3')
->order('id', 'asc')
->paginate($limit);
foreach ($list as $row) {
$row->visible(['id', 'title', 'icon_image', 'weigh', 'siteswitch', 'price']);
}
$result = array("total" => $list->total(), "rows" => $list->items());
return json($result);
}
return $this->view->fetch();
}
}
... ...
<?php
namespace app\admin\controller\agent;
use app\common\controller\Backend;
/**
*
*
* @icon fa fa-circle-o
*/
class Ordertypeprocess extends Backend
{
/**
* Ordertypeprocess模型对象
* @var \app\admin\model\agent\Ordertypeprocess
*/
protected $model = null;
public function _initialize()
{
parent::_initialize();
$this->model = new \app\admin\model\agent\Ordertypeprocess;
}
public function import()
{
parent::import();
}
}
... ...
<?php
namespace app\admin\controller\agent;
use app\common\controller\Backend;
use think\Db;
/**
* 企业年费缴纳管理
*
* @icon fa fa-circle-o
*/
class Paymentlogs extends Backend
{
/**
* Paymentlogs模型对象
* @var \app\admin\model\agent\Paymentlogs
*/
protected $model = null;
public function _initialize()
{
parent::_initialize();
$this->model = new \app\admin\model\agent\Paymentlogs;
$agt_ids = $this->request->param('ids', 0);
if ($agt_ids > 0) {
$ginfo = Db::name('agent_list')
->where(['id' => $agt_ids])
->find();
} else {
$ginfo = [];
}
$this->view->assign('ginfo', $ginfo);
}
/**
* 查看
*/
public function index()
{
//当前是否为关联查询
$this->relationSearch = true;
//设置过滤方法
$this->request->filter(['strip_tags', 'trim']);
if ($this->request->isAjax()) {
$ids = $this->request->param('ids', 0);
if ($ids > 0) {
$wh['agent_list_id'] = ['=', $ids];
} else {
$wh = ' 1=1 ';
}
//如果发送的来源是Selectpage,则转发到Selectpage
if ($this->request->request('keyField')) {
return $this->selectpage();
}
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$list = $this->model
->with(['agentlist'])
->where($where)
->where($wh)
->order($sort, $order)
->paginate($limit);
foreach ($list as $row) {
$row->visible(['id', 'agent_list_id', 'pay_price', 'createtime', 'start_pay_time', 'end_pay_time', 'stu_msg']);
$row->visible(['agentlist']);
$row->getRelation('agentlist')->visible(['agent_name']);
}
$rows = $list->items();
foreach ($rows as $kk => $vv) {
//判断是否过期
$nowtime = time();
if ($nowtime > $vv['end_pay_time']) {
$rows[$kk]['stu_msg'] = '已过期';
} else {
$rows[$kk]['stu_msg'] = '有效';
}
}
$result = array("total" => $list->total(), "rows" => $rows);
return json($result);
}
return $this->view->fetch();
}
/**
* 添加
*/
public function add()
{
if ($this->request->isPost()) {
$params = $this->request->post("row/a");
if ($params) {
$params = $this->preExcludeFields($params);
$params['admin_id'] = $this->auth->id;
if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
$params[$this->dataLimitField] = $this->auth->id;
}
$result = false;
Db::startTrans();
try {
//是否采用模型验证
if ($this->modelValidate) {
$name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
$this->model->validateFailException(true)->validate($validate);
}
$result = $this->model->allowField(true)->save($params);
//处理企业支付时间,更新企业表支付结束时间
$agentpay['start_pay_time'] = strtotime($params['start_pay_time']);
$agentpay['end_pay_time'] = strtotime($params['end_pay_time']);
$agentpay['pay_stu'] = 1;
$agentpay['updatetime'] = time();
Db::name('agent_list')->where(['id' => $params['agent_list_id']])->update($agentpay);
Db::commit();
} catch (ValidateException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (PDOException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($result !== false) {
$this->success();
} else {
$this->error(__('No rows were inserted'));
}
}
$this->error(__('Parameter %s can not be empty', ''));
}
return $this->view->fetch();
}
/**
* 编辑
*/
public function edit($ids = null)
{
$row = $this->model->get($ids);
if (!$row) {
$this->error(__('No Results were found'));
}
$adminIds = $this->getDataLimitAdminIds();
if (is_array($adminIds)) {
if (!in_array($row[$this->dataLimitField], $adminIds)) {
$this->error(__('You have no permission'));
}
}
if ($this->request->isPost()) {
$params = $this->request->post("row/a");
if ($params) {
$params = $this->preExcludeFields($params);
$result = false;
Db::startTrans();
try {
//是否采用模型验证
if ($this->modelValidate) {
$name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
$row->validateFailException(true)->validate($validate);
}
$result = $row->allowField(true)->save($params);
//处理企业支付时间,更新企业表支付结束时间
$agentpay['start_pay_time'] = strtotime($params['start_pay_time']);
$agentpay['end_pay_time'] = strtotime($params['end_pay_time']);
$agentpay['pay_stu'] = 1;
$agentpay['updatetime'] = time();
Db::name('agent_list')->where(['id' => $params['agent_list_id']])->update($agentpay);
Db::commit();
} catch (ValidateException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (PDOException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($result !== false) {
$this->success();
} else {
$this->error(__('No rows were updated'));
}
}
$this->error(__('Parameter %s can not be empty', ''));
}
$this->view->assign("row", $row);
return $this->view->fetch();
}
}
... ...
<?php
namespace app\admin\controller\agent;
use app\common\controller\Backend;
use think\Db;
/**
* 购房售房人信息
*
* @icon fa fa-circle-o
*/
class Payusers extends Backend
{
/**
* Payusers模型对象
* @var \app\admin\model\agent\Payusers
*/
protected $model = null;
public function _initialize()
{
parent::_initialize();
$this->model = new \app\admin\model\agent\Payusers;
$this->view->assign("isnaturalpersonList", $this->model->getIsnaturalpersonList());
$this->view->assign("typeList", $this->model->getTypeList());
}
/**
* 查看
*/
public function index()
{
//当前是否为关联查询
$this->relationSearch = true;
//设置过滤方法
$this->request->filter(['strip_tags', 'trim']);
if ($this->request->isAjax()) {
$ids = $this->request->param('ids', 0);
if ($ids > 0) {
$wh['agent_order_id'] = ['=', $ids];
} else {
$wh = ' 1=1 ';
}
//如果发送的来源是Selectpage,则转发到Selectpage
if ($this->request->request('keyField')) {
return $this->selectpage();
}
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$list = $this->model
->where($where)
->where($wh)
->order('id','asc')
->paginate($limit);
$rows = $list->items();
$result = array("total" => $list->total(), "rows" => $rows);
return json($result);
}
return $this->view->fetch();
}
}
... ...
<?php
namespace app\admin\controller\agent;
use app\common\controller\Backend;
use think\Db;
/**
* 一网通办人员管理
*
* @icon fa fa-circle-o
*/
class Usermobile extends Backend
{
/**
* Usermobile模型对象
* @var \app\admin\model\agent\Usermobile
*/
protected $model = null;
public function _initialize()
{
parent::_initialize();
$this->model = new \app\admin\model\agent\Usermobile;
$this->view->assign("statusList", $this->model->getStatusList());
}
public function import()
{
parent::import();
}
/**
* 查看
*/
public function index()
{
//当前是否为关联查询
$this->relationSearch = true;
//设置过滤方法
$this->request->filter(['strip_tags', 'trim']);
if ($this->request->isAjax()) {
//如果发送的来源是Selectpage,则转发到Selectpage
if ($this->request->request('keyField')) {
return $this->selectpage();
}
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$a = [];
$b = (json_decode((request()->param())['filter'],true))['status'];
if($b === '1'){
}else{
$a['user_id'] = ['<>',''];
}
$list = $this->model
->where($where)
->where($a)
->order('id', 'desc')
->paginate($limit);
$rows = $list->items();
foreach ($rows as $kk => $vv) {
//关联经纪人信息
$agent = Db::name('agent_users')
->where(['jjr_mobile' => $vv['catname']])
->find();
$rows[$kk]['agent_user'] = '-';
$rows[$kk]['userno'] = '-';
if (empty($agent)) {
$rows[$kk]['agent_stu'] = '未注册';
}
if ($agent['jjr_agent_stu'] == '0') {
$rows[$kk]['agent_user'] = $agent['jjr_name'];
$rows[$kk]['userno'] = $agent['userno'];
$rows[$kk]['agent_stu'] = '未审核';
}
if ($agent['jjr_agent_stu'] == '1') {
$rows[$kk]['agent_user'] = $agent['jjr_name'];
$rows[$kk]['userno'] = $agent['userno'];
$rows[$kk]['agent_stu'] = '审核通过';
}
if ($agent['jjr_agent_stu'] == '2') {
$rows[$kk]['agent_user'] = $agent['jjr_name'];
$rows[$kk]['userno'] = $agent['userno'];
$rows[$kk]['agent_stu'] = '不通过';
}
if ($agent['jjr_agent_stu'] == '3') {
$rows[$kk]['agent_user'] = $agent['jjr_name'];
$rows[$kk]['userno'] = $agent['userno'];
$rows[$kk]['agent_stu'] = '离职';
}
if ($agent['jjr_agent_stu'] == '4') {
$rows[$kk]['agent_user'] = $agent['jjr_name'];
$rows[$kk]['userno'] = $agent['userno'];
$rows[$kk]['agent_stu'] = '非正常离职';
}
}
$result = array("total" => $list->total(), "rows" => $rows);
return json($result);
}
return $this->view->fetch();
}
/**
* 添加
*/
public function add()
{
if ($this->request->isPost()) {
$params = $this->request->post("row/a");
if ($params) {
$params = $this->preExcludeFields($params);
//判断手机号码格式
if (!preg_match('/^1[3456789]\d{9}$/ims', $params['catname'])) {
$this->error('手机号码格式不正确');
}
//判断手机号码是否重复
$cksrs = Db::name('agent_user_mobile')
->where(['catname' => $params['catname']])
->find();
if (!empty($cksrs)) {
$this->error('手机号码已存在');
}
if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
$params[$this->dataLimitField] = $this->auth->id;
}
$result = false;
//关联经纪人信息
$agent = Db::name('agent_users')
->where(['jjr_mobile' => $params['catname']])
->find();
$params['user_id'] = $agent['user_id'];
$params['jjr_name'] = $agent['jjr_name'];
$params['userno'] = $agent['userno'];
Db::startTrans();
try {
//是否采用模型验证
if ($this->modelValidate) {
$name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
$this->model->validateFailException(true)->validate($validate);
}
$result = $this->model->allowField(true)->save($params);
Db::commit();
} catch (ValidateException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (PDOException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($result !== false) {
$this->success();
} else {
$this->error(__('No rows were inserted'));
}
}
$this->error(__('Parameter %s can not be empty', ''));
}
return $this->view->fetch();
}
/**
* 编辑
*/
public function edit($ids = null)
{
$row = $this->model->get($ids);
if (!$row) {
$this->error(__('No Results were found'));
}
$adminIds = $this->getDataLimitAdminIds();
if (is_array($adminIds)) {
if (!in_array($row[$this->dataLimitField], $adminIds)) {
$this->error(__('You have no permission'));
}
}
if ($this->request->isPost()) {
$params = $this->request->post("row/a");
if ($params) {
$params = $this->preExcludeFields($params);
//判断手机号码格式
if (!preg_match('/^1[3456789]\d{9}$/ims', $params['catname'])) {
$this->error('手机号码格式不正确');
}
//判断手机号码是否重复
$wh['id'] = ['neq', $row['id']];
$cksrs = Db::name('agent_user_mobile')
->where(['catname' => $params['catname']])
->where($wh)
->find();
if (!empty($cksrs)) {
$this->error('手机号码已存在');
}
$result = false;
//关联经纪人信息
$agent = Db::name('agent_users')
->where(['jjr_mobile' => $params['catname']])
->find();
$params['user_id'] = $agent['user_id'];
$params['jjr_name'] = $agent['jjr_name'];
$params['userno'] = $agent['userno'];
Db::startTrans();
try {
//是否采用模型验证
if ($this->modelValidate) {
$name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
$row->validateFailException(true)->validate($validate);
}
$result = $row->allowField(true)->save($params);
Db::commit();
} catch (ValidateException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (PDOException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($result !== false) {
$this->success();
} else {
$this->error(__('No rows were updated'));
}
}
$this->error(__('Parameter %s can not be empty', ''));
}
$this->view->assign("row", $row);
return $this->view->fetch();
}
}
... ...
<?php
namespace app\admin\controller\wechat;
use app\common\controller\Backend;
use app\admin\model\WechatResponse;
/**
* 微信自动回复管理
*
* @icon fa fa-circle-o
*/
class Autoreply extends Backend
{
protected $model = null;
protected $noNeedRight = ['check_text_unique'];
public function _initialize()
{
parent::_initialize();
$this->model = model('WechatAutoreply');
}
/**
* 编辑
*/
public function edit($ids = null)
{
$row = $this->model->get(['id' => $ids]);
if (!$row) {
$this->error(__('No Results were found'));
}
if ($this->request->isPost()) {
$params = $this->request->post("row/a");
if ($params) {
$row->save($params);
$this->success();
}
$this->error();
}
$response = WechatResponse::get(['eventkey' => $row['eventkey']]);
$this->view->assign("response", $response);
$this->view->assign("row", $row);
return $this->view->fetch();
}
/**
* 判断文本是否唯一
* @internal
*/
public function check_text_unique()
{
$row = $this->request->post("row/a");
$except = $this->request->post("except");
$text = isset($row['text']) ? $row['text'] : '';
if ($this->model->where('text', $text)->where(function ($query) use ($except) {
if ($except) {
$query->where('text', '<>', $except);
}
})->count() == 0) {
$this->success();
} else {
$this->error(__('Text already exists'));
}
}
}
... ...
<?php
namespace app\admin\controller\wechat;
use app\common\controller\Backend;
use think\Controller;
use think\Request;
/**
* 微信配置管理
*
* @icon fa fa-circle-o
*/
class Config extends Backend
{
protected $model = null;
public function _initialize()
{
parent::_initialize();
$this->model = model('WechatConfig');
}
/**
* 添加
*/
public function add()
{
if ($this->request->isPost()) {
$params = $this->request->post("row/a");
if ($params) {
foreach ($params as $k => &$v) {
$v = is_array($v) ? implode(',', $v) : $v;
}
if ($params['mode'] == 'json') {
//JSON字段
$fieldarr = $valuearr = [];
$field = $this->request->post('field/a');
$value = $this->request->post('value/a');
foreach ($field as $k => $v) {
if ($v != '') {
$fieldarr[] = $field[$k];
$valuearr[] = $value[$k];
}
}
$params['value'] = json_encode(array_combine($fieldarr, $valuearr), JSON_UNESCAPED_UNICODE);
}
unset($params['mode']);
try {
//是否采用模型验证
if ($this->modelValidate) {
$name = basename(str_replace('\\', '/', get_class($this->model)));
$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
$this->model->validate($validate);
}
$result = $this->model->save($params);
if ($result !== false) {
$this->success();
} else {
$this->error($this->model->getError());
}
} catch (\think\exception\PDOException $e) {
$this->error($e->getMessage());
}
}
$this->error(__('Parameter %s can not be empty', ''));
}
return $this->view->fetch();
}
/**
* 编辑
*/
public function edit($ids = null)
{
$row = $this->model->get($ids);
if (!$row) {
$this->error(__('No Results were found'));
}
if ($this->request->isPost()) {
$params = $this->request->post("row/a");
if ($params) {
foreach ($params as $k => &$v) {
$v = is_array($v) ? implode(',', $v) : $v;
}
if ($params['mode'] == 'json') {
//JSON字段
$fieldarr = $valuearr = [];
$field = $this->request->post('field/a');
$value = $this->request->post('value/a');
foreach ($field as $k => $v) {
if ($v != '') {
$fieldarr[] = $field[$k];
$valuearr[] = $value[$k];
}
}
$params['value'] = json_encode(array_combine($fieldarr, $valuearr), JSON_UNESCAPED_UNICODE);
}
unset($params['mode']);
try {
//是否采用模型验证
if ($this->modelValidate) {
$name = basename(str_replace('\\', '/', get_class($this->model)));
$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
$row->validate($validate);
}
$result = $row->save($params);
if ($result !== false) {
$this->success();
} else {
$this->error($row->getError());
}
} catch (\think\exception\PDOException $e) {
$this->error($e->getMessage());
}
}
$this->error(__('Parameter %s can not be empty', ''));
}
$this->view->assign("row", $row);
$this->view->assign("value", (array)json_decode($row->value, true));
return $this->view->fetch();
}
}
... ...
<?php
namespace app\admin\controller\wechat;
use addons\wechat\library\Config;
use app\common\controller\Backend;
use app\admin\model\WechatResponse;
use EasyWeChat\Factory;
use think\Exception;
/**
* 菜单管理
*
* @icon fa fa-list-alt
*/
class Menu extends Backend
{
protected $wechatcfg = null;
public function _initialize()
{
parent::_initialize();
$this->wechatcfg = \app\admin\model\WechatConfig::get(['name' => 'menu']);
}
/**
* 查看
*/
public function index()
{
$responselist = array();
$all = WechatResponse::all();
foreach ($all as $k => $v) {
$responselist[$v['eventkey']] = $v['title'];
}
$this->view->assign('responselist', $responselist);
$this->view->assign('menu', (array)json_decode($this->wechatcfg->value, true));
return $this->view->fetch();
}
/**
* 修改
*/
public function edit($ids = null)
{
$menu = $this->request->post("menu");
$menu = (array)json_decode($menu, true);
foreach ($menu as $index => &$item) {
if (isset($item['sub_button'])) {
foreach ($item['sub_button'] as &$subitem) {
if ($subitem['type'] == 'view') {
$allowFields = ['type', 'name', 'url'];
$subitem = ['type' => $subitem['type'], 'name' => $subitem['name'], 'url' => $subitem['url']];
} else {
if ($subitem['type'] == 'miniprogram') {
$allowFields = ['type', 'name', 'url', 'appid', 'pagepath'];
$subitem = ['type' => $subitem['type'], 'name' => $subitem['name'], 'url' => $subitem['url'], 'appid' => $subitem['appid'], 'pagepath' => $subitem['pagepath']];
} else {
$allowFields = ['type', 'name', 'key'];
$subitem = ['type' => $subitem['type'], 'name' => $subitem['name'], 'key' => $subitem['key']];
}
}
$subitem = array_intersect_key($subitem, array_flip($allowFields));
}
} else {
if ($item['type'] == 'view') {
$allowFields = ['type', 'name', 'url'];
} else {
if ($item['type'] == 'miniprogram') {
$allowFields = ['type', 'name', 'url', 'appid', 'pagepath'];
} else {
$allowFields = ['type', 'name', 'key'];
}
}
$item = array_intersect_key($item, array_flip($allowFields));
}
}
$this->wechatcfg->value = json_encode($menu, JSON_UNESCAPED_UNICODE);
$this->wechatcfg->save();
$this->success();
}
/**
* 加载远程菜单
*/
public function remote()
{
$app = Factory::officialAccount(Config::load());
try {
$list = $app->menu->list();
} catch (\Exception $e) {
$this->error($e->getMessage());
}
if (isset($list['menu']['button'])) {
$buttons = $list['menu']['button'];
foreach ($buttons as $index => &$item) {
if (isset($item['sub_button'])) {
if ($item['sub_button']) {
foreach ($item['sub_button'] as $key => &$value) {
if (!isset($value['sub_button']) || !$value['sub_button']) {
unset($value['sub_button']);
}
}
} else {
unset($item['sub_button']);
}
}
}
$this->wechatcfg->value = json_encode($buttons, JSON_UNESCAPED_UNICODE);
$this->wechatcfg->save();
$this->success();
} else {
$this->error("加载菜单失败");
}
}
/**
* 同步到服务器
*/
public function sync($ids = null)
{
$app = Factory::officialAccount(Config::load());
try {
$hasError = false;
$menu = json_decode($this->wechatcfg->value, true);
foreach ($menu as $k => $v) {
if (isset($v['sub_button'])) {
foreach ($v['sub_button'] as $m => $n) {
if ($n['type'] == 'click' && isset($n['key']) && !$n['key']) {
$hasError = true;
break 2;
}
}
} else {
if ($v['type'] == 'click' && isset($v['key']) && !$v['key']) {
$hasError = true;
break;
}
}
}
if (!$hasError) {
try {
$ret = $app->menu->create($menu);
} catch (\Exception $e) {
$this->error($e->getMessage());
}
if ($ret['errcode'] == 0) {
$this->success();
} else {
$this->error($ret['errmsg']);
}
} else {
$this->error(__('Invalid parameters'));
}
} catch (Exception $e) {
$this->error($e->getMessage());
}
}
}
... ...
<?php
namespace app\admin\controller\wechat;
use app\common\controller\Backend;
use addons\wechat\library\Wechat;
/**
* 资源管理
*
* @icon fa fa-list-alt
*/
class Response extends Backend
{
protected $model = null;
protected $searchFields = 'id,title';
public function _initialize()
{
parent::_initialize();
$this->model = model('WechatResponse');
}
/**
* 选择素材
*/
public function select()
{
return $this->view->fetch();
}
/**
* 添加
*/
public function add()
{
if ($this->request->isPost()) {
$params = $this->request->post("row/a");
$params['eventkey'] = isset($params['eventkey']) && $params['eventkey'] ? $params['eventkey'] : uniqid();
$params['content'] = json_encode($params['content']);
$params['createtime'] = time();
if ($params) {
$this->model->save($params);
$this->success();
$this->content = $params;
}
$this->error();
}
$appConfig = Wechat::appConfig();
$this->view->applist = $appConfig;
return $this->view->fetch();
}
/**
* 编辑
*/
public function edit($ids = NULL)
{
$row = $this->model->get($ids);
if (!$row)
$this->error(__('No Results were found'));
if ($this->request->isPost()) {
$params = $this->request->post("row/a");
$params['eventkey'] = isset($params['eventkey']) && $params['eventkey'] ? $params['eventkey'] : uniqid();
$params['content'] = json_encode($params['content']);
if ($params) {
$row->save($params);
$this->success();
}
$this->error();
}
$this->view->assign("row", $row);
$appConfig = Wechat::appConfig();
$this->view->applist = $appConfig;
return $this->view->fetch();
}
}
... ...
<?php
return [
'Text' => '文本',
'Event key' => '响应标识',
'Remark' => '备注',
'Text already exists' => '文本已经存在',
];
... ...
<?php
return [
'name' => '配置名称',
'value' => '配置值',
'Json key' => '键',
'Json value' => '值',
'Json editor' => 'JSON编辑器',
'Insert link' => '插入链接',
'createtime' => '创建时间',
'updatetime' => '更新时间'
];
... ...
<?php
return [
'Resource title' => '资源标题',
'Event key' => '事件标识',
'Event' => '事件标识',
'Text' => '文本',
'App' => '应用',
];
... ...
<?php
namespace app\admin\model;
use think\Model;
class WechatAutoreply extends Model
{
// 自动写入时间戳字段
protected $autoWriteTimestamp = 'int';
// 定义时间戳字段名
protected $createTime = 'createtime';
protected $updateTime = 'updatetime';
}
... ...
<?php
namespace app\admin\model;
use fast\Random;
use think\Model;
class WechatCaptcha extends Model
{
// 表名
protected $name = 'wechat_captcha';
// 自动写入时间戳字段
protected $autoWriteTimestamp = 'int';
// 定义时间戳字段名
protected $createTime = 'createtime';
protected $updateTime = '';
// 追加属性
protected $append = [
];
/**
* 发送验证码
* @param $openid string 用户OpenID
* @param $event string 事件
* @param $ip string IP地址
* @return string
*/
public static function send($openid, $event, $ip)
{
$captcha = self::where(['openid' => $openid, 'event' => $event])->whereTime('createtime', '-2 minutes')->find();
if ($captcha) {
return "验证码发送速度过快,请稍后重试";
}
$code = Random::alnum(4);
$data = [
'event' => $event,
'openid' => $openid,
'code' => $code,
'ip' => $ip,
];
self::create($data);
return "你的验证码是:{$code},2分钟内输入有效";
}
/**
* 检测验证码
* @param $code string 验证码
* @param $event string 事件
* @param $ip string IP
* @return bool
*/
public static function check($code, $event, $ip = null)
{
$ip = is_null($ip) ? request()->ip() : $ip;
$captcha = self::where(['ip' => $ip, 'event' => $event])->whereTime('createtime', '-2 minutes')->find();
if ($captcha && $captcha->code == $code && $captcha->times < 10) {
$captcha->setInc("times");
return true;
}
//验证大于10次或超时
if ($captcha && ($captcha->times >= 10 || time() - $captcha->createtime > 120)) {
$captcha->delete();
}
return false;
}
}
... ...
<?php
namespace app\admin\model;
use think\Model;
class WechatConfig extends Model
{
// 表名,不含前缀
public $name = 'wechat_config';
// 自动写入时间戳字段
protected $autoWriteTimestamp = 'int';
// 定义时间戳字段名
protected $createTime = 'createtime';
protected $updateTime = 'updatetime';
// 追加属性
protected $append = [
];
/**
* 读取指定配置名称的值
* @param string $name
* @return string
*/
public static function value($name)
{
$item = self::get(['name' => $name]);
return $item ? $item->value : '';
}
}
... ...
<?php
namespace app\admin\model;
use think\Model;
class WechatContext extends Model
{
// 自动写入时间戳字段
protected $autoWriteTimestamp = 'int';
// 定义时间戳字段名
protected $createTime = 'createtime';
protected $updateTime = 'updatetime';
}
... ...
<?php
namespace app\admin\model;
use think\Model;
class WechatResponse extends Model
{
// 自动写入时间戳字段
protected $autoWriteTimestamp = 'int';
// 定义时间戳字段名
protected $createTime = 'createtime';
protected $updateTime = 'updatetime';
}
... ...
<link href="__CDN__/assets/addons/wechat/css/menu.css?v={$site.version}" rel="stylesheet">
<style>
.clickbox {margin:0;text-align: left;}
.create-click {
margin-left:0;
}
</style>
<form id="add-form" class="form-horizontal form-ajax" role="form" data-toggle="validator" method="POST" action="">
<div class="form-group">
<label for="c-title" class="control-label col-xs-12 col-sm-2">{:__('Title')}:</label>
<div class="col-xs-12 col-sm-8">
<input type="text" name="row[title]" value="" id="c-title" class="form-control" data-rule="required" />
</div>
</div>
<div class="form-group">
<label for="c-text" class="control-label col-xs-12 col-sm-2">{:__('Text')}:</label>
<div class="col-xs-12 col-sm-8">
<input type="text" name="row[text]" value="" id="c-text" class="form-control" data-rule="required; remote(wechat/autoreply/check_text_unique)" />
</div>
</div>
<div class="form-group">
<label for="c-eventkey" class="control-label col-xs-12 col-sm-2">{:__('Event key')}:</label>
<div class="col-xs-12 col-sm-8">
<input type="hidden" name="row[eventkey]" id="c-eventkey" class="form-control" value="" data-rule="required" readonly />
<div class="clickbox">
<span class="create-click"><a href="{:url('wechat.response/select')}" id="select-resources"><i class="weixin-icon big-add-gray"></i><strong>选择现有资源</strong></a></span>
<span class="create-click"><a href="{:url('wechat.response/add')}" id="add-resources"><i class="weixin-icon big-add-gray"></i><strong>添加新资源</strong></a></span>
</div>
</div>
</div>
<div class="form-group">
<label for="c-remark" class="control-label col-xs-12 col-sm-2">{:__('Remark')}:</label>
<div class="col-xs-12 col-sm-8">
<input type="text" name="row[remark]" value="" id="c-remark" class="form-control" />
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Status')}:</label>
<div class="col-xs-12 col-sm-8">
{:build_radios('row[status]', ['normal'=>__('Normal'), 'hidden'=>__('Hidden')])}
</div>
</div>
<div class="form-group hide layer-footer">
<label class="control-label col-xs-12 col-sm-2"></label>
<div class="col-xs-12 col-sm-8">
<button type="submit" class="btn btn-success btn-embossed disabled">{:__('OK')}</button>
<button type="reset" class="btn btn-default btn-embossed">{:__('Reset')}</button>
</div>
</div>
</form>
... ...
<link href="__CDN__/assets/addons/wechat/css/menu.css?v={$site.version}" rel="stylesheet">
<style>
.clickbox {margin:0;text-align: left;}
.create-click {
margin-left:0;
}
</style>
<form id="edit-form" class="form-horizontal form-ajax" role="form" data-toggle="validator" method="POST" action="">
<div class="form-group">
<label for="c-title" class="control-label col-xs-12 col-sm-2">{:__('Title')}:</label>
<div class="col-xs-12 col-sm-8">
<input type="text" name="row[title]" value="{$row.title}" id="c-title" class="form-control" data-rule="required" />
</div>
</div>
<div class="form-group">
<label for="c-text" class="control-label col-xs-12 col-sm-2">{:__('Text')}:</label>
<div class="col-xs-12 col-sm-8">
<input type="text" name="row[text]" value="{$row.text}" id="c-text" class="form-control" data-rule="required; remote(wechat/autoreply/check_text_unique, except={$row.text})" />
</div>
</div>
<div class="form-group">
<label for="c-eventkey" class="control-label col-xs-12 col-sm-2">{:__('Content')}:</label>
<div class="col-xs-12 col-sm-8">
<div class="clickbox">
<input type="hidden" name="row[eventkey]" id="c-eventkey" class="form-control" value="{$row.eventkey}" data-rule="required" readonly />
<span class="create-click"><a href="wechat/response/select" id="select-resources"><i class="weixin-icon big-add-gray"></i><strong>选择现有资源</strong></a><div class="keytitle">资源名:{:$response['title']}</div></span>
<span class="create-click"><a href="wechat/response/add" id="add-resources"><i class="weixin-icon big-add-gray"></i><strong>添加新资源</strong></a></span>
</div>
</div>
</div>
<div class="form-group">
<label for="c-remark" class="control-label col-xs-12 col-sm-2">{:__('Remark')}:</label>
<div class="col-xs-12 col-sm-8">
<input type="text" name="row[remark]" value="{$row.remark}" id="c-remark" class="form-control" />
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Status')}:</label>
<div class="col-xs-12 col-sm-8">
{:build_radios('row[status]', ['normal'=>__('Normal'), 'hidden'=>__('Hidden')], $row['status'])}
</div>
</div>
<div class="form-group hide layer-footer">
<label class="control-label col-xs-12 col-sm-2"></label>
<div class="col-xs-12 col-sm-8">
<button type="submit" class="btn btn-success btn-embossed disabled">{:__('OK')}</button>
<button type="reset" class="btn btn-default btn-embossed">{:__('Reset')}</button>
</div>
</div>
</form>
... ...
<div class="panel panel-default panel-intro">
{:build_heading()}
<div class="panel-body">
<div id="myTabContent" class="tab-content">
<div class="tab-pane fade active in" id="one">
<div class="widget-body no-padding">
<div id="toolbar" class="toolbar">
{:build_toolbar()}
<div class="dropdown btn-group {:$auth->check('wechat/autoreply/multi')?'':'hide'}">
<a class="btn btn-primary btn-more dropdown-toggle btn-disabled disabled" data-toggle="dropdown"><i class="fa fa-cog"></i> <?= __('More') ?></a>
<ul class="dropdown-menu text-left" role="menu">
<li><a class="btn btn-link btn-multi btn-disabled disabled" href="javascript:;" data-params="status=normal"><i class="fa fa-eye"></i> {:__('Set to normal')}</a></li>
<li><a class="btn btn-link btn-multi btn-disabled disabled" href="javascript:;" data-params="status=hidden"><i class="fa fa-eye-slash"></i> {:__('Set to hidden')}</a></li>
</ul>
</div>
</div>
<table id="table" class="table table-striped table-bordered table-hover"
data-operate-edit="{:$auth->check('wechat/autoreply/edit')}"
data-operate-del="{:$auth->check('wechat/autoreply/del')}"
width="100%">
</table>
</div>
</div>
</div>
</div>
</div>
... ...
<form id="add-form" class="form-horizontal" role="form" data-toggle="validator" method="POST" action="">
<input type="hidden" name="row[mode]" value="textarea" />
<div class="form-group">
<label for="c-name" class="control-label col-xs-12 col-sm-2">{:__('Name')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-name" data-rule="required" class="form-control" name="row[name]" type="text" value="">
</div>
</div>
<div class="form-group">
<label for="c-title" class="control-label col-xs-12 col-sm-2">{:__('Title')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-title" data-rule="required" class="form-control" name="row[title]" type="text" value="">
</div>
</div>
<div class="form-group">
<label for="c-value" class="control-label col-xs-12 col-sm-2">{:__('Value')}:</label>
<div class="col-xs-12 col-sm-8">
<p>
<a href="javascript:;" class="btn btn-info btn-jsoneditor"><i class="fa fa-pencil"></i> {:__('Json editor')}</a>
<a href="javascript:;" class="btn btn-primary btn-insertlink"><i class="fa fa-link"></i> {:__('Insert link')}</a>
</p>
<textarea id="c-value" class="form-control " rows="15" name="row[value]"></textarea>
<dl class="fieldlist hide" rel="1">
<dd>
<ins>{:__('Json key')}</ins>
<ins>{:__('Json value')}</ins>
</dd>
<dd>
<input type="text" name="field[0]" class="form-control" id="field-0" value="" size="10" required />
<input type="text" name="value[0]" class="form-control" id="value-0" value="" size="40" required />
<span class="btn btn-sm btn-danger btn-remove"><i class="fa fa-times"></i></span>
<span class="btn btn-sm btn-primary btn-dragsort"><i class="fa fa-arrows"></i></span>
</dd>
<dd><a href="javascript:;" class="append btn btn-sm btn-success"><i class="fa fa-plus"></i> {:__('Append')}</a></dd>
</dl>
</div>
</div>
<div class="form-group hide layer-footer">
<label class="control-label col-xs-12 col-sm-2"></label>
<div class="col-xs-12 col-sm-8">
<button type="submit" class="btn btn-success btn-embossed disabled">{:__('OK')}</button>
<button type="reset" class="btn btn-default btn-embossed">{:__('Reset')}</button>
</div>
</div>
</form>
... ...
<form id="edit-form" class="form-horizontal" role="form" data-toggle="validator" method="POST" action="">
<input type="hidden" name="row[mode]" value="textarea" />
<div class="form-group">
<label for="c-name" class="control-label col-xs-12 col-sm-2">{:__('Name')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-name" data-rule="required" class="form-control" name="row[name]" type="text" value="{$row.name}">
</div>
</div>
<div class="form-group">
<label for="c-title" class="control-label col-xs-12 col-sm-2">{:__('Title')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-title" data-rule="required" class="form-control" name="row[title]" type="text" value="{$row.title}">
</div>
</div>
<div class="form-group">
<label for="c-value" class="control-label col-xs-12 col-sm-2">{:__('Value')}:</label>
<div class="col-xs-12 col-sm-8">
<textarea id="c-value" class="form-control " rows="15" name="row[value]">{$row.value}</textarea>
</div>
</div>
<div class="form-group hide layer-footer">
<label class="control-label col-xs-12 col-sm-2"></label>
<div class="col-xs-12 col-sm-8">
<button type="submit" class="btn btn-success btn-embossed disabled">{:__('OK')}</button>
<button type="reset" class="btn btn-default btn-embossed">{:__('Reset')}</button>
</div>
</div>
</form>
... ...
<div class="panel panel-default panel-intro">
{:build_heading()}
<div class="panel-body">
<div id="myTabContent" class="tab-content">
<div class="tab-pane fade active in" id="one">
<div class="widget-body no-padding">
<div id="toolbar" class="toolbar">
{:build_toolbar()}
<div class="dropdown btn-group {:$auth->check('wechat/config/multi')?'':'hide'}">
<a class="btn btn-primary btn-more dropdown-toggle btn-disabled disabled" data-toggle="dropdown"><i class="fa fa-cog"></i> {:__('More')}</a>
<ul class="dropdown-menu text-left" role="menu">
<li><a class="btn btn-link btn-multi btn-disabled disabled" href="javascript:;" data-params="status=normal"><i class="fa fa-eye"></i> {:__('Set to normal')}</a></li>
<li><a class="btn btn-link btn-multi btn-disabled disabled" href="javascript:;" data-params="status=hidden"><i class="fa fa-eye-slash"></i> {:__('Set to hidden')}</a></li>
</ul>
</div>
</div>
<table id="table" class="table table-striped table-bordered table-hover"
data-operate-edit="{:$auth->check('wechat/config/edit')}"
data-operate-del="{:$auth->check('wechat/config/del')}"
width="100%">
</table>
</div>
</div>
</div>
</div>
</div>
... ...
<link href="__CDN__/assets/addons/wechat/css/menu.css?v={$site['version']}" rel="stylesheet"/>
<style>
.form-item dl dt {
width: 120px;
}
.form-item dl dd {
margin-left: 120px;
}
.form-item dl dd input {
font-size: 12px;
}
</style>
<div class="panel panel-default panel-intro">
{:build_heading()}
<div class="panel-body">
<div id="myTabContent" class="tab-content">
<div class="tab-pane fade active in" id="one">
<div class="widget-body no-padding">
<div class="weixin-menu-setting clearfix">
<div class="mobile-menu-preview">
<div class="mobile-head-title">{$site.name}</div>
<ul class="menu-list" id="menu-list">
</ul>
</div>
<div class="weixin-body">
<div class="weixin-content" style="display:none">
<div class="item-info">
<form id="form-item" class="form-item" data-value="">
<div class="item-head">
<h4 id="current-item-name">添加子菜单</h4>
<div class="item-delete"><a href="javascript:;" id="item_delete">删除菜单</a></div>
</div>
<div style="margin-top: 20px;" id="item-body">
</div>
</form>
</div>
</div>
<div class="no-weixin-content">
点击左侧菜单进行编辑操作
</div>
</div>
</div>
<div class="text-center" style="position:relative;">
<div class="text-danger" style="width:317px;position:absolute;left:0;top:0;">
<i class="fa fa-lightbulb-o"></i> <small>可直接拖动菜单排序</small>
</div>
<div style="padding-left:337px;">
<a href="javascript:;" id="menuRemote" class="btn btn-success"><i class="fa fa-cloud-download"></i> 加载服务端菜单</a>
<a href="javascript:;" id="menuSyn" class="btn btn-danger"><i class="fa fa-check"></i> 保存并发布</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/html" id="menutpl">
<%for(var i=0; i< menu.length; i++){%>
<%var first=menu[i];%>
<li id="menu-<%=i%>" class="menu-item" data-type="<%=first['type']%>" data-key="<%=first['key']%>" data-name="<%=first['name']%>" data-url="<%=first['url']%>" data-appid="<%=first['appid']%>" data-pagepath="<%=first['pagepath']%>">
<a href="javascript:;" class="menu-link">
<i class="icon-menu-dot"></i> <i class="weixin-icon sort-gray"></i> <span class="title"><%=first['name']%></span>
</a>
<div class="sub-menu-box" style="display:none;">
<ul class="sub-menu-list">
<%if(typeof first['sub_button']!='undefined'){%>
<%for(var j=0; j< first['sub_button'].length; j++){%>
<%var second=first['sub_button'][j];%>
<li id="sub-menu-<%=j%>" class="sub-menu-item" data-type="<%=second['type']%>" data-key="<%=second['key']%>" data-name="<%=second['name']%>" data-url="<%=second['url']%>" data-appid="<%=second['appid']%>" data-pagepath="<%=second['pagepath']%>"><a href="javascript:;"> <i class="weixin-icon sort-gray"></i><span class="sub-title"><%=second['name']%></span></a></li>
<%}%>
<%}%>
<li class="add-sub-item <%if(typeof first['sub_button']!='undefined' && first['sub_button'].length>=5){%>hidden<%}%>"><a href="javascript:;" title="添加子菜单"><span class=" "><i class="weixin-icon add-gray"></i></span></a></li>
</ul>
<i class="arrow arrow-out"></i> <i class="arrow arrow-in"></i>
</div>
</li>
<%}%>
<li class="add-item extra" id="add-item">
<a href="javascript:;" class="menu-link" title="添加菜单"><i class="weixin-icon add-gray"></i></a>
</li>
</script>
<script type="text/html" id="itemtpl">
<dl>
<dt id="current-item-option"><span class="is-sub-item <%=first?'hidden':''%>"></span>菜单标题:</dt>
<dd>
<div class="input-box"><input id="item_title" name="name" type="text" value="<%=name%>"></div>
</dd>
</dl>
<%if(!hasChild){%>
<dl class="is-item">
<dt id="current-item-type"><span class="is-sub-item <%=first?'hidden':''%>"></span>菜单内容:</dt>
<dd>
<%for(var i=0;i< typeList.length; i++){%>
<input id="type<%=i%>" type="radio" name="type" value="<%=typeList[i]['name']%>" <%=typeList[i]['name']==type?'checked':''%> /><label for="type<%=i%>"><span class="lbl_content"><%=typeList[i]['title']%></span></label>
<%}%>
</dd>
</dl>
<div id="menu-content" class="is-item">
<%if(type=='view'){%>
<div class="viewbox is-view">
<p class="menu-content-tips">点击该<span class="is-sub-item <%=first?'hidden':''%>"></span>菜单会跳到以下链接</p>
<dl>
<dt>页面地址:</dt>
<dd>
<div class="input-box"><input type="text" name="url" value="<%=url%>"></div>
</dd>
</dl>
</div>
<%}%>
<%if(type!='view'&&type!='miniprogram'){%>
<div class="clickbox is-click">
<input type="hidden" name="key" id="key" value="<%=key%>"/>
<span class="create-click">
<%if(keytitle){%>
<div class="keytitle">资源名:<%=keytitle%></div>
<%}%>
<a href="{:url('wechat.response/select')}" id="select-resources"><i class="weixin-icon big-add-gray"></i><strong>选择现有资源</strong></a>
</span>
<span class="create-click">
<a href="{:url('wechat.response/add')}" id="add-resources"><i class="weixin-icon big-add-gray"></i><strong>添加新资源</strong></a>
</span>
</div>
<%}%>
<%if(type=='miniprogram'){%>
<div class="viewbox is-miniprogram">
<p class="menu-content-tips">点击该<span class="is-sub-item <%=first?'':'hidden'%>"></span>菜单会跳到以下小程序</p>
<dl>
<dt>小程序ID</dt>
<dd>
<div class="input-box"><input type="text" id="appid" name="appid" placeholder="在小程序后台获取" value="<%=appid%>"></div>
</dd>
</dl>
<dl>
<dt>小程序页面路径:</dt>
<dd>
<div class="input-box"><input type="text" id="pagepath" name="pagepath" placeholder="小程序页面路径" value="<%=pagepath%>"></div>
</dd>
</dl>
<dl>
<dt>页面地址:</dt>
<dd>
<div class="input-box"><input type="text" name="url" placeholder="页面地址,当不支持小程序时会跳转此页面" value="<%=url%>"></div>
</dd>
</dl>
</div>
<%}%>
</div>
<%}%>
</script>
<!--@formatter:off-->
<script type="text/javascript">
var menu = {:json_encode($menu, JSON_UNESCAPED_UNICODE)};
var responselist = {:json_encode($responselist, JSON_UNESCAPED_UNICODE)};
</script>
<!--@formatter:on-->
... ...
<form id="add-form" class="form-horizontal form-ajax" role="form" data-toggle="validator" method="POST" action="">
<div class="form-group">
<label for="module" class="control-label col-xs-12 col-sm-2">{:__('Resource title')}:</label>
<div class="col-xs-12 col-sm-8">
<input type="text" class="form-control" id="title" name="row[title]" value="" data-rule="required" />
</div>
</div>
<div class="form-group">
<label for="remark" class="control-label col-xs-12 col-sm-2">{:__('Memo')}:</label>
<div class="col-xs-12 col-sm-8">
<textarea class="form-control" id="remark" name="row[remark]"></textarea>
</div>
</div>
<div class="form-group">
<label for="content" class="control-label col-xs-12 col-sm-2">{:__('Type')}:</label>
<div class="col-xs-12 col-sm-8">
<input type="radio" name="row[type]" value="text" id="type-text" checked />
<label for="type-text">{:__('Text')}</label>
<input type="radio" name="row[type]" value="app" id="type-app" />
<label for="type-app">{:__('App')}</label>
</div>
</div>
<div id="expand">
</div>
<div class="form-group">
<label for="status" class="control-label col-xs-12 col-sm-2">{:__('Status')}:</label>
<div class="col-xs-12 col-sm-8">
{:build_radios('row[status]', ['normal'=>__('Normal'), 'hidden'=>__('Hidden')])}
</div>
</div>
<div class="form-group {:input('get.callback')?'':'hidden layer-footer'}">
<div class="col-xs-2"></div>
<div class="col-xs-12 col-sm-8">
<button type="submit" class="btn btn-success btn-embossed disabled">{:__('OK')}</button>
<button type="reset" class="btn btn-default btn-embossed">{:__('Reset')}</button>
</div>
</div>
<select name="applist" disabled="true" class="hidden">
{foreach $applist as $k => $v}
<option value="{$k}">{$v.name}</option>
{/foreach}
</select>
</form>
<script>
var apps = {:json_encode($applist)};
var datas = {};
</script>
\ No newline at end of file
... ...
<form id="edit-form" class="form-horizontal form-ajax" role="form" data-toggle="validator" method="POST" action="">
<div class="form-group">
<label for="module" class="control-label col-xs-12 col-sm-2">{:__('Resource title')}:</label>
<div class="col-xs-12 col-sm-8">
<input type="text" class="form-control" id="title" name="row[title]" value="{$row.title}" data-rule="required" />
</div>
</div>
<div class="form-group">
<label for="controller" class="control-label col-xs-12 col-sm-2">{:__('Event key')}:</label>
<div class="col-xs-12 col-sm-8">
<input type='text' class="form-control" id="eventkey" name="row[eventkey]" value="{$row.eventkey}" data-rule="required" readonly />
</div>
</div>
<div class="form-group">
<label for="remark" class="control-label col-xs-12 col-sm-2">{:__('Memo')}:</label>
<div class="col-xs-12 col-sm-8">
<textarea class="form-control" id="remark" name="row[remark]">{$row.remark}</textarea>
</div>
</div>
<div class="form-group">
<label for="content" class="control-label col-xs-12 col-sm-2">{:__('Type')}:</label>
<div class="col-xs-12 col-sm-8">
{:build_radios('row[type]', ['text' => __('Text'), 'app' => __('App')], $row['type'])}
</div>
</div>
<div id="expand">
</div>
<div class="form-group">
<div class="col-xs-2"></div>
<div class="col-xs-12 col-sm-8">
{:build_radios('row[status]', ['normal'=>__('Normal'), 'hidden'=>__('Hidden')], $row['status'])}
</div>
</div>
<div class="form-group hidden layer-footer">
<div class="col-xs-2"></div>
<div class="col-xs-12 col-sm-8">
<button type="submit" class="btn btn-success btn-embossed disabled">{:__('OK')}</button>
<button type="reset" class="btn btn-default btn-embossed">{:__('Reset')}</button>
</div>
</div>
<select name="applist" disabled="true" class="hidden">
{foreach $applist as $k => $v}
<option value="{$k}">{$v.name}</option>
{/foreach}
</select>
</form>
<script>
var apps = {:json_encode($applist)};
var datas = {$row.content};
</script>
\ No newline at end of file
... ...
<div class="panel panel-default panel-intro">
{:build_heading()}
<div class="panel-body">
<div id="myTabContent" class="tab-content">
<div class="tab-pane fade active in" id="one">
<div class="widget-body no-padding">
<div id="toolbar" class="toolbar">
{:build_toolbar();}
</div>
<table id="table" class="table table-bordered table-hover"
data-operate-edit="{:$auth->check('wechat/response/edit')}"
data-operate-del="{:$auth->check('wechat/response/del')}"
width="100%">
</table>
</div>
</div>
</div>
</div>
</div>
... ...
<div class="panel panel-default panel-intro">
{:build_heading()}
<div class="panel-body">
<div id="myTabContent" class="tab-content">
<div class="tab-pane fade active in" id="one">
<div class="widget-body no-padding">
<table id="table" class="table table-bordered table-hover" width="100%">
</table>
</div>
</div>
</div>
</div>
</div>
... ...
... ... @@ -87,4 +87,76 @@ class Index extends Api
return $qrCodeData;
}
}
/***
* 公众号推送审核信息给经纪人
*/
public function senWxmsgToAgentUser($titdesc="", $remark="")
{
$wxopenid="o5ABA4yWDTLRTf3LkBMMHoV7XOvQ";
$sendInfo = array(
'first' => array('value' => urlencode($titdesc), 'color' => "#743A3A"),
'keyword1' => array('value' => urlencode(date('Y-m-d H:i:s', time())), 'color' => '#173177'),
'keyword2' => array('value' => urlencode('企业入驻'), 'color' => '#173177'),
'remark' => array('value' => urlencode($remark), 'color' => '#173177'),
);
if ($wxopenid) {
$config = get_addon_config('wechat');
$tourl = 'https://fdc.xp.yn.cn/h5/';
$ywt_appid = 'wx9f73637c6b8f2c47';
$pagepath = 'pages/home/index';
$res = $this->sendAstuWxMsgToAgent($sendInfo, $wxopenid, $tourl, $config['app_id'], $config['secret'], $ywt_appid, $pagepath);
return $res;
//file_put_contents("pcl_wct_send.log", date("Y-m-d H:i:s") . "1-2-" . json_encode($res, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
}
}
/**
* 微信公众号
* 经纪人审核 消息推送
*/
function sendAstuWxMsgToAgent($info, $openid, $tourl, $appid, $secret, $ywt_appid, $pagepath)
{
$myurl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;
$json_token = $this->http_request($myurl);
$access_tokens = json_decode($json_token, true);
print_r($access_tokens);return;
$access_token = $access_tokens['access_token'];
$template = array(
'touser' => $openid, //
'template_id' => 'zQaLnhEOQxdGOKJlDUAfEoNY4NTmNWy9a9vYzkZjGn8', //模板消息id 必须修改
'url' => $tourl, //点击链接
"miniprogram" => [
"appid" => $ywt_appid,
"pagepath" => $pagepath
],
'topcolor' => "#173177",
'data' => $info
);
$json_template = json_encode($template);
$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;
$json = http_request($url, urldecode($json_template));
$rs = json_decode($json, true);
return $rs;
}
function http_request($url, $data = array())
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
// 我们在POST数据哦!
curl_setopt($ch, CURLOPT_POST, 1);
// 把post的变量加上
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
}
... ...
define(['jquery', 'bootstrap', 'backend', 'form', 'table'], function ($, undefined, Backend, Form, Table) {
var Controller = {
index: function () {
// 初始化表格参数配置
Table.api.init({
extend: {
index_url: 'wechat/autoreply/index',
add_url: 'wechat/autoreply/add',
edit_url: 'wechat/autoreply/edit',
del_url: 'wechat/autoreply/del',
multi_url: 'wechat/autoreply/multi',
}
});
var table = $("#table");
// 初始化表格
table.bootstrapTable({
url: $.fn.bootstrapTable.defaults.extend.index_url,
sortName: 'id',
columns: [
[
{field: 'state', checkbox: true, },
{field: 'id', title: __('Id')},
{field: 'title', title: __('Title')},
{field: 'text', title: __('Text')},
{field: 'eventkey', title: __('Event key')},
{field: 'remark', title: __('Remark')},
{field: 'createtime', title: __('Create time'), formatter: Table.api.formatter.datetime, operate: 'RANGE', addclass: 'datetimerange', sortable: true},
{field: 'updatetime', title: __('Update time'), formatter: Table.api.formatter.datetime, operate: 'RANGE', addclass: 'datetimerange', sortable: true},
{field: 'status', title: __('Status'), formatter: Table.api.formatter.status},
{field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
]
]
});
// 为表格绑定事件
Table.api.bindevent(table);
},
add: function () {
Controller.api.bindevent();
},
edit: function () {
Controller.api.bindevent();
},
api: {
bindevent: function () {
Form.api.bindevent($("form[role=form]"));
var refreshkey = function (data) {
$("input[name='row[eventkey]']").val(data.eventkey).trigger("change");
Layer.closeAll();
var keytitle = data.title;
var cont = $(".clickbox .create-click:first");
$(".keytitle", cont).remove();
if (keytitle) {
cont.append('<div class="keytitle">' + __('Event key') + ':' + keytitle + '</div>');
}
};
$(document).on('click', "#select-resources", function () {
var key = $("input[name='row[eventkey]']").val();
parent.Backend.api.open($(this).attr("href") + "?key=" + key, __('Select'), {callback: refreshkey});
return false;
});
$(document).on('click', "#add-resources", function () {
parent.Backend.api.open($(this).attr("href") + "?key=", __('Add'), {callback: refreshkey});
return false;
});
}
}
};
return Controller;
});
\ No newline at end of file
... ...
define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {
var Controller = {
index: function () {
// 初始化表格参数配置
Table.api.init({
extend: {
index_url: 'wechat/config/index',
add_url: 'wechat/config/add',
edit_url: 'wechat/config/edit',
del_url: 'wechat/config/del',
multi_url: 'wechat/config/multi',
table: 'wechat_config',
}
});
var table = $("#table");
// 初始化表格
table.bootstrapTable({
url: $.fn.bootstrapTable.defaults.extend.index_url,
pk: 'id',
sortName: 'id',
columns: [
[
{field: 'state', checkbox: true},
{field: 'id', title: __('Id')},
{field: 'name', title: __('Name')},
{field: 'title', title: __('Title')},
{field: 'createtime', title: __('Createtime'), formatter: Table.api.formatter.datetime, operate: 'RANGE', addclass: 'datetimerange', sortable: true},
{field: 'updatetime', title: __('Updatetime'), formatter: Table.api.formatter.datetime, operate: 'RANGE', addclass: 'datetimerange', sortable: true},
{field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
]
]
});
// 为表格绑定事件
Table.api.bindevent(table);
},
add: function () {
Controller.api.bindevent();
},
edit: function () {
Controller.api.bindevent();
},
api: {
bindevent: function () {
Form.api.bindevent($("form[role=form]"));
$("input[name='row[type]']:checked").trigger("click");
}
}
};
return Controller;
});
\ No newline at end of file
... ...
define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'sortable'], function ($, undefined, Backend, Table, Form, Sortable) {
var Controller = {
index: function () {
var typeList = [
{name: "click", title: "发送消息"},
{name: "view", title: "跳转网页"},
{name: "miniprogram", title: "跳转小程序"},
{name: "scancode_push", title: "扫码推"},
{name: "scancode_waitmsg", title: "扫码推提示框"},
{name: "pic_sysphoto", title: "拍照发图"},
{name: "pic_photo_or_album", title: "拍照相册发图"},
{name: "pic_weixin", title: "相册发图"},
{name: "location_select", title: "地理位置选择"},
];
String.prototype.subByte = function (start, bytes) {
for (var i = start; bytes > 0; i++) {
var code = this.charCodeAt(i);
bytes -= code < 256 ? 1 : 2;
}
return this.slice(start, i + bytes)
};
//初始化菜单
$("#menu-list").prepend(Template("menutpl", {menu: menu}));
//拖动排序
new Sortable($("#menu-list")[0], {
draggable: 'li.menu-item',
onEnd: function () {
updateChangeMenu();
}
});
//子菜单拖动排序
$(".sub-menu-list").each(function () {
new Sortable(this, {
draggable: 'li.sub-menu-item',
onEnd: function () {
updateChangeMenu();
}
});
});
//添加主菜单
$(document).on('click', '#add-item', function () {
var menu_item_total = $(".menu-item").size();
if (menu_item_total < 3) {
var item = '<li class="menu-item" data-type="click" data-key="" data-name="添加菜单" > <a href="javascript:;" class="menu-link"> <i class="icon-menu-dot"></i> <i class="weixin-icon sort-gray"></i> <span class="title">添加菜单</span> </a> <div class="sub-menu-box" style=""> <ul class="sub-menu-list"><li class=" add-sub-item"><a href="javascript:;" title="添加子菜单"><span class=" "><i class="weixin-icon add-gray"></i></span></a></li> </ul> <i class="arrow arrow-out"></i> <i class="arrow arrow-in"></i> </div></li>';
var itemDom = $(item);
itemDom.insertBefore(this);
itemDom.trigger("click");
$("#item_title").focus().select();
$(".sub-menu-box", itemDom).show();
updateChangeMenu();
new Sortable($(".sub-menu-list", itemDom)[0], {draggable: 'li.sub-menu-item'});
}
});
//切换类型
$(document).on('change', 'input[name=type]', function () {
$(".sub-menu-item.current,.menu-item.current").data("type", $(this).val()).trigger("click");
});
//删除菜单
$(document).on('click', '#item_delete', function () {
var current = $("#menu-list li.current");
var prev = current.prev("li[data-type]");
var next = current.next("li[data-type]");
if (prev.size() == 0 && next.size() == 0 && $(".sub-menu-box", current).size() == 0) {
last = current.closest(".menu-item");
} else if (prev.size() > 0 || next.size() > 0) {
last = prev.size() > 0 ? prev : next;
} else {
last = null;
$(".weixin-content").hide();
$(".no-weixin-content").show();
}
if (current.hasClass("sub-menu-item")) {
$(".add-sub-item", current.parent()).removeClass("hidden");
}
current.remove();
if (last) {
last.trigger('click');
} else {
$("input[name='name']").val('');
}
updateChangeMenu();
});
//更新修改与变动
var updateChangeMenu = function () {
var item = $("#menu-list li.current");
var values = $("#form-item").serializeArray();
$.each(values, function (i, j) {
if (j.name == 'name') {
$(">a", item).html(j.value);
}
item.data(j.name, j.value);
});
menuUpdate();
};
//更新菜单数据
var menuUpdate = function () {
$.post("wechat/menu/edit", {menu: JSON.stringify(getMenuList())}, function (data) {
if (data['code'] == 1) {
} else {
Toastr.error(__('Operation failed'));
}
}, 'json');
};
//获取菜单数据
var getMenuList = function () {
var menus = [];
var sub_button = [];
var menu_i = 0;
var sub_menu_i = 0;
var item;
$("#menu-list li").each(function (i) {
item = $(this);
var name = item.data('name');
if (name != null) {
if (item.hasClass('menu-item')) {
sub_menu_i = 0;
if (item.find('.sub-menu-item').size() > 0) {
menus[menu_i] = {"name": name, "sub_button": "sub_button"}
} else {
menus[menu_i] = $(this).data();
}
if (menu_i > 0) {
menus[menu_i - 1]['sub_button'] = menus[menu_i - 1]['sub_button'] == "sub_button" ? sub_button : menus[menu_i - 1]['sub_button'];
}
sub_button = [];
menu_i++;
} else {
sub_button[sub_menu_i++] = $(this).data();
}
}
});
if (sub_button.length > 0) {
var len = menus.length;
menus[len - 1]['sub_button'] = sub_button;
}
return menus;
};
//添加子菜单
$(document).on('click', ".add-sub-item", function () {
var sub_menu_item_total = $(this).parent().find(".sub-menu-item").size();
if (sub_menu_item_total < 5) {
var item = '<li class="sub-menu-item" data-type="click" data-key="" data-name="添加子菜单"><a href="javascript:;"><span class=" "><i class="weixin-icon sort-gray"></i><span class="sub-title">添加子菜单</span></span></a></li>';
var itemDom = $(item);
itemDom.insertBefore(this);
itemDom.trigger("click");
$("#item_title").focus().select();
updateChangeMenu();
if (sub_menu_item_total == 4) {
$(this).addClass("hidden");
}
}
return false;
});
//主菜单子菜单点击事件
$(document).on('click', ".menu-item, .sub-menu-item", function () {
var hasChild = $(".sub-menu-item", this).size() > 0 ? true : false;
if ($(this).hasClass("sub-menu-item")) {
$("#menu-list li").removeClass('current');
} else {
$("#menu-list li").removeClass('current');
$("#menu-list > li").not(this).find(".sub-menu-box").hide();
$(".sub-menu-box", this).toggle();
}
$(this).addClass('current');
var data = $.extend({}, $(this).data());
data.keytitle = data.key && typeof responselist[data.key] != 'undefined' ? responselist[data.key] : '';
data.typeList = typeList;
data.hasChild = hasChild;
data.first = $(this).hasClass("menu-item") ? true : false;
$(".weixin-content").show();
$(".no-weixin-content").hide();
$("#item-body").html(Template("itemtpl", data));
return false;
});
//触发保存
$("form#form-item").on('change', "input,textarea", function () {
updateChangeMenu();
});
//加载远程菜单
$(document).on('click', "#menuRemote", function () {
Layer.confirm("确认加载远程微信服务端菜单?<br>本地菜单将会被覆盖!!!", {icon: 3}, function () {
$.post("wechat/menu/remote", {}, function (ret) {
var msg = ret.hasOwnProperty("msg") && ret.msg != "" ? ret.msg : "";
if (ret.code == 1) {
Layer.closeAll();
Layer.alert('远程菜单覆盖成功!点击确定刷新页面!', {icon: 1}, function () {
location.reload();
});
} else {
Backend.api.toastr.error(msg ? msg : __('Operation failed'));
}
}, 'json');
});
return false;
});
//点击同步
$(document).on('click', "#menuSyn", function () {
$.post("wechat/menu/sync", {}, function (ret) {
var msg = ret.hasOwnProperty("msg") && ret.msg != "" ? ret.msg : "";
if (ret.code == 1) {
Backend.api.toastr.success('菜单同步更新成功,生效时间请查看微信官网说明,或你重新关注公众号!');
} else {
Backend.api.toastr.error(msg ? msg : __('Operation failed'));
}
}, 'json');
});
//刷新资源
var refreshkey = function (data) {
responselist[data.eventkey] = data.title;
$("input[name=key]").val(data.eventkey).trigger("change");
$("#menu-list li.current").trigger("click");
Layer.closeAll();
};
//选择资源
$(document).on('click', "#select-resources", function () {
var key = $("#key").val();
Backend.api.open($(this).attr("href") + "?key=" + key, __('Select'), {
callback: refreshkey
});
return false;
});
//添加资源
$(document).on('click', "#add-resources", function () {
Backend.api.open($(this).attr("href") + "?key=" + key, __('Add'), {
callback: refreshkey
});
return false;
});
$("#menu-list li.menu-item:first").trigger("click");
},
add: function () {
Form.api.bindevent($("form[role=form]"));
},
edit: function () {
Form.api.bindevent($("form[role=form]"));
}
};
return Controller;
});
... ...
define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'adminlte'], function ($, undefined, Backend, Table, Form, Adminlte) {
var Controller = {
index: function () {
// 初始化表格参数配置
Table.api.init({
extend: {
index_url: 'wechat/response/index',
add_url: 'wechat/response/add',
edit_url: 'wechat/response/edit',
del_url: 'wechat/response/del',
multi_url: 'wechat/response/multi',
}
});
var table = $("#table");
// 初始化表格
table.bootstrapTable({
url: $.fn.bootstrapTable.defaults.extend.index_url,
sortName: 'id',
columns: [
[
{field: 'state', checkbox: true,},
{field: 'id', title: 'ID'},
{field: 'type', title: __('Type')},
{field: 'title', title: __('Resource title')},
{field: 'eventkey', title: __('Event key')},
{field: 'status', title: __('Status'), formatter: Table.api.formatter.status, operate: false},
{field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
]
]
});
// 为表格绑定事件
Table.api.bindevent(table);
},
select: function () {
// 初始化表格参数配置
Table.api.init({
extend: {
index_url: 'wechat/response/index',
}
});
var table = $("#table");
// 初始化表格
table.bootstrapTable({
url: $.fn.bootstrapTable.defaults.extend.index_url,
sortName: 'id',
columns: [
[
{field: 'state', checkbox: true,},
{field: 'id', title: 'ID'},
{field: 'type', title: __('Type')},
{field: 'title', title: __('Title')},
{field: 'eventkey', title: __('Event key')},
{field: 'status', title: __('Status'), formatter: Table.api.formatter.status, operate: false},
{
field: 'operate', title: __('Operate'), events: {
'click .btn-chooseone': function (e, value, row, index) {
Fast.api.close(row);
},
}, formatter: function () {
return '<a href="javascript:;" class="btn btn-danger btn-chooseone btn-xs"><i class="fa fa-check"></i> ' + __('Choose') + '</a>';
}
}
]
]
});
// 为表格绑定事件
Table.api.bindevent(table);
},
add: function () {
Form.api.bindevent($("form[role=form]"), function (data) {
Fast.api.close(data);
});
Controller.api.bindevent();
},
edit: function () {
Form.api.bindevent($("form[role=form]"));
Controller.api.bindevent();
},
api: {
bindevent: function () {
var getAppFileds = function (id) {
var app = apps[id];
var appConfig = app['config'];
var str = '';
for (var i in appConfig) {
var type = appConfig[i]['type'];
var field = appConfig[i]['field'];
var caption = appConfig[i]['caption'];
var defaultvalue = typeof appConfig[i]['defaultvalue'] != 'undefined' ? appConfig[i]['defaultvalue'] : '';
if (type == 'text' || type == 'textarea') {
if (type == 'textarea') {
str += '<div class="form-group"><label for="content" class="control-label col-xs-12 col-sm-2">' + caption + ':</label><div class="col-xs-12 col-sm-8"><textarea ' + appConfig[i]['extend'] + ' class="form-control" name="row[content][' + field + ']" data-rule="' + appConfig[i]['rule'] + '">' + defaultvalue + '</textarea> </div> </div>';
} else {
str += '<div class="form-group"><label for="content" class="control-label col-xs-12 col-sm-2">' + caption + ':</label><div class="col-xs-12 col-sm-8"><input ' + appConfig[i]['extend'] + ' class="form-control" name="row[content][' + field + ']" type="text" value="' + defaultvalue + '" data-rule="' + appConfig[i]['rule'] + '"> </div> </div>';
}
} else {
var options = appConfig[i]['options'];
var html = '';
if (type == 'select') {
for (var j in options) {
html += '<option value="' + j + '">' + options[j] + '</option>';
}
html = '<select ' + appConfig[i]['extend'] + ' class="form-control" name="row[content][' + field + ']">' + html + '</select>';
} else if (type == 'checkbox') {
for (var j in options) {
html += '<input type="checkbox" name="row[content][' + field + '][]" value="' + j + '"> <span>' + options[j] + '</span> ';
}
} else if (type == 'radio') {
var index = 0;
for (var j in options) {
html += '<input type="radio" name="row[content][' + field + ']" value="' + j + '" ' + (index == 0 ? 'checked' : '') + '> <span>' + options[j] + '</span> ';
index++;
}
}
str += '<div class="form-group"><label for="content" class="control-label col-xs-12 col-sm-2">' + caption + ':</label><div class="col-xs-12 col-sm-8">' + html + ' </div> </div>';
}
}
return str;
};
$(document).on('change', "#app", function () {
var app = $(this).val();
$("#appfields").html(getAppFileds(app));
if (datas.app == app) {
delete (datas.app);
var form = $("form.form-ajax");
$.each(datas, function (i, j) {
console.log(i, j);
form.field("row[content][" + i + "]" + ($("input[name='row[content][" + i + "][]']", form).size() > 0 ? '[]' : ''), j);
});
}
Form.api.bindevent("#appfields");
});
$(document).on('click', "input[name='row[type]']", function () {
var type = $(this).val();
if (type == 'text') {
$("#expand").html('<div class="form-group"><label for="content" class="control-label col-xs-12 col-sm-2">文本内容:</label><div class="col-xs-12 col-sm-8"><textarea class="form-control" name="row[content][content]" data-rule="required"></textarea></div></div>');
$("form[role='form']").field("row[content][content]", datas.content);
} else if (type == 'app') {
$("#expand").html('<div class="form-group"><label for="content" class="control-label col-xs-12 col-sm-2">应用:</label><div class="col-xs-12 col-sm-8"><select class="form-control" name="row[content][app]" id="app">' + $("select[name=applist]").html() + '</select></div></div><div id="appfields"><div>');
$("form[role='form']").field("row[content][app]", datas.app);
$("#app").trigger('change');
}
});
$("input[name='row[type]']:checked").trigger("click");
}
}
};
return Controller;
});
\ No newline at end of file
... ...