更新小程序订阅消息

This commit is contained in:
liaofei 2019-12-23 14:41:53 +08:00
parent 4a8c077752
commit cc222e0a9e
31 changed files with 2889 additions and 2202 deletions

View File

@ -13,6 +13,7 @@ use app\admin\model\user\User as UserModel;//用户
use app\admin\model\store\StoreProductReply as StoreProductReplyModel;//评论
use app\admin\model\store\StoreProduct as ProductModel;//产品
use FormBuilder\Json;
use think\facade\Config;
/**
* 首页控制器
@ -26,45 +27,46 @@ class Index extends AuthController
{
//获取当前登录后台的管理员信息
$adminInfo = $this->adminInfo->toArray();
$roles = explode(',',$adminInfo['roles']);
$site_logo = SystemConfig::getOneConfig('menu_name','site_logo')->toArray();
$roles = explode(',', $adminInfo['roles']);
$site_logo = SystemConfig::getOneConfig('menu_name', 'site_logo')->toArray();
$this->assign([
'menuList'=>SystemMenus::menuList(),
'site_logo'=>json_decode($site_logo['value'],true),
'new_order_audio_link'=>sysConfig('new_order_audio_link'),
'role_name'=>SystemRole::where('id',$roles[0])->field('role_name')->find()
'menuList' => SystemMenus::menuList(),
'site_logo' => json_decode($site_logo['value'], true),
'new_order_audio_link' => sys_config('new_order_audio_link'),
'role_name' => SystemRole::where('id', $roles[0])->field('role_name')->find(),
'workermanPort' => Config::get('workerman.admin.port')
]);
return $this->fetch();
}
//后台首页内容
//后台首页内容
public function main()
{
/*首页第一行统计*/
$now_month = strtotime(date('Y-m'));//本月
$pre_month = strtotime(date('Y-m',strtotime('-1 month')));//上月
$pre_month = strtotime(date('Y-m', strtotime('-1 month')));//上月
$now_day = strtotime(date('Y-m-d'));//今日
$pre_day = strtotime(date('Y-m-d',strtotime('-1 day')));//昨天时间戳
$beforyester_day = strtotime(date('Y-m-d',strtotime('-2 day')));//前天时间戳
$pre_day = strtotime(date('Y-m-d', strtotime('-1 day')));//昨天时间戳
$beforyester_day = strtotime(date('Y-m-d', strtotime('-2 day')));//前天时间戳
//待发货数量
$topData['orderDeliveryNum'] = StoreOrderModel::where('status',0)
->where('paid',1)
->where('refund_status',0)
$topData['orderDeliveryNum'] = StoreOrderModel::where('status', 0)
->where('paid', 1)
->where('refund_status', 0)
->count();
//退换货订单数
$topData['orderRefundNum'] = StoreOrderModel::where('paid',1)
->where('refund_status','IN','1')
$topData['orderRefundNum'] = StoreOrderModel::where('paid', 1)
->where('refund_status', 'IN', '1')
->count();
//库存预警
$replenishment_num = SystemConfig::getConfigValue('store_stock') > 0 ? SystemConfig::getConfigValue('store_stock') : 20;//库存预警界限
$topData['stockProduct'] = StoreProduct::where('stock','<=',$replenishment_num)->where('is_show',1)->where('is_del',0)->count();
$topData['stockProduct'] = StoreProduct::where('stock', '<=', $replenishment_num)->where('is_show', 1)->where('is_del', 0)->count();
//待处理提现
$topData['treatedExtract'] = UserExtractModel::where('status',0)->count();
$topData['treatedExtract'] = UserExtractModel::where('status', 0)->count();
//订单数->昨日
$now_day_order_p = StoreOrderModel::where('paid',1)->whereTime('pay_time','yesterday')->count();
$pre_day_order_p = StoreOrderModel::where('paid',1)->where('pay_time','>',$pre_day)->where('pay_time','<',$now_day)->count();
$now_day_order_p = StoreOrderModel::where('paid', 1)->whereTime('pay_time', 'yesterday')->count();
$pre_day_order_p = StoreOrderModel::where('paid', 1)->where('pay_time', '>', $pre_day)->where('pay_time', '<', $now_day)->count();
$first_line['d_num'] = [
'data' => $now_day_order_p ? $now_day_order_p : 0,
'percent' => abs($now_day_order_p - $pre_day_order_p),
@ -72,8 +74,8 @@ class Index extends AuthController
];
//交易额->昨天
$now_month_order_p = StoreOrderModel::where('paid',1)->whereTime('pay_time','yesterday')->sum('pay_price');
$pre_month_order_p = StoreOrderModel::where('paid',1)->where('pay_time','>',$beforyester_day)->where('pay_time','<',$pre_day)->sum('pay_price');
$now_month_order_p = StoreOrderModel::where('paid', 1)->whereTime('pay_time', 'yesterday')->sum('pay_price');
$pre_month_order_p = StoreOrderModel::where('paid', 1)->where('pay_time', '>', $beforyester_day)->where('pay_time', '<', $pre_day)->sum('pay_price');
$first_line['d_price'] = [
'data' => $now_month_order_p > 0 ? $now_month_order_p : 0,
'percent' => abs($now_month_order_p - $pre_month_order_p),
@ -81,8 +83,8 @@ class Index extends AuthController
];
//交易额->月
$now_month_order_p = StoreOrderModel::where('paid',1)->whereTime('pay_time','month')->sum('pay_price');
$pre_month_order_p = StoreOrderModel::where('paid',1)->where('pay_time','>',$pre_month)->where('pay_time','<',$now_month)->value('sum(pay_price)');
$now_month_order_p = StoreOrderModel::where('paid', 1)->whereTime('pay_time', 'month')->sum('pay_price');
$pre_month_order_p = StoreOrderModel::where('paid', 1)->where('pay_time', '>', $pre_month)->where('pay_time', '<', $now_month)->value('sum(pay_price)');
$first_line['m_price'] = [
'data' => $now_month_order_p > 0 ? $now_month_order_p : 0,
'percent' => abs($now_month_order_p - $pre_month_order_p),
@ -90,8 +92,8 @@ class Index extends AuthController
];
//新粉丝->日
$now_day_user = User::where('add_time','>',$now_day)->count();
$pre_day_user = User::where('add_time','>',$pre_day)->where('add_time','<',$now_day)->count();
$now_day_user = User::where('add_time', '>', $now_day)->count();
$pre_day_user = User::where('add_time', '>', $pre_day)->where('add_time', '<', $now_day)->count();
$pre_day_user = $pre_day_user ? $pre_day_user : 0;
$first_line['day'] = [
'data' => $now_day_user ? $now_day_user : 0,
@ -100,8 +102,8 @@ class Index extends AuthController
];
//新粉丝->月
$now_month_user = User::where('add_time','>',$now_month)->count();
$pre_month_user = User::where('add_time','>',$pre_month)->where('add_time','<',$now_month)->count();
$now_month_user = User::where('add_time', '>', $now_month)->count();
$pre_month_user = User::where('add_time', '>', $pre_month)->where('add_time', '<', $now_month)->count();
$first_line['month'] = [
'data' => $now_month_user ? $now_month_user : 0,
'percent' => abs($now_month_user - $pre_month_user),
@ -109,8 +111,8 @@ class Index extends AuthController
];
//本月订单总数
$now_order_info_c = StoreOrderModel::where('add_time','>',$now_month)->count();
$pre_order_info_c = StoreOrderModel::where('add_time','>',$pre_month)->where('add_time','<',$now_month)->count();
$now_order_info_c = StoreOrderModel::where('add_time', '>', $now_month)->count();
$pre_order_info_c = StoreOrderModel::where('add_time', '>', $pre_month)->where('add_time', '<', $now_month)->count();
$order_info['first'] = [
'data' => $now_order_info_c ? $now_order_info_c : 0,
'percent' => abs($now_order_info_c - $pre_order_info_c),
@ -118,10 +120,10 @@ class Index extends AuthController
];
//上月订单总数
$second_now_month = strtotime(date('Y-m',strtotime('-1 month')));
$second_pre_month = strtotime(date('Y-m',strtotime('-2 month')));
$now_order_info_c = StoreOrderModel::where('add_time','>',$pre_month)->where('add_time','<',$now_month)->count();
$pre_order_info_c = StoreOrderModel::where('add_time','>',$second_pre_month)->where('add_time','<',$second_now_month)->count();
$second_now_month = strtotime(date('Y-m', strtotime('-1 month')));
$second_pre_month = strtotime(date('Y-m', strtotime('-2 month')));
$now_order_info_c = StoreOrderModel::where('add_time', '>', $pre_month)->where('add_time', '<', $now_month)->count();
$pre_order_info_c = StoreOrderModel::where('add_time', '>', $second_pre_month)->where('add_time', '<', $second_now_month)->count();
$order_info["second"] = [
'data' => $now_order_info_c ? $now_order_info_c : 0,
'percent' => abs($now_order_info_c - $pre_order_info_c),
@ -141,385 +143,386 @@ class Index extends AuthController
/**
* 订单图表
*/
public function orderchart(){
public function orderchart()
{
header('Content-type:text/json');
$cycle = $this->request->param('cycle')?:'thirtyday';//默认30天
$cycle = $this->request->param('cycle') ?: 'thirtyday';//默认30天
$datalist = [];
switch ($cycle){
switch ($cycle) {
case 'thirtyday':
$datebefor = date('Y-m-d',strtotime('-30 day'));
$datebefor = date('Y-m-d', strtotime('-30 day'));
$dateafter = date('Y-m-d');
//上期
$pre_datebefor = date('Y-m-d',strtotime('-60 day'));
$pre_dateafter = date('Y-m-d',strtotime('-30 day'));
for($i=-30;$i < 0;$i++){
$datalist[date('m-d',strtotime($i.' day'))] = date('m-d',strtotime($i.' day'));
$pre_datebefor = date('Y-m-d', strtotime('-60 day'));
$pre_dateafter = date('Y-m-d', strtotime('-30 day'));
for ($i = -30; $i < 0; $i++) {
$datalist[date('m-d', strtotime($i . ' day'))] = date('m-d', strtotime($i . ' day'));
}
$order_list = StoreOrderModel::where('add_time','between time',[$datebefor,$dateafter])
$order_list = StoreOrderModel::where('add_time', 'between time', [$datebefor, $dateafter])
->field("FROM_UNIXTIME(add_time,'%m-%d') as day,count(*) as count,sum(pay_price) as price")
->group("FROM_UNIXTIME(add_time, '%Y%m%d')")
->order('add_time asc')
->select()->toArray();
if(empty($order_list)) return Json::fail('无数据');
foreach ($order_list as $k=>&$v){
if (empty($order_list)) return Json::fail('无数据');
foreach ($order_list as $k => &$v) {
$order_list[$v['day']] = $v;
}
$cycle_list = [];
foreach ($datalist as $dk=>$dd){
if(!empty($order_list[$dd])){
foreach ($datalist as $dk => $dd) {
if (!empty($order_list[$dd])) {
$cycle_list[$dd] = $order_list[$dd];
}else{
$cycle_list[$dd] = ['count'=>0,'day'=>$dd,'price'=>''];
} else {
$cycle_list[$dd] = ['count' => 0, 'day' => $dd, 'price' => ''];
}
}
$chartdata = [];
$data = [];//临时
$chartdata['yAxis']['maxnum'] = 0;//最大值数量
$chartdata['yAxis']['maxprice'] = 0;//最大值金额
foreach ($cycle_list as $k=>$v){
foreach ($cycle_list as $k => $v) {
$data['day'][] = $v['day'];
$data['count'][] = $v['count'];
$data['price'][] = round($v['price'],2);
if($chartdata['yAxis']['maxnum'] < $v['count'])
$data['price'][] = round($v['price'], 2);
if ($chartdata['yAxis']['maxnum'] < $v['count'])
$chartdata['yAxis']['maxnum'] = $v['count'];//日最大订单数
if($chartdata['yAxis']['maxprice'] < $v['price'])
if ($chartdata['yAxis']['maxprice'] < $v['price'])
$chartdata['yAxis']['maxprice'] = $v['price'];//日最大金额
}
$chartdata['legend'] = ['订单金额','订单数'];//分类
$chartdata['legend'] = ['订单金额', '订单数'];//分类
$chartdata['xAxis'] = $data['day'];//X轴值
//,'itemStyle'=>$series
$series= ['normal'=>['label'=>['show'=>true,'position'=>'top']]];
$chartdata['series'][] = ['name'=>$chartdata['legend'][0],'type'=>'bar','itemStyle'=>$series,'data'=>$data['price']];//分类1值
$chartdata['series'][] = ['name'=>$chartdata['legend'][1],'type'=>'bar','itemStyle'=>$series,'data'=>$data['count']];//分类2值
$series = ['normal' => ['label' => ['show' => true, 'position' => 'top']]];
$chartdata['series'][] = ['name' => $chartdata['legend'][0], 'type' => 'bar', 'itemStyle' => $series, 'data' => $data['price']];//分类1值
$chartdata['series'][] = ['name' => $chartdata['legend'][1], 'type' => 'bar', 'itemStyle' => $series, 'data' => $data['count']];//分类2值
//统计总数上期
$pre_total = StoreOrderModel::where('add_time','between time',[$pre_datebefor,$pre_dateafter])
$pre_total = StoreOrderModel::where('add_time', 'between time', [$pre_datebefor, $pre_dateafter])
->field("count(*) as count,sum(pay_price) as price")
->find();
if($pre_total){
if ($pre_total) {
$chartdata['pre_cycle']['count'] = [
'data' => $pre_total['count']? : 0
'data' => $pre_total['count'] ?: 0
];
$chartdata['pre_cycle']['price'] = [
'data' => $pre_total['price']? : 0
'data' => $pre_total['price'] ?: 0
];
}
//统计总数
$total = StoreOrderModel::where('add_time','between time',[$datebefor,$dateafter])
$total = StoreOrderModel::where('add_time', 'between time', [$datebefor, $dateafter])
->field("count(*) as count,sum(pay_price) as price")
->find();
if($total){
if ($total) {
$cha_count = intval($pre_total['count']) - intval($total['count']);
$pre_total['count'] = $pre_total['count']==0 ? 1 : $pre_total['count'];
$pre_total['count'] = $pre_total['count'] == 0 ? 1 : $pre_total['count'];
$chartdata['cycle']['count'] = [
'data' => $total['count']? : 0,
'percent' => round((abs($cha_count)/intval($pre_total['count'])*100),2),
'data' => $total['count'] ?: 0,
'percent' => round((abs($cha_count) / intval($pre_total['count']) * 100), 2),
'is_plus' => $cha_count > 0 ? -1 : ($cha_count == 0 ? 0 : 1)
];
$cha_price = round($pre_total['price'],2) - round($total['price'],2);
$pre_total['price'] = $pre_total['price']==0 ? 1 : $pre_total['price'];
$cha_price = round($pre_total['price'], 2) - round($total['price'], 2);
$pre_total['price'] = $pre_total['price'] == 0 ? 1 : $pre_total['price'];
$chartdata['cycle']['price'] = [
'data' => $total['price']? : 0,
'percent' => round(abs($cha_price)/$pre_total['price']*100,2),
'data' => $total['price'] ?: 0,
'percent' => round(abs($cha_price) / $pre_total['price'] * 100, 2),
'is_plus' => $cha_price > 0 ? -1 : ($cha_price == 0 ? 0 : 1)
];
}
return app('json')->success('ok',$chartdata);
return app('json')->success('ok', $chartdata);
break;
case 'week':
$weekarray=array(['周日'],['周一'],['周二'],['周三'],['周四'],['周五'],['周六']);
$datebefor = date('Y-m-d',strtotime('-1 week Monday'));
$dateafter = date('Y-m-d',strtotime('-1 week Sunday'));
$order_list = StoreOrderModel::where('add_time','between time',[$datebefor,$dateafter])
$weekarray = array(['周日'], ['周一'], ['周二'], ['周三'], ['周四'], ['周五'], ['周六']);
$datebefor = date('Y-m-d', strtotime('-1 week Monday'));
$dateafter = date('Y-m-d', strtotime('-1 week Sunday'));
$order_list = StoreOrderModel::where('add_time', 'between time', [$datebefor, $dateafter])
->field("FROM_UNIXTIME(add_time,'%w') as day,count(*) as count,sum(pay_price) as price")
->group("FROM_UNIXTIME(add_time, '%Y%m%e')")
->order('add_time asc')
->select()->toArray();
//数据查询重新处理
$new_order_list = [];
foreach ($order_list as $k=>$v){
foreach ($order_list as $k => $v) {
$new_order_list[$v['day']] = $v;
}
$now_datebefor = date('Y-m-d', (time() - ((date('w') == 0 ? 7 : date('w')) - 1) * 24 * 3600));
$now_dateafter = date('Y-m-d',strtotime("+1 day"));
$now_order_list = StoreOrderModel::where('add_time','between time',[$now_datebefor,$now_dateafter])
$now_dateafter = date('Y-m-d', strtotime("+1 day"));
$now_order_list = StoreOrderModel::where('add_time', 'between time', [$now_datebefor, $now_dateafter])
->field("FROM_UNIXTIME(add_time,'%w') as day,count(*) as count,sum(pay_price) as price")
->group("FROM_UNIXTIME(add_time, '%Y%m%e')")
->order('add_time asc')
->select()->toArray();
//数据查询重新处理 key 变为当前值
$new_now_order_list = [];
foreach ($now_order_list as $k=>$v){
foreach ($now_order_list as $k => $v) {
$new_now_order_list[$v['day']] = $v;
}
foreach ($weekarray as $dk=>$dd){
if(!empty($new_order_list[$dk])){
foreach ($weekarray as $dk => $dd) {
if (!empty($new_order_list[$dk])) {
$weekarray[$dk]['pre'] = $new_order_list[$dk];
}else{
$weekarray[$dk]['pre'] = ['count'=>0,'day'=>$weekarray[$dk][0],'price'=>'0'];
} else {
$weekarray[$dk]['pre'] = ['count' => 0, 'day' => $weekarray[$dk][0], 'price' => '0'];
}
if(!empty($new_now_order_list[$dk])){
if (!empty($new_now_order_list[$dk])) {
$weekarray[$dk]['now'] = $new_now_order_list[$dk];
}else{
$weekarray[$dk]['now'] = ['count'=>0,'day'=>$weekarray[$dk][0],'price'=>'0'];
} else {
$weekarray[$dk]['now'] = ['count' => 0, 'day' => $weekarray[$dk][0], 'price' => '0'];
}
}
$chartdata = [];
$data = [];//临时
$chartdata['yAxis']['maxnum'] = 0;//最大值数量
$chartdata['yAxis']['maxprice'] = 0;//最大值金额
foreach ($weekarray as $k=>$v){
foreach ($weekarray as $k => $v) {
$data['day'][] = $v[0];
$data['pre']['count'][] = $v['pre']['count'];
$data['pre']['price'][] = round($v['pre']['price'],2);
$data['pre']['price'][] = round($v['pre']['price'], 2);
$data['now']['count'][] = $v['now']['count'];
$data['now']['price'][] = round($v['now']['price'],2);
if($chartdata['yAxis']['maxnum'] < $v['pre']['count'] || $chartdata['yAxis']['maxnum'] < $v['now']['count']){
$chartdata['yAxis']['maxnum'] = $v['pre']['count']>$v['now']['count']?$v['pre']['count']:$v['now']['count'];//日最大订单数
$data['now']['price'][] = round($v['now']['price'], 2);
if ($chartdata['yAxis']['maxnum'] < $v['pre']['count'] || $chartdata['yAxis']['maxnum'] < $v['now']['count']) {
$chartdata['yAxis']['maxnum'] = $v['pre']['count'] > $v['now']['count'] ? $v['pre']['count'] : $v['now']['count'];//日最大订单数
}
if($chartdata['yAxis']['maxprice'] < $v['pre']['price'] || $chartdata['yAxis']['maxprice'] < $v['now']['price']){
$chartdata['yAxis']['maxprice'] = $v['pre']['price']>$v['now']['price']?$v['pre']['price']:$v['now']['price'];//日最大金额
if ($chartdata['yAxis']['maxprice'] < $v['pre']['price'] || $chartdata['yAxis']['maxprice'] < $v['now']['price']) {
$chartdata['yAxis']['maxprice'] = $v['pre']['price'] > $v['now']['price'] ? $v['pre']['price'] : $v['now']['price'];//日最大金额
}
}
$chartdata['legend'] = ['上周金额','本周金额','上周订单数','本周订单数'];//分类
$chartdata['legend'] = ['上周金额', '本周金额', '上周订单数', '本周订单数'];//分类
$chartdata['xAxis'] = $data['day'];//X轴值
//,'itemStyle'=>$series
$series= ['normal'=>['label'=>['show'=>true,'position'=>'top']]];
$chartdata['series'][] = ['name'=>$chartdata['legend'][0],'type'=>'bar','itemStyle'=>$series,'data'=>$data['pre']['price']];//分类1值
$chartdata['series'][] = ['name'=>$chartdata['legend'][1],'type'=>'bar','itemStyle'=>$series,'data'=>$data['now']['price']];//分类1值
$chartdata['series'][] = ['name'=>$chartdata['legend'][2],'type'=>'line','itemStyle'=>$series,'data'=>$data['pre']['count']];//分类2值
$chartdata['series'][] = ['name'=>$chartdata['legend'][3],'type'=>'line','itemStyle'=>$series,'data'=>$data['now']['count']];//分类2值
$series = ['normal' => ['label' => ['show' => true, 'position' => 'top']]];
$chartdata['series'][] = ['name' => $chartdata['legend'][0], 'type' => 'bar', 'itemStyle' => $series, 'data' => $data['pre']['price']];//分类1值
$chartdata['series'][] = ['name' => $chartdata['legend'][1], 'type' => 'bar', 'itemStyle' => $series, 'data' => $data['now']['price']];//分类1值
$chartdata['series'][] = ['name' => $chartdata['legend'][2], 'type' => 'line', 'itemStyle' => $series, 'data' => $data['pre']['count']];//分类2值
$chartdata['series'][] = ['name' => $chartdata['legend'][3], 'type' => 'line', 'itemStyle' => $series, 'data' => $data['now']['count']];//分类2值
//统计总数上期
$pre_total = StoreOrderModel::where('add_time','between time',[$datebefor,$dateafter])
$pre_total = StoreOrderModel::where('add_time', 'between time', [$datebefor, $dateafter])
->field("count(*) as count,sum(pay_price) as price")
->find();
if($pre_total){
if ($pre_total) {
$chartdata['pre_cycle']['count'] = [
'data' => $pre_total['count']? : 0
'data' => $pre_total['count'] ?: 0
];
$chartdata['pre_cycle']['price'] = [
'data' => $pre_total['price']? : 0
'data' => $pre_total['price'] ?: 0
];
}
//统计总数
$total = StoreOrderModel::where('add_time','between time',[$now_datebefor,$now_dateafter])
$total = StoreOrderModel::where('add_time', 'between time', [$now_datebefor, $now_dateafter])
->field("count(*) as count,sum(pay_price) as price")
->find();
if($total){
if ($total) {
$cha_count = intval($pre_total['count']) - intval($total['count']);
$pre_total['count'] = $pre_total['count']==0 ? 1 : $pre_total['count'];
$pre_total['count'] = $pre_total['count'] == 0 ? 1 : $pre_total['count'];
$chartdata['cycle']['count'] = [
'data' => $total['count']? : 0,
'percent' => round((abs($cha_count)/intval($pre_total['count'])*100),2),
'data' => $total['count'] ?: 0,
'percent' => round((abs($cha_count) / intval($pre_total['count']) * 100), 2),
'is_plus' => $cha_count > 0 ? -1 : ($cha_count == 0 ? 0 : 1)
];
$cha_price = round($pre_total['price'],2) - round($total['price'],2);
$pre_total['price'] = $pre_total['price']==0 ? 1 : $pre_total['price'];
$cha_price = round($pre_total['price'], 2) - round($total['price'], 2);
$pre_total['price'] = $pre_total['price'] == 0 ? 1 : $pre_total['price'];
$chartdata['cycle']['price'] = [
'data' => $total['price']? : 0,
'percent' => round(abs($cha_price)/$pre_total['price']*100,2),
'data' => $total['price'] ?: 0,
'percent' => round(abs($cha_price) / $pre_total['price'] * 100, 2),
'is_plus' => $cha_price > 0 ? -1 : ($cha_price == 0 ? 0 : 1)
];
}
return app('json')->success('ok',$chartdata);
return app('json')->success('ok', $chartdata);
break;
case 'month':
$weekarray=array('01'=>['1'],'02'=>['2'],'03'=>['3'],'04'=>['4'],'05'=>['5'],'06'=>['6'],'07'=>['7'],'08'=>['8'],'09'=>['9'],'10'=>['10'],'11'=>['11'],'12'=>['12'],'13'=>['13'],'14'=>['14'],'15'=>['15'],'16'=>['16'],'17'=>['17'],'18'=>['18'],'19'=>['19'],'20'=>['20'],'21'=>['21'],'22'=>['22'],'23'=>['23'],'24'=>['24'],'25'=>['25'],'26'=>['26'],'27'=>['27'],'28'=>['28'],'29'=>['29'],'30'=>['30'],'31'=>['31']);
$weekarray = array('01' => ['1'], '02' => ['2'], '03' => ['3'], '04' => ['4'], '05' => ['5'], '06' => ['6'], '07' => ['7'], '08' => ['8'], '09' => ['9'], '10' => ['10'], '11' => ['11'], '12' => ['12'], '13' => ['13'], '14' => ['14'], '15' => ['15'], '16' => ['16'], '17' => ['17'], '18' => ['18'], '19' => ['19'], '20' => ['20'], '21' => ['21'], '22' => ['22'], '23' => ['23'], '24' => ['24'], '25' => ['25'], '26' => ['26'], '27' => ['27'], '28' => ['28'], '29' => ['29'], '30' => ['30'], '31' => ['31']);
$datebefor = date('Y-m-01',strtotime('-1 month'));
$dateafter = date('Y-m-d',strtotime(date('Y-m-01')));
$order_list = StoreOrderModel::where('add_time','between time',[$datebefor,$dateafter])
$datebefor = date('Y-m-01', strtotime('-1 month'));
$dateafter = date('Y-m-d', strtotime(date('Y-m-01')));
$order_list = StoreOrderModel::where('add_time', 'between time', [$datebefor, $dateafter])
->field("FROM_UNIXTIME(add_time,'%d') as day,count(*) as count,sum(pay_price) as price")
->group("FROM_UNIXTIME(add_time, '%Y%m%e')")
->order('add_time asc')
->select()->toArray();
//数据查询重新处理
$new_order_list = [];
foreach ($order_list as $k=>$v){
foreach ($order_list as $k => $v) {
$new_order_list[$v['day']] = $v;
}
$now_datebefor = date('Y-m-01');
$now_dateafter = date('Y-m-d',strtotime("+1 day"));
$now_order_list = StoreOrderModel::where('add_time','between time',[$now_datebefor,$now_dateafter])
$now_dateafter = date('Y-m-d', strtotime("+1 day"));
$now_order_list = StoreOrderModel::where('add_time', 'between time', [$now_datebefor, $now_dateafter])
->field("FROM_UNIXTIME(add_time,'%d') as day,count(*) as count,sum(pay_price) as price")
->group("FROM_UNIXTIME(add_time, '%Y%m%e')")
->order('add_time asc')
->select()->toArray();
//数据查询重新处理 key 变为当前值
$new_now_order_list = [];
foreach ($now_order_list as $k=>$v){
foreach ($now_order_list as $k => $v) {
$new_now_order_list[$v['day']] = $v;
}
foreach ($weekarray as $dk=>$dd){
if(!empty($new_order_list[$dk])){
foreach ($weekarray as $dk => $dd) {
if (!empty($new_order_list[$dk])) {
$weekarray[$dk]['pre'] = $new_order_list[$dk];
}else{
$weekarray[$dk]['pre'] = ['count'=>0,'day'=>$weekarray[$dk][0],'price'=>'0'];
} else {
$weekarray[$dk]['pre'] = ['count' => 0, 'day' => $weekarray[$dk][0], 'price' => '0'];
}
if(!empty($new_now_order_list[$dk])){
if (!empty($new_now_order_list[$dk])) {
$weekarray[$dk]['now'] = $new_now_order_list[$dk];
}else{
$weekarray[$dk]['now'] = ['count'=>0,'day'=>$weekarray[$dk][0],'price'=>'0'];
} else {
$weekarray[$dk]['now'] = ['count' => 0, 'day' => $weekarray[$dk][0], 'price' => '0'];
}
}
$chartdata = [];
$data = [];//临时
$chartdata['yAxis']['maxnum'] = 0;//最大值数量
$chartdata['yAxis']['maxprice'] = 0;//最大值金额
foreach ($weekarray as $k=>$v){
foreach ($weekarray as $k => $v) {
$data['day'][] = $v[0];
$data['pre']['count'][] = $v['pre']['count'];
$data['pre']['price'][] = round($v['pre']['price'],2);
$data['pre']['price'][] = round($v['pre']['price'], 2);
$data['now']['count'][] = $v['now']['count'];
$data['now']['price'][] = round($v['now']['price'],2);
if($chartdata['yAxis']['maxnum'] < $v['pre']['count'] || $chartdata['yAxis']['maxnum'] < $v['now']['count']){
$chartdata['yAxis']['maxnum'] = $v['pre']['count']>$v['now']['count']?$v['pre']['count']:$v['now']['count'];//日最大订单数
$data['now']['price'][] = round($v['now']['price'], 2);
if ($chartdata['yAxis']['maxnum'] < $v['pre']['count'] || $chartdata['yAxis']['maxnum'] < $v['now']['count']) {
$chartdata['yAxis']['maxnum'] = $v['pre']['count'] > $v['now']['count'] ? $v['pre']['count'] : $v['now']['count'];//日最大订单数
}
if($chartdata['yAxis']['maxprice'] < $v['pre']['price'] || $chartdata['yAxis']['maxprice'] < $v['now']['price']){
$chartdata['yAxis']['maxprice'] = $v['pre']['price']>$v['now']['price']?$v['pre']['price']:$v['now']['price'];//日最大金额
if ($chartdata['yAxis']['maxprice'] < $v['pre']['price'] || $chartdata['yAxis']['maxprice'] < $v['now']['price']) {
$chartdata['yAxis']['maxprice'] = $v['pre']['price'] > $v['now']['price'] ? $v['pre']['price'] : $v['now']['price'];//日最大金额
}
}
$chartdata['legend'] = ['上月金额','本月金额','上月订单数','本月订单数'];//分类
$chartdata['legend'] = ['上月金额', '本月金额', '上月订单数', '本月订单数'];//分类
$chartdata['xAxis'] = $data['day'];//X轴值
//,'itemStyle'=>$series
$series= ['normal'=>['label'=>['show'=>true,'position'=>'top']]];
$chartdata['series'][] = ['name'=>$chartdata['legend'][0],'type'=>'bar','itemStyle'=>$series,'data'=>$data['pre']['price']];//分类1值
$chartdata['series'][] = ['name'=>$chartdata['legend'][1],'type'=>'bar','itemStyle'=>$series,'data'=>$data['now']['price']];//分类1值
$chartdata['series'][] = ['name'=>$chartdata['legend'][2],'type'=>'line','itemStyle'=>$series,'data'=>$data['pre']['count']];//分类2值
$chartdata['series'][] = ['name'=>$chartdata['legend'][3],'type'=>'line','itemStyle'=>$series,'data'=>$data['now']['count']];//分类2值
$series = ['normal' => ['label' => ['show' => true, 'position' => 'top']]];
$chartdata['series'][] = ['name' => $chartdata['legend'][0], 'type' => 'bar', 'itemStyle' => $series, 'data' => $data['pre']['price']];//分类1值
$chartdata['series'][] = ['name' => $chartdata['legend'][1], 'type' => 'bar', 'itemStyle' => $series, 'data' => $data['now']['price']];//分类1值
$chartdata['series'][] = ['name' => $chartdata['legend'][2], 'type' => 'line', 'itemStyle' => $series, 'data' => $data['pre']['count']];//分类2值
$chartdata['series'][] = ['name' => $chartdata['legend'][3], 'type' => 'line', 'itemStyle' => $series, 'data' => $data['now']['count']];//分类2值
//统计总数上期
$pre_total = StoreOrderModel::where('add_time','between time',[$datebefor,$dateafter])
$pre_total = StoreOrderModel::where('add_time', 'between time', [$datebefor, $dateafter])
->field("count(*) as count,sum(pay_price) as price")
->find();
if($pre_total){
if ($pre_total) {
$chartdata['pre_cycle']['count'] = [
'data' => $pre_total['count']? : 0
'data' => $pre_total['count'] ?: 0
];
$chartdata['pre_cycle']['price'] = [
'data' => $pre_total['price']? : 0
'data' => $pre_total['price'] ?: 0
];
}
//统计总数
$total = StoreOrderModel::where('add_time','between time',[$now_datebefor,$now_dateafter])
$total = StoreOrderModel::where('add_time', 'between time', [$now_datebefor, $now_dateafter])
->field("count(*) as count,sum(pay_price) as price")
->find();
if($total){
if ($total) {
$cha_count = intval($pre_total['count']) - intval($total['count']);
$pre_total['count'] = $pre_total['count']==0 ? 1 : $pre_total['count'];
$pre_total['count'] = $pre_total['count'] == 0 ? 1 : $pre_total['count'];
$chartdata['cycle']['count'] = [
'data' => $total['count']? : 0,
'percent' => round((abs($cha_count)/intval($pre_total['count'])*100),2),
'data' => $total['count'] ?: 0,
'percent' => round((abs($cha_count) / intval($pre_total['count']) * 100), 2),
'is_plus' => $cha_count > 0 ? -1 : ($cha_count == 0 ? 0 : 1)
];
$cha_price = round($pre_total['price'],2) - round($total['price'],2);
$pre_total['price'] = $pre_total['price']==0 ? 1 : $pre_total['price'];
$cha_price = round($pre_total['price'], 2) - round($total['price'], 2);
$pre_total['price'] = $pre_total['price'] == 0 ? 1 : $pre_total['price'];
$chartdata['cycle']['price'] = [
'data' => $total['price']? : 0,
'percent' => round(abs($cha_price)/$pre_total['price']*100,2),
'data' => $total['price'] ?: 0,
'percent' => round(abs($cha_price) / $pre_total['price'] * 100, 2),
'is_plus' => $cha_price > 0 ? -1 : ($cha_price == 0 ? 0 : 1)
];
}
return app('json')->success('ok',$chartdata);
return app('json')->success('ok', $chartdata);
break;
case 'year':
$weekarray=array('01'=>['一月'],'02'=>['二月'],'03'=>['三月'],'04'=>['四月'],'05'=>['五月'],'06'=>['六月'],'07'=>['七月'],'08'=>['八月'],'09'=>['九月'],'10'=>['十月'],'11'=>['十一月'],'12'=>['十二月']);
$datebefor = date('Y-01-01',strtotime('-1 year'));
$dateafter = date('Y-12-31',strtotime('-1 year'));
$order_list = StoreOrderModel::where('add_time','between time',[$datebefor,$dateafter])
$weekarray = array('01' => ['一月'], '02' => ['二月'], '03' => ['三月'], '04' => ['四月'], '05' => ['五月'], '06' => ['六月'], '07' => ['七月'], '08' => ['八月'], '09' => ['九月'], '10' => ['十月'], '11' => ['十一月'], '12' => ['十二月']);
$datebefor = date('Y-01-01', strtotime('-1 year'));
$dateafter = date('Y-12-31', strtotime('-1 year'));
$order_list = StoreOrderModel::where('add_time', 'between time', [$datebefor, $dateafter])
->field("FROM_UNIXTIME(add_time,'%m') as day,count(*) as count,sum(pay_price) as price")
->group("FROM_UNIXTIME(add_time, '%Y%m')")
->order('add_time asc')
->select()->toArray();
//数据查询重新处理
$new_order_list = [];
foreach ($order_list as $k=>$v){
foreach ($order_list as $k => $v) {
$new_order_list[$v['day']] = $v;
}
$now_datebefor = date('Y-01-01');
$now_dateafter = date('Y-m-d');
$now_order_list = StoreOrderModel::where('add_time','between time',[$now_datebefor,$now_dateafter])
$now_order_list = StoreOrderModel::where('add_time', 'between time', [$now_datebefor, $now_dateafter])
->field("FROM_UNIXTIME(add_time,'%m') as day,count(*) as count,sum(pay_price) as price")
->group("FROM_UNIXTIME(add_time, '%Y%m')")
->order('add_time asc')
->select()->toArray();
//数据查询重新处理 key 变为当前值
$new_now_order_list = [];
foreach ($now_order_list as $k=>$v){
foreach ($now_order_list as $k => $v) {
$new_now_order_list[$v['day']] = $v;
}
foreach ($weekarray as $dk=>$dd){
if(!empty($new_order_list[$dk])){
foreach ($weekarray as $dk => $dd) {
if (!empty($new_order_list[$dk])) {
$weekarray[$dk]['pre'] = $new_order_list[$dk];
}else{
$weekarray[$dk]['pre'] = ['count'=>0,'day'=>$weekarray[$dk][0],'price'=>'0'];
} else {
$weekarray[$dk]['pre'] = ['count' => 0, 'day' => $weekarray[$dk][0], 'price' => '0'];
}
if(!empty($new_now_order_list[$dk])){
if (!empty($new_now_order_list[$dk])) {
$weekarray[$dk]['now'] = $new_now_order_list[$dk];
}else{
$weekarray[$dk]['now'] = ['count'=>0,'day'=>$weekarray[$dk][0],'price'=>'0'];
} else {
$weekarray[$dk]['now'] = ['count' => 0, 'day' => $weekarray[$dk][0], 'price' => '0'];
}
}
$chartdata = [];
$data = [];//临时
$chartdata['yAxis']['maxnum'] = 0;//最大值数量
$chartdata['yAxis']['maxprice'] = 0;//最大值金额
foreach ($weekarray as $k=>$v){
foreach ($weekarray as $k => $v) {
$data['day'][] = $v[0];
$data['pre']['count'][] = $v['pre']['count'];
$data['pre']['price'][] = round($v['pre']['price'],2);
$data['pre']['price'][] = round($v['pre']['price'], 2);
$data['now']['count'][] = $v['now']['count'];
$data['now']['price'][] = round($v['now']['price'],2);
if($chartdata['yAxis']['maxnum'] < $v['pre']['count'] || $chartdata['yAxis']['maxnum'] < $v['now']['count']){
$chartdata['yAxis']['maxnum'] = $v['pre']['count']>$v['now']['count']?$v['pre']['count']:$v['now']['count'];//日最大订单数
$data['now']['price'][] = round($v['now']['price'], 2);
if ($chartdata['yAxis']['maxnum'] < $v['pre']['count'] || $chartdata['yAxis']['maxnum'] < $v['now']['count']) {
$chartdata['yAxis']['maxnum'] = $v['pre']['count'] > $v['now']['count'] ? $v['pre']['count'] : $v['now']['count'];//日最大订单数
}
if($chartdata['yAxis']['maxprice'] < $v['pre']['price'] || $chartdata['yAxis']['maxprice'] < $v['now']['price']){
$chartdata['yAxis']['maxprice'] = $v['pre']['price']>$v['now']['price']?$v['pre']['price']:$v['now']['price'];//日最大金额
if ($chartdata['yAxis']['maxprice'] < $v['pre']['price'] || $chartdata['yAxis']['maxprice'] < $v['now']['price']) {
$chartdata['yAxis']['maxprice'] = $v['pre']['price'] > $v['now']['price'] ? $v['pre']['price'] : $v['now']['price'];//日最大金额
}
}
$chartdata['legend'] = ['去年金额','今年金额','去年订单数','今年订单数'];//分类
$chartdata['legend'] = ['去年金额', '今年金额', '去年订单数', '今年订单数'];//分类
$chartdata['xAxis'] = $data['day'];//X轴值
//,'itemStyle'=>$series
$series= ['normal'=>['label'=>['show'=>true,'position'=>'top']]];
$chartdata['series'][] = ['name'=>$chartdata['legend'][0],'type'=>'bar','itemStyle'=>$series,'data'=>$data['pre']['price']];//分类1值
$chartdata['series'][] = ['name'=>$chartdata['legend'][1],'type'=>'bar','itemStyle'=>$series,'data'=>$data['now']['price']];//分类1值
$chartdata['series'][] = ['name'=>$chartdata['legend'][2],'type'=>'line','itemStyle'=>$series,'data'=>$data['pre']['count']];//分类2值
$chartdata['series'][] = ['name'=>$chartdata['legend'][3],'type'=>'line','itemStyle'=>$series,'data'=>$data['now']['count']];//分类2值
$series = ['normal' => ['label' => ['show' => true, 'position' => 'top']]];
$chartdata['series'][] = ['name' => $chartdata['legend'][0], 'type' => 'bar', 'itemStyle' => $series, 'data' => $data['pre']['price']];//分类1值
$chartdata['series'][] = ['name' => $chartdata['legend'][1], 'type' => 'bar', 'itemStyle' => $series, 'data' => $data['now']['price']];//分类1值
$chartdata['series'][] = ['name' => $chartdata['legend'][2], 'type' => 'line', 'itemStyle' => $series, 'data' => $data['pre']['count']];//分类2值
$chartdata['series'][] = ['name' => $chartdata['legend'][3], 'type' => 'line', 'itemStyle' => $series, 'data' => $data['now']['count']];//分类2值
//统计总数上期
$pre_total = StoreOrderModel::where('add_time','between time',[$datebefor,$dateafter])
$pre_total = StoreOrderModel::where('add_time', 'between time', [$datebefor, $dateafter])
->field("count(*) as count,sum(pay_price) as price")
->find();
if($pre_total){
if ($pre_total) {
$chartdata['pre_cycle']['count'] = [
'data' => $pre_total['count']? : 0
'data' => $pre_total['count'] ?: 0
];
$chartdata['pre_cycle']['price'] = [
'data' => $pre_total['price']? : 0
'data' => $pre_total['price'] ?: 0
];
}
//统计总数
$total = StoreOrderModel::where('add_time','between time',[$now_datebefor,$now_dateafter])
$total = StoreOrderModel::where('add_time', 'between time', [$now_datebefor, $now_dateafter])
->field("count(*) as count,sum(pay_price) as price")
->find();
if($total){
if ($total) {
$cha_count = intval($pre_total['count']) - intval($total['count']);
$pre_total['count'] = $pre_total['count']==0 ? 1 : $pre_total['count'];
$pre_total['count'] = $pre_total['count'] == 0 ? 1 : $pre_total['count'];
$chartdata['cycle']['count'] = [
'data' => $total['count']? : 0,
'percent' => round((abs($cha_count)/intval($pre_total['count'])*100),2),
'data' => $total['count'] ?: 0,
'percent' => round((abs($cha_count) / intval($pre_total['count']) * 100), 2),
'is_plus' => $cha_count > 0 ? -1 : ($cha_count == 0 ? 0 : 1)
];
$cha_price = round($pre_total['price'],2) - round($total['price'],2);
$pre_total['price'] = $pre_total['price']==0 ? 1 : $pre_total['price'];
$cha_price = round($pre_total['price'], 2) - round($total['price'], 2);
$pre_total['price'] = $pre_total['price'] == 0 ? 1 : $pre_total['price'];
$chartdata['cycle']['price'] = [
'data' => $total['price']? : 0,
'percent' => round(abs($cha_price)/$pre_total['price']*100,2),
'data' => $total['price'] ?: 0,
'percent' => round(abs($cha_price) / $pre_total['price'] * 100, 2),
'is_plus' => $cha_price > 0 ? -1 : ($cha_price == 0 ? 0 : 1)
];
}
return app('json')->success('ok',$chartdata);
return app('json')->success('ok', $chartdata);
break;
default:
break;
@ -527,16 +530,18 @@ class Index extends AuthController
}
/**
* 用户图表
*/
public function userchart(){
public function userchart()
{
header('Content-type:text/json');
$starday = date('Y-m-d',strtotime('-30 day'));
$starday = date('Y-m-d', strtotime('-30 day'));
$yesterday = date('Y-m-d');
$user_list = UserModel::where('add_time','between time',[$starday,$yesterday])
$user_list = UserModel::where('add_time', 'between time', [$starday, $yesterday])
->field("FROM_UNIXTIME(add_time,'%m-%e') as day,count(*) as count")
->group("FROM_UNIXTIME(add_time, '%Y%m%e')")
->order('add_time asc')
@ -547,17 +552,17 @@ class Index extends AuthController
$chartdata['yAxis']['maxnum'] = 0;//最大值数量
$chartdata['xAxis'] = [date('m-d')];//X轴值
$chartdata['series'] = [0];//分类1值
if(!empty($user_list)) {
foreach ($user_list as $k=>$v){
if (!empty($user_list)) {
foreach ($user_list as $k => $v) {
$data['day'][] = $v['day'];
$data['count'][] = $v['count'];
if($chartdata['yAxis']['maxnum'] < $v['count'])
if ($chartdata['yAxis']['maxnum'] < $v['count'])
$chartdata['yAxis']['maxnum'] = $v['count'];
}
$chartdata['xAxis'] = $data['day'];//X轴值
$chartdata['series'] = $data['count'];//分类1值
}
return app('json')->success('ok',$chartdata);
return app('json')->success('ok', $chartdata);
}
/**
@ -565,20 +570,20 @@ class Index extends AuthController
* @param int $newTime
* @return false|string
*/
public function Jnotice($newTime=30)
public function Jnotice($newTime = 30)
{
header('Content-type:text/json');
$data = [];
$data['ordernum'] = StoreOrderModel::statusByWhere(1)->count();//待发货
$replenishment_num = SystemConfig::getConfigValue('store_stock') > 0 ? SystemConfig::getConfigValue('store_stock') : 2;//库存预警界限
$data['inventory'] = ProductModel::where('stock','<=',$replenishment_num)->where('is_show',1)->where('is_del',0)->count();//库存
$data['commentnum'] = StoreProductReplyModel::where('is_reply',0)->count();//评论
$data['reflectnum'] = UserExtractModel::where('status',0)->count();;//提现
$data['msgcount'] = intval($data['ordernum'])+intval($data['inventory'])+intval($data['commentnum'])+intval($data['reflectnum']);
$data['inventory'] = ProductModel::where('stock', '<=', $replenishment_num)->where('is_show', 1)->where('is_del', 0)->count();//库存
$data['commentnum'] = StoreProductReplyModel::where('is_reply', 0)->count();//评论
$data['reflectnum'] = UserExtractModel::where('status', 0)->count();;//提现
$data['msgcount'] = intval($data['ordernum']) + intval($data['inventory']) + intval($data['commentnum']) + intval($data['reflectnum']);
//新订单提醒
$data['newOrderId']=StoreOrderModel::statusByWhere(1)->where('is_remind',0)->column('order_id','id');
if(count($data['newOrderId'])) StoreOrderModel::where('order_id','in',$data['newOrderId'])->update(['is_remind'=>1]);
return app('json')->success('ok',$data);
$data['newOrderId'] = StoreOrderModel::statusByWhere(1)->where('is_remind', 0)->column('order_id', 'id');
if (count($data['newOrderId'])) StoreOrderModel::where('order_id', 'in', $data['newOrderId'])->update(['is_remind' => 1]);
return app('json')->success('ok', $data);
}
}

View File

@ -127,13 +127,7 @@ SCRIPT;
],Url::buildUrl('/user/bill/2')->suffix(false)->build());
break;
case 'routine':
RoutineTemplate::sendOut('ORDER_REFUND_SUCCESS',$UserRecharge['uid'],[
'keyword1'=>$UserRecharge['order_id'],
'keyword2'=>date('Y-m-d H:i:s',time()),
'keyword3'=>$UserRecharge['price'],
'keyword4'=>'余额充值退款',
'keyword5'=>'亲,您充值的金额已退款,本次退款'. $data['refund_price'].'金额',
]);
RoutineTemplate::sendRechargeSuccess($UserRecharge,$data['refund_price']);
break;
}
UserBill::expend('系统退款',$UserRecharge['uid'],'now_money','user_recharge_refund',$refund_price,$id,$UserRecharge['price'],'退款给用户'.$refund_price.'元');

View File

@ -3,6 +3,7 @@
namespace app\admin\controller\routine;
use app\admin\controller\AuthController;
use crmeb\services\CacheService;
use crmeb\services\FormBuilder as Form;
use crmeb\services\UtilService as Util;
use crmeb\services\JsonService as Json;
@ -19,10 +20,10 @@ class RoutineTemplate extends AuthController
public function index()
{
$where = Util::getMore([
['name',''],
['status','']
],$this->request);
$this->assign('where',$where);
['name', ''],
['status', '']
], $this->request);
$this->assign('where', $where);
$this->assign(RoutineTemplateModel::SystemPage($where));
return $this->fetch();
}
@ -34,15 +35,16 @@ class RoutineTemplate extends AuthController
public function create()
{
$f = array();
$f[] = Form::input('tempkey','模板编号');
$f[] = Form::input('tempid','模板ID');
$f[] = Form::input('name','模板名');
$f[] = Form::input('content','回复内容')->type('textarea');
$f[] = Form::radio('status','状态',1)->options([['label'=>'开启','value'=>1],['label'=>'关闭','value'=>0]]);
$form = Form::make_post_form('添加模板消息',$f,Url::buildUrl('save'));
$f[] = Form::input('tempkey', '模板编号');
$f[] = Form::input('tempid', '模板ID');
$f[] = Form::input('name', '模板名');
$f[] = Form::input('content', '回复内容')->type('textarea');
$f[] = Form::radio('status', '状态', 1)->options([['label' => '开启', 'value' => 1], ['label' => '关闭', 'value' => 0]]);
$form = Form::make_post_form('添加模板消息', $f, Url::buildUrl('save'));
$this->assign(compact('form'));
return $this->fetch('public/form-builder');
}
public function save()
{
$data = Util::postMore([
@ -50,16 +52,17 @@ class RoutineTemplate extends AuthController
'tempid',
'name',
'content',
['status',0]
['status', 0]
]);
if($data['tempkey'] == '') return Json::fail('请输入模板编号');
if($data['tempkey'] != '' && RoutineTemplateModel::be($data['tempkey'],'tempkey'))
if ($data['tempkey'] == '') return Json::fail('请输入模板编号');
if ($data['tempkey'] != '' && RoutineTemplateModel::be($data['tempkey'], 'tempkey'))
return Json::fail('请输入模板编号已存在,请重新输入');
if($data['tempid'] == '') return Json::fail('请输入模板ID');
if($data['name'] == '') return Json::fail('请输入模板名');
if($data['content'] == '') return Json::fail('请输入回复内容');
if ($data['tempid'] == '') return Json::fail('请输入模板ID');
if ($data['name'] == '') return Json::fail('请输入模板名');
if ($data['content'] == '') return Json::fail('请输入回复内容');
$data['add_time'] = time();
RoutineTemplateModel::create($data);
CacheService::clear();
return Json::successful('添加模板消息成功!');
}
@ -70,15 +73,15 @@ class RoutineTemplate extends AuthController
*/
public function edit($id)
{
if(!$id) return $this->failed('数据不存在');
if (!$id) return $this->failed('数据不存在');
$product = RoutineTemplateModel::get($id);
if(!$product) return Json::fail('数据不存在!');
if (!$product) return Json::fail('数据不存在!');
$f = array();
$f[] = Form::input('tempkey','模板编号',$product->getData('tempkey'))->disabled(1);
$f[] = Form::input('name','模板名',$product->getData('name'))->disabled(1);
$f[] = Form::input('tempid','模板ID',$product->getData('tempid'));
$f[] = Form::radio('status','状态',$product->getData('status'))->options([['label'=>'开启','value'=>1],['label'=>'关闭','value'=>0]]);
$form = Form::make_post_form('编辑模板消息',$f,Url::buildUrl('update',compact('id')));
$f[] = Form::input('tempkey', '模板编号', $product->getData('tempkey'))->disabled(1);
$f[] = Form::input('name', '模板名', $product->getData('name'))->disabled(1);
$f[] = Form::input('tempid', '模板ID', $product->getData('tempid'));
$f[] = Form::radio('status', '状态', $product->getData('status'))->options([['label' => '开启', 'value' => 1], ['label' => '关闭', 'value' => 0]]);
$form = Form::make_post_form('编辑模板消息', $f, Url::buildUrl('update', compact('id')));
$this->assign(compact('form'));
return $this->fetch('public/form-builder');
}
@ -87,13 +90,14 @@ class RoutineTemplate extends AuthController
{
$data = Util::postMore([
'tempid',
['status',0]
['status', 0]
]);
if($data['tempid'] == '') return Json::fail('请输入模板ID');
if(!$id) return $this->failed('数据不存在');
if ($data['tempid'] == '') return Json::fail('请输入模板ID');
if (!$id) return $this->failed('数据不存在');
$product = RoutineTemplateModel::get($id);
if(!$product) return Json::fail('数据不存在!');
RoutineTemplateModel::edit($data,$id);
if (!$product) return Json::fail('数据不存在!');
RoutineTemplateModel::edit($data, $id);
CacheService::clear();
return Json::successful('修改成功!');
}
@ -104,11 +108,13 @@ class RoutineTemplate extends AuthController
*/
public function delete($id)
{
if(!$id) return Json::fail('数据不存在!');
if(!RoutineTemplateModel::del($id))
if (!$id) return Json::fail('数据不存在!');
if (!RoutineTemplateModel::del($id))
return Json::fail(RoutineTemplateModel::getErrorInfo('删除失败,请稍候再试!'));
else
else {
CacheService::clear();
return Json::successful('删除成功!');
}
}

View File

@ -3,6 +3,7 @@
namespace app\admin\controller\system;
use app\admin\controller\AuthController;
use crmeb\services\CacheService;
use crmeb\services\JsonService as Json;
/**
@ -48,7 +49,7 @@ class Clear extends AuthController
}
}
}
CacheService::clear();
return app('json')->successful('数据缓存刷新成功!');
}

View File

@ -12,6 +12,8 @@ namespace app\admin\controller\system;
use app\admin\controller\AuthController;
use app\admin\model\store\StoreProduct;
use crmeb\services\JsonService as Json;
use crmeb\services\SystemConfigService;
use think\facade\Config;
use think\facade\Db;
/**
@ -19,117 +21,137 @@ use think\facade\Db;
* Class SystemclearData
* @package app\admin\controller\system
*/
class SystemclearData extends AuthController
class SystemclearData extends AuthController
{
public function index(){
return $this->fetch();
public function index()
{
return $this->fetch();
}
//清除用户数据
public function userRelevantData(){
self::clearData('user_recharge',1);
self::clearData('user_address',1);
self::clearData('user_bill',1);
self::clearData('user_enter',1);
self::clearData('user_extract',1);
self::clearData('user_notice',1);
self::clearData('user_notice_see',1);
self::clearData('wechat_qrcode',1);
self::clearData('wechat_message',1);
self::clearData('store_visit',1);
self::clearData('store_coupon_user',1);
self::clearData('store_coupon_issue_user',1);
self::clearData('store_bargain_user',1);
self::clearData('store_bargain_user_help',1);
self::clearData('store_product_reply',1);
self::clearData('store_product_cate',1);
self::clearData('routine_qrcode',1);
self::clearData('routine_form_id',1);
self::clearData('user_sign',1);
self::clearData('user_task_finish',1);
self::clearData('user_level',1);
self::clearData('user_token',1);
self::clearData('user_group',1);
public function userRelevantData()
{
self::clearData('user_recharge', 1);
self::clearData('user_address', 1);
self::clearData('user_bill', 1);
self::clearData('user_enter', 1);
self::clearData('user_extract', 1);
self::clearData('user_notice', 1);
self::clearData('user_notice_see', 1);
self::clearData('wechat_qrcode', 1);
self::clearData('wechat_message', 1);
self::clearData('store_visit', 1);
self::clearData('store_coupon_user', 1);
self::clearData('store_coupon_issue_user', 1);
self::clearData('store_bargain_user', 1);
self::clearData('store_bargain_user_help', 1);
self::clearData('store_product_reply', 1);
self::clearData('store_product_cate', 1);
self::clearData('routine_qrcode', 1);
self::clearData('routine_form_id', 1);
self::clearData('user_sign', 1);
self::clearData('user_task_finish', 1);
self::clearData('user_level', 1);
self::clearData('user_token', 1);
self::clearData('user_group', 1);
$this->delDirAndFile('./public/uploads/store/comment');
self::clearData('store_product_relation',1);
self::clearData('store_product_relation', 1);
return Json::successful('清除数据成功!');
}
//清除商城数据
public function storeData(){
self::clearData('store_coupon',1);
self::clearData('store_coupon_issue',1);
self::clearData('store_bargain',1);
self::clearData('store_combination',1);
self::clearData('store_combination_attr',1);
self::clearData('store_combination_attr_result',1);
self::clearData('store_combination_attr_value',1);
self::clearData('store_product_attr',1);
self::clearData('store_product_cate',1);
self::clearData('store_product_attr_result',1);
self::clearData('store_product_attr_value',1);
self::clearData('store_seckill',1);
self::clearData('store_seckill_attr',1);
self::clearData('store_seckill_attr_result',1);
self::clearData('store_seckill_attr_value',1);
self::clearData('store_product',1);
self::clearData('store_visit',1);
public function storeData()
{
self::clearData('store_coupon', 1);
self::clearData('store_coupon_issue', 1);
self::clearData('store_bargain', 1);
self::clearData('store_combination', 1);
self::clearData('store_combination_attr', 1);
self::clearData('store_combination_attr_result', 1);
self::clearData('store_combination_attr_value', 1);
self::clearData('store_product_attr', 1);
self::clearData('store_product_cate', 1);
self::clearData('store_product_attr_result', 1);
self::clearData('store_product_attr_value', 1);
self::clearData('store_seckill', 1);
self::clearData('store_seckill_attr', 1);
self::clearData('store_seckill_attr_result', 1);
self::clearData('store_seckill_attr_value', 1);
self::clearData('store_product', 1);
self::clearData('store_visit', 1);
return Json::successful('清除数据成功!');
}
//清除产品分类
public function categoryData(){
self::clearData('store_category',1);
public function categoryData()
{
self::clearData('store_category', 1);
return Json::successful('清除数据成功!');
}
//清除订单数据
public function orderData(){
self::clearData('store_order',1);
self::clearData('store_order_cart_info',1);
self::clearData('store_order_status',1);
self::clearData('store_pink',1);
self::clearData('store_cart',1);
self::clearData('store_order_status',1);
public function orderData()
{
self::clearData('store_order', 1);
self::clearData('store_order_cart_info', 1);
self::clearData('store_order_status', 1);
self::clearData('store_pink', 1);
self::clearData('store_cart', 1);
self::clearData('store_order_status', 1);
return Json::successful('清除数据成功!');
}
//清除客服数据
public function kefuData(){
self::clearData('store_service',1);
public function kefuData()
{
self::clearData('store_service', 1);
$this->delDirAndFile('./public/uploads/store/service');
self::clearData('store_service_log',1);
self::clearData('store_service_log', 1);
return Json::successful('清除数据成功!');
}
//清除微信管理数据
public function wechatData(){
self::clearData('wechat_media',1);
self::clearData('wechat_reply',1);
self::clearData('cache',1);
public function wechatData()
{
self::clearData('wechat_media', 1);
self::clearData('wechat_reply', 1);
self::clearData('cache', 1);
$this->delDirAndFile('./public/uploads/wechat');
return Json::successful('清除数据成功!');
}
//清除所有附件
public function uploadData(){
self::clearData('system_attachment',1);
self::clearData('system_attachment_category',1);
public function uploadData()
{
self::clearData('system_attachment', 1);
self::clearData('system_attachment_category', 1);
$this->delDirAndFile('./public/uploads/');
return Json::successful('清除上传文件成功!');
}
//清除微信用户
public function wechatuserData(){
self::clearData('wechat_user',1);
self::clearData('user',1);
public function wechatuserData()
{
self::clearData('wechat_user', 1);
self::clearData('user', 1);
return Json::successful('清除数据成功!');
}
//清除内容分类
public function articledata(){
self::clearData('article_category',1);
self::clearData('article',1);
self::clearData('article_content',1);
public function articledata()
{
self::clearData('article_category', 1);
self::clearData('article', 1);
self::clearData('article_content', 1);
return Json::successful('清除数据成功!');
}
//清除系统记录
public function systemdata(){
self::clearData('system_notice_admin',1);
self::clearData('system_log',1);
public function systemdata()
{
self::clearData('system_notice_admin', 1);
self::clearData('system_log', 1);
return Json::successful('清除数据成功!');
}
@ -140,39 +162,91 @@ class SystemclearData extends AuthController
*/
public function undata($type = 1)
{
switch ((int)$type){
switch ((int)$type) {
case 1:
\app\admin\model\system\SystemAttachment::where('module_type',2)->delete();
$fileImage = \app\admin\model\system\SystemAttachment::where('module_type', 2)->field(['att_dir', 'satt_dir'])->select();
foreach ($fileImage as $image) {
if ($image['att_dir'] && ($imagePath = strstr($image['att_dir'], 'uploads')) !== false) {
if (is_file($imagePath))
unlink($imagePath);
unset($imagePath);
}
if ($image['satt_dir'] && ($imagePath = strstr($image['satt_dir'], 'uploads')) !== false) {
if (is_file($imagePath))
unlink($imagePath);
unset($imagePath);
}
}
\app\admin\model\system\SystemAttachment::where('module_type', 2)->delete();
@unlink('uploads/follow/follow.jpg');//删除海报二维码
break;
case 2:
StoreProduct::where('is_del',1)->delete();
StoreProduct::where('is_del', 1)->delete();
break;
case 3:
$value = $this->request->param('value');
if (!$value)
return Json::fail('请输入需要更换的域名');
if (!verify_domain($value))
return Json::fail('域名不合法');
$siteUrl = SystemConfigService::get('site_url', true);
$siteUrlJosn = str_replace('http://', 'http:\\/\\/', $siteUrl);
$valueJosn = str_replace('http://', 'http:\\/\\/', $value);
$prefix = Config::get('database.connections.' . Config::get('database.default') . '.prefix');
$sql = [
"UPDATE `{$prefix}system_attachment` SET `att_dir` = replace(att_dir ,'{$siteUrl}','{$value}'),`satt_dir` = replace(satt_dir ,'{$siteUrl}','{$value}')",
"UPDATE `{$prefix}store_product` SET `image` = replace(image ,'{$siteUrl}','{$value}'),`slider_image` = replace(slider_image ,'{$siteUrl}','{$value}'),`description`= replace(description,'{$siteUrl}','{$value}')",
"UPDATE `{$prefix}store_product_attr_value` SET `image` = replace(image ,'{$siteUrl}','{$value}')",
"UPDATE `{$prefix}store_seckill` SET `image` = replace(image ,'{$siteUrl}','{$value}'),`images` = replace(images,'{$siteUrl}','{$value}'),`description` = replace(description,'{$siteUrl}','{$value}')",
"UPDATE `{$prefix}store_combination` SET `image` = replace(image ,'{$siteUrl}','{$value}'),`images` = replace(images,'{$siteUrl}','{$value}'),`description` = replace(description,'{$siteUrl}','{$value}')",
"UPDATE `{$prefix}store_bargain` SET `image` = replace(image ,'{$siteUrl}','{$value}'),`images` = replace(images,'{$siteUrl}','{$value}'),`description` = replace(description,'{$siteUrl}','{$value}')",
"UPDATE `{$prefix}system_config` SET `value` = replace(value ,'{$siteUrlJosn}','{$valueJosn}')",
"UPDATE `{$prefix}article_category` SET `image` = replace(`image` ,'{$siteUrl}','{$value}')",
"UPDATE `{$prefix}article` SET `image_input` = replace(`image_input` ,'{$siteUrl}','{$value}')",
"UPDATE `{$prefix}article_content` SET `content` = replace(`content` ,'{$siteUrl}','{$value}')",
"UPDATE `{$prefix}store_category` SET `pic` = replace(`pic` ,'{$siteUrl}','{$value}')",
"UPDATE `{$prefix}system_group_data` SET `value` = replace(value ,'{$siteUrlJosn}','{$valueJosn}')"
];
try {
foreach ($sql as $item) {
db::execute($item);
}
} catch (\Throwable $e) {
return Json::fail('替换失败,失败原因:' . $e->getMessage());
}
return Json::success('替换成功!');
break;
}
return Json::successful('清除数据成功!');
}
//清除制定表数据
public function clearData($table_name,$status){
$table_name = config('database.connections.' . config('database.default'))['prefix'].$table_name;
if($status){
@db::execute('TRUNCATE TABLE '.$table_name);
}else{
@db::execute('DELETE FROM'.$table_name);
public function clearData($table_name, $status)
{
$table_name = config('database.connections.' . config('database.default'))['prefix'] . $table_name;
if ($status) {
@db::execute('TRUNCATE TABLE ' . $table_name);
} else {
@db::execute('DELETE FROM' . $table_name);
}
}
//递归删除文件
function delDirAndFile($dirName,$subdir=true){
if ($handle = @opendir("$dirName")){
while(false !== ($item = readdir($handle))){
if($item != "." && $item != ".."){
if(is_dir("$dirName/$item"))
$this->delDirAndFile("$dirName/$item",false);
function delDirAndFile($dirName, $subdir = true)
{
if ($handle = @opendir("$dirName")) {
while (false !== ($item = readdir($handle))) {
if ($item != "." && $item != "..") {
if (is_dir("$dirName/$item"))
$this->delDirAndFile("$dirName/$item", false);
else
@unlink("$dirName/$item");
}
}
closedir($handle);
if(!$subdir) @rmdir($dirName);
if (!$subdir) @rmdir($dirName);
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -5,6 +5,7 @@
* Date: 2018-03-03
* Time: 16:47
*/
namespace app\admin\model\user;
use app\admin\model\wechat\WechatUser;
@ -40,9 +41,9 @@ class UserExtract extends BaseModel
* @param $uid
* @return mixed
*/
public static function userExtractTotalPrice($uid,$status=1,$where=[])
public static function userExtractTotalPrice($uid, $status = 1, $where = [])
{
return self::getModelTime($where,self::where('uid','in',$uid)->where('status',$status))->sum('extract_price')?:0;
return self::getModelTime($where, self::where('uid', 'in', $uid)->where('status', $status))->sum('extract_price') ?: 0;
}
public static function extractStatistics()
@ -54,7 +55,7 @@ class UserExtract extends BaseModel
//已提现金额
$data['priced'] = floatval(self::where('status', 1)->sum('extract_price'));
//未提现金额
$data['brokerage_not'] = bcsub(bcsub($data['brokerage_count'], $data['priced'], 2), $data['price'], 2);
$data['brokerage_not'] = bcsub(bcsub($data['brokerage_count'], $data['priced'], 2), $data['price'], 2);
return compact('data');
}
@ -65,61 +66,56 @@ class UserExtract extends BaseModel
public static function systemPage($where)
{
$model = new self;
if($where['date'] != '') {
if ($where['date'] != '') {
list($startTime, $endTime) = explode(' - ', $where['date']);
$model = $model->where('a.add_time', '>', strtotime($startTime));
$model = $model->where('a.add_time', '<', (int)bcadd(strtotime($endTime), 86400, 0));
}
if($where['status'] != '') $model = $model->where('a.status',$where['status']);
if($where['extract_type'] != '') $model = $model->where('a.extract_type',$where['extract_type']);
if($where['nireid'] != '') $model = $model->where('a.real_name|a.id|b.nickname|a.bank_code|a.alipay_code','like',"%$where[nireid]%");
if ($where['status'] != '') $model = $model->where('a.status', $where['status']);
if ($where['extract_type'] != '') $model = $model->where('a.extract_type', $where['extract_type']);
if ($where['nireid'] != '') $model = $model->where('a.real_name|a.id|b.nickname|a.bank_code|a.alipay_code', 'like', "%$where[nireid]%");
$model = $model->alias('a');
$model = $model->field('a.*,b.nickname');
$model = $model->join('user b','b.uid=a.uid','LEFT');
$model = $model->join('user b', 'b.uid=a.uid', 'LEFT');
$model = $model->order('a.id desc');
return self::page($model, $where);
}
public static function changeFail($id,$fail_msg)
public static function changeFail($id, $fail_msg)
{
$fail_time = time();
$data =self::get($id);
$extract_number=$data['extract_price'];
$mark='提现失败,退回佣金'.$extract_number.'元';
$uid=$data['uid'];
$data = self::get($id);
$extract_number = $data['extract_price'];
$mark = '提现失败,退回佣金' . $extract_number . '元';
$uid = $data['uid'];
$status = -1;
$User= User::where('uid', $uid)->find()->toArray();
UserBill::income('提现失败',$uid,'now_money','extract',$extract_number,$id,bcadd($User['now_money'],$extract_number,2),$mark);
User::bcInc($uid,'brokerage_price',$extract_number,'uid');
$extract_type='未知方式';
switch ($data['extract_type']){
$User = User::where('uid', $uid)->find()->toArray();
UserBill::income('提现失败', $uid, 'now_money', 'extract', $extract_number, $id, bcadd($User['now_money'], $extract_number, 2), $mark);
User::bcInc($uid, 'brokerage_price', $extract_number, 'uid');
$extract_type = '未知方式';
switch ($data['extract_type']) {
case 'alipay':
$extract_type='支付宝';
$extract_type = '支付宝';
break;
case 'bank':
$extract_type='银行卡';
$extract_type = '银行卡';
break;
case 'weixin':
$extract_type='微信';
$extract_type = '微信';
break;
}
if(strtolower($User['user_type']) == 'wechat'){
WechatTemplateService::sendTemplate(WechatUser::where('uid',$uid)->value('openid'),WechatTemplateService::USER_BALANCE_CHANGE,[
'first'=> $mark,
'keyword1'=>'佣金提现',
'keyword2'=>date('Y-m-d H:i:s',time()),
'keyword3'=>$extract_number,
'remark'=>'错误原因:'.$fail_msg
],Url::buildUrl('/user/cashrecord')->suffix('')->domain(true)->build());
}else if(strtolower($User['user_type'])=='routine'){
RoutineTemplate::sendOut('USER_EXTRACT_FALSE',$uid,[
'keyword1'=>$fail_msg,
'keyword2'=>$extract_number,
'keyword3'=>$extract_type,
'keyword4'=>date('Y-m-d H:i:s',time()),
]);
if (strtolower($User['user_type']) == 'wechat') {
WechatTemplateService::sendTemplate(WechatUser::where('uid', $uid)->value('openid'), WechatTemplateService::USER_BALANCE_CHANGE, [
'first' => $mark,
'keyword1' => '佣金提现',
'keyword2' => date('Y-m-d H:i:s', time()),
'keyword3' => $extract_number,
'remark' => '错误原因:' . $fail_msg
], Url::buildUrl('/user/cashrecord')->suffix('')->domain(true)->build());
} else if (strtolower($User['user_type']) == 'routine') {
RoutineTemplate::sendExtractFail($uid, $fail_msg, $extract_number, $User['nickname']);
}
return self::edit(compact('fail_time','fail_msg','status'),$id);
return self::edit(compact('fail_time', 'fail_msg', 'status'), $id);
}
public static function changeSuccess($id)
@ -127,29 +123,24 @@ class UserExtract extends BaseModel
$data = self::get($id);
$extractNumber = $data['extract_price'];
$mark = '成功提现佣金'.$extractNumber.'元';
$wechatUserInfo = WechatUser::where('uid',$data['uid'])->field('openid,user_type,routine_openid')->find();
$extract_type='未知方式';
switch ($data['extract_type']){
$mark = '成功提现佣金' . $extractNumber . '元';
$wechatUserInfo = WechatUser::where('uid', $data['uid'])->field('openid,user_type,routine_openid,nickname')->find();
$extract_type = '未知方式';
switch ($data['extract_type']) {
case 'alipay':
$extract_type='支付宝';
$extract_type = '支付宝';
break;
case 'bank':
$extract_type='银行卡';
$extract_type = '银行卡';
break;
case 'weixin':
$extract_type='微信';
$extract_type = '微信';
break;
}
if($wechatUserInfo){
if(strtolower($wechatUserInfo->user_type)=='routine'){
RoutineTemplate::sendOut('USER_EXTRACT_TRUE',$data['uid'],[
'keyword1'=>$extractNumber.'元',
'keyword2'=>'审核成功',
'keyword3'=>date('Y-m-d H:i:s', time()),
'keyword4'=>$extract_type,
]);
}else if(strtolower($wechatUserInfo->user_type)=='wechat'){
if ($wechatUserInfo) {
if (strtolower($wechatUserInfo->user_type) == 'routine') {
RoutineTemplate::sendExtractSuccess($data['uid'], $extractNumber, $wechatUserInfo->nickname);
} else if (strtolower($wechatUserInfo->user_type) == 'wechat') {
WechatTemplateService::sendTemplate($wechatUserInfo->openid, WechatTemplateService::USER_BALANCE_CHANGE, [
'first' => $mark,
'keyword1' => '佣金提现',
@ -159,163 +150,169 @@ class UserExtract extends BaseModel
], Url::buildUrl('/user/cashrecord')->suffix('')->domain(true)->build());
}
}
return self::edit(['status'=>1],$id);
return self::edit(['status' => 1], $id);
}
//测试数据
public static function test(){
$uids=User::order('uid desc')->limit(2,20)->field(['uid','nickname'])->select()->toArray();
$type=['bank','alipay','weixin'];
foreach ($uids as $item){
$data=[
'uid'=>$item['uid'],
'real_name'=>$item['nickname'],
'extract_type'=>isset($type[rand(0,2)]) ? $type[rand(0,2)] :'alipay',
'bank_code'=>rand(1000000,999999999),
'bank_address'=>'中国',
'alipay_code'=>rand(1000,9999999),
'extract_price'=>rand(100,9999),
'mark'=>'测试数据',
'add_time'=>time(),
'status'=>1,
'wechat'=>rand(999,878788).$item['uid'],
public static function test()
{
$uids = User::order('uid desc')->limit(2, 20)->field(['uid', 'nickname'])->select()->toArray();
$type = ['bank', 'alipay', 'weixin'];
foreach ($uids as $item) {
$data = [
'uid' => $item['uid'],
'real_name' => $item['nickname'],
'extract_type' => isset($type[rand(0, 2)]) ? $type[rand(0, 2)] : 'alipay',
'bank_code' => rand(1000000, 999999999),
'bank_address' => '中国',
'alipay_code' => rand(1000, 9999999),
'extract_price' => rand(100, 9999),
'mark' => '测试数据',
'add_time' => time(),
'status' => 1,
'wechat' => rand(999, 878788) . $item['uid'],
];
self::create($data);
}
}
//获取头部提现信息
public static function getExtractHead(){
public static function getExtractHead()
{
//本月提现人数
$month=self::getModelTime(['data'=>'month'],self::where('status', 1))->group('uid')->count();
$month = self::getModelTime(['data' => 'month'], self::where('status', 1))->group('uid')->count();
//本月提现笔数
$new_month=self::getModelTime(['data'=>'month'],self::where('status', 1))->distinct(true)->count();
$new_month = self::getModelTime(['data' => 'month'], self::where('status', 1))->distinct(true)->count();
//上月提现人数
$last_month=self::whereTime('add_time','last month')->where('status',1)->group('uid')->distinct(true)->count();
$last_month = self::whereTime('add_time', 'last month')->where('status', 1)->group('uid')->distinct(true)->count();
//上月提现笔数
$last_count=self::whereTime('add_time','last month')->where('status',1)->count();
$last_count = self::whereTime('add_time', 'last month')->where('status', 1)->count();
//本月提现金额
$extract_price=self::getModelTime(['data'=>'month'],self::where('status', 1))->sum('extract_price');
$extract_price = self::getModelTime(['data' => 'month'], self::where('status', 1))->sum('extract_price');
//上月提现金额
$last_extract_price=self::whereTime('add_time','last month')->where('status',1)->sum('extract_price');
$last_extract_price = self::whereTime('add_time', 'last month')->where('status', 1)->sum('extract_price');
return [
[
'name'=>'总提现人数',
'field'=>'个',
'count'=>self::where('status', 1)->group('uid')->count(),
'content'=>'',
'background_color'=>'layui-bg-blue',
'sum'=>'',
'class'=>'fa fa-bar-chart',
'name' => '总提现人数',
'field' => '个',
'count' => self::where('status', 1)->group('uid')->count(),
'content' => '',
'background_color' => 'layui-bg-blue',
'sum' => '',
'class' => 'fa fa-bar-chart',
],
[
'name'=>'总提现笔数',
'field'=>'笔',
'count'=>self::where('status', 1)->distinct(true)->count(),
'content'=>'',
'background_color'=>'layui-bg-cyan',
'sum'=>'',
'class'=>'fa fa-line-chart',
'name' => '总提现笔数',
'field' => '笔',
'count' => self::where('status', 1)->distinct(true)->count(),
'content' => '',
'background_color' => 'layui-bg-cyan',
'sum' => '',
'class' => 'fa fa-line-chart',
],
[
'name'=>'本月提现人数',
'field'=>'人',
'count'=>$month,
'content'=>'',
'background_color'=>'layui-bg-orange',
'sum'=>'',
'class'=>'fa fa-line-chart',
'name' => '本月提现人数',
'field' => '人',
'count' => $month,
'content' => '',
'background_color' => 'layui-bg-orange',
'sum' => '',
'class' => 'fa fa-line-chart',
],
[
'name'=>'本月提现笔数',
'field'=>'笔',
'count'=>$new_month,
'content'=>'',
'background_color'=>'layui-bg-green',
'sum'=>'',
'class'=>'fa fa-line-chart',
'name' => '本月提现笔数',
'field' => '笔',
'count' => $new_month,
'content' => '',
'background_color' => 'layui-bg-green',
'sum' => '',
'class' => 'fa fa-line-chart',
],
[
'name'=>'本月提现金额',
'field'=>'元',
'count'=>$extract_price,
'content'=>'提现总金额',
'background_color'=>'layui-bg-cyan',
'sum'=>self::where('status', 1)->sum('extract_price'),
'class'=>'fa fa-line-chart',
'name' => '本月提现金额',
'field' => '元',
'count' => $extract_price,
'content' => '提现总金额',
'background_color' => 'layui-bg-cyan',
'sum' => self::where('status', 1)->sum('extract_price'),
'class' => 'fa fa-line-chart',
],
[
'name'=>'上月提现人数',
'field'=>'个',
'count'=>$last_month,
'content'=>'环比增幅',
'background_color'=>'layui-bg-blue',
'sum'=>$last_month==0 ? '100%' :bcdiv($month,$last_month,2)*100,
'class'=>$last_month==0 ? 'fa fa-level-up':'fa fa-level-down',
'name' => '上月提现人数',
'field' => '个',
'count' => $last_month,
'content' => '环比增幅',
'background_color' => 'layui-bg-blue',
'sum' => $last_month == 0 ? '100%' : bcdiv($month, $last_month, 2) * 100,
'class' => $last_month == 0 ? 'fa fa-level-up' : 'fa fa-level-down',
],
[
'name'=>'上月提现笔数',
'field'=>'笔',
'count'=>$last_count,
'content'=>'环比增幅',
'background_color'=>'layui-bg-black',
'sum'=>$last_count==0 ? '100%':bcdiv($new_month,$last_count,2)*100,
'class'=>$last_count==0 ? 'fa fa-level-up':'fa fa-level-down',
'name' => '上月提现笔数',
'field' => '笔',
'count' => $last_count,
'content' => '环比增幅',
'background_color' => 'layui-bg-black',
'sum' => $last_count == 0 ? '100%' : bcdiv($new_month, $last_count, 2) * 100,
'class' => $last_count == 0 ? 'fa fa-level-up' : 'fa fa-level-down',
],
[
'name'=>'上月提现金额',
'field'=>'元',
'count'=>$last_extract_price,
'content'=>'环比增幅',
'background_color'=>'layui-bg-gray',
'sum'=>$last_extract_price==0 ? '100%':bcdiv($extract_price,$last_extract_price,2)*100,
'class'=>$last_extract_price==0 ? 'fa fa-level-up':'fa fa-level-down',
'name' => '上月提现金额',
'field' => '元',
'count' => $last_extract_price,
'content' => '环比增幅',
'background_color' => 'layui-bg-gray',
'sum' => $last_extract_price == 0 ? '100%' : bcdiv($extract_price, $last_extract_price, 2) * 100,
'class' => $last_extract_price == 0 ? 'fa fa-level-up' : 'fa fa-level-down',
],
];
}
//获取提现分布图和提现人数金额曲线图
public static function getExtractList($where,$limit=15){
$legdata=['提现人数','提现金额'];
$list=self::getModelTime($where,self::where('status',1))
public static function getExtractList($where, $limit = 15)
{
$legdata = ['提现人数', '提现金额'];
$list = self::getModelTime($where, self::where('status', 1))
->field('FROM_UNIXTIME(add_time,"%Y-%c-%d") as un_time,count(uid) as count,sum(extract_price) as sum_price')->group('un_time')->order('un_time asc')->select();
if(count($list)) $list=$list->toArray();
if (count($list)) $list = $list->toArray();
$xdata = [];
$itemList = [0=>[],1=>[]];
$itemList = [0 => [], 1 => []];
$chatrList = [];
$zoom = '';
foreach ($list as $value){
$xdata[]=$value['un_time'];
$itemList[0][]=$value['count'];
$itemList[1][]=$value['sum_price'];
foreach ($list as $value) {
$xdata[] = $value['un_time'];
$itemList[0][] = $value['count'];
$itemList[1][] = $value['sum_price'];
}
foreach ($legdata as $key=>$name){
$item['name']=$name;
$item['type']='line';
$item['data']=$itemList[$key];
$chatrList[]=$item;
foreach ($legdata as $key => $name) {
$item['name'] = $name;
$item['type'] = 'line';
$item['data'] = $itemList[$key];
$chatrList[] = $item;
}
unset($item,$name,$key);
if(count($xdata)>$limit) $zoom=$xdata[$limit-5];
unset($item, $name, $key);
if (count($xdata) > $limit) $zoom = $xdata[$limit - 5];
//饼状图
$cake=['支付宝','银行卡','微信'];
$fenbulist=self::getModelTime($where,self::where('status',1))
$cake = ['支付宝', '银行卡', '微信'];
$fenbulist = self::getModelTime($where, self::where('status', 1))
->field('count(uid) as count,extract_type')->group('extract_type')->order('count asc')->select();
if(count($fenbulist)) $fenbulist = $fenbulist->toArray();
$sum_count = self::getModelTime($where,self::where('status',1))->count();
$color = ['#FB7773','#81BCFE','#91F3FE'];
if (count($fenbulist)) $fenbulist = $fenbulist->toArray();
$sum_count = self::getModelTime($where, self::where('status', 1))->count();
$color = ['#FB7773', '#81BCFE', '#91F3FE'];
$fenbudata = [];
foreach ($fenbulist as $key=>$item){
if($item['extract_type']=='bank'){
$item_date['name']='银行卡';
}else if($item['extract_type']=='alipay'){
$item_date['name']='支付宝';
}else if($item['extract_type']=='weixin'){
$item_date['name']='微信';
foreach ($fenbulist as $key => $item) {
if ($item['extract_type'] == 'bank') {
$item_date['name'] = '银行卡';
} else if ($item['extract_type'] == 'alipay') {
$item_date['name'] = '支付宝';
} else if ($item['extract_type'] == 'weixin') {
$item_date['name'] = '微信';
}
$item_date['value']=bcdiv($item['count'],$sum_count,2)*100;
$item_date['itemStyle']['color']=$color[$key];
$fenbudata[]=$item_date;
$item_date['value'] = bcdiv($item['count'], $sum_count, 2) * 100;
$item_date['itemStyle']['color'] = $color[$key];
$fenbudata[] = $item_date;
}
return compact('xdata','chatrList','legdata','zoom','cake','fenbudata');
return compact('xdata', 'chatrList', 'legdata', 'zoom', 'cake', 'fenbudata');
}
/**
@ -323,9 +320,10 @@ class UserExtract extends BaseModel
* @param int $uid
* @return int|mixed
*/
public static function getUserCountPrice($uid = 0){
if(!$uid) return 0;
$price = self::where('uid',$uid)->where('status',1)->sum('extract_price');
public static function getUserCountPrice($uid = 0)
{
if (!$uid) return 0;
$price = self::where('uid', $uid)->where('status', 1)->sum('extract_price');
return $price ? $price : 0;
}
@ -334,8 +332,9 @@ class UserExtract extends BaseModel
* @param int $uid
* @return int|string
*/
public static function getUserCountNum($uid = 0){
if(!$uid) return 0;
return self::where('uid',$uid)->count();
public static function getUserCountNum($uid = 0)
{
if (!$uid) return 0;
return self::where('uid', $uid)->count();
}
}

View File

@ -266,6 +266,7 @@
{include file="public/style"}
<script>
window.newOrderAudioLink='{$new_order_audio_link}';
window.workermanPort = '{$workermanPort}';
</script>
<script src="{__FRAME_PATH}js/index.js"></script>
</body>

View File

@ -0,0 +1,35 @@
{extend name="public/container"}
{block name="content"}
<div class="ibox-content order-info">
<div class="row">
<div class="col-sm-12">
<div class="panel panel-default">
<div class="panel-heading">
<img src="{$spread.avatar}" width="50" height="50" style="border-radius: 60px;" />
<span style="font-size: 16px">{$spread.nickname}</span>
</div>
<div class="panel-body">
<div class="row show-grid">
<div class="col-xs-6" style="color: #ff0005">余额:¥ {$spread.now_money}</div>
<div class="col-xs-6">UID{$spread.uid}</div>
<div class="col-xs-6" style="color: green">佣金:¥ {$spread.brokerage_price}</div>
<div class="col-xs-6">真实姓名:{$spread.real_name}</div>
<div class="col-xs-6">身份证:{$spread.card_id}</div>
<div class="col-xs-6">手机号码:{$spread.phone}</div>
<div class="col-xs-6">生日:{$spread.birthday}</div>
<div class="col-xs-6">积分:{$spread.integral}</div>
<div class="col-xs-6">用户备注:{$spread.mark}</div>
<div class="col-xs-6">最后登录时间:{$spread.last_time|date="Y/m/d H:i"}</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="{__FRAME_PATH}js/content.min.js?v=1.0.0"></script>
{/block}
{block name="script"}
{/block}

View File

@ -70,11 +70,6 @@ class AuthController
return app('json')->success('成功');
}
public function test()
{
echo 'test';
}
/**
* 验证码发送
* @param Request $request

View File

@ -12,7 +12,6 @@ use app\models\user\UserBill;
use app\models\user\WechatUser;
use app\Request;
use crmeb\services\GroupDataService;
use crmeb\services\SystemConfigService;
use crmeb\services\UploadService;
use crmeb\services\UtilService;
use crmeb\services\workerman\ChannelService;
@ -38,28 +37,29 @@ class PublicController
$menus = GroupDataService::getData('routine_home_menus') ?: [];//TODO 首页按钮
$roll = GroupDataService::getData('routine_home_roll_news') ?: [];//TODO 首页滚动新闻
$activity = GroupDataService::getData('routine_home_activity', 3) ?: [];//TODO 首页活动区域图片
$site_name = sysConfig('site_name');
$site_name = sys_config('site_name');
$routine_index_page = GroupDataService::getData('routine_index_page');
$info['fastInfo'] = $routine_index_page[0]['fast_info'] ?? '';//sysConfig('fast_info');//TODO 快速选择简介
$info['bastInfo'] = $routine_index_page[0]['bast_info'] ?? '';//sysConfig('bast_info');//TODO 精品推荐简介
$info['firstInfo'] = $routine_index_page[0]['first_info'] ?? '';//sysConfig('first_info');//TODO 首发新品简介
$info['salesInfo'] = $routine_index_page[0]['sales_info'] ?? '';//sysConfig('sales_info');//TODO 促销单品简介
$logoUrl = sysConfig('routine_index_logo');//TODO 促销单品简介
if (strstr($logoUrl, 'http') === false) $logoUrl = sysConfig('site_url') . $logoUrl;
$info['fastInfo'] = $routine_index_page[0]['fast_info'] ?? '';//sys_config('fast_info');//TODO 快速选择简介
$info['bastInfo'] = $routine_index_page[0]['bast_info'] ?? '';//sys_config('bast_info');//TODO 精品推荐简介
$info['firstInfo'] = $routine_index_page[0]['first_info'] ?? '';//sys_config('first_info');//TODO 首发新品简介
$info['salesInfo'] = $routine_index_page[0]['sales_info'] ?? '';//sys_config('sales_info');//TODO 促销单品简介
$logoUrl = sys_config('routine_index_logo');//TODO 促销单品简介
if (strstr($logoUrl, 'http') === false && $logoUrl) $logoUrl = sys_config('site_url') . $logoUrl;
$logoUrl = str_replace('\\', '/', $logoUrl);
$fastNumber = $routine_index_page[0]['fast_number'] ?? 6;//sysConfig('fast_number');//TODO 快速选择分类个数
$bastNumber = $routine_index_page[0]['bast_number'] ?? 6;//sysConfig('bast_number');//TODO 精品推荐个数
$firstNumber = $routine_index_page[0]['first_number'] ?? 6;//sysConfig('first_number');//TODO 首发新品个数
$info['fastList'] = StoreCategory::byIndexList((int)$fastNumber);//TODO 快速选择分类个数
$info['bastList'] = StoreProduct::getBestProduct('id,image,store_name,cate_id,price,ot_price,IFNULL(sales,0) + IFNULL(ficti,0) as sales,unit_name', (int)$bastNumber, $request->uid());//TODO 精品推荐个数
$info['firstList'] = StoreProduct::getNewProduct('id,image,store_name,cate_id,price,unit_name,IFNULL(sales,0) + IFNULL(ficti,0) as sales', (int)$firstNumber, $request->uid());//TODO 首发新品个数
$fastNumber = $routine_index_page[0]['fast_number'] ?? 0;//sys_config('fast_number');//TODO 快速选择分类个数
$bastNumber = $routine_index_page[0]['bast_number'] ?? 0;//sys_config('bast_number');//TODO 精品推荐个数
$firstNumber = $routine_index_page[0]['first_number'] ?? 0;//sys_config('first_number');//TODO 首发新品个数
$info['fastList'] = StoreCategory::byIndexList((int)$fastNumber, false);//TODO 快速选择分类个数
$info['bastList'] = StoreProduct::getBestProduct('id,image,store_name,cate_id,price,ot_price,IFNULL(sales,0) + IFNULL(ficti,0) as sales,unit_name', (int)$bastNumber, $request->uid(), false);//TODO 精品推荐个数
$info['firstList'] = StoreProduct::getNewProduct('id,image,store_name,cate_id,price,unit_name,IFNULL(sales,0) + IFNULL(ficti,0) as sales', (int)$firstNumber, $request->uid(), false);//TODO 首发新品个数
$info['bastBanner'] = GroupDataService::getData('routine_home_bast_banner') ?? [];//TODO 首页精品推荐图片
$benefit = StoreProduct::getBenefitProduct('id,image,store_name,cate_id,price,ot_price,stock,unit_name', 3);//TODO 首页促销单品
$lovely = GroupDataService::getData('routine_home_new_banner') ?: [];//TODO 首发新品顶部图
$likeInfo = StoreProduct::getHotProduct('id,image,store_name,cate_id,price,unit_name', 3);//TODO 热门榜单 猜你喜欢
$couponList = StoreCouponIssue::getIssueCouponList($request->uid(), 3);
$subscribe = WechatUser::where('uid', $request->uid() ?? 0)->value('subscribe') ? true : false;
return app('json')->successful(compact('banner', 'menus', 'roll', 'info', 'activity', 'lovely', 'benefit', 'likeInfo', 'logoUrl', 'couponList', 'site_name','subscribe'));
$newGoodsBananr = sys_config('new_goods_bananr');
return app('json')->successful(compact('banner', 'menus', 'roll', 'info', 'activity', 'lovely', 'benefit', 'likeInfo', 'logoUrl', 'couponList', 'site_name', 'subscribe','newGoodsBananr'));
}
/**
@ -68,11 +68,11 @@ class PublicController
*/
public function share()
{
$data['img'] = sysConfig('wechat_share_img');
if (strstr($data['img'], 'http') === false) $data['img'] = sysConfig('site_url') . $data['img'];
$data['img'] = sys_config('wechat_share_img');
if (strstr($data['img'], 'http') === false) $data['img'] = sys_config('site_url') . $data['img'];
$data['img'] = str_replace('\\', '/', $data['img']);
$data['title'] = sysConfig('wechat_share_title');
$data['synopsis'] = sysConfig('wechat_share_synopsis');
$data['title'] = sys_config('wechat_share_title');
$data['synopsis'] = sys_config('wechat_share_synopsis');
return app('json')->successful(compact('data'));
}
@ -89,11 +89,11 @@ class PublicController
{
$menusInfo = GroupDataService::getData('routine_my_menus') ?? [];
$user = $request->user();
$vipOpen = sysConfig('vip_open');
$vipOpen = sys_config('vip_open');
$vipOpen = is_string($vipOpen) ? (int)$vipOpen : $vipOpen;
foreach ($menusInfo as $key => &$value) {
$value['pic'] = UtilService::setSiteUrl($value['pic']);
if ($value['id'] == 137 && !(intval(sysConfig('store_brokerage_statu')) == 2 || $user->is_promoter == 1))
$value['pic'] = set_file_url($value['pic']);
if ($value['id'] == 137 && !(intval(sys_config('store_brokerage_statu')) == 2 || $user->is_promoter == 1))
unset($menusInfo[$key]);
if ($value['id'] == 174 && !StoreService::orderServiceStatus($user->uid))
unset($menusInfo[$key]);
@ -149,7 +149,7 @@ class PublicController
$start_uploads = 0;
$start_uploads++;
Cache::set('start_uploads_' . $request->uid(), $start_uploads, 86400);
$res['dir'] = UploadService::pathToUrl($res['dir']);
$res['dir'] = path_to_url($res['dir']);
if (strpos($res['dir'], 'http') === false) $res['dir'] = $request->domain() . $res['dir'];
return app('json')->successful('图片上传成功!', ['name' => $res['name'], 'url' => $res['dir']]);
}
@ -210,8 +210,8 @@ class PublicController
['code', ''],
], $request, true);
try {
$code = $codeUrl ? UtilService::setImageBase64($codeUrl) : false;
$image = $imageUrl ? UtilService::setImageBase64($imageUrl) : false;
$code = $codeUrl ? image_to_base64($codeUrl) : false;
$image = $imageUrl ? image_to_base64($imageUrl) : false;
return app('json')->successful(compact('code', 'image'));
} catch (\Exception $e) {
return app('json')->fail($e->getMessage());

View File

@ -4,8 +4,10 @@
namespace app\api\controller\wechat;
use app\models\routine\RoutineTemplate;
use app\models\user\WechatUser;
use app\Request;
use crmeb\services\CacheService;
use crmeb\services\MiniProgramService;
use crmeb\services\UtilService;
use app\models\user\UserToken;
@ -13,6 +15,7 @@ use crmeb\services\SystemConfigService;
use app\models\user\User;
use app\models\routine\RoutineFormId;
use think\facade\Cache;
use crmeb\services\SubscribeTemplateService;
/**
* 小程序相关
@ -34,20 +37,20 @@ class AuthController
public function mp_auth(Request $request)
{
$cache_key = '';
list($code,$post_cache_key,$login_type) = UtilService::postMore([
['code',''],
['cache_key',''],
['login_type','']
],$request,true);
$session_key = Cache::get('eb_api_code_'.$post_cache_key);
list($code, $post_cache_key, $login_type) = UtilService::postMore([
['code', ''],
['cache_key', ''],
['login_type', '']
], $request, true);
$session_key = Cache::get('eb_api_code_' . $post_cache_key);
if (!$code && !$session_key)
return app('json')->fail('授权失败,参数有误');
if($code && !$session_key){
if ($code && !$session_key) {
try {
$userInfoCong = MiniProgramService::getUserInfo($code);
$session_key = $userInfoCong['session_key'];
$cache_key = md5(time().$code);
Cache::set('eb_api_code_'.$cache_key,$session_key,86400);
$cache_key = md5(time() . $code);
Cache::set('eb_api_code_' . $cache_key, $session_key, 86400);
} catch (\Exception $e) {
return app('json')->fail('获取session_key失败请检查您的配置', ['line' => $e->getLine(), 'message' => $e->getMessage()]);
}
@ -72,12 +75,12 @@ class AuthController
$userInfo['session_key'] = $session_key;
$userInfo['login_type'] = $login_type;
$uid = WechatUser::routineOauth($userInfo);
$userInfo = User::where('uid',$uid)->find();
if($userInfo->login_type == 'h5' && ($h5UserInfo = User::where(['account'=>$userInfo->phone,'phone'=>$userInfo->phone,'user_type'=>'h5'])->find()))
$userInfo = User::where('uid', $uid)->find();
if ($userInfo->login_type == 'h5' && ($h5UserInfo = User::where(['account' => $userInfo->phone, 'phone' => $userInfo->phone, 'user_type' => 'h5'])->find()))
$token = UserToken::createToken($userInfo, 'routine');
else
$token = UserToken::createToken($userInfo, 'routine');
if($token) {
if ($token) {
event('UserLogin', [$userInfo, $token]);
return app('json')->successful('登陆成功!', [
'token' => $token->token,
@ -85,7 +88,7 @@ class AuthController
'expires_time' => strtotime($token->expires_time),
'cache_key' => $cache_key
]);
}else
} else
return app('json')->fail('获取用户访问token失败!');
}
@ -96,20 +99,20 @@ class AuthController
*/
public function get_logo(Request $request)
{
$logoType = $request->get('type',1);
$logoType = $request->get('type', 1);
switch ((int)$logoType) {
case 1:
$logo = sysConfig('routine_logo');
$logo = sys_config('routine_logo');
break;
case 2:
$logo = sysConfig('wechat_avatar');
$logo = sys_config('wechat_avatar');
break;
default:
$logo = '';
break;
}
if (strstr($logo,'http') === false && $logo) $logo = sysConfig('site_url').$logo;
return app('json')->successful(['logo_url'=>str_replace('\\','/',$logo)]);
if (strstr($logo, 'http') === false && $logo) $logo = sys_config('site_url') . $logo;
return app('json')->successful(['logo_url' => str_replace('\\', '/', $logo)]);
}
/**
@ -119,10 +122,10 @@ class AuthController
*/
public function set_form_id(Request $request)
{
$formId = $request->post('formId','');
if(!$formId) return app('json')->fail('缺少form id');
RoutineFormId::SetFormId($formId,$request->uid());
return app('json')->successful('保存form id 成功!',['uid'=>$request->uid()]);
$formId = $request->post('formId', '');
if (!$formId) return app('json')->fail('缺少form id');
RoutineFormId::SetFormId($formId, $request->uid());
return app('json')->successful('保存form id 成功!', ['uid' => $request->uid()]);
}
/**
@ -132,4 +135,21 @@ class AuthController
{
MiniProgramService::handleNotify();
}
/**
* 获取小程序订阅消息id
* @return mixed
*/
public function teml_ids()
{
$temlIdsName = SubscribeTemplateService::getConstants();
$temlIdsList = CacheService::get('TEML_IDS_LIST', function () use ($temlIdsName) {
$temlId = [];
foreach ($temlIdsName as $key => $item) {
$temlId[strtolower($key)] = SubscribeTemplateService::setTemplateId($item);
}
return $temlId;
});
return app('json')->success($temlIdsList);
}
}

View File

@ -8,8 +8,8 @@ use app\models\user\User;
use app\models\user\UserToken;
use app\models\user\WechatUser;
use app\Request;
use crmeb\utils\Canvas;
use crmeb\services\WechatService;
use crmeb\utils\Canvas;
use think\facade\Cookie;
/**
@ -25,6 +25,7 @@ class WechatController
*/
public function serve()
{
ob_clean();
return WechatService::serve();
}
@ -33,6 +34,7 @@ class WechatController
*/
public function notify()
{
ob_clean();
WechatService::handleNotify();
}
@ -61,7 +63,7 @@ class WechatController
try {
$wechatInfo = WechatService::oauthService()->user()->getOriginal();
} catch (\Exception $e) {
return app('json')->fail('授权失败');
return app('json')->fail('授权失败', ['message' => $e->getMessage(), 'line' => $e->getLine()]);
}
if (!isset($wechatInfo['nickname'])) {
$wechatInfo = WechatService::getUserInfo($wechatInfo['openid']);
@ -99,12 +101,13 @@ class WechatController
$path = 'uploads/follow/';
$imageType = 'jpg';
$name = 'follow';
$siteUrl = sysConfig('site_url');
if (file_exists($path . $name . '.' . $imageType)) {
return app('json')->success('ok', ['path' => $siteUrl . '/' . $path . $name . '.' . $imageType]);
$siteUrl = sys_config('site_url');
$imageUrl = $path . $name . '.' . $imageType;
if (file_exists($imageUrl)) {
return app('json')->success('ok', ['path' => $siteUrl . '/' . $imageUrl]);
}
$canvas->setImageUrl('static/qrcode/follow.png')->setImageHeight(720)->setImageWidth(500)->pushImageValue();
$wechatQrcode = sysConfig('wechat_qrcode');
$wechatQrcode = sys_config('wechat_qrcode');
if (($strlen = stripos($wechatQrcode, 'uploads')) !== false) {
$wechatQrcode = substr($wechatQrcode, $strlen);
}
@ -114,5 +117,4 @@ class WechatController
$image = $canvas->setFileName($name)->setImageType($imageType)->setPath($path)->setBackgroundWidth(500)->setBackgroundHeight(720)->starDrawChart();
return app('json')->success('ok', ['path' => $image ? $siteUrl . '/' . $image : '']);
}
}

View File

@ -2,6 +2,8 @@
namespace app\models\routine;
use app\admin\model\wechat\StoreService as ServiceModel;
use crmeb\basic\BaseModel;
use crmeb\utils\Template;
use app\models\store\StoreOrder;
use app\models\user\WechatUser;
@ -12,7 +14,7 @@ use app\models\user\WechatUser;
* Class RoutineTemplate
* @package app\models\routine
*/
class RoutineTemplate
class RoutineTemplate extends BaseModel
{
/**
* 数据表主键
@ -26,51 +28,99 @@ class RoutineTemplate
*/
protected $name = 'routine_template';
public static function sendOrderTakeOver()
/**
* 确认收货
* @param $order
* @param $title
* @return bool
*/
public static function sendOrderTakeOver($order, $title)
{
return self::sendOut('OREDER_TAKEVER', $order['uid'], [
'thing1' => $order['order_id'],
'thing2' => $title,
'date5' => date('Y-m-d H:i:s', time()),
], '/pages/order_details/index?order_id=' . $order['order_id']);
}
/**
* 送货和发货
* @param $order
* @param int $isGive
* @param int $isGive 0 = 同城配送, 1 = 快递发货
* @return bool
*/
public static function sendOrderPostage($order, $isGive = 0)
{
if ($isGive) {
$data['keyword1'] = $order['order_id'];
$data['keyword2'] = $order['delivery_name'];
$data['keyword3'] = $order['delivery_id'];
$data['keyword4'] = date('Y-m-d H:i:s', time());
$data['keyword5'] = '您的商品已经发货请注意查收';
return self::sendOut('ORDER_POSTAGE_SUCCESS', $order['uid'], $data);
} else {
$data['keyword1'] = $order['order_id'];
$data['keyword2'] = $order['delivery_name'];
$data['keyword3'] = $order['delivery_id'];
$data['keyword4'] = date('Y-m-d H:i:s', time());
return self::sendOut('ORDER_DELIVER_SUCCESS', $order['uid'], $data);
if (is_string($order['cart_id']))
$order['cart_id'] = json_decode($order['cart_id'], true);
$storeTitle = StoreOrder::getProductTitle($order['cart_id']);
$storeTitle = StoreOrder::getSubstrUTf8($storeTitle, 20,'UTF-8','');
if ($isGive) {//快递发货
return self::sendOut('ORDER_DELIVER_SUCCESS', $order['uid'], [
'character_string2' => $order['delivery_id'],
'thing1' => $order['delivery_name'],
'time3' => date('Y-m-d H:i:s', time()),
'thing5' => $storeTitle,
], '/pages/order_details/index?order_id=' . $order['order_id']);
} else {//同城配送
return self::sendOut('ORDER_POSTAGE_SUCCESS', $order['uid'], [
'thing8' => $storeTitle,
'character_string1' => $order['order_id'],
'name4' => $order['delivery_name'],
'phone_number10' => $order['delivery_id']
], '/pages/order_details/index?order_id=' . $order['order_id']);
}
}
/**
* 退款成功发送消息
* 充值金额退款
* @param $UserRecharge
* @param $refund_price
* @return bool
*/
public static function sendRechargeSuccess($UserRecharge, $refund_price)
{
return self::sendOut('ORDER_REFUND', $UserRecharge['uid'], [
'thing1' => '亲,您充值的金额已退款,本次退款' . $refund_price . '金额',
'thing2' => '余额充值退款',
'amount3' => $UserRecharge['price'],
'character_string6' => $UserRecharge['order_id'],
], '/pages/user_bill/index?type=2');
}
/**
* 订单退款成功发送消息
* @param array $order
* @return bool
*/
public static function sendOrderRefundSuccess($order = array())
{
if (!$order) return false;
$data['keyword1'] = $order['order_id'];
$data['keyword2'] = date('Y-m-d H:i:s', time());
$data['keyword3'] = $order['pay_price'];
if ($order['pay_type'] == 'yue') $data['keyword4'] = '余额支付';
else if ($order['pay_type'] == 'weixin') $data['keyword4'] = '微信支付';
else if ($order['pay_type'] == 'offline') $data['keyword4'] = '线下支付';
$data['keyword5']['value'] = '已成功退款';
return self::sendOut('ORDER_REFUND_SUCCESS', $order['uid'], $data);
if (is_string($order['cart_id']))
$order['cart_id'] = json_decode($order['cart_id'], true);
$storeTitle = StoreOrder::getProductTitle($order['cart_id']);
$storeTitle = StoreOrder::getSubstrUTf8($storeTitle, 20,'UTF-8','');
return self::sendOut('ORDER_REFUND', $order['uid'], [
'thing1' => '已成功退款',
'thing2' => $storeTitle,
'amount3' => $order['pay_price'],
'character_string6' => $order['order_id']
], '/pages/order_details/index?order_id=' . $order['order_id'] . '&isReturen=1');
}
/**
* 订单退款失败
* @param $order
* @return bool
*/
public static function sendOrderRefundFail($order, $storeTitle)
{
return self::sendOut('ORDER_REFUND', $order['uid'], [
'thing1' => '退款失败',
'thing2' => $storeTitle,
'amount3' => $order['pay_price'],
'character_string6' => $order['order_id']
], '/pages/order_details/index?order_id=' . $order['order_id'] . '&isReturen=1');
}
/**
@ -79,14 +129,15 @@ class RoutineTemplate
* @param string $refundReasonWap
* @param array $adminList
*/
public static function sendOrderRefundStatus($order = array(), $refundReasonWap = '', $adminList = array())
public static function sendOrderRefundStatus($order)
{
$data['keyword1'] = $order['order_id'];
$data['keyword2'] = $refundReasonWap;
$data['keyword3'] = date('Y-m-d H:i:s', time());
$data['keyword4'] = $order['pay_price'];
$data['keyword5'] = '原路返回';
foreach ($adminList as $uid) {
$data['character_string4'] = $order['order_id'];
$data['date5'] = date('Y-m-d H:i:s', time());
$data['amount2'] = $order['pay_price'];
$data['phrase7'] = '申请退款中';
$data['thing8'] = '请及时处理';
$kefuIds = ServiceModel::where('notify', 1)->column('uid', 'uid');
foreach ($kefuIds as $uid) {
self::sendOut('ORDER_REFUND_STATUS', $uid, $data);
}
}
@ -100,35 +151,122 @@ class RoutineTemplate
*/
public static function sendBargainSuccess($bargain = array(), $bargainUser = array(), $bargainUserId = 0)
{
$data['keyword1'] = $bargain['title'];
$data['keyword2'] = $bargainUser['bargain_price'];
$data['keyword3'] = $bargainUser['bargain_price_min'];
$data['keyword4'] = $bargainUser['price'];
$data['keyword5'] = $bargainUser['bargain_price_min'];
$data['keyword6'] = '恭喜您,已经砍到最低价了';
return self::sendOut('BARGAIN_SUCCESS', $bargainUser['uid'], $data);
$data['thing1'] = $bargain['title'];
$data['amount2'] = $bargainUser['min_price'];
$data['thing3'] = '恭喜您,已经砍到最低价了';
return self::sendOut('BARGAIN_SUCCESS', $bargainUser['uid'], $data, '/pages/activity/user_goods_bargain_list/index');
}
/**
* 订单支付成功发送模板消息
* @param string $formId
* @param string $orderId
* @param $uid
* @param $pay_price
* @param $orderId
* @param $payTime
* @return bool|void
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
*/
public static function sendOrderSuccess($formId = '', $orderId = '')
public static function sendOrderSuccess($uid, $pay_price, $orderId)
{
if ($orderId == '') return;
$order = StoreOrder::where('order_id', $orderId)->find();
$data['keyword1'] = $orderId;
$data['keyword2'] = date('Y-m-d H:i:s', time());
$data['keyword3'] = '已支付';
$data['keyword4'] = $order['pay_price'];
if ($order['pay_type'] == 'yue') $data['keyword5'] = '余额支付';
else if ($order['pay_type'] == 'weixin') $data['keyword5'] = '微信支付';
return self::sendOut('ORDER_PAY_SUCCESS', $order['uid'], $data, $formId, '/pages/order_details/index?order_id=' . $orderId);
$data['character_string1'] = $orderId;
$data['amount2'] = $pay_price . '元';
$data['date3'] = date('Y-m-d H:i:s', time());
return self::sendOut('ORDER_PAY_SUCCESS', $uid, $data, '/pages/order_details/index?order_id=' . $orderId);
}
/**
*提现失败
* @param $uid
* @param $msg
* @param $extract_number
* @param $extract_type
* @return bool
*/
public static function sendExtractFail($uid, $msg, $extract_number, $nickname)
{
return self::sendOut('USER_EXTRACT', $uid, [
'thing1' => '提现失败:' . $msg,
'amount2' => $extract_number . '元',
'thing3' => $nickname,
'date4' => date('Y-m-d H:i:s', time())
], '/pages/user_spread_money/index');
}
/**
* 提现成功
* @param $uid
* @param $extract_number
* @param $nickname
* @return bool
*/
public static function sendExtractSuccess($uid, $extract_number, $nickname)
{
return self::sendOut('USER_EXTRACT', $uid, [
'thing1' => '提现成功',
'amount2' => $extract_number . '元',
'thing3' => $nickname,
'date4' => date('Y-m-d H:i:s', time())
], '/pages/user_spread_money/index');
}
/**
* 拼团成功通知
* @param $uid
* @param $pinkTitle
* @param $nickname
* @param $pinkTime
* @param $count
* @return bool
*/
public static function sendPinkSuccess($uid, $pinkTitle, $nickname, $pinkTime, $count, string $link = '')
{
return self::sendOut('PINK_TRUE', $uid, [
'thing1' => StoreOrder::getSubstrUTf8($pinkTitle, 20,'UTF-8',''),
'name3' => $nickname,
'date5' => date('Y-m-d H:i:s', $pinkTime),
'number2' => $count
], $link);
}
/**
* 拼团状态通知
* @param $uid
* @param $pinkTitle
* @param $count
* @param $remarks
* @return bool
*/
public static function sendPinkFail($uid, $pinkTitle, $count, $remarks, $link)
{
return self::sendOut('PINK_STATUS', $uid, [
'thing2' => StoreOrder::getSubstrUTf8($pinkTitle,20,'UTF-8',''),
'thing1' => $count,
'thing3' => $remarks
], $link);
}
/**
* 赠送积分消息提醒
* @param $uid
* @param $order
* @param $gainIntegral
* @param $integral
* @return bool
*/
public static function sendUserIntegral($uid, $order, $gainIntegral, $integral)
{
if (!$order) return false;
if (is_string($order['cart_id']))
$order['cart_id'] = json_decode($order['cart_id'], true);
$storeTitle = StoreOrder::getProductTitle($order['cart_id']);
$storeTitle = StoreOrder::getSubstrUTf8($storeTitle, 20);
return self::sendOut('INTEGRAL_ACCOUT', $uid, [
'character_string2' => $order['order_id'],
'thing3' => $storeTitle,
'amount4' => $order['pay_price'],
'number5' => $gainIntegral,
'number6' => $integral
], '/pages/user_bill/index?type=2');
}
/**
@ -136,26 +274,13 @@ class RoutineTemplate
* @param string $TempCode 模板消息常量名称
* @param int $uid 用户uid
* @param array $data 模板内容
* @param string $formId formId
* @param string $link 跳转链接
* @return bool
*/
public static function sendOut($TempCode, $uid = null, $data = null, $formId = '', $link = '')
public static function sendOut(string $tempCode, $uid, array $data, string $link = '')
{
try {
$openid = WechatUser::uidToOpenid($uid);
if (!$openid) return false;
if (!$formId) {
$form = RoutineFormId::getFormIdOne($uid, true);
if (!$form) return false;
if (isset($form['id'])) RoutineFormId::where('id', $form['id'])->delete();
} else {
$form['form_id'] = $formId;
}
return Template::instance()->routine()->setTemplateUrl($link)->setTemplateOpenId($openid)
->setTemplateData($data)->setTemplateFormId($form['form_id'])->setTemplateCode($TempCode)->send();
} catch (\Exception $e) {
return false;
}
$openid = WechatUser::uidToOpenid($uid);
if (!$openid) return false;
return Template::instance()->subscribe()->setTemplateUrl($link)->setTemplateOpenId($openid)->setTemplateData($data)->setTemplateCode($tempCode)->send();
}
}

View File

@ -74,8 +74,9 @@ class StoreCategory extends BaseModel
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
*/
public static function byIndexList($limit = 4, $field = 'id,cate_name,pid,pic')
public static function byIndexList($limit = 4,bool $bool = true, $field = 'id,cate_name,pid,pic')
{
if(!$limit && !$bool) return [];
return self::where('pid', '>', 0)->where('is_show', 1)->field($field)->order('sort DESC')->limit($limit)->select();
}

File diff suppressed because it is too large Load Diff

View File

@ -58,9 +58,9 @@ class StoreProduct extends BaseModel
else return false;
}
public static function getGoodList($limit=18,$field='*')
public static function getGoodList($limit = 18, $field = '*')
{
return self::validWhere()->where('is_good',1)->order('sort desc,id desc')->limit($limit)->field($field)->select();
return self::validWhere()->where('is_good', 1)->order('sort desc,id desc')->limit($limit)->field($field)->select();
}
public static function validWhere()
@ -104,8 +104,8 @@ class StoreProduct extends BaseModel
if ($salesOrder) $baseOrder = $salesOrder == 'desc' ? 'sales DESC' : 'sales ASC';//虚拟销量
if ($baseOrder) $baseOrder .= ', ';
$model->order($baseOrder . 'sort DESC, add_time DESC');
$list = $model->page((int)$page, (int)$limit)->field('id,store_name,cate_id,image,IFNULL(sales,0) + IFNULL(ficti,0) as sales,price,stock')->select()->each(function ($item) use($uid,$type){
if($type) {
$list = $model->page((int)$page, (int)$limit)->field('id,store_name,cate_id,image,IFNULL(sales,0) + IFNULL(ficti,0) as sales,price,stock')->select()->each(function ($item) use ($uid, $type) {
if ($type) {
$item['is_att'] = StoreProductAttrValueModel::where('product_id', $item['id'])->count() ? true : false;
if ($uid) $item['cart_num'] = StoreCart::where('is_pay', 0)->where('is_del', 0)->where('is_new', 0)->where('type', 'product')->where('product_id', $item['id'])->where('uid', $uid)->value('cart_num');
else $item['cart_num'] = 0;
@ -154,8 +154,9 @@ class StoreProduct extends BaseModel
* @param int $limit
* @return false|\PDOStatement|string|\think\Collection
*/
public static function getNewProduct($field = '*', $limit = 0, $uid = 0)
public static function getNewProduct($field = '*', $limit = 0, $uid = 0, bool $bool = true)
{
if (!$limit && !$bool) return [];
$model = self::where('is_new', 1)->where('is_del', 0)->where('mer_id', 0)
->where('stock', '>', 0)->where('is_show', 1)->field($field)
->order('sort DESC, id DESC');
@ -192,11 +193,11 @@ class StoreProduct extends BaseModel
*/
public static function getHotProductLoading($field = '*', $page = 0, $limit = 0)
{
if(!$limit) return [];
if (!$limit) return [];
$model = self::where('is_hot', 1)->where('is_del', 0)->where('mer_id', 0)
->where('stock', '>', 0)->where('is_show', 1)->field($field)
->order('sort DESC, id DESC');
if($page) $model->page($page, $limit);
if ($page) $model->page($page, $limit);
$list = $model->select();
if (is_object($list)) return $list->toArray();
return $list;
@ -208,8 +209,9 @@ class StoreProduct extends BaseModel
* @param int $limit
* @return false|\PDOStatement|string|\think\Collection
*/
public static function getBestProduct($field = '*', $limit = 0, $uid = 0)
public static function getBestProduct($field = '*', $limit = 0, $uid = 0, bool $bool = true)
{
if (!$limit && !$bool) return [];
$model = self::where('is_best', 1)->where('is_del', 0)->where('mer_id', 0)
->where('stock', '>', 0)->where('is_show', 1)->field($field)
->order('sort DESC, id DESC');
@ -217,7 +219,7 @@ class StoreProduct extends BaseModel
return self::setLevelPrice($model->select(), $uid);
}
/*
/**
* 设置会员价格
* @param object | array $list 产品列表
* @param int $uid 用户uid
@ -226,7 +228,7 @@ class StoreProduct extends BaseModel
public static function setLevelPrice($list, $uid, $isSingle = false)
{
if (is_object($list)) $list = count($list) ? $list->toArray() : [];
if (!sysConfig('vip_open')) {
if (!sys_config('vip_open')) {
if (is_array($list)) return $list;
return $isSingle ? $list : 0;
}
@ -314,13 +316,14 @@ class StoreProduct extends BaseModel
} else {
$res = false !== self::where('id', $productId)->dec('stock', $num)->inc('sales', $num)->update();
}
if($res){
if ($res) {
$stock = self::where('id', $productId)->value('stock');
$replenishment_num = sysConfig('store_stock') ?? 0;//库存预警界限
if($replenishment_num >= $stock){
try{
ChannelService::instance()->send('STORE_STOCK', ['id'=>$productId]);
}catch (\Exception $e){}
$replenishment_num = sys_config('store_stock') ?? 0;//库存预警界限
if ($replenishment_num >= $stock) {
try {
ChannelService::instance()->send('STORE_STOCK', ['id' => $productId]);
} catch (\Exception $e) {
}
}
}
return $res;
@ -359,7 +362,7 @@ class StoreProduct extends BaseModel
*/
public static function getPacketPrice($storeInfo, $productValue)
{
$store_brokerage_ratio = sysConfig('store_brokerage_ratio');
$store_brokerage_ratio = sys_config('store_brokerage_ratio');
$store_brokerage_ratio = bcdiv($store_brokerage_ratio, 100, 2);
if (count($productValue)) {
$Maxkey = self::getArrayMax($productValue, 'price');
@ -452,11 +455,12 @@ class StoreProduct extends BaseModel
* @param string $field
* @return mixed
*/
public static function getProductField($id,$field = 'store_name'){
if(is_array($id))
return self::where('id','in',$id)->field($field)->select();
public static function getProductField($id, $field = 'store_name')
{
if (is_array($id))
return self::where('id', 'in', $id)->field($field)->select();
else
return self::where('id',$id)->value($field);
return self::where('id', $id)->value($field);
}
}

View File

@ -28,33 +28,34 @@ class SystemStore extends BaseModel
protected $name = 'system_store';
public static function getLatlngAttr($value,$data)
public static function getLatlngAttr($value, $data)
{
return $data['latitude'].','.$data['longitude'];
return $data['latitude'] . ',' . $data['longitude'];
}
public static function verificWhere()
{
return self::where('is_show',1)->where('is_del',0);
return self::where('is_show', 1)->where('is_del', 0);
}
/*
* 获取门店信息
* @param int $id
* */
public static function getStoreDispose($id = 0,$felid='')
public static function getStoreDispose($id = 0, $felid = '')
{
if($id)
$storeInfo = self::verificWhere()->where('id',$id)->find();
if ($id)
$storeInfo = self::verificWhere()->where('id', $id)->find();
else
$storeInfo = self::verificWhere()->find();
if($storeInfo) {
if ($storeInfo) {
$storeInfo['latlng'] = self::getLatlngAttr(null, $storeInfo);
$storeInfo['valid_time'] = $storeInfo['valid_time'] ? explode(' - ', $storeInfo['valid_time']) : [];
$storeInfo['_valid_time'] = str_replace('-','/',($storeInfo['valid_time'][0] ?? '').' ~ '.($storeInfo['valid_time'][1]) ?? '');
$storeInfo['day_time'] = $storeInfo['day_time'] ? str_replace(' - ',' ~ ',$storeInfo['day_time']) : [];
$storeInfo['_detailed_address'] = $storeInfo['address'].' '.$storeInfo['detailed_address'];
$storeInfo['_valid_time'] = str_replace('-', '/', ($storeInfo['valid_time'][0] ?? '') . ' ~ ' . ($storeInfo['valid_time'][1] ?? ""));
$storeInfo['day_time'] = $storeInfo['day_time'] ? str_replace(' - ', ' ~ ', $storeInfo['day_time']) : [];
$storeInfo['_detailed_address'] = $storeInfo['address'] . ' ' . $storeInfo['detailed_address'];
$storeInfo['address'] = $storeInfo['address'] ? explode(',', $storeInfo['address']) : [];
if($felid) return $storeInfo[$felid] ?? '';
if ($felid) return $storeInfo[$felid] ?? '';
}
return $storeInfo;
}

View File

@ -15,6 +15,7 @@ use app\models\routine\RoutineTemplate;
use app\models\store\StoreOrderCartInfo;
use app\models\user\User;
use crmeb\services\YLYService;
use think\facade\Log;
use think\facade\Route;
/** 消息通知静态类
@ -52,7 +53,7 @@ class NoticeRepositories
//订单支付成功后给客服发送客服消息
CustomerRepository::sendOrderPaySuccessCustomerService($order, 1);
} else if ($routineOpenid && in_array($order['is_channel'],[1,2])) {//小程序发送模板消息
RoutineTemplate::sendOrderSuccess($formId, $order['order_id']);
RoutineTemplate::sendOrderSuccess($order['uid'],$order['pay_price'], $order['order_id']);
//订单支付成功后给客服发送客服消息
CustomerRepository::sendOrderPaySuccessCustomerService($order, 0);
}
@ -61,7 +62,7 @@ class NoticeRepositories
}
}
//打印小票
$switch = sysConfig('pay_success_printing_switch') ? true : false;
$switch = sys_config('pay_success_printing_switch') ? true : false;
if ($switch) {
try {
$order['cart_id'] = is_string($order['cart_id']) ? json_decode($order['cart_id'], true) : $order['cart_id'];
@ -74,7 +75,7 @@ class NoticeRepositories
$value['productInfo']['store_name'] = StoreOrderCartInfo::getSubstrUTf8($value['productInfo']['store_name'], 10, 'UTF-8', '');
$product[] = $value;
}
YLYService::instance()->setContent(sysConfig('site_name'), is_object($order) ? $order->toArray() : $order, $product)->orderPrinting();
YLYService::instance()->setContent(sys_config('site_name'), is_object($order) ? $order->toArray() : $order, $product)->orderPrinting();
} catch (\Exception $e) {
Log::error('小票打印出现错误,错误原因:' . $e->getMessage());
}

View File

@ -44,9 +44,13 @@ class CacheService
* @param bool $default
* @return mixed
*/
public static function get(string $name, $default = false)
public static function get(string $name, $default = false, int $expire = null)
{
return self::handler()->remember($name, $default);
//这里不要去读取缓存配置,会导致死循环
$expire = $expire ?: SystemConfigService::get('cache_config', null, true);
if (!is_int($expire))
$expire = (int)$expire;
return self::handler()->remember($name, $default, $expire);
}
/**

View File

@ -39,7 +39,7 @@ class MiniProgramService
'key' => trim($payment['pay_routine_key']),
'cert_path' => realpath('.' . $payment['pay_routine_client_cert']),
'key_path' => realpath('.' . $payment['pay_routine_client_key']),
'notify_url' => $wechat['site_url'] . Url::buildUrl('/api/routine/notify')
'notify_url' => $wechat['site_url'] . Url::buildUrl('/api/routine/notify')->suffix(false)->build()
];
return $config;
}
@ -133,6 +133,15 @@ class MiniProgramService
return self::miniprogram()->notice;
}
/**
* 订阅模板消息接口
* @return \crmeb\utils\ProgramSubscribe
*/
public static function SubscribenoticeService()
{
return self::miniprogram()->now_notice;
}
/**发送小程序模版消息
* @param $openid
* @param $templateId
@ -150,6 +159,21 @@ class MiniProgramService
return $notice->send($message);
}
/**
* 发送订阅消息
* @param string $touser 接收者(用户)的 openid
* @param string $templateId 所需下发的订阅模板id
* @param array $data 模板内容,格式形如 { "key1": { "value": any }, "key2": { "value": any } }
* @param string $link 击模板卡片后的跳转页面,仅限本小程序内的页面。支持带参数,示例index?foo=bar。该字段不填则模板无跳转。
* @return \EasyWeChat\Support\Collection|null
* @throws \EasyWeChat\Core\Exceptions\HttpException
* @throws \EasyWeChat\Core\Exceptions\InvalidArgumentException
*/
public static function sendSubscribeTemlate(string $touser,string $templateId,array $data,string $link = '')
{
return self::SubscribenoticeService()->to($touser)->template($templateId)->andData($data)->withUrl($link)->send();
}
/**
* 支付

View File

@ -0,0 +1,206 @@
<?php
namespace crmeb\services;
use app\admin\model\wechat\WechatUser;
use app\admin\model\wechat\StoreService as ServiceModel;
use app\models\routine\RoutineTemplate;
use crmeb\interfaces\ProviderInterface;
use think\facade\Db;
/**
* 小程序模板消息
* Class RoutineTemplate
* @package app\routine\model\routine
*/
class SubscribeTemplateService implements ProviderInterface
{
//订单发货提醒(送货)
const ORDER_POSTAGE_SUCCESS = 1128;
//提现成功通知
const USER_EXTRACT = 1470;
//确认收货通知
const OREDER_TAKEVER = 1481;
//订单取消
const ORDER_CLONE = 1134;
//订单发货提醒(快递)
const ORDER_DELIVER_SUCCESS = 1458;
//拼团成功
const PINK_TRUE = 3098;
//砍价成功
const BARGAIN_SUCCESS = 2727;
//核销成功通知
const ORDER_WRITE_OFF = 3116;
//新订单提醒
const ORDER_NEW = 1476;
//退款通知
const ORDER_REFUND = 1451;
//充值成功
const RECHARGE_SUCCESS = 755;
//订单支付成功
const ORDER_PAY_SUCCESS = 1927;
//申请退款通知 管理员提醒
const ORDER_REFUND_STATUS = 1468;
//积分到账提醒
const INTEGRAL_ACCOUT = 335;
//拼团状态通知
const PINK_STATUS = 3353;
public static function getConstants($code = '')
{
$oClass = new \ReflectionClass(__CLASS__);
$stants = $oClass->getConstants();
if ($code) return isset($stants[$code]) ? $stants[$code] : '';
else return $stants;
}
public function register($config)
{
}
/**
* 根据模板编号获取模板ID
* @param string $tempKey
* @return mixed|string
*/
public static function setTemplateId($tempKey = '')
{
if ($tempKey == '') return '';
return RoutineTemplate::where('tempkey', $tempKey)->where('status', 1)->value('tempid');
}
/**
* 发送订阅模板消息
* @param string $tempCode 所需下发的模板编号
* @param string $openId 接收者(用户)的 openid
* @param array $dataKey 模板内容,不填则下发空模板
* @param string $link 点击模板卡片后的跳转页面,仅限本小程序内的页面。支持带参数,示例index?foo=bar。该字段不填则模板无跳转
* @return bool|\EasyWeChat\Support\Collection|null
*/
public static function sendTemplate(string $tempCode,string $openId,array $dataKey, string $link = '')
{
if (!$openId || !$tempCode) return false;
return MiniProgramService::sendSubscribeTemlate($openId, trim(self::setTemplateId(self::getConstants($tempCode))), $dataKey, $link);
}
/**服务进度通知
* @param array $data
* @param null $url
* @param string $defaultColor
* @return bool
*/
public static function sendAdminNoticeTemplate(array $data, $url = null, $defaultColor = '')
{
$adminIds = explode(',', trim(sys_config('site_store_admin_uids')));
$kefuIds = ServiceModel::where('notify', 1)->column('uid', 'uid');
if (empty($adminIds[0])) {
$adminList = array_unique($kefuIds);
} else {
$adminList = array_unique(array_merge($adminIds, $kefuIds));
}
if (!is_array($adminList) || empty($adminList)) return false;
foreach ($adminList as $uid) {
try {
$openid = WechatUser::uidToRoutineOpenid($uid);
} catch (\Exception $e) {
continue;
}
// self::sendTemplate($openid,self::ADMIN_NOTICE,$data,$url,$defaultColor);
}
}
/**
* 返回所有支持的行业列表
* @return \EasyWeChat\Support\Collection
*/
public static function getIndustry()
{
return MiniProgramService::noticeService()->getIndustry();
}
/**
* 修改账号所属行业
* 主行业 副行业 代码
* IT科技 互联网/电子商务 1
* IT科技 IT软件与服务 2
* IT科技 IT硬件与设备 3
* IT科技 电子技术 4
* IT科技 通信与运营商 5
* IT科技 网络游戏 6
* 金融业 银行 7
* 金融业 基金|理财|信托 8
* 金融业 保险 9
* 餐饮 餐饮 10
* 酒店旅游 酒店 11
* 酒店旅游 旅游 12
* 运输与仓储 快递 13
* 运输与仓储 物流 14
* 运输与仓储 仓储 15
* 教育 培训 16
* 教育 院校 17
* 政府与公共事业 学术科研 18
* 政府与公共事业 交警 19
* 政府与公共事业 博物馆 20
* 政府与公共事业 公共事业|非盈利机构 21
* 医药护理 医药医疗 22
* 医药护理 护理美容 23
* 医药护理 保健与卫生 24
* 交通工具 汽车相关 25
* 交通工具 摩托车相关 26
* 交通工具 火车相关 27
* 交通工具 飞机相关 28
* 房地产 建筑 29
* 房地产 物业 30
* 消费品 消费品 31
* 商业服务 法律 32
* 商业服务 会展 33
* 商业服务 中介服务 34
* 商业服务 认证 35
* 商业服务 审计 36
* 文体娱乐 传媒 37
* 文体娱乐 体育 38
* 文体娱乐 娱乐休闲 39
* 印刷 印刷 40
* 其它 其它 41
* @param $industryId1
* @param $industryId2
* @return \EasyWeChat\Support\Collection
*/
public static function setIndustry($industryId1, $industryId2)
{
return MiniProgramService::noticeService()->setIndustry($industryId1, $industryId2);
}
/**
* 获取所有模板列表
* @return \EasyWeChat\Support\Collection
*/
public static function getPrivateTemplates()
{
return MiniProgramService::noticeService()->getPrivateTemplates();
}
/**
* 删除指定ID的模板
* @param $templateId
* @return \EasyWeChat\Support\Collection
*/
public static function deletePrivateTemplate($templateId)
{
return MiniProgramService::noticeService()->deletePrivateTemplate($templateId);
}
/**
* 添加模板并获取模板ID
* @param $shortId
* @return \EasyWeChat\Support\Collection
*/
public static function addTemplate($shortId)
{
return MiniProgramService::noticeService()->addTemplate($shortId);
}
}

View File

@ -13,6 +13,7 @@ use crmeb\services\storage\Qiniu;
use crmeb\traits\LogicTrait;
use think\exception\ValidateException;
use think\facade\Filesystem;
use Guzzle\Http\EntityBody;
use think\File;
/**
@ -191,7 +192,7 @@ class UploadService
{
$info = [];
try {
$uploadType = $this->uploadType ?: sysConfig('upload_type');
$uploadType = $this->uploadType ?: sys_config('upload_type');
//TODO 没有选择默认使用本地上传
if (!$uploadType)
$uploadType = 1;
@ -257,8 +258,6 @@ class UploadService
if (!isset($header['Content-Length'])) $header['Content-Length'] = 0;
if (!isset($header['Content-Type'])) $header['Content-Type'] = 'image/jpeg';
} catch (\Exception $e) {
$header['Content-Length'] = 0;
$header['Content-Type'] = 'image/jpeg';
}
return $header;
}
@ -301,7 +300,7 @@ class UploadService
*/
public function uploadLocalStream($key, $content, $root = '')
{
$siteUrl = sysConfig('site_url') . '/';
$siteUrl = sys_config('site_url') . '/';
$path = self::uploadDir($this->uploadPath, $root);
$path = str_replace('\\', DS, $path);
$path = str_replace('/', DS, $path);
@ -325,7 +324,7 @@ class UploadService
*/
public function imageStream($key, $content, $root = '')
{
$uploadType = sysConfig('upload_type');
$uploadType = sys_config('upload_type');
//TODO 没有选择默认使用本地上传
if (!$uploadType) $uploadType = 1;
$info = [];
@ -405,11 +404,10 @@ class UploadService
*/
public function file($fileName)
{
if (!isset($_FILES[$fileName])) return self::setError('上传文件不存在!');
$extension = strtolower(pathinfo($_FILES[$fileName]['name'], PATHINFO_EXTENSION));
if (strtolower($extension) == 'php' || !$extension)
return self::setError('上传文件非法!');
$file = request()->file($fileName);
if (!$file) return self::setError('上传文件不存在!');
if (strtolower($file->getOriginalExtension()) === 'php' || !$file->getOriginalExtension())
return self::setError('上传文件非法!');
if ($this->autoValidate) {
try {
validate([$fileName => $this->imageValidate])->check([$fileName => $file]);
@ -422,11 +420,11 @@ class UploadService
return self::successful(str_replace('\\', '/', $fileName));
}
public static function pathToUrl($path)
{
return trim(str_replace(DS, '/', $path), '.');
}
/**
* 打开图片
* @param $filePath
* @return \think\Image
*/
public function openImage($filePath)
{
return \think\Image::open($filePath);
@ -443,7 +441,13 @@ class UploadService
*/
public function thumb($filePath, $ratio = 5, $pre = 's_')
{
$img = $this->openImage($filePath);
try {
$img = $this->openImage($filePath);
} catch (\Throwable $e) {
$dir = dirname($filePath);
$fileName = basename($filePath);
return $dir . DS . $fileName;
}
$width = $img->width() * $ratio / 10;
$height = $img->height() * $ratio / 10;
$dir = dirname($filePath);
@ -453,4 +457,14 @@ class UploadService
if (substr($savePath, 0, 2) == './') return substr($savePath, 1, strlen($savePath));
return DS . $savePath;
}
/**
* TODO 转为文件流
* @param $resource
* @return EntityBody
*/
public static function resourceStream($resource)
{
return EntityBody::factory($resource)->__toString();
}
}

View File

@ -3,6 +3,7 @@
namespace crmeb\services;
use app\models\system\Cache as CacheModel;
use crmeb\exceptions\AuthException;
use crmeb\interfaces\ProviderInterface;
use crmeb\traits\LogicTrait;

View File

@ -4,6 +4,7 @@
* @author: xaboy<365615158@qq.com>
* @day: 2017/11/11
*/
namespace crmeb\traits;
use think\db\Query;
@ -13,14 +14,15 @@ trait ModelTrait
{
public static function get($where)
{
if(!is_array($where)){
if (!is_array($where)) {
return self::find($where);
}else{
} else {
return self::where($where)->find();
}
}
public static function all($function){
public static function all($function)
{
$query = self::newQuery();
$function($query);
return $query->select();
@ -34,7 +36,7 @@ trait ModelTrait
*/
public static function setAll($group, $replace = false)
{
return self::insertAll($group,$replace);
return self::insertAll($group, $replace);
}
/**
@ -44,17 +46,17 @@ trait ModelTrait
* @param $field
* @return bool $type 返回成功失败
*/
public static function edit($data,$id,$field = null)
public static function edit($data, $id, $field = null)
{
$model = new self;
if(!$field) $field = $model->getPk();
if (!$field) $field = $model->getPk();
// return false !== $model->update($data,[$field=>$id]);
// return 0 < $model->update($data,[$field=>$id])->result;
$res = $model->update($data,[$field=>$id]);
if(isset($res->result))
$res = $model->update($data, [$field => $id]);
if (isset($res->result))
return 0 < $res->result;
else if(isset($res['data']['result']))
return 0 < $res['data']['result'];
else if (isset($res['data']['result']))
return 0 < $res['data']['result'];
else
return false !== $res;
}
@ -69,8 +71,8 @@ trait ModelTrait
public static function be($map, $field = '')
{
$model = (new self);
if(!is_array($map) && empty($field)) $field = $model->getPk();
$map = !is_array($map) ? [$field=>$map] : $map;
if (!is_array($map) && empty($field)) $field = $model->getPk();
$map = !is_array($map) ? [$field => $map] : $map;
return 0 < $model->where($map)->count();
}
@ -95,40 +97,41 @@ trait ModelTrait
*/
public static function page($model = null, $eachFn = null, $params = [], $limit = 20)
{
if(is_numeric($eachFn) && is_numeric($model)){
return parent::page($model,$eachFn);
if (is_numeric($eachFn) && is_numeric($model)) {
return parent::page($model, $eachFn);
}
if(is_numeric($eachFn)){
if (is_numeric($eachFn)) {
$limit = $eachFn;
$eachFn = null;
}else if(is_array($eachFn)){
} else if (is_array($eachFn)) {
$params = $eachFn;
$eachFn = null;
}
if(is_callable($model)){
if (is_callable($model)) {
$eachFn = $model;
$model = null;
}elseif(is_numeric($model)){
} elseif (is_numeric($model)) {
$limit = $model;
$model = null;
}elseif(is_array($model)){
} elseif (is_array($model)) {
$params = $model;
$model = null;
}
if(is_numeric($params)){
if (is_numeric($params)) {
$limit = $params;
$params = [];
}
$paginate = $model === null ? self::paginate($limit,false,['query'=>$params]) : $model->paginate($limit,false,['query'=>$params]);
$paginate = $model === null ? self::paginate($limit, false, ['query' => $params]) : $model->paginate($limit, false, ['query' => $params]);
$list = is_callable($eachFn) ? $paginate->each($eachFn) : $paginate;
$page = $list->render();
$total = $list->total();
return compact('list','page','total');
return compact('list', 'page', 'total');
}
/**
* 获取分页 生成where 条件和 whereOr 支持多表查询生成条件
* @param object $model 模型对象
@ -139,115 +142,129 @@ trait ModelTrait
* @param string $like 模糊查找 关键字
* @return array
*/
public static function setWherePage($model=null,$where=[],$field=[],$fieldOr=[],$fun=null,$like='LIKE'){
if(!is_array($where) || !is_array($field)) return false;
if($model===null) $model=new self();
public static function setWherePage($model = null, $where = [], $field = [], $fieldOr = [], $fun = null, $like = 'LIKE')
{
if (!is_array($where) || !is_array($field)) return false;
if ($model === null) $model = new self();
//处理等于行查询
foreach ($field as $key=>$item){
if(($count=strpos($item,'.'))===false){
if(isset($where[$item]) && $where[$item]!='') {
$model=$model->where($item,$where[$item]);
foreach ($field as $key => $item) {
if (($count = strpos($item, '.')) === false) {
if (isset($where[$item]) && $where[$item] != '') {
$model = $model->where($item, $where[$item]);
}
}else{
$item_l=substr($item,$count+1);
if(isset($where[$item_l]) && $where[$item_l]!=''){
$model=$model->where($item,$where[$item_l]);
} else {
$item_l = substr($item, $count + 1);
if (isset($where[$item_l]) && $where[$item_l] != '') {
$model = $model->where($item, $where[$item_l]);
}
}
}
//回收变量
unset($count,$key,$item,$item_l);
unset($count, $key, $item, $item_l);
//处理模糊查询
if(!empty($fieldOr) && is_array($fieldOr) && isset($fieldOr[0])){
if(($count=strpos($fieldOr[0],'.'))===false){
if(isset($where[$fieldOr[0]]) && $where[$fieldOr[0]]!='') {
$model=$model->where(self::get_field($fieldOr),$like,"%".$where[$fieldOr[0]]."%");
if (!empty($fieldOr) && is_array($fieldOr) && isset($fieldOr[0])) {
if (($count = strpos($fieldOr[0], '.')) === false) {
if (isset($where[$fieldOr[0]]) && $where[$fieldOr[0]] != '') {
$model = $model->where(self::get_field($fieldOr), $like, "%" . $where[$fieldOr[0]] . "%");
}
}else{
$item_l = substr($fieldOr[0],$count+1);
if(isset($where[$item_l]) && $where[$item_l]!='') {
$model=$model->where(self::get_field($fieldOr),$like,"%".$where[$item_l]."%");
} else {
$item_l = substr($fieldOr[0], $count + 1);
if (isset($where[$item_l]) && $where[$item_l] != '') {
$model = $model->where(self::get_field($fieldOr), $like, "%" . $where[$item_l] . "%");
}
}
}
unset($count,$key,$item,$item_l);
unset($count, $key, $item, $item_l);
return $model;
}
/**
* 字符串拼接
* @param int|array $id
* @param string $str
* @return string
*/
private static function get_field($id,$str='|'){
if(is_array($id)){
$sql="";
$i=0;
foreach($id as $val){
private static function get_field($id, $str = '|')
{
if (is_array($id)) {
$sql = "";
$i = 0;
foreach ($id as $val) {
$i++;
if($i<count($id)){
$sql.=$val.$str;
}else{
$sql.=$val;
if ($i < count($id)) {
$sql .= $val . $str;
} else {
$sql .= $val;
}
}
return $sql;
}else{
return $sql;
} else {
return $id;
}
}
/**
* 条件切割
* @param string $order
* @param string $file
* @return string
*/
public static function setOrder($order,$file='-'){
if(empty($order)) return '';
return str_replace($file,' ',$order);
public static function setOrder($order, $file = '-')
{
if (empty($order)) return '';
return str_replace($file, ' ', $order);
}
/**
* 获取时间段之间的model
* @param int|string $time
* @param string $ceil
* @return array
*/
public static function getModelTime($where,$model=null,$prefix='add_time',$data='data',$field=' - '){
public static function getModelTime($where, $model = null, $prefix = 'add_time', $data = 'data', $field = ' - ')
{
if ($model == null) $model = new self;
if(!isset($where[$data])) return $model;
switch ($where[$data]){
case 'today':case 'week':case 'month':case 'year':case 'yesterday':
$model=$model->whereTime($prefix,$where[$data]);
break;
if (!isset($where[$data])) return $model;
switch ($where[$data]) {
case 'today':
case 'week':
case 'month':
case 'year':
case 'yesterday':
$model = $model->whereTime($prefix, $where[$data]);
break;
case 'quarter':
list($startTime,$endTime)=self::getMonth();
list($startTime, $endTime) = self::getMonth();
$model = $model->where($prefix, '>', strtotime($startTime));
$model = $model->where($prefix, '<', strtotime($endTime));
break;
case 'lately7':
$model = $model->where($prefix,'between',[strtotime("-7 day"),time()]);
$model = $model->where($prefix, 'between', [strtotime("-7 day"), time()]);
break;
case 'lately30':
$model = $model->where($prefix,'between',[strtotime("-30 day"),time()]);
$model = $model->where($prefix, 'between', [strtotime("-30 day"), time()]);
break;
default:
if(strstr($where[$data],$field)!==false){
if (strstr($where[$data], $field) !== false) {
list($startTime, $endTime) = explode($field, $where[$data]);
$model = $model->where($prefix, '>', strtotime($startTime));
$model = $model->where($prefix, '<', bcadd(strtotime($endTime),86400,0));
$model = $model->where($prefix, '<', bcadd(strtotime($endTime), 86400, 0));
}
break;
}
return $model;
}
/**
* 获取去除html去除空格去除软回车,软换行,转换过后的字符串
* @param string $str
* @return string
*/
public static function HtmlToMbStr($str){
return trim(strip_tags(str_replace(["\n","\t","\r"," ","&nbsp;"],'',htmlspecialchars_decode($str))));
public static function HtmlToMbStr($str)
{
return trim(strip_tags(str_replace(["\n", "\t", "\r", " ", "&nbsp;"], '', htmlspecialchars_decode($str))));
}
/**
* 截取中文指定字节
* @param string $str
@ -256,27 +273,31 @@ trait ModelTrait
* @param string $file
* @return string
*/
public static function getSubstrUTf8($str,$utf8len=100,$chaet='UTF-8',$file='....'){
if(mb_strlen($str,$chaet) > $utf8len){
$str = mb_substr($str,0,$utf8len,$chaet).$file;
public static function getSubstrUTf8($str, $utf8len = 100, $chaet = 'UTF-8', $file = '....')
{
if (mb_strlen($str, $chaet) > $utf8len) {
$str = mb_substr($str, 0, $utf8len, $chaet) . $file;
}
return $str;
}
/**
* 获取本季度 time
* @param int|string $time
* @param string $ceil
* @return array
*/
public static function getMonth($time='',$ceil=0){
if($ceil!=0)
$season = ceil(date('n') /3)-$ceil;
public static function getMonth($time = '', $ceil = 0)
{
if ($ceil != 0)
$season = ceil(date('n') / 3) - $ceil;
else
$season = ceil(date('n') /3);
$firstday = date('Y-m-01',mktime(0,0,0,($season - 1) *3 +1,1,date('Y')));
$lastday = date('Y-m-t',mktime(0,0,0,$season * 3,1,date('Y')));
return array($firstday,$lastday);
$season = ceil(date('n') / 3);
$firstday = date('Y-m-01', mktime(0, 0, 0, ($season - 1) * 3 + 1, 1, date('Y')));
$lastday = date('Y-m-t', mktime(0, 0, 0, $season * 3, 1, date('Y')));
return array($firstday, $lastday);
}
/**
* 高精度 加法
* @param int|string $uid id
@ -286,14 +307,14 @@ trait ModelTrait
* @param int $acc 精度
* @return bool
*/
public static function bcInc($key, $incField, $inc, $keyField = null, $acc=2)
public static function bcInc($key, $incField, $inc, $keyField = null, $acc = 2)
{
if(!is_numeric($inc)) return false;
if (!is_numeric($inc)) return false;
$model = new self();
if($keyField === null) $keyField = $model->getPk();
$result = self::where($keyField,$key)->find();
if(!$result) return false;
$new = bcadd($result[$incField],$inc,$acc);
if ($keyField === null) $keyField = $model->getPk();
$result = self::where($keyField, $key)->find();
if (!$result) return false;
$new = bcadd($result[$incField], $inc, $acc);
$result->$incField = $new;
return false !== $result->save();
// return false !== $model->where($keyField,$key)->update([$incField=>$new]);
@ -310,15 +331,15 @@ trait ModelTrait
* @param int $acc 精度
* @return bool
*/
public static function bcDec($key, $decField, $dec, $keyField = null, $minus = false, $acc=2)
public static function bcDec($key, $decField, $dec, $keyField = null, $minus = false, $acc = 2)
{
if(!is_numeric($dec)) return false;
if (!is_numeric($dec)) return false;
$model = new self();
if($keyField === null) $keyField = $model->getPk();
$result = self::where($keyField,$key)->find();
if(!$result) return false;
if(!$minus && $result[$decField] < $dec) return false;
$new = bcsub($result[$decField],$dec,$acc);
if ($keyField === null) $keyField = $model->getPk();
$result = self::where($keyField, $key)->find();
if (!$result) return false;
if (!$minus && $result[$decField] < $dec) return false;
$new = bcsub($result[$decField], $dec, $acc);
$result->$decField = $new;
return false !== $result->save();
// return false !== $model->where($keyField,$key)->update([$decField=>$new]);

View File

@ -11,18 +11,19 @@ use EasyWeChat\Core\Exceptions\InvalidArgumentException;
* Class ProgramSubscribe
* @package crmeb\utils
* @method $this
* @method $this withTemplate(string $template_id) 设置模板id
* @method $this template(string $template_id) 设置模板id
* @method $this withTemplateId(string $template_id) 设置模板id
* @method $this andTemplateId(string $template_id) 设置模板id
* @method $this andTemplate(string $template_id) 设置模板id
* @method $this andUses(string $template_id) 设置模板id
* @method $this andTo(string $touser) 设置opendid
* @method $this to(string $touser) 设置opendid
* @method $this andReceiver(string $touser) 设置opendid
* @method $this withReceiver(string $touser) 设置opendid
* @method $this with(array $data) 设置发送内容
* @method $this andData(array $data) 设置发送内容
* @method $this withData(array $data) 设置发送内容
* @method $this data(array $data) 设置发送内容
* @method $this withUrl(string $page) 设置跳转路径
*/
class ProgramSubscribe extends AbstractAPI
{
@ -205,13 +206,33 @@ class ProgramSubscribe extends AbstractAPI
}
/**
* TODO: 未实现
* @param $data
* @return mixed
* 设置订阅消息发送data
* @param array $data
* @return array
*/
protected function formatData($data)
protected function formatData(array $data)
{
return $data;
$return = [];
foreach ($data as $key => $item) {
if (is_scalar($item)) {
$value = $item;
} elseif (is_array($item) && !empty($item)) {
if (isset($item['value'])) {
$value = strval($item['value']);
} elseif (count($item) < 2) {
$value = array_shift($item);
} else {
[$value] = $item;
}
} else {
$value = 'error data item.';
}
$return[$key] = ['value' => $value];
}
return $return;
}
@ -230,8 +251,8 @@ class ProgramSubscribe extends AbstractAPI
'uses' => 'template_id',
'to' => 'touser',
'receiver' => 'touser',
'url' => 'url',
'link' => 'url',
'url' => 'page',
'link' => 'page',
'data' => 'data',
'with' => 'data',
];

View File

@ -20,22 +20,24 @@ use think\app\Url;
* @method $this setTemplateFormId(string $templateFormId) 设置发送模板消息formid
* @method $this setTemplateDefaultColor(string $templateDefaultColor) 设置发送模板消息默认背景颜色
* @method $this setTemplateCode(string $templateCode) 设置模板id
* @method $this setSendType($sendType) 设置发送类型句柄 1 = 小程序 2 = 公众号
* @method $this setHandleType($handleType) 设置发送类型句柄 1 = 小程序 2 = 公众号
* @method $this setDefaultData($defaultData) 设置默认数据
* @method $this setTemplateUrl(Url $url, string $sux = '') 设置跳转Url
* @method $this routine() 设置当前发送类型句柄为 小程序
* @method $this wechat() 设置当前发送类型句柄为 公众号
* @method $this subscribe() 设置当前发送类型句柄为 小程序订阅消息
*/
class Template
{
use LogicTrait;
/**
* 注册服务 会自动添加$providers对应的key名称方法方便设置$sendType
* 注册服务 会自动添加$providers对应的key名称方法方便设置$handleType
* @var array
*/
protected $providers = [
'routine' => \crmeb\services\ProgramTemplateService::class,
'subscribe' => \crmeb\services\SubscribeTemplateService::class,
'wechat' => \crmeb\services\WechatTemplateService::class,
];
@ -49,7 +51,7 @@ class Template
'templateData' => [[], 'array'],
'templateUrl' => [null, 'callable', 'postpositionUrl'],
'templateFormId' => [null, 'string'],
'sendType' => [null, 'string'],
'handleType' => [null, 'string'],
'templateOpenId' => [null, 'string'],
'templateOpenId' => [null, 'string'],
];
@ -88,7 +90,7 @@ class Template
* 发送类型 对应 $providers key
* @var string | int
*/
protected $sendType;
protected $handleType;
/**
* 接收人openid 小程序 公众号使用
@ -118,7 +120,7 @@ class Template
*/
public function postpositionUrl($url, string $suffix = '')
{
if($url instanceof Url)
if ($url instanceof Url)
$url = $url->suffix($suffix)->domain(true)->build();
return $url;
}
@ -129,16 +131,16 @@ class Template
protected function validate()
{
$keys = array_keys($this->providers);
if (is_string($this->sendType)) {
if (!in_array($this->sendType, $keys))
throw new AuthException('设置的发送类型句柄不存在:' . $this->sendType);
} elseif (is_int($this->sendType)) {
if ($this->sendType > count($keys))
throw new AuthException('设置的发送类型句柄不存在:' . $this->sendType);
$this->sendType = $keys[$this->sendType - 1];
if (is_string($this->handleType)) {
if (!in_array($this->handleType, $keys))
throw new AuthException('设置的发送类型句柄不存在:' . $this->handleType);
} elseif (is_int($this->handleType)) {
if ($this->handleType > count($keys))
throw new AuthException('设置的发送类型句柄不存在:' . $this->handleType);
$this->handleType = $keys[$this->handleType - 1];
}
if (!$this->sendType)
if (!$this->handleType)
throw new AuthException('请设置发送类型句柄');
if (!$this->templateData)
@ -160,7 +162,7 @@ class Template
$this->validate();
$resource = null;
switch ($this->sendType) {
switch ($this->handleType) {
case 'routine':
$resource = self::$instance->routine->sendTemplate(
$this->templateCode,
@ -180,6 +182,14 @@ class Template
$this->templateDefaultColor
);
break;
case 'subscribe':
$resource = self::$instance->subscribe->sendTemplate(
$this->templateCode,
$this->templateOpenId,
$this->templateData,
$this->templateUrl
);
break;
default:
$resource = false;
break;
@ -206,7 +216,7 @@ class Template
$this->templateDefaultColor = null;
$this->templateData = [];
$this->templateUrl = null;
$this->sendType = null;
$this->handleType = null;
$this->templateFormId = null;
$this->templateCode = null;
return $this;

View File

@ -258,7 +258,8 @@ switch ($step) {
if ($ret) {
$message = '<li><span class="correct_span">&radic;</span>创建数据表['.$dbPrefix.$matches[2] . ']完成!<span style="float: right;">'.date('Y-m-d H:i:s').'</span></li> ';
} else {
$message = '<li><span class="correct_span error_span">&radic;</span>创建数据表['.$dbPrefix.$matches[2] . ']失败!<span style="float: right;">'.date('Y-m-d H:i:s').'</span></li>';
$err = mysqli_error($conn);
$message = '<li><span class="correct_span error_span">&radic;</span>创建数据表['.$dbPrefix.$matches[2] . ']失败!失败原因:'.$err.'<span style="float: right;">'.date('Y-m-d H:i:s').'</span></li>';
}
$i++;
$arr = array('n' => $i, 'msg' => $message);

View File

@ -269,22 +269,21 @@
time--;
}, 1000)
},
getNotice:function () {
getNotice: function () {
var that = this;
$.ajax({
url: '/admin/index/Jnotice',
type: 'get',
dataType: 'json',
success: function (rem) {
that.setNoticeDate(rem.data);
that.setNoticeDate(rem.data);
},
error: function (err) {
}
})
},
setNoticeDate:function(data)
{
setNoticeDate: function (data) {
$('#msgcount').html(data.msgcount);
$('#ordernum').html(data.ordernum + '个');
$('#inventory').html(data.inventory + '个');
@ -302,44 +301,44 @@
var ws = new Socket;
ws.setVm(this);
this.$on('ADMIN_NEW_PUSH',function (data) {
this.$on('ADMIN_NEW_PUSH', function (data) {
that.setNoticeDate(data);
})
this.$on('NEW_ORDER', function(data){
this.$on('NEW_ORDER', function (data) {
that.$Notice.info({
title: '新订单',
duration: 8,
desc: '您有一个新的订单(' + data.order_id + '),请注意查看'
});
if(window.newOrderAudioLink) (new Audio(window.newOrderAudioLink)).play();
if (window.newOrderAudioLink) (new Audio(window.newOrderAudioLink)).play();
});
this.$on('NEW_REFUND_ORDER', function(data){
this.$on('NEW_REFUND_ORDER', function (data) {
that.$Notice.warning({
title: '订单提醒',
duration: 8,
desc: '您有一个订单(' + data.order_id + ')申请退款,请注意查看'
});
if(window.newOrderAudioLink) (new Audio(window.newOrderAudioLink)).play();
if (window.newOrderAudioLink) (new Audio(window.newOrderAudioLink)).play();
});
this.$on('WITHDRAW', function(data){
this.$on('WITHDRAW', function (data) {
that.$Notice.warning({
title: '提现提醒',
duration: 8,
desc: '有用户申请提现(' + data.id + '),请注意查看'
})
});
this.$on('STORE_STOCK', function(data){
this.$on('STORE_STOCK', function (data) {
that.$Notice.warning({
title: '库存预警',
duration: 8,
desc: '(' + data.id + ')商品库存不足,请注意查看'
})
});
this.$on('PAY_SMS_SUCCESS', function(data){
this.$on('PAY_SMS_SUCCESS', function (data) {
that.$Notice.info({
title: '短信充值成功',
duration: 8,
desc: '恭喜您充值'+ data.price +'元,获得'+ data.number +'条短信'
desc: '恭喜您充值' + data.price + '元,获得' + data.number + '条短信'
})
});
}
@ -359,7 +358,7 @@
};
Socket.prototype = {
setVm: function(vm) {
setVm: function (vm) {
this.vm = vm;
},
onOpen: function () {
@ -391,8 +390,9 @@
console.log('ws error', e.data ? JSON.parse(e.data).message : '');
},
getUrl: function () {
var ishttps = 'https:' == document.location.protocol ? true : false;
return ( ishttps ? 'wss': 'ws' )+'://' + document.URL.split('//')[1].split('/')[0] + ':20002';
var ishttps = 'https:' == document.location.protocol ? true : false,
workermanPort = window.workermanPort ? window.workermanPort : 20002;
return (ishttps ? 'wss' : 'ws') + '://' + document.URL.split('//')[1].split('/')[0] + ':' + workermanPort;
}
};

View File

@ -1,7 +1,6 @@
<?php
use think\facade\Route;
//账号密码登录
Route::post('login', 'AuthController/login')->name('login')
->middleware(\app\http\middleware\AllowOriginMiddleware::class);
@ -38,7 +37,7 @@ Route::group(function () {
Route::get('admin/order/time', 'admin.StoreOrderController/time')->name('adminOrderTime');//订单交易额时间统计
Route::post('admin/order/offline', 'admin.StoreOrderController/offline')->name('adminOrderOffline');//订单支付
Route::post('admin/order/refund', 'admin.StoreOrderController/refund')->name('adminOrderRefund');//订单退款
Route::post('order/order_verific', 'order.StoreOrderController/order_verific')->name('order');//订单核销
Route::post('order/order_verific','order.StoreOrderController/order_verific')->name('order');//订单核销
})->middleware(\app\http\middleware\AllowOriginMiddleware::class)->middleware(\app\http\middleware\AuthTokenMiddleware::class, true)->middleware(\app\http\middleware\CustomerMiddleware::class);
//会员授权接口
@ -50,7 +49,7 @@ Route::group(function () {
//产品类
Route::get('product/code/:id', 'store.StoreProductController/code')->name('productCode');//产品分享二维码 推广员
//公共类
//公共类
Route::post('upload/image', 'PublicController/upload_image')->name('uploadImage');//图片上传
//用户类 客服聊天记录
Route::get('user/service/list', 'user.StoreService/lst')->name('userServiceList');//客服列表
@ -74,8 +73,8 @@ Route::group(function () {
Route::post('collect/del', 'user.UserController/collect_del')->name('collectDel');//取消收藏
Route::post('collect/all', 'user.UserController/collect_all')->name('collectAll');//批量添加收藏
Route::get('brokerage_rank', 'user.UserController/brokerage_rank')->name('brokerageRank');//佣金排行
Route::get('rank', 'user.UserController/rank')->name('rank');//推广人排行
Route::get('brokerage_rank','user.UserController/brokerage_rank')->name('brokerageRank');//佣金排行
Route::get('rank','user.UserController/rank')->name('rank');//推广人排行
//用戶类 分享
Route::post('user/share', 'PublicController/user_share')->name('user_share');//记录用户分享
//用户类 点赞
@ -194,6 +193,7 @@ Route::group(function () {
Route::post('wechat/mp_auth', 'wechat.AuthController/mp_auth')->name('mpAuth');//小程序登陆
Route::get('wechat/get_logo', 'wechat.AuthController/get_logo')->name('getLogo');//小程序登陆授权展示logo
Route::post('wechat/set_form_id', 'wechat.AuthController/set_form_id')->name('setFormId');//小程序登陆收集form id
Route::get('wechat/teml_ids', 'wechat.AuthController/teml_ids')->name('wechatTemlIds');//微信授权
//物流公司
Route::get('logistics', 'PublicController/logistics')->name('logistics');//物流公司列表
@ -208,17 +208,18 @@ Route::group(function () {
Route::post('sms/pay/notify', 'PublicController/sms_pay_notify')->name('smsPayNotify'); //短信购买异步通知
//获取关注微信公众号海报
Route::get('wechat/follow', 'wechat.WechatController/follow')->name('Follow');
Route::get('wechat/follow','wechat.WechatController/follow')->name('Follow');
})->middleware(\app\http\middleware\AllowOriginMiddleware::class)->middleware(\app\http\middleware\AuthTokenMiddleware::class, false);
Route::miss(function () {
if (app()->request->isOptions())
Route::miss(function() {
if(app()->request->isOptions())
return \think\Response::create('ok')->code(200)->header([
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Headers' => 'Authori-zation,Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With',
'Access-Control-Allow-Methods' => 'GET,POST,PATCH,PUT,DELETE,OPTIONS,DELETE',
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Headers' => 'Authori-zation,Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With',
'Access-Control-Allow-Methods' => 'GET,POST,PATCH,PUT,DELETE,OPTIONS,DELETE',
]);
else
return \think\Response::create()->code(404);