Init Repo

This commit is contained in:
root
2019-09-06 23:53:10 +08:00
commit f0ef89dfbb
7905 changed files with 914138 additions and 0 deletions

BIN
hyhproject/common/.DS_Store vendored Executable file

Binary file not shown.

BIN
hyhproject/common/._.DS_Store Executable file

Binary file not shown.

View File

@ -0,0 +1,12 @@
<?php
namespace wstmart\common\behavior;
/**
* ============================================================================
* 初始化基础数据
*/
class InitConfig
{
public function run(&$params){
WSTConf('CONF',WSTConfig());
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,15 @@
<?php
/**
* ============================================================================
*/
return [
'module_init'=> [
'wstmart\\admin\\behavior\\InitConfig'
],
'action_begin'=> [
'wstmart\\admin\\behavior\\ListenLoginStatus',
'wstmart\\admin\\behavior\\ListenPrivilege',
'wstmart\\admin\\behavior\\ListenOperate'
]
]
?>

View File

@ -0,0 +1,16 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
return [
'exception_handle' => '\\wstmart\\common\\exception\\WstAppHttpException',
// 默认输出类型
'default_return_type' => 'json',
];

View File

@ -0,0 +1,25 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
\think\Route::rule([
'mselfshop'=>'app/shops/selfshop', //自营店铺
'mbrands'=>'app/brands/index', //自营店铺
'mstreet'=>'app/shops/shopstreet', //自营店铺
'mlogin'=>'app/users/login', //用户登录
'mregister'=>'app/users/toregister', //用户注册
'mforget'=>'app/users/forgetpass', //找回密码
'mgoods-<goodsId>'=>'app/goods/detail',
'mshops-<shopId>'=>'app/shops/index',
'mhshops-<shopId>'=>'app/shops/home',
'mlist'=>'app/goods/lists',
'mnews'=>'app/news/view',
'mcategoty'=>'app/goodscats/index',
'mshopgoods'=>'app/shops/shopgoodslist',
]);

236
hyhproject/common/conf/config.php Executable file
View File

@ -0,0 +1,236 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
return [
// +----------------------------------------------------------------------
// | 应用设置
// +----------------------------------------------------------------------
// 应用调试模式
'app_debug' => true,
// 应用Trace
'app_trace' => false,
// 应用模式状态
'app_status' => '',
// 是否支持多模块
'app_multi_module' => true,
// 入口自动绑定模块
'auto_bind_module' => false,
// 注册的根命名空间
'root_namespace' => [],
// 扩展配置文件
'extra_config_list' => ['database', 'validate'],
// 扩展函数文件
'extra_file_list' => [THINK_PATH.'helper'.EXT,WST_COMM."function.php",WST_HOME_COMM."function.php",WST_ADMIN_COMM."function.php"],
// 默认输出类型
'default_return_type' => 'html',
// 默认AJAX 数据返回格式,可选json xml ...
'default_ajax_return' => 'json',
// 默认JSONP格式返回的处理方法
'default_jsonp_handler' => 'jsonpReturn',
// 默认JSONP处理方法
'var_jsonp_handler' => 'callback',
// 默认时区
'default_timezone' => 'PRC',
// 是否开启多语言
'lang_switch_on' => false,
// 默认全局过滤方法 用逗号分隔多个
'default_filter' => 'trim,WSTHtmlspecialchars',
// 默认语言
'default_lang' => 'zh-cn',
// 应用类库后缀
'class_suffix' => false,
// 控制器类后缀
'controller_suffix' => false,
// +----------------------------------------------------------------------
// | 模块设置
// +----------------------------------------------------------------------
// 默认模块名
'default_module' => 'home',
// 禁止访问模块
'deny_module_list' => ['common'],
// 默认控制器名
'default_controller' => 'Index',
// 默认操作名
'default_action' => 'index',
// 默认验证器
'default_validate' => '',
// 默认的空控制器名
'empty_controller' => '',
// 操作方法后缀
'action_suffix' => '',
// 自动搜索控制器
'controller_auto_search' => false,
// +----------------------------------------------------------------------
// | URL设置
// +----------------------------------------------------------------------
// PATHINFO变量名 用于兼容模式
'var_pathinfo' => 's',
// 兼容PATH_INFO获取
'pathinfo_fetch' => ['ORIG_PATH_INFO', 'REDIRECT_PATH_INFO', 'REDIRECT_URL'],
// pathinfo分隔符
'pathinfo_depr' => '/',
// URL伪静态后缀
'url_html_suffix' => 'html',
// URL普通方式参数 用于自动生成
'url_common_param' => true,
// URL参数方式 0 按名称成对解析 1 按顺序解析
'url_param_type' => 0,
// 是否开启路由
'url_route_on' => true,
// 路由配置文件(支持配置多个)
'route_config_file' => ['route','mobile'.DS.'route'],
// 是否强制使用路由
'url_route_must' => false,
// 域名部署
'url_domain_deploy' => true,
// 域名根如thinkphp.cn
'url_domain_root' => '',
// 是否自动转换URL中的控制器和操作名
'url_convert' => true,
// 默认的访问控制器层
'url_controller_layer' => 'controller',
// 表单请求类型伪装变量
'var_method' => '_method',
// +----------------------------------------------------------------------
// | 模板设置
// +----------------------------------------------------------------------
'template' => [
// 模板引擎类型 支持 php think 支持扩展
'type' => 'Think',
// 模板路径
'view_path' => '',
// 模板后缀
'view_suffix' => 'html',
// 模板文件名分隔符
'view_depr' => DS,
// 模板引擎普通标签开始标记
'tpl_begin' => '{',
// 模板引擎普通标签结束标记
'tpl_end' => '}',
// 标签库标签开始标记
'taglib_begin' => '{',
// 标签库标签结束标记
'taglib_end' => '}',
// 预加载自定义模板标签
'taglib_pre_load' => 'wstmart\common\taglib\Wst',
],
// 视图输出字符串内容替换
'view_replace_str' => [
'__ROOT__'=>str_replace('/index.php','',\think\Request::instance()->root()),
'__APP__'=>\think\Request::instance()->root(),
'__STATIC__'=>str_replace('/index.php','',\think\Request::instance()->root()).'/static',
'__IMGURL__'=>'http://img.zgqlg.com.cn'
],
// 默认跳转页面对应的模板文件
'dispatch_success_tmpl' => THINK_PATH . 'tpl' . DS . 'dispatch_jump.tpl',
'dispatch_error_tmpl' => THINK_PATH . 'tpl' . DS . 'dispatch_jump.tpl',
// +----------------------------------------------------------------------
// | 异常及错误设置
// +----------------------------------------------------------------------
// 异常页面的模板文件
'exception_tmpl' => THINK_PATH . 'tpl' . DS . 'think_exception.tpl',
// 错误显示信息,非调试模式有效
'error_message' => '页面错误!请稍后再试~',
// 显示错误信息
'show_error_msg' => true,
// 异常处理handle类 留空使用 \think\exception\Handle
'exception_handle' => '\\wstmart\\common\\exception\\WstHttpException',
// +----------------------------------------------------------------------
// | 日志设置
// +----------------------------------------------------------------------
'log' => [
// 日志记录方式,内置 file socket 支持扩展
'type' => 'File',
// 日志保存目录
'path' => LOG_PATH,
// 日志记录级别
'level' => [],
],
// +----------------------------------------------------------------------
// | Trace设置 开启 app_trace 后 有效
// +----------------------------------------------------------------------
'trace' => [
// 内置Html Console 支持扩展
'type' => 'Html',
],
// +----------------------------------------------------------------------
// | 缓存设置
// +----------------------------------------------------------------------
'cache' => [
// 驱动方式
'type' => 'File',
// 缓存保存目录
'path' => CACHE_PATH,
// 缓存前缀
'prefix' => 'WSTMART_',
// 缓存有效期 0表示永久缓存
'expire' => 0,
],
// +----------------------------------------------------------------------
// | 会话设置
// +----------------------------------------------------------------------
'session' => [
'id' => '',
// SESSION_ID的提交变量,解决flash上传跨域
'var_session_id' => '',
// SESSION 前缀
'prefix' => 'hyh_',
// 驱动方式 支持redis memcache memcached
'type' => '',
// 是否自动开启 SESSION
'auto_start' => true,
],
// +----------------------------------------------------------------------
// | Cookie设置
// +----------------------------------------------------------------------
'cookie' => [
// cookie 名称前缀
'prefix' => 'WSTMART_',
// cookie 保存时间
'expire' => 0,
// cookie 保存路径
'path' => '/',
// cookie 有效域名
'domain' => '',
// cookie 启用安全传输
'secure' => false,
// httponly设置
'httponly' => '',
// 是否使用 setcookie
'setcookie' => true,
],
//分页配置
'paginate' => [
'type' => 'bootstrap',
'var_page' => 'page',
'list_rows' => 15,
]
];

View File

@ -0,0 +1,236 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
return [
// +----------------------------------------------------------------------
// | 应用设置
// +----------------------------------------------------------------------
// 应用调试模式
'app_debug' => true,
// 应用Trace
'app_trace' => false,
// 应用模式状态
'app_status' => '',
// 是否支持多模块
'app_multi_module' => true,
// 入口自动绑定模块
'auto_bind_module' => false,
// 注册的根命名空间
'root_namespace' => [],
// 扩展配置文件
'extra_config_list' => ['database', 'validate'],
// 扩展函数文件
'extra_file_list' => [THINK_PATH.'helper'.EXT,WST_COMM."function.php",WST_HOME_COMM."function.php",WST_ADMIN_COMM."function.php"],
// 默认输出类型
'default_return_type' => 'html',
// 默认AJAX 数据返回格式,可选json xml ...
'default_ajax_return' => 'json',
// 默认JSONP格式返回的处理方法
'default_jsonp_handler' => 'jsonpReturn',
// 默认JSONP处理方法
'var_jsonp_handler' => 'callback',
// 默认时区
'default_timezone' => 'PRC',
// 是否开启多语言
'lang_switch_on' => false,
// 默认全局过滤方法 用逗号分隔多个
'default_filter' => 'trim,WSTHtmlspecialchars',
// 默认语言
'default_lang' => 'zh-cn',
// 应用类库后缀
'class_suffix' => false,
// 控制器类后缀
'controller_suffix' => false,
// +----------------------------------------------------------------------
// | 模块设置
// +----------------------------------------------------------------------
// 默认模块名
'default_module' => 'home',
// 禁止访问模块
'deny_module_list' => ['common'],
// 默认控制器名
'default_controller' => 'Index',
// 默认操作名
'default_action' => 'index',
// 默认验证器
'default_validate' => '',
// 默认的空控制器名
'empty_controller' => '',
// 操作方法后缀
'action_suffix' => '',
// 自动搜索控制器
'controller_auto_search' => false,
// +----------------------------------------------------------------------
// | URL设置
// +----------------------------------------------------------------------
// PATHINFO变量名 用于兼容模式
'var_pathinfo' => 's',
// 兼容PATH_INFO获取
'pathinfo_fetch' => ['ORIG_PATH_INFO', 'REDIRECT_PATH_INFO', 'REDIRECT_URL'],
// pathinfo分隔符
'pathinfo_depr' => '/',
// URL伪静态后缀
'url_html_suffix' => 'html',
// URL普通方式参数 用于自动生成
'url_common_param' => true,
// URL参数方式 0 按名称成对解析 1 按顺序解析
'url_param_type' => 0,
// 是否开启路由
'url_route_on' => true,
// 路由配置文件(支持配置多个)
'route_config_file' => ['route','mobile'.DS.'route'],
// 是否强制使用路由
'url_route_must' => false,
// 域名部署
'url_domain_deploy' => true,
// 域名根如thinkphp.cn
'url_domain_root' => '',
// 是否自动转换URL中的控制器和操作名
'url_convert' => true,
// 默认的访问控制器层
'url_controller_layer' => 'controller',
// 表单请求类型伪装变量
'var_method' => '_method',
// +----------------------------------------------------------------------
// | 模板设置
// +----------------------------------------------------------------------
'template' => [
// 模板引擎类型 支持 php think 支持扩展
'type' => 'Think',
// 模板路径
'view_path' => '',
// 模板后缀
'view_suffix' => 'html',
// 模板文件名分隔符
'view_depr' => DS,
// 模板引擎普通标签开始标记
'tpl_begin' => '{',
// 模板引擎普通标签结束标记
'tpl_end' => '}',
// 标签库标签开始标记
'taglib_begin' => '{',
// 标签库标签结束标记
'taglib_end' => '}',
// 预加载自定义模板标签
'taglib_pre_load' => 'wstmart\common\taglib\Wst',
],
// 视图输出字符串内容替换
'view_replace_str' => [
'__ROOT__'=>str_replace('/index.php','',\think\Request::instance()->root()),
'__APP__'=>\think\Request::instance()->root(),
'__STATIC__'=>str_replace('/index.php','',\think\Request::instance()->root()).'/static',
'__IMGURL__'=>'http://img.heyuanhui.cn'
],
// 默认跳转页面对应的模板文件
'dispatch_success_tmpl' => THINK_PATH . 'tpl' . DS . 'dispatch_jump.tpl',
'dispatch_error_tmpl' => THINK_PATH . 'tpl' . DS . 'dispatch_jump.tpl',
// +----------------------------------------------------------------------
// | 异常及错误设置
// +----------------------------------------------------------------------
// 异常页面的模板文件
'exception_tmpl' => THINK_PATH . 'tpl' . DS . 'think_exception.tpl',
// 错误显示信息,非调试模式有效
'error_message' => '页面错误!请稍后再试~',
// 显示错误信息
'show_error_msg' => true,
// 异常处理handle类 留空使用 \think\exception\Handle
'exception_handle' => '\\wstmart\\common\\exception\\WstHttpException',
// +----------------------------------------------------------------------
// | 日志设置
// +----------------------------------------------------------------------
'log' => [
// 日志记录方式,内置 file socket 支持扩展
'type' => 'File',
// 日志保存目录
'path' => LOG_PATH,
// 日志记录级别
'level' => [],
],
// +----------------------------------------------------------------------
// | Trace设置 开启 app_trace 后 有效
// +----------------------------------------------------------------------
'trace' => [
// 内置Html Console 支持扩展
'type' => 'Html',
],
// +----------------------------------------------------------------------
// | 缓存设置
// +----------------------------------------------------------------------
'cache' => [
// 驱动方式
'type' => 'File',
// 缓存保存目录
'path' => CACHE_PATH,
// 缓存前缀
'prefix' => 'WSTMART_',
// 缓存有效期 0表示永久缓存
'expire' => 0,
],
// +----------------------------------------------------------------------
// | 会话设置
// +----------------------------------------------------------------------
'session' => [
'id' => '',
// SESSION_ID的提交变量,解决flash上传跨域
'var_session_id' => '',
// SESSION 前缀
'prefix' => 'hyh_',
// 驱动方式 支持redis memcache memcached
'type' => '',
// 是否自动开启 SESSION
'auto_start' => true,
],
// +----------------------------------------------------------------------
// | Cookie设置
// +----------------------------------------------------------------------
'cookie' => [
// cookie 名称前缀
'prefix' => 'WSTMART_',
// cookie 保存时间
'expire' => 0,
// cookie 保存路径
'path' => '/',
// cookie 有效域名
'domain' => '',
// cookie 启用安全传输
'secure' => false,
// httponly设置
'httponly' => '',
// 是否使用 setcookie
'setcookie' => true,
],
//分页配置
'paginate' => [
'type' => 'bootstrap',
'var_page' => 'page',
'list_rows' => 15,
]
];

View File

@ -0,0 +1,13 @@
<?php
/**
* ============================================================================
*/
return [
'module_init'=> [
'wstmart\\home\\behavior\\InitConfig'
],
'action_begin'=> [
'wstmart\\home\\behavior\\ListenProtectedUrl'
]
]
?>

View File

@ -0,0 +1,14 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
return [
'exception_handle' => '\\wstmart\\common\\exception\\WstMoblieHttpException',
];

View File

@ -0,0 +1,25 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
\think\Route::rule([
'mselfshop'=>'mobile/shops/selfshop', //自营店铺
'mbrands'=>'mobile/brands/index', //自营店铺
'mstreet'=>'mobile/shops/shopstreet', //自营店铺
'mlogin'=>'mobile/users/login', //用户登录
'mregister'=>'mobile/users/toregister', //用户注册
'mforget'=>'mobile/users/forgetpass', //找回密码
'mgoods-<goodsId>'=>'mobile/goods/detail',
'mshops-<shopId>'=>'mobile/shops/index',
'mhshops-<shopId>'=>'mobile/shops/home',
'mlist'=>'mobile/goods/lists',
'mnews'=>'mobile/news/view',
'mcategoty'=>'mobile/goodscats/index',
'mshopgoods'=>'mobile/shops/shopgoodslist',
]);

View File

@ -0,0 +1,34 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
\think\Route::rule([
//PC版优化
'index'=>'home/index/index', //商品分类
'category-<cat>'=>'home/goods/lists', //商品分类
'search'=>'home/goods/search', //商品搜索
'goods-<id>'=>'home/goods/detail', //商品
'brands'=>'home/brands/index', //品牌
'street'=>'home/shops/shopstreet', //品牌
'service-<id>'=>'home/helpcenter/view', //帮助中心
'service'=>'home/helpcenter/view', //帮助中心
'news-<id>'=>'home/news/view', //新闻
'news'=>'home/news/view', //新闻
'newscats-<catId>'=>'home/news/nlist', //新闻
'newscats'=>'home/news/nlist', //新闻
'login'=>'home/users/login', //用户登录页
'register'=>'home/users/regist', //用户登录页
'forget'=>'home/users/forgetpass', //找回密码
'forget-step1'=>'home/users/forgetpasst', //找回密码
'forget-success'=>'home/users/forgetpassf', //找回密码
'forget-step3'=>'home/users/resetpass', //找回密码
'shop-login'=>'home/shops/login', //商家登录
'selfshop'=>'home/shops/selfshop', //自营店铺
'shop-<shopId>'=>'home/shops/home' //店铺主页
]);

10
hyhproject/common/conf/tags.php Executable file
View File

@ -0,0 +1,10 @@
<?php
/**
* ============================================================================
*/
return [
'app_begin'=> [
'wstmart\\common\\behavior\\InitConfig'
]
]
?>

View File

@ -0,0 +1,14 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
return [
'exception_handle' => '\\wstmart\\common\\exception\\WstWechatHttpException',
];

View File

@ -0,0 +1,18 @@
<?php
namespace wstmart\common\exception;
use think\exception\Handle;
// APP异常处理类
class WstAppHttpException extends Handle
{
public function render(\Exception $e)
{
if(config('app_debug')){
return parent::render($e);
}else{
//die('{"status":-111,"msg":"数据读取出现未知错误!"}');
die('{"status":-111,"msg":"'.$e->getMessage().'"}');
}
}
}

View File

@ -0,0 +1,20 @@
<?php
namespace wstmart\common\exception;
/**
* ============================================================================
*/
use think\exception\Handle;
class WstHttpException extends Handle
{
public function render(\Exception $e)
{
if(config('app_debug')){
return parent::render($e);
}else{
header("Location:".url('home/error/index'));
}
}
}

View File

@ -0,0 +1,17 @@
<?php
namespace wstmart\common\exception;
use think\exception\Handle;
// 手机版异常处理类
class WstMoblieHttpException extends Handle
{
public function render(\Exception $e)
{
if(config('app_debug')){
return parent::render($e);
}else{
header("Location:".url('mobile/error/index'));
}
}
}

View File

@ -0,0 +1,17 @@
<?php
namespace wstmart\common\exception;
use think\exception\Handle;
// 微信版异常处理类
class WstWechatHttpException extends Handle
{
public function render(\Exception $e)
{
if(config('app_debug')){
return parent::render($e);
}else{
header("Location:".url('wechat/error/index'));
}
}
}

View File

@ -0,0 +1,23 @@
<?php
namespace wstmart\common\model;
/**
* ============================================================================
* 插件类
*/
class Addons extends Base{
public function getAddonsMaps(){
$addons = cache('WST_ADDONS_MAPS');
if(!$addons){
$list = $this->where(["dataFlag"=>1])->field("name,title")->select();
$addons = array();
for($i=0,$j=count($list);$i<$j;$i++){
$addon = $list[$i];
$addons[strtolower($addon["name"])] = $addon["title"];
}
cache('WST_ADDONS_MAPS',$addons,86400);
}
return $addons;
}
}

12
hyhproject/common/model/Ads.php Executable file
View File

@ -0,0 +1,12 @@
<?php
namespace wstmart\common\model;
/**
* ============================================================================
* 广告类
*/
class Ads extends Base{
public function recordClick(){
$id = (int)input('id');
return $this->where("adId=$id")->setInc('adClickNum');
}
}

View File

@ -0,0 +1,77 @@
<?php
namespace wstmart\common\model;
/**
* ============================================================================
* 基础控业务处理
*/
use think\Model;
use think\Db;
vendor('oss-sdk.autoload');
use OSS\OssClient;
use OSS\Core\OssException;
const OSS_ACCESS_ID = 'LTAIfppBmzIHRPV0';
const OSS_ACCESS_KEY = 'OdsoQBa30zzPC38Jq9EmefbqSgFZnX';
const OSS_ENDPOINT = 'oss-cn-hongkong.aliyuncs.com';
const OSS_BUCKET = 'qlgmall';
const OSS_WEB_SITE = 'img.zgqlg.com.cn';
class Aliyunoss extends Model {
public $ossClient;
private $oss_access_id;
private $oss_access_key;
private $oss_endpoint;
private $oss_bucket;
private $oss_web_site;
public function __construct(){
parent::__construct();
$this->oss_access_id = OSS_ACCESS_ID;
$this->oss_access_key = OSS_ACCESS_KEY;
$this->oss_endpoint = OSS_ENDPOINT;
$this->oss_bucket = OSS_BUCKET;
$this->oss_web_site = OSS_WEB_SITE;
$this->ossClient = new OssClient($this->oss_access_id,$this->oss_access_key,$this->oss_endpoint);
}
/**
* [getInfo 获取图片信息]
* @param [type] $object [oss图片名]
* @return [type] [description]
*/
public function getInfo($object){
$options = array(
//不能 加入这个OssClient::OSS_FILE_DOWNLOAD如果加入会下载下来
// OssClient::OSS_FILE_DOWNLOAD =>'upload/image/2018-06/5b1b478de0a8123.jpg',
OssClient::OSS_PROCESS => "image/info", );
$rs = $this->ossClient->getObject($this->oss_bucket, $object,$options);
return json_decode($rs,true);
die;
}
/**
* [uploadFile 图片上传]
* @param [type] $object [上传后的文件名]
* @param [type] $file [上传前的文件路径]
* @return [type] [description]
*/
public function uploadFile($object,$file){
try{
$this->ossClient->uploadFile($this->oss_bucket, $object,$file);
return true;
}catch(OssException $e){
$e->getMessage();
return false;
}
}
/**
* [del 删除文件]
* @param [type] $object [oss文件名包含路径]
* @return [type] [description]
*/
public function del($object){
try{
$this->ossClient->deleteObject($this->oss_bucket,$object);
}catch(OssException $e){
return $e->getMessage();
}
}
}

View File

@ -0,0 +1,76 @@
<?php
namespace wstmart\common\model;
/**
* ============================================================================
* 地区类
*/
class Areas extends Base{
/**
* 获取所有城市-根据字母分类
*/
public function getCityGroupByKey(){
$rs = array();
$rslist = $this->where('isShow=1 AND dataFlag = 1 AND areaType=1')->field('areaId,areaName,areaKey')->order('areaKey, areaSort')->select();
foreach ($rslist as $key =>$row){
$rs[$row["areaKey"]][] = $row;
}
return $rs;
}
/**
* 获取城市列表
*/
public function getCitys(){
return $this->where('isShow=1 AND dataFlag = 1 AND areaType=1')->field('areaId,areaName')->order('areaKey, areaSort')->select();
}
public function getArea($areaId2){
$rs = $this->where(["isShow"=>1,"dataFlag"=>1,"areaType"=>1,"areaId"=>$areaId2])->field('areaId,areaName,areaKey')->find();
return $rs;
}
/**
* 获取地区列表
*/
public function listQuery($parentId = 0){
$parentId = ($parentId>0)?$parentId:(int)input('parentId');
return $this->where(['isShow'=>1,'dataFlag'=>1,'parentId'=>$parentId])->field('areaId,areaName,parentId')->order('areaSort desc')->select();
}
/**
* 获取指定对象
*/
public function getById($id){
return $this->where(["areaId"=>(int)$id])->find()->toArray();
}
/**
* 根据子分类获取其父级分类
*/
public function getParentIs($id,$data = array()){
$data[] = $id;
$parentId = $this->where('areaId',$id)->value('parentId');
if($parentId==0){
krsort($data);
return $data;
}else{
return $this->getParentIs($parentId, $data);
}
}
/**
* 获取自己以及父级的地区名称
*/
public function getParentNames($id,$data = array()){
$areas = $this->where('areaId',$id)->field('parentId,areaName')->find();
$data[] = $areas['areaName'];
if((int)$areas['parentId']==0){
krsort($data);
return $data;
}else{
return $this->getParentNames((int)$areas['parentId'], $data);
}
}
/**
* 检测是否还存在下级
*/
public function hasChild($areaId){
return $this->where(['parentId'=>(int)$areaId,'dataFlag'=>1,'isShow'=>1])->find();
}
}

View File

@ -0,0 +1,85 @@
<?php
namespace wstmart\common\model;
use think\Db;
/**
* ============================================================================
* 验证处理类
*/
class Auth extends Base{
protected $table = '';
public function __construct(){
parent::__construct();
$this->table = Db::name('auth_personal');
}
public function setTable($tableName='auth_company'){
$this->table = Db::name($tableName);
}
public function getStatusTextAttr($value,$data){
$status = [-1=>'已拒绝',0=>'待审核',1=>'已通过'];
return $status[$data['status']];
}
/**
* 获取单条信息
* @param [type] $where [description]
* @param string $field [description]
* @return [type] [description]
*/
public function getInfo($where,$field='*'){
return $this->table->where($where)->field($field)->find();
}
/**
* 获取单条信息
* @param [type] $where [description]
* @param string $field [description]
* @return [type] [description]
*/
public function getField($where,$field='id'){
return $this->table->where($where)->value($field);
}
/**
* 插入单条信息
* @param string $data [description]
* @return [type] [description]
*/
public function insertInfo($data){
$data['createTime'] = time();
return $this->table->insert($data);
}
/**
* 更新单条信息
* @param [type] $where [description]
* @param string $data [description]
* @return [type] [description]
*/
public function updateInfo($where,$data){
return $this->table->where($where)->update($data);
}
/**
* 根据手机号获取单条信息
* @param [type] $where [description]
* @param string $data [description]
* @return [type] [description]
*/
public function getAuthInfoByMobile($userPhone){
$where['userPhone']=$userPhone;
$where['dataFlag'] = 1;
$userInfo = getUserInfo($where,'userId,authType');
if(!$userInfo) return WSTReturn('手机号不存在');
if(1 == $userInfo['authType']){//个人认证
$field = 'householdName uName,householdIdCard idCard';
}elseif(0 == $userInfo['authType']){
return WSTReturn('请联系该用户实名认证');
}elseif(2 == $userInfo['authType']){
$this->setTable('auth_company');
$field = 'trueName uName,idCard';
//return WSTReturn('合作账号不可亲人认证');
}
$rs = $this->getInfo(['userId'=>$userInfo['userId']],$field);
if($rs){
return WSTReturn('成功',1,$rs);
}
return WSTReturn('获取失败,状态异常');
}
}

View File

@ -0,0 +1,81 @@
<?php
namespace wstmart\common\model;
use think\Db;
/**
* ============================================================================
* 验证处理类
*/
class AuthFamily extends Base{
protected $table = '';
public function __construct(){
parent::__construct();
$this->table = Db::name('auth_family_report');
}
public function setTable($tableName='auth_family_personal'){
$this->table = Db::name($tableName);
}
public function getStatusTextAttr($value,$data){
$status = [-1=>'已拒绝',0=>'待审核',1=>'已通过'];
return $status[$data['status']];
}
/**
* 获取单条信息
* @param [type] $where [description]
* @param string $field [description]
* @return [type] [description]
*/
public function getInfo($where,$field='*'){
$where['dataFlag'] = 1;
return $this->table->where($where)->field($field)->find();
}
/**
* 获取单条信息
* @param [type] $where [description]
* @param string $field [description]
* @return [type] [description]
*/
public function getField($where,$field='id'){
$where['dataFlag'] = 1;
return $this->table->where($where)->value($field);
}
/**
* 获取多条信息
* @param [type] $where [description]
* @param string $field [description]
* @return [type] [description]
*/
public function getList($where,$field='id'){
$where['dataFlag'] = 1;
return $this->table->where($where)->field($field)->select();;
}
/**
* 获取多条信息
* @param [type] $where [description]
* @param string $field [description]
* @return [type] [description]
*/
public function getSelect($where,$field='id'){
$where['dataFlag'] = 1;
return $this->table->where($where)->field($field)->paginate(input('pageSize/d',10))->toArray();;
}
/**
* 插入单条信息
* @param string $data [description]
* @return [type] [description]
*/
public function insertInfo($data){
$data['createTime'] = time();
return $this->table->insert($data);
}
/**
* 更新单条信息
* @param [type] $where [description]
* @param string $data [description]
* @return [type] [description]
*/
public function updateInfo($where,$data){
return $this->table->where($where)->update($data);
}
}

View File

@ -0,0 +1,19 @@
<?php
namespace wstmart\common\model;
/**
* ============================================================================
* 银行业务处理
*/
class Banks extends Base{
/**
* 列表
*/
public function listQuery(){
$data = cache('WST_BANKS');
if(!$data){
$data = $this->where('dataFlag',1)->field('bankId,bankName')->select();
cache('WST_BANKS',$data,31536000);
}
return $data;
}
}

View File

@ -0,0 +1,25 @@
<?php
namespace wstmart\common\model;
use think\Model;
use think\Db;
/**
* ============================================================================
* 基础模型器
*/
class Base extends Model {
/**
* 获取空模型
*/
public function getEModel($tables){
$rs = Db::query('show columns FROM `'.config('database.prefix').$tables."`");
$obj = [];
if($rs){
foreach($rs as $key => $v) {
$obj[$v['Field']] = $v['Default'];
if($v['Key'] == 'PRI')$obj[$v['Field']] = 0;
}
}
return $obj;
}
}

View File

@ -0,0 +1,84 @@
<?php
namespace wstmart\common\model;
use think\Db;
/**
* ============================================================================
* 品牌业务处理类
*/
class Brands extends Base{
/**
* 获取品牌列表
*/
public function pageQuery($pagesize){
$id = (int)input('id');
$where['b.dataFlag']=1;
if($id>1){
$where['gcb.catId']=$id;
}
$rs = $this->alias('b')
->join('__CAT_BRANDS__ gcb','gcb.brandId=b.brandId','left')
->where($where)
->field('b.brandId,brandName,brandImg,gcb.catId')
->group('b.brandId,gcb.catId')
->order('b.sortNo asc')
->paginate($pagesize)->toArray();
return $rs;
}
/**
* 获取品牌列表
*/
public function listQuery($catId){
$rs = Db::name('cat_brands')->alias('l')
->join('__BRANDS__ b','b.brandId=l.brandId and b.dataFlag=1 and l.catId='.$catId)
->field('b.brandId,b.brandName,b.brandImg')
->group('b.brandId')
->order('b.sortNo asc')
->select();
return $rs;
}
/**
* 商品筛选品牌查询
*/
public function goodsListQuery($catId){
$rs = Db::name('cat_brands')->alias('l')
->join('__BRANDS__ b','b.brandId=l.brandId and b.dataFlag=1 and l.catId='.$catId)
->join('__GOODS__ g','g.brandId=b.brandId','inner')
->field('b.brandId,b.brandName,b.brandImg')
->group('b.brandId')
->order('b.sortNo asc')
->select();
return $rs;
}
/**
* 根据商品id获取可供选择的品牌
*/
public function canChoseBrands($goodsId){
$rs = Db::name('cat_brands')->alias('l')
->join('__BRANDS__ b','b.brandId=l.brandId and b.dataFlag=1')
->join('__GOODS__ g','g.brandId=b.brandId','inner')
->where(['g.goodsId'=>['in',$goodsId]])
->field('b.brandId,b.brandName,b.brandImg')
->group('b.brandId')
->order('b.sortNo asc')
->select();
return $rs;
}
/**
* 根据品牌id获取商品id
*/
public function getGoodsIds($brandIds){
$rs = Db::name('goods')->field('goodsId')->where(['brandId'=>['in',$brandIds],'dataFlag'=>1,'isSale'=>1,'goodsStatus'=>1])->select();
if(!empty($rs)){
$bIds = [];
foreach($rs as $k=>$v){
$bIds[$k] = $v['goodsId'];
}
return $bIds;
}
return [];
}
}

610
hyhproject/common/model/Carts.php Executable file
View File

@ -0,0 +1,610 @@
<?php
namespace wstmart\common\model;
use think\Db;
/**
* ============================================================================
* 购物车业务处理类
*/
class Carts extends Base{
/**
* 加入购物车
*/
public function addCart(){
//return WSTReturn("系统调试中,暂不支持购买,请等待调试完成", -1);
$userId = (int)session('WST_USER.userId');
$goodsId = (int)input('post.goodsId');
//goods_specs表的规格ID
$goodsSpecId = (int)input('post.goodsSpecId');
$type = (int)input('post.type');
//mark 添加验证
//$m = new \addons\hyhsale\model\Hyhsale();
// if($type == 0 && model('\addons\hyhsale\model\Hyhsale')->getEffectiveGoods(['goodsId'=>$goodsId,'specsId'=>$goodsSpecId])){
// return WSTReturn("秒杀活动商品请点击立即购买!", -1);
// }
$cartNum = (int)input('post.buyNum',1);
$cartNum = ($cartNum>0)?$cartNum:1;
if($userId==0)return WSTReturn('加入购物车失败,请先登录');
//验证传过来的商品是否合法
$chk = $this->checkGoodsSaleSpec($goodsId,$goodsSpecId);
if($chk['status']==-1)return $chk;
//检测库存是否足够
if($chk['data']['stock']<$cartNum)return WSTReturn("加入购物车失败,商品库存不足", -1);
//添加实物商品
if($chk['data']['goodsType']==0){
$goodsSpecId = $chk['data']['goodsSpecId'];
$goods = $this->where(['userId'=>$userId,'goodsId'=>$goodsId,'goodsSpecId'=>$goodsSpecId])->select();
if(empty($goods)){
$data = array();
$data['userId'] = $userId;
$data['goodsId'] = $goodsId;
$data['goodsSpecId'] = $goodsSpecId;
$data['isCheck'] = 1;
$data['cartNum'] = $cartNum;
$rs = $this->save($data);
}else{
$rs = $this->where(['userId'=>$userId,'goodsId'=>$goodsId,'goodsSpecId'=>$goodsSpecId])->setInc('cartNum',$cartNum);
}
if(false !==$rs){
if($type==1){
$cartId = $this->where(['userId'=>$userId,'goodsId'=>$goodsId,'goodsSpecId'=>$goodsSpecId])->value('cartId');
$this->where("cartId = ".$cartId." and userId=".$userId)->setField('isCheck',1);
$this->where("cartId != ".$cartId." and userId=".$userId)->setField('isCheck',0);
$this->where(['cartId' =>$cartId,'userId'=>$userId])->setField('cartNum',$cartNum);
}
return WSTReturn("添加成功", 1);
}
}else{
//非实物商品
$carts = [];
$carts['goodsId'] = $goodsId;
$carts['cartNum'] = $cartNum;
session('TMP_CARTS',$carts);
return WSTReturn("添加成功", 1,['forward'=>'quickSettlement']);
}
return WSTReturn("加入购物车失败", -1);
}
/**
* 验证商品是否合法
*/
public function checkGoodsSaleSpec($goodsId,$goodsSpecId){
$goods = model('Goods')->where(['goodsStatus'=>1,'dataFlag'=>1,'isSale'=>1,'goodsId'=>$goodsId])->field('goodsId,isSpec,goodsStock,goodsType')->find();
if(empty($goods))return WSTReturn("添加失败,无效的商品信息", -1);
$goodsStock = (int)$goods['goodsStock'];
//有规格的话查询规格是否正确
if($goods['isSpec']==1){
//商品规格详细列表页
$specs = Db::name('goods_specs')->where(['goodsId'=>$goodsId,'dataFlag'=>1])->field('id,isDefault,specStock')->select();
if(count($specs)==0){
return WSTReturn("添加失败,无效的商品信息", -1);
}
//默认规格ID
$defaultGoodsSpecId = 0;
//默认规格库存
$defaultGoodsSpecStock = 0;
//是否找到规格
$isFindSpecId = false;
foreach ($specs as $key => $v){
//获取默认的规格
if($v['isDefault']==1){
$defaultGoodsSpecId = $v['id'];
$defaultGoodsSpecStock = (int)$v['specStock'];
}
//找到相关的规格
if($v['id']==$goodsSpecId){
$goodsStock = (int)$v['specStock'];
$isFindSpecId = true;
}
}
if($defaultGoodsSpecId==0)return WSTReturn("添加失败,无效的商品信息", -1);//有规格却找不到规格的话就报错
//if(!$isFindSpecId)return WSTReturn("添加失败,未找到该规格信息", -1);//修改没有规格直接不能买 mark hsf 20180313
if(!$isFindSpecId)return WSTReturn("", 1,['goodsSpecId'=>$defaultGoodsSpecId,'stock'=>$defaultGoodsSpecStock,'goodsType'=>$goods['goodsType']]);//如果没有找到的话就取默认的规格 mark hsf 20180313
return WSTReturn("", 1,['goodsSpecId'=>$goodsSpecId,'stock'=>$goodsStock,'goodsType'=>$goods['goodsType']]);
}else{
return WSTReturn("", 1,['goodsSpecId'=>0,'stock'=>$goodsStock,'goodsType'=>$goods['goodsType']]);
}
}
/**
* 删除购物车里的商品
*/
public function delCart(){
$userId = (int)session('WST_USER.userId');
$id = input('post.id');
$id = explode(',',WSTFormatIn(",",$id));
$id = array_filter($id);
$this->where("userId = ".$userId." and cartId in(".implode(',', $id).")")->delete();
return WSTReturn("删除成功", 1);
}
/**
* 取消购物车商品选中状态
*/
public function disChkGoods($goodsId,$goodsSpecId,$userId){
$this->save(['isCheck'=>0],['userId'=>$userId,'goodsId'=>$goodsId,'goodsSpecId'=>$goodsSpecId]);
}
/**
* 获取session中购物车列表
*/
public function getQuickCarts($uId=0){
$userId = ($uId==0)?(int)session('WST_USER.userId'):$uId;
$tmp_carts = session('TMP_CARTS');
$where = [];
$where['goodsId'] = $tmp_carts['goodsId'];
$rs = Db::name('goods')->alias('g')
->join('__SHOPS__ s','s.shopId=g.shopId','left')
->where($where)
->field('s.userId,s.shopId,s.shopName,g.goodsId,s.shopQQ,shopWangWang,g.goodsName,g.shopPrice,g.goodsStock,g.goodsImg,g.goodsCatId,g.isFreeShipping')
->find();
if(empty($rs))return ['carts'=>[],'goodsTotalMoney'=>0,'goodsTotalNum'=>0];
$rs['cartNum'] = $tmp_carts['cartNum'];
$carts = [];
$cartShop = [];
$goodsTotalNum = 1;
$goodsTotalMoney = 0;
//勿删!为插件促销活动做准备接口
$rs['promotion'] = [];//商品要优惠的活动
$cartShop['promotion'] = [];//店铺要优惠的活动
$cartShop['promotionMoney'] = 0;//店铺要优惠的金额
//---------------------------
$cartShop['isFreeShipping'] = true;
$cartShop['shopId'] = $rs['shopId'];
$cartShop['shopName'] = $rs['shopName'];
$cartShop['shopQQ'] = $rs['shopQQ'];
$cartShop['userId'] = $rs['userId'];
$cartShop['shopWangWang'] = $rs['shopWangWang'];
//判断能否购买预设allowBuy值为10为将来的各种情况预留10个情况值从0到9
$rs['allowBuy'] = 10;
if($rs['goodsStock']<0){
$rs['allowBuy'] = 0;//库存不足
}else if($rs['goodsStock']<$tmp_carts['cartNum']){
//$rs['allowBuy'] = 1;//库存比购买数小
$rs['cartNum'] = $rs['goodsStock'];
}
$cartShop['goodsMoney'] = $rs['shopPrice'] * $rs['cartNum'];
$goodsTotalMoney = $goodsTotalMoney + $rs['shopPrice'] * $rs['cartNum'];
$rs['specNames'] = [];
$rs['cartId'] = $rs['goodsId'];
unset($rs['shopName']);
$cartShop['list'][] = $rs;
$carts[$cartShop['shopId']] = $cartShop;
$cartData = ['carts'=>$carts,'goodsTotalMoney'=>$goodsTotalMoney,'goodsTotalNum'=>$goodsTotalNum,'promotionMoney'=>0];
//店铺优惠活动监听
hook("afterQueryCarts",["carts"=>&$cartData,'isSettlement'=>true,'isVirtual'=>true,'uId'=>$userId]);
return $cartData;
}
/**
* 获取购物车列表
* isSettlement 是结算页面
* uId 会员ID默认为当前ID
* areaId2 市id
*/
public function getCarts($isSettlement = false, $uId=0, $areaId2=0){//添加会员地址判断 mark hsf 20171116
$userId = ($uId==0)?(int)session('WST_USER.userId'):$uId;
$where = [];
$where['c.userId'] = $userId;
$where['g.dataFlag'] = 1;
$where['g.goodsStatus'] = 1;
$where['g.isSale'] = 1;
$where['s.dataFlag'] = 1;
$where['s.shopStatus'] = 1;
$where['s.status'] = 1;
if($isSettlement)$where['c.isCheck'] = 1;//在结算页面,就获取选中的商品
//获取购物车产品,包括选中和未选中的
$rs = Db::name('carts')->alias('c')->join('__GOODS__ g','c.goodsId=g.goodsId','inner')
->join('__SHOPS__ s','s.shopId=g.shopId','left')
->join('__GOODS_SPECS__ gs','c.goodsSpecId=gs.id','left')
->where($where)
->field('c.goodsSpecId,c.cartId,s.userId,s.shopId,s.shopName,g.goodsId,s.shopQQ,shopWangWang,g.goodsName,g.shopPrice,g.goodsStock,g.isSpec,gs.specPrice,gs.specStock,g.goodsImg,c.isCheck,gs.specIds,c.cartNum,g.goodsCatId,g.freight,g.isFreeShipping,gs.initNum,gs.whslePrice,g.marketPrice')
->select();//添加返回起批量和批发价 mark hsf 20171117
//dump($rs);die;
$carts = [];
$goodsIds = [];
$goodsTotalNum = 0;
$goodsTotalMoney = 0;
//将同一个店铺的商品整合到一块
foreach ($rs as $key =>$v){
if(!isset($carts[$v['shopId']]['goodsMoney']))$carts[$v['shopId']]['goodsMoney'] = 0;
if(!isset($carts[$v['shopId']]['isFreeShipping']))$carts[$v['shopId']]['isFreeShipping'] = true;
//勿删!为插件促销活动做准备接口
$v['promotion'] = [];//商品优惠活动
$carts[$v['shopId']]['promotion'] = [];//店铺优惠活动
$carts[$v['shopId']]['promotionMoney'] = 0;//店铺要优惠的金额
//----------------------------
$carts[$v['shopId']]['shopId'] = $v['shopId'];
$carts[$v['shopId']]['shopName'] = $v['shopName'];
$carts[$v['shopId']]['shopQQ'] = $v['shopQQ'];
$carts[$v['shopId']]['userId'] = $v['userId'];
//如果店铺一旦不包邮了,那么就不用去判断商品是否包邮了
if($v['isFreeShipping']==0 && $carts[$v['shopId']]['isFreeShipping'])$carts[$v['shopId']]['isFreeShipping'] = false;
$carts[$v['shopId']]['shopWangWang'] = $v['shopWangWang'];
if($v['isSpec']==1){
$v['shopPrice'] = $v['specPrice'];
$v['goodsStock'] = $v['specStock'];
}else{
$v['initNum'] = 0;//添加返回起批量和批发价 mark hsf 20171117
$v['whslePrice'] = 0;//添加返回起批量和批发价 mark hsf 20171117
}
//$v['initNum'] = $v['initNum'];//添加返回起批量和批发价 mark hsf 20171117
//$v['whslePrice'] = $v['whslePrice'];//添加返回起批量和批发价 mark hsf 20171117
//判断能否购买预设allowBuy值为10为将来的各种情况预留10个情况值从0到9
$v['allowBuy'] = 10;
if($v['goodsStock']<0){
$v['allowBuy'] = 0;//库存不足
}else if($v['goodsStock']<$v['cartNum']){
//$v['allowBuy'] = 1;//库存比购买数小
$v['cartNum'] = $v['goodsStock'];
}
//如果是结算的话,则要过滤了不符合条件的商品
if($isSettlement && $v['allowBuy']!=10){
$this->disChkGoods($v['goodsId'],(int)$v['goodsSpecId'],(int)session('WST_USER.userId'));
continue;
}
if($v['isCheck']==1){
$carts[$v['shopId']]['goodsMoney'] = $carts[$v['shopId']]['goodsMoney'] + $v['shopPrice'] * $v['cartNum'];
$goodsTotalMoney = $goodsTotalMoney + $v['shopPrice'] * $v['cartNum'];
$goodsTotalNum++;
}
$v['specNames'] = [];
unset($v['shopName']);
$carts[$v['shopId']]['list'][] = $v;
if(!in_array($v['goodsId'],$goodsIds))$goodsIds[] = $v['goodsId'];
}
//dump($carts);die;
//加载规格值
if(count($goodsIds)>0){
$specs = DB::name('spec_items')->alias('s')->join('__SPEC_CATS__ sc','s.catId=sc.catId','left')
->where(['s.goodsId'=>['in',$goodsIds],'s.dataFlag'=>1])->field('catName,itemId,itemName')->select();
if(count($specs)>0){
$specMap = [];
foreach ($specs as $key =>$v){
$specMap[$v['itemId']] = $v;
}
foreach ($carts as $key =>$shop){
foreach ($shop['list'] as $skey =>$v){
$strName = [];
if($v['specIds']!=''){
$str = explode(':',$v['specIds']);
foreach ($str as $vv){
if(isset($specMap[$vv]))$strName[] = $specMap[$vv];
}
}
$carts[$key]['list'][$skey]['specNames'] = $strName;
}
}
}
}
$cartData = ['carts'=>$carts,'goodsTotalMoney'=>$goodsTotalMoney,'goodsTotalNum'=>$goodsTotalNum,'promotionMoney'=>0];
//秒杀活动监听
hook("beforeSettlement",["carts"=>&$cartData]);
$allShippingMoney = 0;
if(empty($cartData['carts']['is_seckilling'])){
//dump($cartData);die;
//店铺优惠活动监听
hook("afterQueryCarts",["carts"=>&$cartData,'isSettlement'=>$isSettlement,'isVirtual'=>false,'uId'=>$userId]);
//批发插件 mart hsf 20171116
hook("mobileControllerCartsSettlement",["carts"=>&$cartData]);
//ect整合相关优惠还有判断不能和在线支付商品一块
hook("ectIntegration",["carts"=>&$cartData,'isSettlement'=>$isSettlement,'uId'=>$userId]);
//11.11会场商品结算钩子
hook("orderCatsDoubleEleven",["carts"=>&$cartData,'isSettlement'=>$isSettlement,'uId'=>$userId]);
}
$freight=0;
/*添加运费计算 ,要先算店铺活动,不然满送运费有问题 mark hsf 20171116 */
$carts = &$cartData['carts'];
foreach ($carts as $val) {
if(!isset($carts[$val['shopId']]['shippingMoney']))$carts[$val['shopId']]['shippingMoney'] = 0;
if($val['isFreeShipping']){
$freight = 0;
}else{
foreach ($val['list'] as &$value) {
$freight += $value['freight'];
}
// if($areaId2){
// $freight = WSTOrderFreight($val['shopId'],$areaId2);
// }else{
// $freight = WSTOrderFreight($val['shopId'],-1);
// }
}
$carts[$val['shopId']]['shippingMoney'] += $freight;//累计运费
$allShippingMoney += $freight;
}
//foreach ($carts as $v) {
$cartData['goodsTotalMoney'] += $allShippingMoney;//$v['shippingMoney'];
//}
/*-------end--------*/
// $cartData['goodsTotalMoney']-=$cartData['promotionMoney'];
// $cartData['goodsTotalMoney'] = $cartData['goodsTotalMoney'] > 0 ? $cartData['goodsTotalMoney'] : 0;
$cartData['all_carts_num'] = $this->where('userId='.$userId)->count();//添加会员的购物车产品数量 mark hsf 20180111
$cartData['allShippingMoney'] = $allShippingMoney;//添加总运费
return $cartData;
}
/**
* 获取购物车商品列表
*/
public function getCartInfo($isSettlement = false){
$userId = (int)session('WST_USER.userId');
$where = [];
$where['c.userId'] = $userId;
if($isSettlement)$where['c.isCheck'] = 1;
$rs = $this->alias('c')->join('__GOODS__ g','c.goodsId=g.goodsId','inner')
->join('__GOODS_SPECS__ gs','c.goodsSpecId=gs.id','left')
->where($where)
->field('c.goodsSpecId,c.cartId,g.goodsId,g.goodsName,g.shopPrice,g.goodsStock,g.isSpec,gs.specPrice,gs.specStock,g.goodsImg,c.isCheck,gs.specIds,c.cartNum')
->select();
$goodsIds = [];
$goodsTotalMoney = 0;
$goodsTotalNum = 0;
foreach ($rs as $key =>$v){
if(!in_array($v['goodsId'],$goodsIds))$goodsIds[] = $v['goodsId'];
if($v['isSpec']==1){
$v['shopPrice'] = $v['specPrice'];
$v['goodsStock'] = $v['specStock'];
}
if($v['goodsStock']<$v['cartNum']){
$v['cartNum'] = $v['goodsStock'];
}
$goodsTotalMoney = $goodsTotalMoney + $v['shopPrice'] * $v['cartNum'];
$rs[$key]['goodsImg'] = WSTImg($v['goodsImg']);
}
//加载规格值
if(count($goodsIds)>0){
$specs = DB::name('spec_items')->alias('s')->join('__SPEC_CATS__ sc','s.catId=sc.catId','left')
->where(['s.goodsId'=>['in',$goodsIds],'s.dataFlag'=>1])->field('itemId,itemName')->select();
if(count($specs)>0){
$specMap = [];
foreach ($specs as $key =>$v){
$specMap[$v['itemId']] = $v;
}
foreach ($rs as $key =>$v){
$strName = [];
if($v['specIds']!=''){
$str = explode(':',$v['specIds']);
foreach ($str as $vv){
if(isset($specMap[$vv]))$strName[] = $specMap[$vv]['itemName'];
}
}
$rs[$key]['specNames'] = $strName;
}
}
}
$goodsTotalNum = count($rs);
return ['list'=>$rs,'goodsTotalMoney'=>sprintf("%.2f", $goodsTotalMoney),'goodsTotalNum'=>$goodsTotalNum];
}
/**
* 修改购物车商品状态
*/
public function changeCartGoods(){
$isCheck = Input('post.isCheck/d',-1);
$buyNum = Input('post.buyNum/d',1);
if($buyNum<1)$buyNum = 1;
$id = Input('post.id/d');
$userId = (int)session('WST_USER.userId');
$data = [];
if($isCheck!=-1)$data['isCheck'] = $isCheck;
$data['cartNum'] = $buyNum;
$this->where(['userId'=>$userId,'cartId'=>$id])->update($data);
return WSTReturn("操作成功", 1);
}
/**
* 批量修改购物车商品状态
*/
public function batchChangeCartGoods(){
$ids = input('ids');
if($ids=='')return WSTReturn("操作失败");
$ids = explode(',',WSTFormatIn(',',$ids));
$userId = (int)session('WST_USER.userId');
$isCheck = ((int)input('post.isCheck/d',-1)==1)?1:0;
$this->where(['userId'=>$userId,'cartId'=>['in',$ids]])->update(['isCheck'=>$isCheck]);
return WSTReturn("操作成功", 1);
}
/**
* 计算订单金额
*/
public function getCartMoney($uId=0){
$data = ['shops'=>[],'totalMoney'=>0,'totalGoodsMoney'=>0];
$areaId = input('areaId2/d',-1);
$userId = $uId==0?(int)session('WST_USER.userId'):$uId;
//计算各店铺运费及金额
$deliverType = (int)input('deliverType');//0是快递1是自提自提的不要运费先取消 mark 20170907
$carts = $this->getCarts(true,$userId,$areaId);//计算价格添加城市运费 mark hsf 20171222
$data['couponMoney'] = 0;//定义一个变量存储11.11优惠券价格
$data['maxScoreMoneySum'] = 0;//定义一个变量,存储惠宝数量
//批发插件 mart hsf 20171116
//hook("mobileControllerCartsSettlement",["carts"=>&$carts]);
$shopFreight = 0;
$maxScoreMoney = 0;//初始化最大可用惠宝数 mark hsf 20171117
$total_promotion_money = 0;//初始化合计优惠 mark hsf 20170303
foreach ($carts['carts'] as &$v){//优化一下循环效率 mark hsf 20171118
/**
* 修改运费计算
* 因为在获取购物车产品信息时已经加上运费了
* mark hsf 20171222
*/
// if($v['isFreeShipping']){
// $data['shops'][$v['shopId']]['freight'] = 0;
// }else{
// $shopFreight = ($deliverType==1)?0:WSTOrderFreight($v['shopId'],$areaId);
// $data['shops'][$v['shopId']]['freight'] = $shopFreight;
// }
if($v['isFreeShipping']){
$shopFreight = 0;
}else{
if($deliverType == 0){
$shopFreight = $v['shippingMoney'];
}
}
$data['shops'][$v['shopId']]['freight'] = $shopFreight;
/****************end****************/
$data['shops'][$v['shopId']]['oldGoodsMoney'] = $v['goodsMoney'];
$data['shops'][$v['shopId']]['goodsMoney'] = $v['goodsMoney']+$shopFreight-$v['promotionMoney'];
$data['totalGoodsMoney'] += $v['goodsMoney']-$v['promotionMoney'];
$data['totalMoney'] += $v['goodsMoney'] + $shopFreight-$v['promotionMoney'];
$total_promotion_money += $v['promotionMoney'];//合计优惠 mark hsf 20170303
/*
* 计算最大可用惠宝,添加验证批发价的惠宝可抵用 mark hsf 20171117
*/
// foreach ($v['list'] as &$val) {
// if(isset($val['isWhsle'])){//是批发价的
// $maxScoreMoney += (int)($val['shopPrice'] * $val['cartNum'] * HuiWhsleScale());//可用惠宝默认抵10%
// }else{
// $maxScoreMoney += (int)($val['shopPrice'] * $val['cartNum'] * HuiScale());
// }
// }
/****************end****************/
}
//批发插件 mart hsf 20171116
hook("mobileControllerCartsSettlement",["carts"=>&$carts]);
//放钩子计算11.11订单的分类商品使用优惠券后的金额
hook("orderCatsCouponEleven",['data'=>&$data,'carts'=>&$carts,'isSettlement'=>true,'uId'=>$userId]);
if(isset($data['couponMoney']) && $data['couponMoney'] > 0 ){
$total_promotion_money += $data['couponMoney'];
}
//此处放钩子计算商家使用优惠券后的金额-根据优惠券ID计算
hook("afterCalculateCartMoney",["data"=>&$data,'carts'=>$carts,'isVirtual'=>false,'uId'=>$userId]);
//ect整合相关优惠还有判断不能和在线支付商品一块
hook("ectIntegration",["carts"=>&$carts,'isSettlement'=>true,'uId'=>$userId]);
$maxScoreMoney = $data['maxScoreMoneySum']-($total_promotion_money * HuiScale());//减去优惠过的
$maxScoreMoney = $maxScoreMoney < 0 ? 0 : $maxScoreMoney;//防止负数 mark 20180303
// dump($data) ;die;
$data['totalGoodsMoney'] = ($data['totalGoodsMoney']>$data['totalMoney'])?$data['totalMoney']:$data['totalGoodsMoney'];
$data['maxScore'] = 0;
$data['maxScoreMoney'] = 0;
$data['useScore'] = 0;
$data['scoreMoney'] = 0;
//计算最大可用惠宝
/**
* 最多金额抵用20% mark 20170907
*/
$maxScore = round(WSTScoreToMoney($maxScoreMoney,true),2);//WSTScoreToMoney($data['totalGoodsMoney'],true);
/****************end****************/
//最大可用惠宝不能大于用户惠宝
$user = model('users')->getFieldsById($userId,'userScore');
if($maxScore>$user['userScore']){
$maxScore = $user['userScore'];
$maxScoreMoney = WSTScoreToMoney($maxScore);
}
$data['maxScore'] = $maxScore;
$data['maxScoreMoney'] = $maxScoreMoney;
//判断是否使用惠宝
$isUseScore = (int)input('isUseScore');
if($isUseScore==1){
//不能比用户惠宝还多
$useScore = input('useScore');
if($useScore>$maxScore)$useScore = $maxScore;
$data['useScore'] = $useScore;
$data['scoreMoney'] = WSTScoreToMoney($useScore);
}
if((isset($carts['is_seckilling']) && $carts['is_seckilling'] == 1) || (isset($carts['promotion_goods']) && $carts['promotion_goods'] == 1)){//不可抵用惠宝
$data['useScore']=0;
$data['scoreMoney']=0;
}
//$carts['promotionMoney'] = isset($carts['promotionMoney']) ? $carts['promotionMoney'] : 0;
$data['couponMoney'] = isset($data['couponMoney']) ? $data['couponMoney'] : 0;
$data['realTotalMoney'] = WSTPositiveNum($data['totalMoney'] - $data['scoreMoney']- $data['couponMoney']);
//dump($data);
return WSTReturn('',1,$data);
}
public function getQuickCartMoney($uId=0){
$data = ['shops'=>[],'totalMoney'=>0,'totalGoodsMoney'=>0];
$areaId = input('post.areaId2/d',-1);
//计算各店铺运费及金额
$carts = $this->getQuickCarts(true);
$cart = current($carts['carts']);
$data['shops'][$cart['shopId']]['freight'] = 0;
$data['shops'][$cart['shopId']]['goodsMoney'] = $cart['goodsMoney'];
$data['totalGoodsMoney'] = $cart['goodsMoney'];
$data['totalMoney'] += $cart['goodsMoney'];
//此处放钩子计算商家使用优惠券后的金额-根据优惠券ID计算
hook("afterCalculateCartMoney",["data"=>&$data,'carts'=>$carts,'isVirtual'=>true]);
$data['totalGoodsMoney'] = ($data['totalGoodsMoney']>$data['totalMoney'])?$data['totalMoney']:$data['totalGoodsMoney'];
$data['maxScore'] = 0;
$data['maxScoreMoney'] = 0;
$data['useScore'] = 0;
$data['scoreMoney'] = 0;
/*************计算最大可用惠宝************/
$maxScoreMoney = (int)($data['totalGoodsMoney'] * HuiScale());
$maxScore = WSTScoreToMoney($maxScoreMoney,true);
//$maxScoreMoney = $data['totalGoodsMoney'];
//$maxScore = WSTScoreToMoney($data['totalGoodsMoney'],true);
/***********end*************/
//最大可用惠宝不能大于用户惠宝
$userId = $uId==0?(int)session('WST_USER.userId'):$uId;
$user = model('users')->getFieldsById($userId,'userScore');
if($maxScore>$user['userScore']){
$maxScore = $user['userScore'];
$maxScoreMoney = WSTScoreToMoney($maxScore,true);
}
$data['maxScore'] = $maxScore;
$data['maxScoreMoney'] = $maxScoreMoney;
//判断是否使用惠宝
$isUseScore = (int)input('isUseScore');
if($isUseScore==1){
//不能比用户惠宝还多
$useScore = (int)input('useScore');
if($useScore>$maxScore)$useScore = $maxScore;
$data['useScore'] = $useScore;
$data['scoreMoney'] = WSTScoreToMoney($useScore);
}
$data['realTotalMoney'] = WSTPositiveNum($data['totalMoney'] - $data['scoreMoney']);
return WSTReturn('',1,$data);
}
/**
* 删除购物车商品
*/
public function delCartByUpdate($goodsId){
if(is_array($goodsId)){
$this->where(['goodsId'=>['in',$goodsId]])->delete();
}else{
$this->where('goodsId',$goodsId)->delete();
}
}
/**
* app购物车推荐商品
* uId 会员ID默认为当前ID
*/
public function recommendGoods($uId=0){
$pageSize = (int)input('pageSize/d',10);
$userId = ($uId==0)?(int)session('WST_USER.userId'):$uId;
$where = [];
$where['c.userId'] = $userId;
//获取购物车产品,包括选中和未选中的
$catsGoods = Db::name('carts')->alias('c')->join('__GOODS__ g','c.goodsId=g.goodsId','inner')
->where($where)
->Distinct(true)
->cache(true,60)
->column('g.goodsCatId');
$recommendGoods = Db::name('goods')->where(['goodsCatId'=>['in',$catsGoods]])->field('goodsId,goodsName,goodsImg,shopPrice')->order('saleNum desc')->cache(true,60)->paginate($pageSize)
->toArray();
return WSTReturn('',1,$recommendGoods);
}
}

View File

@ -0,0 +1,91 @@
<?php
namespace wstmart\common\model;
/**
* ============================================================================
* 提现账号业务处理器
*/
class CashConfigs extends Base{
/**
* 获取列表
*/
public function pageQuery($targetType,$targetId){
$type = (int)input('post.type',-1);
$where = [];
$where['targetType'] = (int)$targetType;
$where['targetId'] = (int)$targetId;
$where['c.dataFlag'] = 1;
if(in_array($type,[0,1]))$where['moneyType'] = $type;
$page = $this->alias('c')->join('__BANKS__ b','c.accTargetId=b.bankId')->where($where)->field('b.bankName,c.*')->order('c.id desc')->paginate()->toArray();
if(count($page['Rows'])>0){
foreach($page['Rows'] as $key => $v){
$areas = model('areas')->getParentNames($v['accAreaId']);
$page['Rows'][$key]['areaName'] = implode('',$areas);
}
}
return $page;
}
/**
* 获取列表
*/
public function listQuery($targetType,$targetId){
$where = [];
$where['targetType'] = (int)$targetType;
$where['targetId'] = (int)$targetId;
$where['dataFlag'] = 1;
return $this->where($where)->field('id,accNo,accUser')->select();
}
/**
* 获取资料
*/
public function getById($id){
$config = $this->get($id);
$areas = model('areas')->getParentIs($config['accAreaId']);
$config['accAreaIdPath'] = implode('_',$areas)."_";
return $config;
}
/**
* 新增卡号
*/
public function add(){
$data = input('post.');
$data['targetType'] = 0;
$data['targetId'] = (int)session('WST_USER.userId');
$data['accType'] = 3;
$data['userId'] = (int)session('WST_USER.userId');
$data['createTime'] = date('Y-m-d H:i:s');
WSTUnset($data,'id');
$result = $this->validate('CashConfigs.add')->allowField(true)->save($data);
if(false !== $result){
return WSTReturn("新增成功", 1,['id'=>$this->id]);
}else{
return WSTReturn($this->getError(),-1);
}
}
/**
* 编辑卡号
*/
public function edit(){
$id = (int)input('id');
$data = input('post.');
$userId = (int)session('WST_USER.userId');
WSTUnset($data,'id,targetType,targetId,accType,createTime');
$result = $this->validate('CashConfigs.edit')->allowField(true)->save($data,['id'=>$id,'targetId'=>$userId]);
if(false !== $result){
return WSTReturn("编辑成功", 1);
}else{
return WSTReturn($this->getError(),-1);
}
}
/**
* 删除提现账号
*/
public function del(){
$object = $this->get((int)input('id'));
$object->dataFlag = -1;
$result = $object->save();
if(false !== $result){
return WSTReturn('操作成功',1);
}
return WSTReturn('操作失败',-1);
}
}

View File

@ -0,0 +1,258 @@
<?php
namespace wstmart\common\model;
use think\Db;
/**
* ============================================================================
* 提现流水业务处理器
*/
class CashDraws extends Base{
/**
* 获取列表
*/
public function pageQuery($targetType,$targetId){
$type = (int)input('post.type',-1);
$where = [];
$where['targetType'] = (int)$targetType;
$where['targetId'] = (int)$targetId;
if(in_array($type,[0,1]))$where['moneyType'] = $type;
return $this->where($where)->order('cashId desc')->paginate()->toArray();
}
/**
* 申请提现
*/
public function drawMoney(){
$userId = (int)session('WST_USER.userId');
$money = (float)input('money');
$accId = (float)input('accId');
$payPwd = input('payPwd');
$decrypt_data = WSTRSA($payPwd);
if($decrypt_data['status']==1){
$payPwd = $decrypt_data['data'];
}else{
return WSTReturn('提现申请失败');
}
$limitMoney = (float)WSTConf('CONF.drawCashUserLimit');
if($money<$limitMoney)return WSTReturn('提取金额必须大于或等于¥'.$limitMoney.'方可提现');
if($payPwd=='')return WSTReturn('支付密码不能为空');
//加载提现账号信息
$acc = Db::name('cash_configs')->alias('cc')
->join('__BANKS__ b','cc.accTargetId=b.bankId')->where(['cc.dataFlag'=>1,'id'=>$accId])
->field('b.bankName,cc.*')->find();
if(empty($acc))return WSTReturn('提现账号不存在');
$areas = model('areas')->getParentNames($acc['accAreaId']);
//加载用户
$user = model('users')->get($userId);
$userMoney = $user->userMoney;
$rechargeMoney = $user->rechargeMoney;
$payPwd = md5($payPwd.$user->loginSecret);
if($payPwd!=$user->payPwd)return WSTReturn('支付密码错误');
if($money>($userMoney-$rechargeMoney))return WSTReturn('提取金额不能大于用户可提现金额');
//减去要提取的金额
$user->userMoney = $user->userMoney-$money;
$user->lockMoney = $user->lockMoney+$money;
Db::startTrans();
try{
$result = $user->save();
if(false !==$result){
//创建提现记录
$data = [];
$data['targetType'] = 0;
$data['targetId'] = $userId;
$data['money'] = $money;
$data['accType'] = 3;
$data['accTargetName'] = $acc['bankName'];
$data['accAreaName'] = implode('',$areas);
$data['accNo'] = $acc['accNo'];
$data['accUser'] = $acc['accUser'];
$data['cashSatus'] = 0;
$data['cashConfigId'] = $accId;
$data['createTime'] = date('Y-m-d H:i:s');
$data['cashNo'] = '';
$this->save($data);
$this->cashNo = $this->cashId.(fmod($this->cashId,7));
$this->save();
//判断是否需要发送管理员短信
$tpl = WSTMsgTemplates('PHONE_ADMIN_CASH_DRAWS');
if((int)WSTConf('CONF.smsOpen')==1 && (int)WSTConf('CONF.smsCashDrawsTip')==1 && $tpl['tplContent']!='' && $tpl['status']=='1'){
$params = ['tpl'=>$tpl,'params'=>['CASH_NO'=>$this->cashNo]];
$staffs = Db::name('staffs')->where(['staffId'=>['in',explode(',',WSTConf('CONF.cashDrawsTipUsers'))],'staffStatus'=>1,'dataFlag'=>1])->field('staffPhone')->select();
for($i=0;$i<count($staffs);$i++){
if($staffs[$i]['staffPhone']=='')continue;
$m = new LogSms();
$rv = $m->sendAdminSMS(0,$staffs[$i]['staffPhone'],$params,'drawMoney','');
}
}
//微信消息
if((int)WSTConf('CONF.wxenabled')==1){
//判断是否需要发送给管理员消息
if((int)WSTConf('CONF.wxCashDrawsTip')==1){
$params = [];
$params['CASH_NO'] = $this->cashNo;
$params['LOGIN_NAME'] = session('WST_USER.loginName');
$params['MONEY'] = $money;
$params['CASH_TIME'] = date('Y-m-d H:i:s');
WSTWxBatchMessage(['CODE'=>'WX_ADMIN_CASH_DRAW','userType'=>3,'userId'=>explode(',',WSTConf('CONF.cashDrawsTipUsers')),'params'=>$params]);
}
}
Db::commit();
return WSTReturn('提现申请成功,请留意系统信息',1);
}
}catch (\Exception $e) {
Db::rollback();errLog($e);
return WSTReturn('提现申请失败',-1);
}
}
//旺旺券提现
public function drawWangByShop(){
$shopId = (int)session('WST_USER.shopId');
$userId = (int)session('WST_USER.userId');
$money = (float)input('money');
$payPwd = input('payPwd');
$limitMoney = (float)WSTConf('CONF.drawCashShopLimit');
if($money<$limitMoney)return WSTReturn('提取金额必须大于或等于¥'.$limitMoney.'方可提现');
if($payPwd=='')return WSTReturn('操作密码不能为空');
$shops = model('shops')->get($shopId);
//加载用户
$user = model('users')->get($userId);
$payPwd = md5($payPwd.$user->loginSecret);
if($payPwd!=$user->payPwd)return WSTReturn('操作密码错误');
if($money>$user->wangNum)return WSTReturn('提取金额不能大于商家的已获旺旺券额');
//减去要提取的金额
$user->wangNum = $user->wangNum-$money;
Db::startTrans();
try{
$result = $user->save();
if(false !==$result){
$money = round($money - (dataConf('drawWangScale')*0.01),2);//产品券手续费
//创建提现记录
$data = [];
$data['targetType'] = 1;
$data['targetId'] = $shopId;
$data['money'] = $money;
$data['accType'] = 3;
$data['accTargetName'] = $shops['bankName'];
$data['accAreaName'] = '';
$data['accNo'] = $shops['bankNo'];
$data['accUser'] = $shops['accountName'];
$data['cashSatus'] = 0;
$data['cashConfigId'] = 0;
$data['createTime'] = date('Y-m-d H:i:s');
$data['cashNo'] = '';
$this->save($data);
$this->cashNo = $this->cashId.(fmod($this->cashId,7));
$this->save();
//判断是否需要发送管理员短信
$tpl = WSTMsgTemplates('PHONE_ADMIN_CASH_DRAWS');
if((int)WSTConf('CONF.smsOpen')==1 && (int)WSTConf('CONF.smsCashDrawsTip')==1 && $tpl['tplContent']!='' && $tpl['status']=='1'){
$params = ['tpl'=>$tpl,'params'=>['CASH_NO'=>$this->cashNo]];
$staffs = Db::name('staffs')->where(['staffId'=>['in',explode(',',WSTConf('CONF.cashDrawsTipUsers'))],'staffStatus'=>1,'dataFlag'=>1])->field('staffPhone')->select();
for($i=0;$i<count($staffs);$i++){
if($staffs[$i]['staffPhone']=='')continue;
$m = new LogSms();
$rv = $m->sendAdminSMS(0,$staffs[$i]['staffPhone'],$params,'drawMoney','');
}
}
//微信消息
if((int)WSTConf('CONF.wxenabled')==1){
//判断是否需要发送给管理员消息
if((int)WSTConf('CONF.wxCashDrawsTip')==1){
$params = [];
$params['CASH_NO'] = $this->cashNo;
$params['LOGIN_NAME'] = session('WST_USER.loginName');
$params['MONEY'] = $money;
$params['CASH_TIME'] = date('Y-m-d H:i:s');
WSTWxBatchMessage(['CODE'=>'WX_ADMIN_CASH_DRAW','userType'=>3,'userId'=>explode(',',WSTConf('CONF.cashDrawsTipUsers')),'params'=>$params]);
}
}
Db::commit();
return WSTReturn('提现申请成功,请留意系统信息',1);
}
}catch (\Exception $e) {
Db::rollback();errLog($e);
return WSTReturn('提现申请失败',-1);
}
}
public function drawMoneyByShop(){
$shopId = (int)session('WST_USER.shopId');
$userId = (int)session('WST_USER.userId');
$money = (float)input('money');
$accId = (float)input('accId');
$payPwd = input('payPwd');
$decrypt_data = WSTRSA($payPwd);
if($decrypt_data['status']==1){
$payPwd = $decrypt_data['data'];
}else{
return WSTReturn('提现申请失败');
}
$limitMoney = (float)WSTConf('CONF.drawCashShopLimit');
if($money<$limitMoney)return WSTReturn('提取金额必须大于或等于¥'.$limitMoney.'方可提现');
if($payPwd=='')return WSTReturn('支付密码不能为空');
$shops = model('shops')->get($shopId);
$shopMoney = $shops->shopMoney;
$rechargeMoney = $shops->rechargeMoney;
$areas = model('areas')->getParentNames($shops->bankAreaId);
$bank = model('banks')->get($shops->bankId);
//加载用户
$user = model('users')->get($userId);
$payPwd = md5($payPwd.$user->loginSecret);
if($payPwd!=$user->payPwd)return WSTReturn('支付密码错误');
if($money>($shopMoney-$rechargeMoney))return WSTReturn('提取金额不能大于商家的可提现金额');
//减去要提取的金额
$shops->shopMoney = $shops->shopMoney-$money;
$shops->lockMoney = $shops->lockMoney+$money;
Db::startTrans();
try{
$result = $shops->save();
if(false !==$result){
//创建提现记录
$data = [];
$data['targetType'] = 1;
$data['targetId'] = $shopId;
$data['money'] = $money;
$data['accType'] = 3;
$data['accTargetName'] = $bank['bankName'];
$data['accAreaName'] = implode('',$areas);
$data['accNo'] = $shops['bankNo'];
$data['accUser'] = $shops['bankUserName'];
$data['cashSatus'] = 0;
$data['cashConfigId'] = 0;
$data['createTime'] = date('Y-m-d H:i:s');
$data['cashNo'] = '';
$this->save($data);
$this->cashNo = $this->cashId.(fmod($this->cashId,7));
$this->save();
//判断是否需要发送管理员短信
$tpl = WSTMsgTemplates('PHONE_ADMIN_CASH_DRAWS');
if((int)WSTConf('CONF.smsOpen')==1 && (int)WSTConf('CONF.smsCashDrawsTip')==1 && $tpl['tplContent']!='' && $tpl['status']=='1'){
$params = ['tpl'=>$tpl,'params'=>['CASH_NO'=>$this->cashNo]];
$staffs = Db::name('staffs')->where(['staffId'=>['in',explode(',',WSTConf('CONF.cashDrawsTipUsers'))],'staffStatus'=>1,'dataFlag'=>1])->field('staffPhone')->select();
for($i=0;$i<count($staffs);$i++){
if($staffs[$i]['staffPhone']=='')continue;
$m = new LogSms();
$rv = $m->sendAdminSMS(0,$staffs[$i]['staffPhone'],$params,'drawMoney','');
}
}
//微信消息
if((int)WSTConf('CONF.wxenabled')==1){
//判断是否需要发送给管理员消息
if((int)WSTConf('CONF.wxCashDrawsTip')==1){
$params = [];
$params['CASH_NO'] = $this->cashNo;
$params['LOGIN_NAME'] = session('WST_USER.loginName');
$params['MONEY'] = $money;
$params['CASH_TIME'] = date('Y-m-d H:i:s');
WSTWxBatchMessage(['CODE'=>'WX_ADMIN_CASH_DRAW','userType'=>3,'userId'=>explode(',',WSTConf('CONF.cashDrawsTipUsers')),'params'=>$params]);
}
}
Db::commit();
return WSTReturn('提现申请成功,请留意系统信息',1);
}
}catch (\Exception $e) {
Db::rollback();errLog($e);
return WSTReturn('提现申请失败',-1);
}
}
}

View File

@ -0,0 +1,24 @@
<?php
namespace wstmart\common\model;
use think\Db;
/**
* ============================================================================
* 充值项业务处理
*/
class ChargeItems extends Base{
/**
* 分页
*/
public function queryList(){
$where = [];
$where['dataFlag'] = 1;
return $this->where($where)->field(true)->order('itemSort asc,id asc')->select();
}
public function getItemMoney($itmeId){
$where = [];
$where['dataFlag'] = 1;
$where['id'] = $itmeId;
return $this->where($where)->field("chargeMoney,giveMoney")->find();
}
}

View File

@ -0,0 +1,81 @@
<?php
namespace wstmart\common\model;
use think\Db;
/**
* ============================================================================
* 会员银行卡类
*/
class CompanyBank extends Base{
protected $table = '';
public function __construct(){
parent::__construct();
$this->table = Db::name('company_bank');
}
public function setTable($tableName='user_bank'){
$this->table = Db::name($tableName);
}
public function getStatusTextAttr($value,$data){
$status = [-1=>'已拒绝',0=>'待审核',1=>'已通过'];
return $status[$data['status']];
}
/**
* 获取单条信息
* @param [type] $where [description]
* @param string $field [description]
* @return [type] [description]
*/
public function getInfo($where,$field='*'){
$where['dataFlag'] = 1;
return $this->table->where($where)->field($field)->find();
}
/**
* 获取单条信息
* @param [type] $where [description]
* @param string $field [description]
* @return [type] [description]
*/
public function getField($where,$field='id'){
$where['dataFlag'] = 1;
return $this->table->where($where)->value($field);
}
/**
* 获取多条信息
* @param [type] $where [description]
* @param string $field [description]
* @return [type] [description]
*/
public function getSelect($where,$field='id'){
$where['dataFlag'] = 1;
return $this->table->where($where)->field($field)->paginate(input('pageSize/d',10))->toArray();
}
/**
* 获取多条信息不分页
* @param [type] $where [description]
* @param string $field [description]
* @return [type] [description]
*/
public function getList($where,$field='id'){
$where['dataFlag'] = 1;
return $this->table->where($where)->field($field)->select();
}
/**
* 插入单条信息
* @param string $data [description]
* @return [type] [description]
*/
public function insertInfo($data){
$data['createTime'] = time();
return $this->table->insert($data);
}
/**
* 更新单条信息
* @param [type] $where [description]
* @param string $data [description]
* @return [type] [description]
*/
public function updateInfo($where,$data){
return $this->table->where($where)->update($data);
}
}

View File

@ -0,0 +1,244 @@
<?php
namespace wstmart\common\model;
use think\Db;
class Ectwallet extends Base{
protected $table = 'hyh_user_ectwallet';
/**
* 获取地址列表
*/
public function listQuery($uId=0){
$userId = ((int)$uId==0)?(int)session('WST_USER.userId'):$uId;
$where = ['userId'=>(int)$userId,'dataFlag'=>1];
$rs = $this->order('isDefault desc, eWalletId desc')->where($where)->select();
return $rs;
}
/**
* 新增
*/
public function add($uId=0){
$data = input('post.');
unset($data['eWalletId']);
$data['userId'] = ((int)$uId==0)?(int)session('WST_USER.userId'):$uId;
$data['createTime'] = time();
if($data['userId']==0)return WSTReturn('新增失败,请先登录');
$result = $this->validate('EctWallet.add')->allowField(true)->save($data);
if(false !== $result){
if((int)input('post.isDefault')==1){
$this->where("eWalletId != $this->eWalletId and userId=".$data['userId'])->setField('isDefault',0);
}
return WSTReturn('新增成功',1,['eWalletId'=>$this->eWalletId]);
}else{
return WSTReturn($this->getError(),-1);
}
}
/**
* [infoById 根据钱包地址id 获取钱包地址信息]
* @param [type] $eWalletId [钱包地址id]
* @return [type] [description]
*/
public function infoById($eWalletId){
$where['eWalletId'] = (int)($eWalletId);
$data = Db::name('user_ectwallet')->where($where)->field('eWalletId,eAddress')->find();
if(!empty($data))return $data;
}
/**
* 编辑
*/
public function edit($uId=0){
$userId = ((int)$uId==0)?(int)session('WST_USER.userId'):$uId;
$id = (int)input('post.eWalletId/d');
$data = input('post.');
$result = $this->validate('EctWallet.edit')->allowField(true)->save($data,['eWalletId'=>$id,'userId'=>$userId]);
//修改默认地址
if((int)input('post.isDefault')==1)
$this->where("eWalletId != $id and userId=".$userId)->setField('isDefault',0);
if(false !== $result){
return WSTReturn("编辑成功", 1);
}else{
return WSTReturn($this->getError(),-1);
}
}
/**
* 删除
*/
public function del($uId=0){
$userId = ((int)$uId==0)?(int)session('WST_USER.userId'):$uId;
$id = input('post.eWalletId/d');
$data = [];
$data['dataFlag'] = -1;
$result = $this->update($data,['eWalletId'=>$id,'userId'=>$userId]);
if(false !== $result){
return WSTReturn("删除成功", 1);
}else{
return WSTReturn($this->getError(),-1);
}
}
/**
* 设置为默认地址
*/
public function setDefault($uId=0){
$userId = ((int)$uId==0)?(int)session('WST_USER.userId'):$uId;
$id = (int)input('post.eWalletId');
$this->where(["eWalletId"=>['<>',$id],'userId'=>$userId] )->setField('isDefault',0);
$rs = $this->where("eWalletId = $id and userId=".$userId)->setField('isDefault',1);
if(false !== $rs){
return WSTReturn("设置成功", 1);
}else{
return WSTReturn($this->getError(),-1);
}
}
/**
* 获取默认地址
*/
public function getDefaultAddress($uId=0){
$userId = ((int)$uId==0)?(int)session('WST_USER.userId'):$uId;
$where = ['userId'=>$userId,'dataFlag'=>1,'isDefault'=>1];
$rs = Db::name('user_ectwallet')->where($where)->field('eWalletId,eAddress')->find();
if(empty($rs))return '';
return $rs;
}
/**
* 获取ect数目
*/
public function getEctAddress($uId=0){
$userId = ((int)($uId==0))?(int)session('WST_USER.userId'):$uId;
$address = cache('USER_BLOCK_ADDRESS_'.$userId);
if(!$address){
$where = ['userId'=>$userId];
$address= Db::name('block_user_ect_address')->where($where)->value('address');
if($address){
cache('USER_BLOCK_ADDRESS_'.$userId,$address,0);
}
}
return WSTReturn('',1,['userId'=>$userId,'address'=>$address]);
}
/**
* 获取ect数目
*/
public function getEctNum($uId=0){
$userId = ((int)($uId==0))?(int)session('WST_USER.userId'):$uId;
$where = ['userId'=>$userId];
$num = Db::name('users')->where($where)->value('userECT');
return $num;
}
/**
* 获取ect充值记录
*/
public function getEctRechargeLog($uId=0){
$userId = ((int)($uId==0))?(int)session('WST_USER.userId'):$uId;
if($userId==0) return WSTReturn('请先登录','-999');
$where = ['userId'=>$userId];
$rs['list'] = Db::name('block_user_ect_recharge_log')->where($where)->order('id desc')->field('status,value,createTime')->paginate(10)->toArray();
$rs['address'] = '';
$cacheData = cache('USER_BLOCK_ADDRESS_'.$userId);
if($cacheData){
$rs['address'] = $cacheData;
}else{
$address= Db::name('block_user_ect_address')->where($where)->value('address');
if($address){
$rs['address'] = $address;
cache('USER_BLOCK_ADDRESS_'.$userId,$address,0);
}
}
return $rs;
}
/**
* 获取ect提现记录
*/
public function getUserEctCashLog($uId=0){
$userId = ((int)($uId==0))?(int)session('WST_USER.userId'):$uId;
if($userId==0) return WSTReturn('请先登录','-999');
$where = ['userId'=>$userId];
$rs['list'] = Db::name('user_ect_cash_log')->where($where)->order('id desc')->field('status,ectNum,toAccount,createTime')->paginate(10)->toArray();
return $rs;
}
/**
* 获取ect变更记录
*/
public function getEctLog($uId=0){
$userId = ((int)($uId==0))?(int)session('WST_USER.userId'):$uId;
$where = ['userId'=>$userId];
$rs = Db::name('user_ect_log')->where($where)->order('createTime desc')->paginate(10)->toArray();
return $rs;
}
/**
* 提现
*/
public function withdraw($uId=0){
//return WSTReturn('系统调试中,请稍候重试',-1);
$userId = ((int)($uId==0))?(int)session('WST_USER.userId'):$uId;
if($userId==0)return WSTReturn('请先登录','-999');
//获取提现ect数量
$ectNum = abs((float)input('post.ectNum'));
//获取支付密码
$payPwd = input('post.payPwd');
//获取钱包地址
$eAddress = trim(input('post.eAddress'));
$where = ['userId'=>$userId,'eAddress'=>$eAddress];
$exist = $this->where($where)->find();
if(empty($exist))return WSTReturn('地址不正确',-1);
if($payPwd=='')return WSTReturn('密码不能为空');
$user = model('users')->get($userId);
//获取用户ECT数量
$userECT = (float)$user->userECT;
if($ectNum<500)return WSTReturn('ECT数量最低提取500',-1);
//与用户ect数量作比较
if($userECT<$ectNum)return WSTReturn('ECT数量不足',-1);
//与数据库支付密码作比较
if(md5($payPwd.$user->loginSecret) !=$user->payPwd)return WSTReturn('支付密码错误',-1);
$fp = fopen("cash.lock", "r");
if(flock($fp,LOCK_EX | LOCK_NB)) {//if(flock($fp,LOCK_EX))阻塞(等待)模式
// if(Db::table('rd_user_give_coin')->where(['user_id'=>$user->hyhlm_id])->find() || Db::table('rd_user_give_car_coin')->where(['user_id'=>$user->hyhlm_id])->find()){
// flock($fp,LOCK_UN);
// fclose($fp);
// return WSTReturn('系统调试中,请稍候重试',-1);
// }
// if($user->userType == 0){
// flock($fp,LOCK_UN);
// fclose($fp);
// return WSTReturn('系统调试中,请稍候重试',-1);
// }
$dataSrc = 4;
$remark ="提现";
$ectType = 2;
$update =array('userECT'=>['exp','userECT-'.$ectNum]);
Db::startTrans();
try {
$rs = ectLog($userId,$ectNum,$dataSrc,$remark,$update,$ectType);
$cash_id = $this->ectCashLog($userId,$ectNum,$eAddress,'');
if($rs && $cash_id){
flock($fp,LOCK_UN);
fclose($fp);
Db::commit();
return WSTReturn('提现成功,预计审核次日到账(节假日顺延),请耐心等待!',-1);
// return WSTReturn('提现成功',1,['id'=>$cash_id]);
}else{
Db::rollback();errLog($e);
flock($fp,LOCK_UN);
fclose($fp);
return WSTReturn('提现失败,请重试!',-1);
}
} catch (Exception $e) {
Db::rollback();errLog($e);
return WSTReturn('提现失败,请重试',-1);
}
}else{
fclose($fp);
return WSTReturn('系统繁忙,请稍后再试');
}
}
function ectCashLog($userId,$ectNum,$toAccount,$remark=''){
$data['userId'] = $userId;
$data['ectNum'] = $ectNum;
$data['toAccount'] = $toAccount;
$data['dataRemarks'] = $remark;
$data['createTime'] = time();
// $disabled_ids = [888,1843,15,892,1359,2150];
// if(in_array($userId,$disabled_ids)){
// $data['status'] = 2;
// }
return Db::name('user_ect_cash_log')->insertGetid($data);
}
}

View File

@ -0,0 +1,15 @@
<?php
namespace wstmart\common\model;
/**
* ============================================================================
* 快递业务处理类
*/
use think\Db;
class Express extends Base{
/**
* 获取快递列表
*/
public function listQuery(){
return $this->where('dataFlag',1)->select();
}
}

View File

@ -0,0 +1,118 @@
<?php
namespace wstmart\common\model;
use think\Db;
use wstmart\common\model\Shops;
/**
* ============================================================================
* 收藏类
*/
class Favorites extends Base{
/**
* 关注的商品列表
*/
public function listGoodsQuery(){
$pagesize = input("param.pagesize/d");
$userId = (int)session('WST_USER.userId');
$page = Db::name("favorites")->alias('f')
->join('__GOODS__ g','g.goodsId = f.targetId','left')
->join('__SHOPS__ s','s.shopId = g.shopId','left')
->field('f.favoriteId,f.targetId,g.goodsId,g.goodsName,g.goodsImg,g.shopPrice,g.marketPrice,g.saleNum,g.appraiseNum,s.shopId,s.shopName')
->where(['f.userId'=> $userId,'favoriteType'=> 0])
->order('f.favoriteId desc')
->paginate($pagesize)->toArray();
foreach ($page['Rows'] as $key =>$v){
//认证
$shop = new Shops();
$accreds = $shop->shopAccreds($v["shopId"]);
$page['Rows'][$key]['accreds'] = $accreds;
}
return $page;
}
/**
* 关注的店铺列表
*/
public function listShopQuery(){
$pagesize = input("param.pagesize/d");
$userId = (int)session('WST_USER.userId');
$page = Db::name("favorites")->alias('f')
->join('__SHOPS__ s','s.shopId = f.targetId','left')
->field('f.favoriteId,f.targetId,s.shopId,s.shopName,s.shopImg')
->where(['f.userId'=> $userId,'favoriteType'=> 1])
->order('f.favoriteId desc')
->paginate($pagesize)->toArray();
foreach ($page['Rows'] as $key =>$v){
//商品列表
$goods = db('goods')->where(['dataFlag'=> 1,'isSale'=>1,'goodsStatus'=> 1,'shopId'=> $v["shopId"]])->field('goodsId,goodsName,shopPrice,goodsImg')
->limit(10)->order('saleTime desc')->select();
$page['Rows'][$key]['goods'] = $goods;
}
return $page;
}
/**
* 取消关注
*/
public function del(){
$id = input("param.id");
$type = input("param.type/d");
$userId = (int)session('WST_USER.userId');
$ids = explode(',',$id);
if(empty($ids))return WSTReturn("取消失败", -1);
$rs = $this->where(['favoriteId'=> ['in',$ids],'favoriteType'=> $type,'userId'=>$userId])->delete();
if(false !== $rs){
return WSTReturn("取消成功", 1);
}else{
return WSTReturn($this->getError(),-1);
}
}
/**
* 新增关注
*/
public function add(){
$id = input("param.id/d");
$type = input("param.type/d");
$userId = (int)session('WST_USER.userId');
if($userId==0)return WSTReturn('关注失败,请先登录');
//判断记录是否存在
$isFind = false;
if($type==0){
$c = Db::name('goods')->where(['goodsStatus'=>1,'dataFlag'=>1,'goodsId'=>$id])->count();
$isFind = ($c>0);
}else{
$c = Db::name('shops')->where(['shopStatus'=>1,'dataFlag'=>1,'shopId'=>$id])->count();
$isFind = ($c>0);
}
if(!$isFind)return WSTReturn("关注失败,无效的关注对象", -1);
$data = [];
$data['userId'] = $userId;
$data['favoriteType'] = $type;
$data['targetId'] = $id;
//判断是否已关注
$rc = $this->where($data)->count();
if($rc>0)return WSTReturn("关注成功", 1);
$data['createTime'] = date('Y-m-d H:i:s');
$rs = $this->save($data);
if(false !== $rs){
return WSTReturn("关注成功", 1,['fId'=>$this->favoriteId]);
}else{
return WSTReturn($this->getError(),-1);
}
}
/**
* 判断是否已关注
*/
public function checkFavorite($id,$type,$uId=0){
$userId = ($uId==0)?(int)session('WST_USER.userId'):$uId;
$rs = $this->where(['userId'=>$userId,'favoriteType'=>$type,'targetId'=>$id])->find();
return empty($rs)?0:$rs['favoriteId'];
}
/**
* 关注数
*/
public function followNum($id,$type){
$rs = $this->where(['favoriteType'=>$type,'targetId'=>$id])->count();
return $rs;
}
}

229
hyhproject/common/model/Goods.php Executable file
View File

@ -0,0 +1,229 @@
<?php
namespace wstmart\common\model;
use think\Db;
/**
* ============================================================================
* 商品类
*/
class Goods extends Base{
/**
* 获取店铺商品列表
*/
public function shopGoods($shopId){
$msort = input("param.msort/d");
$mdesc = input("param.mdesc/d");
$order = array('g.saleTime'=>'desc');
$orderFile = array('1'=>'g.isHot','2'=>'g.saleNum','3'=>'g.shopPrice','4'=>'g.shopPrice','5'=>'(gs.totalScore/gs.totalUsers)','6'=>'g.saleTime');
$orderSort = array('0'=>'asc','1'=>'desc');
if($msort>0){
$order = array($orderFile[$msort]=>$orderSort[$mdesc]);
}
$goodsName = input("param.goodsName");//搜索店鋪名
$words = $where = $where2 = $where3 = $where4 = [];
if($goodsName!=""){
$words = explode(" ",$goodsName);
}
if(!empty($words)){
$sarr = array();
foreach ($words as $key => $word) {
if($word!=""){
$sarr[] = "g.goodsName like '%$word%'";
}
}
$where4 = implode(" or ", $sarr);
}
$sprice = input("param.sprice");//开始价格
$eprice = input("param.eprice");//结束价格
if($sprice!="")$where2 = "g.shopPrice >= ".(float)$sprice;
if($eprice!="")$where3 = "g.shopPrice <= ".(float)$eprice;
$ct1 = input("param.ct1/d");
$ct2 = input("param.ct2/d");
if($ct1>0)$where['shopCatId1'] = $ct1;
if($ct2>0)$where['shopCatId2'] = $ct2;
$goods = Db::name('goods')->alias('g')
->join('__GOODS_SCORES__ gs','gs.goodsId = g.goodsId','left')
->where(['g.shopId'=>$shopId,'g.isSale'=>1,'g.goodsStatus'=>1,'g.dataFlag'=>1])
->where($where)->where($where2)->where($where3)->where($where4)
->field('g.goodsId,g.goodsName,g.goodsImg,g.shopPrice,g.marketPrice,g.saleNum,g.appraiseNum,g.goodsStock,g.isFreeShipping,g.saleTime,gallery')//添加上架时间 mark 20170103
->order($order)
->paginate(input('pagesize/d'))->toArray();
return $goods;
}
/**
* 新增商品
*/
public function goodsAdd(){
$shopId = (int)input('post.shopId');
$data = input('post.');
$specsIds = input('post.specsIds');
$basicsMoney = isset($data['basicsMoney']) ? $data['basicsMoney'] : 0;
if(!is_numeric($basicsMoney)){
return WSTReturn("商品成本价请填写数字");
}
$aloneShop = false;//Db::name('alone_shops')->where(['shopId'=>$shopId,'dataFlag'=>1])->find();
// if($aloneShop && !$basicsMoney){
// return WSTReturn("请填写成本价");
// }
WSTUnset($data,'goodsId,statusRemarks,goodsStatus,dataFlag,basicsMoney');
if(isset($data['goodsName'])){
if(!WSTCheckFilterWords($data['goodsName'],WSTConf("CONF.limitWords"))){
return WSTReturn("商品名称包含非法字符");
}
}
if(isset($data['goodsTips'])){
if(!WSTCheckFilterWords($data['goodsTips'],WSTConf("CONF.limitWords"))){
return WSTReturn("商品促销信息包含非法字符");
}
}
if(isset($data['goodsDesc'])){
if(!WSTCheckFilterWords($data['goodsDesc'],WSTConf("CONF.limitWords"))){
return WSTReturn("商品描述包含非法字符");
}
}
if(WSTConf("CONF.isGoodsVerify")==1){
$data['goodsStatus'] = 0;
}else{
$data['goodsStatus'] = 1;
}
$data['shopId'] = $shopId;
$data['saleTime'] = date('Y-m-d H:i:s');
$data['createTime'] = date('Y-m-d H:i:s');
$goodsCats = model('GoodsCats')->getParentIs($data['goodsCatId']);
$data['goodsCatIdPath'] = implode('_',$goodsCats)."_";
if($data['goodsType']==0){
$data['isSpec'] = ($specsIds!='')?1:0;
}else{
$data['isSpec'] = 0;
}
Db::startTrans();
try{
//保存插件数据钩子
hook('beforeEidtGoods',['data'=>&$data]);
$shop = model('shops')->get($shopId);
if($shop['dataFlag'] ==-1 || $shop['shopStatus'] != 1)$data['isSale'] = 0;
$result = $this->validate(true)->allowField(true)->save($data);
if(false !== $result){
$goodsId = $this->goodsId;
//ect支付方式
// $ectPay=(int)input('ectPay');
// $ect['goodsId']=$goodsId;
// $ect['ectPay']=$ectPay;
// Db::name('goods_pay')->insert($ect);
//商品图片
WSTUseImages(0, $goodsId, $data['goodsImg']);
//商品相册
WSTUseImages(0, $goodsId, $data['gallery']);
//商品描述图片
WSTEditorImageRocord(0, $goodsId, '',$data['goodsDesc']);
//建立商品评分记录
$gs = [];
$gs['goodsId'] = $goodsId;
$gs['shopId'] = $shopId;
Db::name('goods_scores')->insert($gs);
//如果是实物商品并且有销售规格则保存销售和规格值
if($data['goodsType']==0 && $specsIds!=''){
$specsIds = explode(',',$specsIds);
$specsArray = [];
foreach ($specsIds as $v){
$vs = explode('-',$v);
foreach ($vs as $vv){
if(!in_array($vv,$specsArray))$specsArray[] = $vv;
}
}
//保存规格名称
$specMap = [];
foreach ($specsArray as $v){
$vv = explode('_',$v);
$sitem = [];
$sitem['shopId'] = $shopId;
$sitem['catId'] = (int)$vv[0];
$sitem['goodsId'] = $goodsId;
$sitem['itemName'] = input('post.specName_'.$vv[0]."_".$vv[1]);
$sitem['itemImg'] = input('post.specImg_'.$vv[0]."_".$vv[1]);
$sitem['dataFlag'] = 1;
$sitem['createTime'] = date('Y-m-d H:i:s');
$itemId = Db::name('spec_items')->insertGetId($sitem);
if($sitem['itemImg']!='')WSTUseImages(0, $itemId, $sitem['itemImg']);
$specMap[$v] = $itemId;
}
//保存销售规格
$defaultPrice = 0;//最低价
$totalStock = 0;//总库存
$gspecArray = [];
$isFindDefaultSpec = false;
$defaultSpec = Input('post.defaultSpec');
foreach ($specsIds as $v){
$vs = explode('-',$v);
$goodsSpecIds = [];
foreach ($vs as $gvs){
$goodsSpecIds[] = $specMap[$gvs];
}
$gspec = [];
$gspec['specIds'] = implode(':',$goodsSpecIds);
$gspec['shopId'] = $shopId;
$gspec['goodsId'] = $goodsId;
$gspec['productNo'] = Input('productNo_'.$v);
$gspec['marketPrice'] = (float)Input('marketPrice_'.$v);
$gspec['specPrice'] = (float)Input('specPrice_'.$v);
$gspec['specStock'] = (int)Input('specStock_'.$v);
$gspec['warnStock'] = (int)Input('warnStock_'.$v);
//设置默认规格
if($defaultSpec==$v){
$isFindDefaultSpec = true;
$defaultPrice = $gspec['specPrice'];
$gspec['isDefault'] = 1;
}else{
$gspec['isDefault'] = 0;
}
$gspecArray[] = $gspec;
//获取总库存
$totalStock = $totalStock + $gspec['specStock'];
}
if(!$isFindDefaultSpec)return WSTReturn("请选择推荐规格");
if(count($gspecArray)>0){
Db::name('goods_specs')->insertAll($gspecArray);
//更新默认价格和总库存
$this->where('goodsId',$goodsId)->update(['isSpec'=>1,'shopPrice'=>$defaultPrice,'goodsStock'=>$totalStock]);
}
}
//保存商品属性
$attrsArray = [];
$attrRs = Db::name('attributes')->where(['goodsCatId'=>['in',$goodsCats],'isShow'=>1,'dataFlag'=>1])
->field('attrId')->select();
foreach ($attrRs as $key =>$v){
$attrs = [];
$attrs['attrVal'] = input('attr_'.$v['attrId']);
if($attrs['attrVal']=='')continue;
$attrs['shopId'] = $shopId;
$attrs['goodsId'] = $goodsId;
$attrs['attrId'] = $v['attrId'];
$attrs['createTime'] = date('Y-m-d H:i:s');
$attrsArray[] = $attrs;
}
if(count($attrsArray)>0)Db::name('goods_attributes')->insertAll($attrsArray);
if($aloneShop){
//保存商品成本价
$basicsArray = [];
$now = time();
$basicsArray['shopId'] = $shopId;
$basicsArray['goodsId'] = $goodsId;
$basicsArray['basicsMoney'] = $basicsMoney;
$basicsArray['createTime'] = $now;
Db::name('alone_goods')->insert($basicsArray);
}
hook('afterGoodsEct',['data'=>&$data,'goodsId'=>$goodsId]);
Db::commit();
return WSTReturn("新增成功", 1,['id'=>$goodsId]);
}else{
return WSTReturn($this->getError(),-1);
}
}catch (\Exception $e) {
Db::rollback();errLog($e);
return WSTReturn('新增失败',-1);
}
}
}

View File

@ -0,0 +1,327 @@
<?php
namespace wstmart\common\model;
/**
* ============================================================================
* 评价类
*/
use think\Db;
class GoodsAppraises extends Base{
public function queryByPage(){
$shopId = (int)session('WST_USER.shopId');
$where = [];
$where['g.goodsStatus'] = 1;
$where['g.dataFlag'] = 1;
$where['g.isSale'] = 1;
$c1Id = (int)input('cat1');
$c2Id = (int)input('cat2');
$goodsName = input('goodsName');
if($goodsName != ''){
$where['g.goodsName'] = ['like',"%$goodsName%"];
}
if($c2Id!=0 && $c1Id!=0){
$where['g.shopCatId2'] = $c2Id;
}else if($c1Id!=0){
$where['g.shopCatId1'] = $c1Id;
}
$where['g.shopId'] = $shopId;
$model = model('goods');
$data = $model->alias('g')
->field('g.goodsId,g.goodsImg,g.goodsName,ga.shopReply,ga.id gaId,ga.replyTime,ga.goodsScore,ga.serviceScore,ga.timeScore,ga.content,ga.images,u.loginName')
->join('__GOODS_APPRAISES__ ga','g.goodsId=ga.goodsId','inner')
->join('__USERS__ u','u.userId=ga.userId','inner')
->where($where)
->paginate()->toArray();
if($data !== false){
return WSTReturn('',1,$data);
}else{
return WSTReturn($this->getError(),-1);
}
}
/**
* 用户评价
*/
public function userAppraise(){
$userId = (int)session('WST_USER.userId');
$where = [];
$where['g.goodsStatus'] = 1;
$where['g.dataFlag'] = 1;
$where['g.isSale'] = 1;
$where['ga.userId'] = $userId;
$model = model('goods');
$data = $model->alias('g')
->field('g.goodsId,g.goodsImg,g.goodsName,ga.goodsScore,ga.serviceScore,ga.timeScore,ga.content,ga.images,ga.shopReply,ga.replyTime,s.shopName,u.userName,o.orderNo')
->join('__GOODS_APPRAISES__ ga','g.goodsId=ga.goodsId','inner')
->join('__ORDERS__ o','o.orderId=ga.orderId','inner')
->join('__USERS__ u','u.userId=ga.userId','inner')
->join('__SHOPS__ s','o.shopId=s.shopId','inner')
->where($where)
->paginate()->toArray();
if($data !== false){
return WSTReturn('',1,$data);
}else{
return WSTReturn($this->getError(),-1);
}
}
/**
* 添加评价
*/
public function add($uId=0){
//检测订单是否有效
$orderId = (int)input('orderId');
$goodsId = (int)input('goodsId');
$goodsSpecId = (int)input('goodsSpecId');
$orderGoodsId = (int)input('orderGoodsId');
// 没有传order_goods表的id
if($orderGoodsId==0)return WSTReturn('数据出错,请联系管理员');
$userId = ((int)$uId==0)?(int)session('WST_USER.userId'):$uId;
$goodsScore = (int)input('goodsScore');
$timeScore = (int)input('timeScore');
$serviceScore = (int)input('serviceScore');
$content = input('content');
if(isset($content)){
if(!WSTCheckFilterWords($content,WSTConf("CONF.limitWords"))){
return WSTReturn("点评内容包含非法字符");
}
}
$orders = model('orders')->where(['orderId'=>$orderId,'userId'=>$userId,'dataFlag'=>1])->field('orderStatus,orderNo,isAppraise,orderScore,shopId')->find();
if(empty($orders))return WSTReturn("无效的订单");
if($orders['orderStatus']!=2)return WSTReturn("订单状态已改变,请刷新订单后再尝试!");
//检测商品是否已评价
$apCount = $this->where(['orderGoodsId'=>$orderGoodsId,'dataFlag'=>1])->count();
if($apCount>0)return WSTReturn("该商品已评价!");
Db::startTrans();
try{
//增加订单评价
$data = [];
$data['userId'] = $userId;
$data['goodsSpecId'] = $goodsSpecId;
$data['goodsId'] = $goodsId;
$data['shopId'] = $orders['shopId'];
$data['orderId'] = $orderId;
$data['goodsScore'] = $goodsScore;
$data['serviceScore'] = $serviceScore;
$data['timeScore']= $timeScore;
$data['content'] = $content;
$data['images'] = input('images');
$data['createTime'] = date('Y-m-d H:i:s');
$data['orderGoodsId'] = $orderGoodsId;
$rs = $this->validate('GoodsAppraises.add')->allowField(true)->save($data);
if($rs !==false){
$lastId = $this->id;
WSTUseImages(0, $this->id, $data['images']);
//增加商品评分
$prefix = config('database.prefix');
$updateSql = "update ".$prefix."goods_scores set
totalScore=totalScore+".(int)($goodsScore+$serviceScore+$timeScore).",
goodsScore=goodsScore+".(int)$goodsScore.",
serviceScore=serviceScore+".(int)$serviceScore.",
timeScore=timeScore+".(int)$timeScore.",
totalUsers=totalUsers+1,goodsUsers=goodsUsers+1,serviceUsers=serviceUsers+1,timeUsers=timeUsers+1
where goodsId=".$goodsId;
Db::execute($updateSql);
//增加商品评价数
Db::name('goods')->where('goodsId',$goodsId)->setInc('appraiseNum');
//增加店铺评分
$updateSql = "update ".$prefix."shop_scores set
totalScore=totalScore+".(int)($goodsScore+$serviceScore+$timeScore).",
goodsScore=goodsScore+".(int)$goodsScore.",
serviceScore=serviceScore+".(int)$serviceScore.",
timeScore=timeScore+".(int)$timeScore.",
totalUsers=totalUsers+1,goodsUsers=goodsUsers+1,serviceUsers=serviceUsers+1,timeUsers=timeUsers+1
where shopId=".$orders['shopId'];
Db::execute($updateSql);
// 查询该订单是否已经完成评价,修改orders表中的isAppraise
$ogRs = Db::name('order_goods')->alias('og')
->join('__GOODS_APPRAISES__ ga','og.orderId=ga.orderId and og.goodsId=ga.goodsId and og.goodsSpecId=ga.goodsSpecId','left')
->where('og.orderId',$orderId)->field('og.id,ga.id gid')->select();
$isFinish = true;
foreach ($ogRs as $key => $v){
if($v['id']>0 && $v['gid']==''){
$isFinish = false;
break;
}
}
//订单商品全部评价完则修改订单状态
if($isFinish){
if(WSTConf("CONF.isAppraisesScore")==1){
$appraisesScore = (int)WSTConf('CONF.appraisesScore');
if($appraisesScore>0){
//给用户增加惠宝
$score = [];
$score['userId'] = $userId;
$score['score'] = $appraisesScore;
$score['dataSrc'] = 1;
$score['dataId'] = $orderId;
$score['dataRemarks'] = "评价订单【".$orders['orderNo']."】获得惠宝".$appraisesScore."";
$score['scoreType'] = 1;
$score['createTime'] = date('Y-m-d H:i:s');
model('UserScores')->add($score,true);
}
}
//修改订单评价状态
model('orders')->where('orderId',$orderId)->update(['isAppraise'=>1,'isClosed'=>1]);
}
//发送一条商家信息
$tpl = WSTMsgTemplates('ORDER_APPRAISES');
$orderGoods = Db::name('order_goods')->where(['orderId'=>$orderId,'goodsId'=>$goodsId,'goodsSpecId'=>$goodsSpecId])->field('goodsName')->find();
$shopId = $orders['shopId'];
if( $tpl['tplContent']!='' && $tpl['status']=='1'){
$find = ['${ORDER_NO}','${GOODS}'];
$replace = [$orders['orderNo'],$orderGoods['goodsName']];
$msg = array();
$msg["shopId"] = $shopId;
$msg["tplCode"] = $tpl["tplCode"];
$msg["msgType"] = 1;
$msg["content"] = str_replace($find,$replace,$tpl['tplContent']);
$msg["msgJson"] = ['from'=>6,'dataId'=>$lastId];
model("common/MessageQueues")->add($msg);
}
//微信消息
if((int)WSTConf('CONF.wxenabled')==1){
$params = [];
$params['ORDER_NO'] = $orders['orderNo'];
$params['GOODS'] = $orderGoods['goodsName'];
$msg = array();
$tplCode = "WX_ORDER_APPRAISES";
$msg["shopId"] = $shopId;
$msg["tplCode"] = $tplCode;
$msg["msgType"] = 4;
$msg["paramJson"] = ['CODE'=>$tplCode,'URL'=>'','params'=>$params] ;
$msg["msgJson"] = "";
model("common/MessageQueues")->add($msg);
}
Db::commit();
return WSTReturn('评价成功',1);
}else{
return WSTReturn($this->getError(),-1);
}
}catch (\Exception $e) {
Db::rollback();errLog($e);
return WSTReturn('评价失败',-1);
}
}
/**
* 根据商品id取评论
*/
public function getById(){
// 处理匿名
$anonymous = (int)input('anonymous',1);
$goodsId = (int)input('goodsId');
$where = ['ga.goodsId'=>$goodsId,
'ga.dataFlag'=>1,
'ga.isShow'=>1];
// 筛选条件
$type = input('type');
$filterWhere = '';
switch ($type) {
case 'pic':// 晒图
$filterWhere['ga.images'] = ['<>',''];
break;
case 'best':// 好评
$filterWhere = "(ga.goodsScore+ga.serviceScore+ga.timeScore)>=15*0.9";
break;
case 'good':// 中评
$filterWhere = "(ga.goodsScore+ga.serviceScore+ga.timeScore)>=15*0.6 and (ga.goodsScore+ga.serviceScore+ga.timeScore)<15*0.9";
break;
case 'bad':// 差评
$filterWhere = "(ga.goodsScore+ga.serviceScore+ga.timeScore)<15*0.6";
break;
}
$rs = $this->alias('ga')
->field('DISTINCT(ga.id),ga.content,ga.images,ga.shopReply,ga.replyTime,ga.createTime,ga.goodsScore,ga.serviceScore,ga.timeScore,ga.shopId,ga.orderId,s.shopName,u.userPhoto,u.loginName,u.userTotalScore,goodsSpecNames')
->join('__USERS__ u','ga.userId=u.userId','left')
->join('__ORDER_GOODS__ og','og.orderId=ga.orderId and og.goodsId=ga.goodsId','inner')
->join('__SHOPS__ s','ga.shopId=s.shopId','inner')
->where($where)
->where($filterWhere)
->paginate()
->toArray();
foreach($rs['Rows'] as $k=>$v){
// 格式化时间
$rs['Rows'][$k]['createTime'] = date('Y-m-d',strtotime($v['createTime']));
$rs['Rows'][$k]['goodsSpecNames'] = str_replace('@@_@@','',$v['goodsSpecNames']);
// 总评分
$rs['Rows'][$k]['avgScore'] = ceil(($v['goodsScore'] + $v['serviceScore'] + $v['timeScore'])/3);
if($anonymous){
$start = floor((strlen($v['loginName'])/2))-1;
$rs['Rows'][$k]['loginName'] = substr_replace($v['loginName'],'***',$start,3);
}
//获取用户等级
$rrs = WSTUserRank($v['userTotalScore']);
$rs['Rows'][$k]['userTotalScore'] = $rrs['userrankImg'];
$rs['Rows'][$k]['rankName'] = empty($rrs['rankName'])?' ':$rrs['rankName'];
}
// 获取该商品 各评价数
$eachApprNum = $this->getGoodsEachApprNum($goodsId);
$rs['bestNum'] = $eachApprNum['best'];
$rs['goodNum'] = $eachApprNum['good'];
$rs['badNum'] = $eachApprNum['bad'];
$rs['picNum'] = $eachApprNum['pic'];
$rs['sum'] = $eachApprNum['sum'];
if($rs!==false){
return WSTReturn('',1,$rs);
}else{
return WSTReturn($this->getError(),-1);
}
}
/**
* 根据商品id获取各评价数
*/
public function getGoodsEachApprNum($goodsId){
$rs = $this->field('(goodsScore+timeScore+serviceScore) as sumScore')->where(['dataFlag'=>1,'isShow'=>1,'goodsId'=>$goodsId])->select();
$data = [];
$best=0;
$good=0;
$bad=0;
foreach($rs as $k=>$v){
$sumScore = $v['sumScore'];
// 计算好、差评数
if($sumScore >= 15*0.9){
++$best;
}else if($sumScore < 15*0.6){
++$bad;
}
}
$data['best'] = $best;
$data['bad'] = $bad;
$data['good'] = count($rs)-$best-$bad;
// 晒图评价数
$data['pic'] = $this->where(['dataFlag'=>1,'isShow'=>1,'goodsId'=>$goodsId,'images'=>['<>','']])->count();
// 总评价数
$data['sum'] = $this->where(['dataFlag'=>1,'isShow'=>1,'goodsId'=>$goodsId])->count();
return $data;
}
/**
* 商家回复评价
*/
public function shopReply(){
$id = (int)input('id');
$data['shopReply'] = input('reply');
$data['replyTime'] = date('Y-m-d');
$rs = $this->where('id',$id)->update($data);
if($rs !== false){
return WSTReturn('回复成功',1);
}else{
return WSTReturn('回复失败',-1);
}
}
}

View File

@ -0,0 +1,64 @@
<?php
namespace wstmart\common\model;
use think\Db;
/**
* ============================================================================
* 商品分类类
*/
class GoodsCats extends Base{
/**
* 获取列表
*/
public function listQuery($parentId,$isFloor = -1,$field='*'){
$dbo = $this->where(['dataFlag'=>1,'isShow'=>1,'parentId'=>$parentId]);
if($isFloor!=-1)$dbo->where('isFloor',$isFloor);
return $dbo->field($field)->order('catSort asc')->select();
}
/**
* 根据子分类获取其父级分类
*/
public function getParentIs($id,$data = array()){
$data[] = $id;
$parentId = $this->where('catId',$id)->value('parentId');
if($parentId==0){
krsort($data);
return $data;
}else{
return $this->getParentIs($parentId, $data);
}
}
public function getParentNames($id){
if($id<=0)return [];
$ids = $this->getParentIs($id);
$rs = Db::name('goodsCats')->where('catId','in',$ids)->field('catName')->order('catId desc')->select();
$names = [];
foreach($rs as $v){
$names[] = $v['catName'];
}
return $names;
}
/**
* 获取首页楼层
*/
public function getFloors(){
$cats1 = Db::name('goods_cats')->where(['dataFlag'=>1, 'isShow' => 1,'parentId'=>0,'isFloor'=>1])
->field("catName,catId,subTitle")->order('catSort asc')->limit(10)->select();
if(!empty($cats1)){
$ids = [];
foreach ($cats1 as $key =>$v){
$ids[] = $v['catId'];
}
$cats2 = [];
$rs = Db::name('goods_cats')->where(['dataFlag'=>1, 'isShow' => 1,'parentId'=>['in',$ids],'isFloor'=>1])
->field("parentId,catName,catId,subTitle")->order('catSort asc')->select();
foreach ($rs as $key => $v){
$cats2[$v['parentId']][] = $v;
}
foreach ($cats1 as $key =>$v){
$cats1[$key]['children'] = (isset($cats2[$v['catId']]))?$cats2[$v['catId']]:[];
}
}
return $cats1;
}
}

View File

@ -0,0 +1,167 @@
<?php
namespace wstmart\common\model;
/**
* ============================================================================
* 商品咨询类
*/
class GoodsConsult extends Base{
/**
* 根据商品id获取商品咨询
*/
public function listQuery(){
$goodsId = (int)input('goodsId');
$type = (int)input('type');
$consultKey = input('consultKey');
$where = [];
$where['gc.dataFlag'] = 1;
$where['gc.isShow'] = 1;
$where['gc.goodsId'] = $goodsId;
// 筛选类别
if($type>0){$where['gc.consultType'] = $type;}
// 关键字搜索
if($consultKey!=''){$where['gc.consultContent'] = ['like',"%$consultKey%"];}
$rs = $this->alias('gc')
->join('__USERS__ u','u.userId=gc.userId','left')
->field('gc.*,u.loginName')
->where($where)
->order('gc.createTime desc')
->paginate(input('pagesize/d',5))->toArray();
if(!empty($rs['Rows'])){
foreach($rs['Rows'] as $k=>&$v){
// 解义
$v['consultContent'] = htmlspecialchars_decode($v['consultContent']);
// 处理匿名
if($v['userId']>0){
// 替换中间两个字符
$start = floor((strlen($v['loginName'])/2))-1;
$v['loginName'] = substr_replace($v['loginName'],'**',$start,2);
}
}
}
return WSTReturn('', 1,$rs);
}
/**
* 根据商品id获取一条最新商品咨询
*/
public function firstQuery($id){
$where = [];
$where['gc.dataFlag'] = 1;
$where['gc.isShow'] = 1;
$where['gc.goodsId'] = $id;
$rs = $this->alias('gc')->join('__USERS__ u','u.userId=gc.userId','left')
->where($where)->field('gc.*,u.loginName')->order('gc.createTime desc')->find();
if(!empty($rs)){
// 解义
$rs['consultContent'] = htmlspecialchars_decode($rs['consultContent']);
// 处理匿名
if($rs['userId']>0){
// 替换中间两个字符
$start = floor((strlen($rs['loginName'])/2))-1;
$rs['loginName'] = substr_replace($rs['loginName'],'**',$start,2);
}
}
return $rs;
}
/**
* 添加
*/
public function add($uId=0){
$userId = ($uId==0)?(int)session('WST_USER.userId'):$uId;
$data = input('param.');
$data['userId'] = $userId;
// 检测是否含有系统禁用关键字
if(!WSTCheckFilterWords($data['consultContent'],WSTConf("CONF.limitWords"))){
return WSTReturn("咨询内容包含非法字符");
}
// 转义,防止xss攻击
$data['consultContent'] = htmlspecialchars($data['consultContent']);
$rs = $this->validate('GoodsConsult.add')->allowField(true)->save($data);
if($rs===false){
return WSTReturn($this->getError(),-1);
}
return WSTReturn('提交成功', 1);
}
/**
* 根据店铺id获取商品咨询
*/
public function pageQuery(){
// 查询条件
$type = (int)input('consultType');
$consultKey = (int)input('consultKey');
$shopId = (int)session('WST_USER.shopId');
$where = [];
$where['g.shopId'] = $shopId;
if($type>0){$where['consultType'] = $type;}
if($consultKey!=0){$where['consultContent'] = ['like',"%$consultKey%"];}
$rs = $this->alias('gc')
->join('__USERS__ u','u.userId=gc.userId','left')
->join('__GOODS__ g','g.goodsId=gc.goodsId','inner')
->field('gc.*,u.loginName,g.goodsName,g.goodsImg')
->where($where)
->order('gc.replyTime asc,gc.createTime desc')
->paginate(5)->toArray();
if(!empty($rs['Rows'])){
foreach($rs['Rows'] as $k=>&$v){
// 解义
$v['consultContent'] = htmlspecialchars_decode($v['consultContent']);
$v['reply'] = htmlspecialchars_decode($v['reply']);
// 处理匿名
if($v['userId']>0){
// 替换中间两个字符
$start = floor((strlen($v['loginName'])/2))-1;
$v['loginName'] = substr_replace($v['loginName'],'**',$start,2);
}
}
}
return WSTReturn('', 1,$rs);
}
/**
* 商家回复
*/
public function reply(){
$data = input('param.');
// 检测是否含有系统禁用关键字
if(!WSTCheckFilterWords($data['reply'],WSTConf("CONF.limitWords"))){
return WSTReturn("回复内容包含非法字符");
}
// 转义,防止xss攻击
$data['reply'] = htmlspecialchars($data['reply']);
$data['replyTime'] = date('Y-m-d H:i:s');
// 检测是否已经回复过了
$hasReply = $this->where(['id'=>(int)$data['id']])->value('reply');
if($hasReply!='')return WSTReturn('该咨询已回复,请刷新页面后重试~');
$rs = $this->validate('GoodsConsult.edit')->allowField(true)->update($data);
if($rs===false){
return WSTReturn($this->getError(),-1);
}
return WSTReturn('提交成功', 1);
}
/**
* 根据用户id获取商品咨询
*/
public function myConsultByPage(){
$userId = (int)session('WST_USER.userId');
$where = [];
$where['gc.userId'] = $userId;
$where['gc.dataFlag'] = 1;
$where['gc.isShow'] = 1;
$rs = $this->alias('gc')
->join('__GOODS__ g','g.goodsId=gc.goodsId')
->field('gc.*,g.goodsName,g.goodsImg')
->where($where)
->order('gc.createTime desc')
->paginate(input('pagesize/d'))->toArray();
if(!empty($rs['Rows'])){
foreach($rs['Rows'] as $k=>&$v){
// 解义
$v['consultContent'] = htmlspecialchars_decode($v['consultContent']);
}
}
return WSTReturn('', 1,$rs);
}
}

View File

@ -0,0 +1,11 @@
<?php
namespace wstmart\common\model;
use think\Db;
use think\Loader;
/**
* ============================================================================
* 虚拟商品卡券模型
*/
class GoodsVirtuals extends Base{
}

View File

@ -0,0 +1,91 @@
<?php
namespace wstmart\common\model;
use think\Db;
/**
* ============================================================================
* 菜单业务处理
*/
class HomeMenus extends Base{
/**
* 获取菜单树
*/
public function getMenus(){
$data = cache('WST_HOME_MENUS');
if(!$data){
$rs = $this->where(['isShow'=>1,'dataFlag'=>1])
->field('menuId,parentId,menuName,menuUrl,menuType')->order('menuSort asc,menuId asc')->select();
$m1 = ['0'=>[],'1'=>[]];
$tmp = [];
//获取第一级
foreach ($rs as $key => $v){
if($v['parentId']==0){
$m1[$v['menuType']][$v['menuId']] = ['menuId'=>$v['menuId'],'parentId'=>$v['parentId'],'menuName'=>$v['menuName'],'menuUrl'=>$v['menuUrl']];
}else{
$tmp[$v['parentId']][] = ['menuId'=>$v['menuId'],'parentId'=>$v['parentId'],'menuName'=>$v['menuName'],'menuUrl'=>$v['menuUrl']];
}
}
//获取第二级
foreach ($m1 as $key => $v){
foreach ($v as $key1 => $v1){
if(isset($tmp[$v1['menuId']]))$m1[$key][$key1]['list'] = $tmp[$v1['menuId']];
}
}
//获取第三级
foreach ($m1 as $key => $v){
foreach ($v as $key1 => $v1){
if(isset($v1['list'])){
foreach ($v1['list'] as $key2 => $v2){
if(isset($tmp[$v2['menuId']]))$m1[$key][$key1]['list'][$key2]['list'] = $tmp[$v2['menuId']];
}
}
}
}
cache('WST_HOME_MENUS',$m1,31536000);
return $m1;
}
return $data;
}
/**
* 获取菜单URL
*/
public function getMenusUrl(){
$data = cache('WST_PRO_MENUS');
if(!$data){
$list = $this->where('dataFlag',1)->order('menuType asc')->select();
$menus = [];
foreach($list as $key => $v){
$menus[strtolower($v['menuUrl'])] = $v['menuType'];
if($v['menuOtherUrl']!=''){
$str = explode(',',$v['menuOtherUrl']);
foreach ($str as $vkey => $vv){
if($vv=='')continue;
$menus[strtolower($vv)] = $v['menuType'];
}
}
}
cache('WST_PRO_MENUS',$menus,31536000);
return $menus;
}
return $data;
}
/**
* 角色可访问url
*/
public function getShopMenuUrls(){
$wst_user = session('WST_USER');
$shopUrls = [];
if(!empty($wst_user)){
$roleId = isset($wst_user["roleId"])?(int)$wst_user["roleId"]:0;
if($roleId>0){
$role = model("home/ShopRoles")->getById($roleId);
$menuUrls = $role["menuUrls"];
$shopUrls = array_merge($menuUrls,$shopUrls);
}
}
return $shopUrls;
}
}

View File

@ -0,0 +1,9 @@
<?php
namespace wstmart\common\model;
/**
* ============================================================================
* 广告类
*/
class Hooks extends Base{
}

View File

@ -0,0 +1,126 @@
<?php
namespace wstmart\common\model;
use think\Db;
/**
* ============================================================================
* 收藏类
*/
class Informs extends Base{
/**
* 跳到举报列表
*/
public function inform(){
$id = input('id');
$type = input('type');
$userId = (int)session('WST_USER.userId');
//判断用户是否拥有举报权利
$s = Db::name('users')->where("userId=$userId")->find();
if($s['isInform']==0)return WSTReturn("你已被禁止举报!", -1);
//判断记录是否存在
$isFind = false;
$c = Db::name('goods')->where(['goodsStatus'=>1,'dataFlag'=>1,'goodsId'=>$id])->find();
$isFind = ($c>0);
if(!$isFind)return WSTReturn("举报失败,无效的举报对象", -1);
$shopId = $c['shopId'];
$s = Db::name('shops')->where(['shopStatus'=>1,'dataFlag'=>1,'shopId'=>$shopId])->field('shopName,shopId')->find();
$c = array_merge($c,$s);
return WSTReturn('',1,$c);
}
/**
* 获取用户举报列表
*/
public function queryUserInformByPage(){
$userId = (int)session('WST_USER.userId');
$informStatus = (int)Input('informStatus');
$where['oc.informTargetId'] = $userId;
if($informStatus>=0){
$where['oc.informStatus'] = $informStatus;
}
$rs = $this->alias('oc')
->join('__SHOPS__ s','oc.shopId=s.shopId','left')
->join('__GOODS__ o','oc.goodId=o.goodsId and o.dataFlag=1','inner')
->order('oc.informId asc')
->where($where)
->paginate()->toArray();
foreach($rs['Rows'] as $k=>$v){
if($v['informStatus']==0){
$rs['Rows'][$k]['informStatus'] = '等待处理';
}elseif($v['informStatus']==1){
$rs['Rows'][$k]['informStatus'] = '无效举报';
}elseif($v['informStatus']==2){
$rs['Rows'][$k]['informStatus'] = '有效举报';
}elseif($v['informStatus']==3){
$rs['Rows'][$k]['informStatus'] = '恶意举报';
}
}
if($rs !== false){
return WSTReturn('',1,$rs);
}else{
return WSTReturn($this->getError(),-1);
}
}
// 判断是否已经举报过
public function alreadyInform($goodsId,$userId){
return $this->field('informId')->where("goodId=$goodsId and informTargetId=$userId")->find();
}
/**
* 保存订单举报信息
*/
public function saveInform(){
$userId = (int)session('WST_USER.userId');
$data['goodId'] = (int)input('goodsId');
//判断是否提交过举报
$rs = $this->alreadyInform($data['goodId'],$userId);
if((int)$rs['informId']>0){
return WSTReturn("该订单已进行了举报,请勿重提提交举报信息",-1);
}
Db::startTrans();
try{
$data['informTargetId'] = $userId;
$data['shopId'] = (int)input('shopsId');
$data['informStatus'] = 0;
$data['informType'] = (int)input('informType');
$data['informTime'] = date('Y-m-d H:i:s');
$data['informAnnex'] = input('informAnnex');
$data['informContent'] = input('informContent');
$rs = $this->save($data);
if($rs !==false){
Db::commit();
return WSTReturn('',1);
}else{
return WSTReturn($this->getError(),-1);
}
}catch (\Exception $e) {
Db::rollback();errLog($e);
}
return WSTReturn('举报失败',-1);
}
/**
* 获取举报详情
*/
public function getUserInformDetail($userType = 0){
$userId = (int)session('WST_USER.userId');
$id = (int)Input('id');
if($userId==0){
$where['informTargetId']=$userId;
}
//获取举报信息
$where['informId'] = $id;
$rs = Db::name('informs')->alias('oc')
->field('oc.*,o.goodsId ,o.goodsName, o.goodsImg , s.shopId , s.shopName')
->join('__SHOPS__ s','oc.shopId=s.shopId','left')
->join('__GOODS__ o','oc.goodId=o.goodsId and o.dataFlag=1','inner')
->where($where)->find();
if($rs){
if($rs['informAnnex']!='')$rs['informAnnex'] = explode(',',$rs['informAnnex']);
}
return $rs;
}
}

View File

@ -0,0 +1,63 @@
<?php
namespace wstmart\common\model;
/**
* ============================================================================
* 发票信息类
*/
class Invoices extends Base{
/**
* 列表查询
*/
public function pageQuery($limit=0,$uId=0){
$userId = $uId==0?(int)session('WST_USER.userId'):$uId;
return $this->where(['userId'=>$userId,'dataFlag'=>1])->limit($limit)->select();
}
/**
* 新增
*/
public function add($uId=0){
$userId = ($uId==0)?(int)session('WST_USER.userId'):$uId;
$data = input('param.');
$data['userId'] = $userId;
$data['createTime'] = date('Y-m-d H:i:s');
$rs = $this->validate('Invoices.add')->allowField(true)->save($data);
if($rs!==false)return WSTReturn('新增成功',1,['id'=>$this->id]);
return WSTReturn($this->getError(),-1);
}
/**
* 修改
*/
public function edit($uId=0){
$userId = ($uId==0)?(int)session('WST_USER.userId'):$uId;
$data = input('param.');
$rs = $this->validate('Invoices.edit')->allowField(true)->save($data,['id'=>$data['id'],'userId'=>$userId]);
if($rs!==false)return WSTReturn('修改成功',1);
return WSTReturn($this->getError(),-1);
}
/**
* 删除
*/
public function del(){
$id = (int)input('id');
$userId = (int)session('WST_USER.userId');
$rs = $this->where(['id'=>$id,'userId'=>$userId])->setField(['dataFlag'=>-1]);
if($rs!==false)return WSTReturn('删除成功',1);
return WSTReturn('删除失败');
}
/**
* 获取发票信息【存入订单表字段】
*/
public function getInviceInfo($id){
if($id==0)return json_encode(['invoiceHead'=>'个人']);// 所需发票为个人时
$userId = (int)session('WST_USER.userId');
$rs = $this->where(['id'=>$id,'userId'=>$userId,'dataFlag'=>1])->find();
if(empty($rs))return [];
$jsonArr = [];
$jsonArr['type'] = 0;//0:纸质发票 1:电子发票【后续扩展】
$jsonArr['invoiceHead'] = $rs['invoiceHead'];
$jsonArr['invoiceCode'] = $rs['invoiceCode'];
$jsonArr['id'] = $rs['id'];
return json_encode($jsonArr);
}
}

View File

@ -0,0 +1,187 @@
<?php
namespace wstmart\common\model;
use think\Db;
/**
* ============================================================================
* 资金流水业务处理器
*/
class LogMoneys extends Base{
/**
* 获取列表
*/
public function pageQuery($targetType,$targetId){
$type = (int)input('post.type',-1);
$where['targetType'] = (int)$targetType;
$where['targetId'] = (int)$targetId;
if(in_array($type,[0,1]))$where['moneyType'] = $type;
$page = $this->where($where)->order('id desc')->paginate()->toArray();
foreach ($page['Rows'] as $key => $v){
$page['Rows'][$key]['dataSrc'] = WSTLangMoneySrc($v['dataSrc']);
}
return $page;
}
/**
* 获取商家质保金流水
*/
public function pageDeposit($targetType,$targetId){
// $where['targetType'] = (int)$targetType;
$targetId = (int)$targetId;
$data = Db::name('shops_deposit_detail')->where(['shopId'=>$targetId])->order('payTime desc')->paginate()->toArray();
// dump($data);die;
foreach ($data['Rows'] as &$v){
$v['createTime'] = date('Y-m-d H:i:s',$v['payTime']);
$v['money'] = $v['cashDeposit'];
if($v['payType'] == 1){
$v['dataSrc'] = '店铺认证通过时缴纳';
$v['moneyType'] = 1;
}elseif($v['payType'] == 2){
$v['dataSrc'] = '店铺订单中缴纳';
$v['moneyType'] = 1;
}elseif($v['payType'] == 3){
$v['dataSrc'] = '店铺充值缴纳';
$v['moneyType'] = 1;
}elseif($v['payType'] == 4){
$v['dataSrc'] = '店铺违规扣除';
$v['moneyType'] = 0;
}
$v['remark'] = $v['dataSrc'];
}
// dump($data);die;
return $data;
}
/**
* $lm['targetType'] = 1;//0:用户 1:商家
$lm['targetId'] = $order->shopId;//用户/商家ID
$lm['dataId'] = $order->orderId;
$lm['dataSrc'] = 1;//1:交易订单 2积分支出
$lm['remark'] = '交易订单【'.$order->orderNo.'】退款剩余收入¥'.$backShopNum;
$lm['moneyType'] = 1;//1:收入 0:支出
$lm['money'] = $backShopNum;
$lm['payType'] = 'qlgpay';
$lm['moneyName'] = 1;//1产品券2优惠券3旺旺券4现金券
$lm['createTime'] = $nowTime;
*/
public function addMoneyLog($targetType,$targetId,$dataId,$dataSrc,$remark,$moneyType,$money,$payType,$moneyName=0){
$lm['targetType'] = $targetType;//0:用户 1:商家
$lm['targetId'] = $targetId;//用户/商家ID
$lm['dataId'] = $dataId;
$lm['dataSrc'] = $dataSrc;//1:交易订单 2积分支出
$lm['remark'] = $remark;
$lm['moneyType'] = $moneyType;//1:收入 0:支出
$lm['money'] = $money;
$lm['payType'] = $payType;
$lm['moneyName'] = $moneyName;
$lm['createTime'] = date('Y-m-d H:i:s');
$this->insert($lm);
if($moneyName && $moneyName <=3 ){
$moneyNames = ['1'=>'productNum','2'=>'couponsNum','3'=>'wangNum'];
if($targetType == 1){
$userId = Db::name('shops')->where('shopId',$targetId)->value('userId');
}else{
$userId = $targetId;
}
if($moneyType == 1){
return Db::name('users')->where(["userId"=>$userId])->setInc($moneyNames[$moneyName],$money);//增加
}else{
return Db::name('users')->where(["userId"=>$userId])->setDec($moneyNames[$moneyName],$money);//减少
}
}
return true;
}
public function complateRecharge($obj){
$trade_no = $obj["trade_no"];
$orderNo = $obj["out_trade_no"];
$targetId = (int)$obj["targetId"];
$targetType = (int)$obj["targetType"];
$itemId = (int)$obj["itemId"];
$payFrom = (int)$obj["payFrom"];
$payMoney = (float)$obj["total_fee"];
$log = $this->where(["tradeNo"=>$trade_no,"payType"=>$payFrom])->find();
if(!empty($log)){
return WSTReturn('已充值',-1);
}
Db::startTrans();
try {
$giveMoney = 0;
if($itemId>0){
$item = Db::name('charge_items')->where(["id"=>$itemId,"dataFlag"=>1])->field("chargeMoney,giveMoney")->find();
$chargeMoney = $item["chargeMoney"];
if($payMoney>=$chargeMoney){
$giveMoney = $item["giveMoney"];
}
}
$chargeMoney = $payMoney+$giveMoney;
if($targetType==1){
$data = array();
$data["shopMoney"] = array("exp","shopMoney+".$chargeMoney);
$data["rechargeMoney"] = array("exp","rechargeMoney+".$chargeMoney);
model('shops')->where(["shopId"=>$targetId])->update($data);
}else{
$data = array();
$data["userMoney"] = array("exp","userMoney+".$chargeMoney);
$data["rechargeMoney"] = array("exp","rechargeMoney+".$chargeMoney);
model('users')->where(["userId"=>$targetId])->update($data);
}
//创建一条充值流水记录
$lm = [];
$lm['targetType'] = $targetType;
$lm['targetId'] = $targetId;
$lm['dataId'] = $orderNo;
$lm['dataSrc'] = 4;
$lm['remark'] = '钱包充值 ¥'.$payMoney.(($giveMoney>0)?("元,送 ¥".$giveMoney.""):"");
$lm['moneyType'] = 1;
$lm['money'] = $chargeMoney;
$lm['payType'] = $payFrom;
$lm['tradeNo'] = $trade_no;
$lm['createTime'] = date('Y-m-d H:i:s');
model('LogMoneys')->save($lm);
Db::commit();
return WSTReturn('充值成功',1);
} catch (Exception $e) {
Db::rollback();errLog($e);
return WSTReturn('充值失败',-1);
}
}
/**
* 新增记录
*/
public function add($log){
$log['createTime'] = date('Y-m-d H:i:s');
//dump($log);
if($log['moneyType']==1){
if($log['targetType']==1){
if($log['payType']==='ect'){
ectLog($log['targetId'],$log['money'],12,'结算',['userECT'=>['exp','userECT+'.$log['money']]],1);
}else {
Db::name('shops')->where(["shopId" => $log['targetId']])->setInc('shopMoney', $log['money']);
}
}else{
if($log['payType']==='ect'){
//dump('gfdgfd');
ectLog($log['targetId'],$log['money'],13,'退款',['userECT'=>['exp','userECT+'.$log['money']]],1);
}else{
Db::name('users')->where(["userId"=>$log['targetId']])->setInc('userMoney',$log['money']);
}
}
}else{
if($log['targetType']==1){
Db::name('shops')->where(["shopId"=>$log['targetId']])->setDec('shopMoney',$log['money']);
}else{
if($log['payType']==='ect'){
ectLog($log['targetId'],$log['money'],11,'购物',['userECT'=>['exp','userECT-'.$log['money']]],2);
}else{
Db::name('users')->where(["userId"=>$log['targetId']])->setDec('userMoney',$log['money']);
}
}
}
}
}

View File

@ -0,0 +1,36 @@
<?php
namespace wstmart\common\model;
/**
* ============================================================================
* 支付参数日志类
*/
class LogPayParams extends Base{
/**
* 添加支付日志
*/
public function addPayLog($obj){
$this->delPayLog(["transId"=>$obj["transId"]]);
$obj['createTime'] = date('Y-m-d H:i:s');
$this->insert($obj);
}
/**
* 获取支付日志
*/
public function getPayLog($obj){
$rs = $this->where($obj)->find();
if(!empty($rs)){
return json_decode($rs["paramsVa"],true);
}
return $rs;
}
/**
* 删除支付日志
*/
public function delPayLog($obj){
return $this->where($obj)->delete();
}
}

View File

@ -0,0 +1,32 @@
<?php
namespace wstmart\common\model;
use think;
/**
* ============================================================================
* 支付日志类
*/
class LogPays extends Base{
/**
* 添加支付日志
*/
public function addPayLog($obj){
$obj['createTime'] = date('Y-m-d H:i:s');
$this->insert($obj);
}
/**
* 获取支付日志
*/
public function getPayLog($obj){
return $this->where($obj)->find();
}
/**
* 删除支付日志
*/
public function delPayLog($obj){
return $this->where($obj)->delete();
}
}

View File

@ -0,0 +1,112 @@
<?php
namespace wstmart\common\model;
/**
* ============================================================================
* 短信日志类
*/
class LogSms extends Base{
/**
* 写入并发送短讯记录
*/
public function sendSMS($smsSrc,$phoneNumber,$params,$smsFunc,$verfyCode,$userId=0){
//判断有没有开启短信功能
if((int)WSTConf('CONF.smsOpen')==0)return WSTReturn('未开启短信接口');
$userId = $userId>0?(int)session('WST_USER.userId'):$userId;
$ip = request()->ip();
//检测短信验证码验证是否正确
//if(WSTConf("CONF.smsVerfy")==1){
// if(WSTVisitModule() == 'home'){//pc版的有验证码 mark 2011204
// $smsverfy = input("post.smsVerfy");
// $rs = WSTVerifyCheck($smsverfy);
// if(!$rs){
// return WSTReturn("验证码不正确!",-2);
// }
// }
//}
//检测是否超过每日短信发送数
$date = date('Y-m-d');
$smsRs = $this->field("count(smsId) counts,max(createTime) createTime")
->where(["smsPhoneNumber"=>$phoneNumber])
->whereTime('createTime', 'between', [$date.' 00:00:00', $date.' 23:59:59'])->find();
if($smsRs['counts']>(int)WSTConf("CONF.smsLimit")){
return WSTReturn("超出每日短信限制!");
}
if($smsRs['createTime'] !='' && ((time()-strtotime($smsRs['createTime']))<120)){
return WSTReturn("请勿频繁发送短信验证");
}
//检测IP是否超过发短信次数
$ipRs = $this->field("count(smsId) counts,max(createTime) createTime")
->where(["smsIP"=>$ip])
->whereTime('createTime', 'between', [$date.' 00:00:00', $date.' 23:59:59'])->find();
if($ipRs['counts']>(int)WSTConf("CONF.smsLimit")){
return WSTReturn("发送短信验证次数过多!");
}
//if($ipRs['createTime']!='' && ((time()-strtotime($ipRs['createTime']))<120)){
// return WSTReturn("请勿频繁发送短信验证!");
//}
$data = array();
$data['smsSrc'] = $smsSrc;
$data['smsUserId'] = $userId;
$data['smsPhoneNumber'] = $phoneNumber;
$data['smsContent'] = 'N/A';
$data['smsReturnCode'] = '';
$data['smsCode'] = $verfyCode;
$data['smsIP'] = $ip;
$data['smsFunc'] = $smsFunc;
$data['createTime'] = date('Y-m-d H:i:s');
$this->data($data)->save();
$rdata = ['msg'=>'短信发送失败!','status'=>-1];
hook('sendSMS',['phoneNumber'=>$phoneNumber,"params"=>$params,'smsId'=>$this->smsId,'status'=>&$rdata]);
return $rdata;
}
/** 商家短信通知 mark hsf 20180421*/
public function sendShopSMS($smsSrc,$phoneNumber,$params,$smsFunc,$verfyCode,$userId){
//判断有没有开启短信功能
if((int)WSTConf('CONF.smsOpen')==0)return WSTReturn('未开启短信接口');
//$shopInfo = GetShopInfo($shopId,'userId');
$ip = request()->ip();
$data = array();
$data['smsSrc'] = $smsSrc;
$data['smsUserId'] = $userId;
$data['smsPhoneNumber'] = $phoneNumber;
$data['smsContent'] = 'N/A';
$data['smsReturnCode'] = '';
$data['smsCode'] = $verfyCode;
$data['smsIP'] = $ip;
$data['smsFunc'] = $smsFunc;
$data['createTime'] = date('Y-m-d H:i:s');
$this->save($data);
//dump($params);
//$rdata = ['msg'=>'短信发送失败!','status'=>-1];
hook('sendSMS',['phoneNumber'=>$phoneNumber,"params"=>$params,'smsId'=>$this->smsId,'status'=>&$rdata]);
return $rdata;
}
/**
* 写入并发送管理员短讯记录
*/
public function sendAdminSMS($smsSrc,$phoneNumber,$params,$smsFunc,$verfyCode,$userId=0){
//判断有没有开启短信功能
if((int)WSTConf('CONF.smsOpen')==0)return WSTReturn('未开启短信接口');
$userId = $userId>0?(int)session('WST_USER.userId'):$userId;
$ip = request()->ip();
$data = array();
$data['smsSrc'] = $smsSrc;
$data['smsUserId'] = $userId;
$data['smsPhoneNumber'] = $phoneNumber;
$data['smsContent'] = 'N/A';
$data['smsReturnCode'] = '';
$data['smsCode'] = $verfyCode;
$data['smsIP'] = $ip;
$data['smsFunc'] = $smsFunc;
$data['createTime'] = date('Y-m-d H:i:s');
$this->save($data);
$rdata = ['msg'=>'短信发送失败!','status'=>-1];
hook('sendSMS',['phoneNumber'=>$phoneNumber,"params"=>$params,'smsId'=>$this->smsId,'status'=>&$rdata]);
return $rdata;
}
}

View File

@ -0,0 +1,72 @@
<?php
namespace wstmart\common\model;
use think\Db;
/**
* ============================================================================
* 消息队列
*/
class MessageQueues extends Base{
/**
* 新增
*/
public function add($param){
$shopId = $param["shopId"];
$tplCode = $param["tplCode"];
$msgcat = Db::name("shop_message_cats")->where(["msgCode"=>$tplCode])->find();
$msgDataId = $msgcat["msgDataId"];
$msgType = $param['msgType'];
$dbo = Db::name("shop_roles sr")
->join("__SHOP_USERS__ su","sr.id=su.roleId");
if($msgType==4){
$dbo = $dbo->join("__USERS__ u","su.userId=u.userId")
->where("u.wxOpenId!=''");
}
// 'SELECT `su`.`userId` FROM hyh_shop_roles sr INNER JOIN `hyh_shop_users` `su` ON `sr`.`id`=`su`.`roleId` WHERE ( su.dataFlag=1 and FIND_IN_SET(1,sr.privilegeMsgs) )'
//添加店铺ID验证 mark hsf 20180403
$list = $dbo->where("su.dataFlag=1 AND FIND_IN_SET(".$msgDataId.",sr.privilegeMsgs) AND su.shopId={$shopId}")->field("su.userId")->select();
$suser = array();
if($msgType==4){
$suser = Db::name("shop_users su")->join("__USERS__ u","su.userId=u.userId")
->where(["su.shopId"=>$shopId,"su.roleId"=>0])
->where("u.wxOpenId!=''")
->field("su.userId")->find();
}else{
$suser = Db::name("shop_users")->where(["shopId"=>$shopId,"roleId"=>0])->field("userId")->find();
}
if(!empty($suser)){
$list[] = $suser;
}
if($msgType==1){
foreach ($list as $key => $user) {
WSTSendMsg($user['userId'],$param['content'],$param['msgJson'],$msgType);
}
}else{
$dataAll = [];
$paramJson = $param["paramJson"];
foreach ($list as $key => $user) {
$data = [];
$paramJson["userId"] = $user["userId"];
$data['userId'] = $user["userId"];
$data['msgType'] = $msgType;
$data['msgCode'] = $param['tplCode'];
$data['paramJson'] = json_encode($paramJson);
$data['msgJson'] = $param['msgJson'];
$data['createTime'] = date('Y-m-d H:i:s');
$data['sendStatus'] = 0;
$dataAll[] = $data;
}
Db::name("message_queues")->insertAll($dataAll);
}
}
/**
* 发送成功修改状态
*/
public function edit($id){
$data = [];
$data['sendStatus'] = 1;
$result = $this->where(["id"=>$id])->save($data);
return $result;
}
}

View File

@ -0,0 +1,83 @@
<?php
namespace wstmart\common\model;
use wstmart\home\model\Shops;
/**
* ============================================================================
* 商城消息
*/
class Messages extends Base{
/**
* 获取列表
*/
public function pageQuery(){
$userId = (int)session('WST_USER.userId');
$where = ['receiveUserId'=>(int)$userId,'dataFlag'=>1];
$page = model('Messages')->where($where)->order('msgStatus asc,id desc')->paginate(input('pagesize/d'))->toArray();
foreach ($page['Rows'] as $key => $v){
$page['Rows'][$key]['msgContent'] = WSTMSubstr(strip_tags(htmlspecialchars_decode($v['msgContent'])),0,140);
}
return $page;
}
/**
* 获取某一条消息详情
*/
public function getById(){
$userId = (int)session('WST_USER.userId');
$id = (int)input('msgId');
$data = $this->get(['id'=>$id,'receiveUserId'=>$userId]);
if(!empty($data)){
$data['msgContent'] = htmlspecialchars_decode($data['msgContent']);
if($data['msgStatus']==0)
model('Messages')->where('id',$id)->setField('msgStatus',1);
}
return $data;
}
/**
* 删除
*/
public function del(){
$userId = (int)session('WST_USER.userId');
$id = input('id/d');
$data = [];
$data['dataFlag'] = -1;
$result = $this->update($data,['id'=>$id,'receiveUserId'=>$userId]);
if(false !== $result){
return WSTReturn("删除成功", 1);
}else{
return WSTReturn($this->getError(),-1);
}
}
/**
* 批量删除
*/
public function batchDel(){
$userId = (int)session('WST_USER.userId');
$ids = input('ids/a');
$data = [];
$data['dataFlag'] = -1;
$result = $this->update($data,['id'=>['in',$ids],'receiveUserId'=>$userId]);
if(false !== $result){
return WSTReturn("删除成功", 1);
}else{
return WSTReturn($this->getError(),-1);
}
}
/**
* 标记为已读
*/
public function batchRead(){
$userId = (int)session('WST_USER.userId');
$ids = input('ids/a');
$data = [];
$data['msgStatus'] = 1;
$result = $this->update($data,['id'=>['in',$ids],'receiveUserId'=>$userId]);
if(false !== $result){
return WSTReturn("操作成功", 1);
}else{
return WSTReturn($this->getError(),-1);
}
}
}

View File

@ -0,0 +1,292 @@
<?php
namespace wstmart\common\model;
use think\Db;
/**
* ============================================================================
* 订单投诉类
*/
class OrderComplains extends Base{
/**
* 获取用户投诉列表
*/
public function queryUserComplainByPage(){
$userId = (int)session('WST_USER.userId');
$orderNo = (int)Input('orderNo');
$where['o.userId'] = $userId;
if($orderNo>0){
$where['o.orderNo'] = ['like',"%$orderNo%"];
}
$rs = $this->alias('oc')
->field('oc.complainId,o.orderId,o.orderNo,s.shopId,s.shopName,oc.complainContent,oc.complainStatus,oc.complainTime,o.orderCode')
->join('__SHOPS__ s','oc.respondTargetId=s.shopId','left')
->join('__ORDERS__ o','oc.orderId=o.orderId and o.dataFlag=1','inner')
->order('oc.complainId desc')
->where($where)
->paginate()->toArray();
foreach($rs['Rows'] as $k=>$v){
if($v['complainStatus']==0){
$rs['Rows'][$k]['complainStatus'] = '等待处理';
}elseif($v['complainStatus']==1){
$rs['Rows'][$k]['complainStatus'] = '等待被投诉方回应';
}elseif($v['complainStatus']==2 || $v['complainStatus']==3 ){
$rs['Rows'][$k]['complainStatus'] = '等待仲裁';
}elseif($v['complainStatus']==4){
$rs['Rows'][$k]['complainStatus'] = '已仲裁';
}
$rs['Rows'][$k]['orderCodeTitle'] = WSTOrderCodeTitle($v['orderCode']);
}
if($rs !== false){
return WSTReturn('',1,$rs);
}else{
return WSTReturn($this->getError(),-1);
}
}
/**
* 获取订单信息
*/
public function getOrderInfo(){
$userId = (int)session('WST_USER.userId');
$orderId = (int)Input('orderId');
//判断是否提交过投诉
$rs = $this->alreadyComplain($orderId,$userId);
$data = array('complainStatus'=>1);
if($rs['complainId']==''){
$where['o.orderId'] = $orderId;
$where['o.userId'] = $userId;
//获取订单信息
$order = db('orders')->alias('o')
->field('o.realTotalMoney,o.orderNo,o.orderId,o.createTime,o.deliverMoney,s.shopName,s.shopId')
->join('__SHOPS__ s','o.shopId=s.shopId','left')
->where($where)
->find();
if($order){
//获取相关商品
$goods = $this->getOrderGoods($orderId);
$order["goodsList"] = $goods;
}
$data['order'] = $order;
$data['complainStatus'] = 0;
}
return $data;
}
// 判断是否已经投诉过
public function alreadyComplain($orderId,$userId){
return $this->field('complainId')->where("orderId=$orderId and complainTargetId=$userId")->find();
}
//获取相关商品
public function getOrderGoods($orderId){
return db('goods')->alias('g')
->field('og.orderId, og.goodsId ,g.goodsSn, og.goodsName , og.goodsPrice shopPrice,og.goodsImg')
->join('__ORDER_GOODS__ og','g.goodsId = og.goodsId','inner')
->where("og.orderId=$orderId")
->select();
}
/**
* 保存订单投诉信息
*/
public function saveComplain(){
$userId = (int)session('WST_USER.userId');
$data['orderId'] = (int)input('orderId');
//判断订单是否该用户的
$order = db('orders')->field('orderId,shopId,orderNo')->where("userId=$userId")->find($data['orderId']);
if(!$order){
return WSTReturn('无效的订单信息',-1);
}
//判断是否提交过投诉
$rs = $this->alreadyComplain($data['orderId'],$userId);
if((int)$rs['complainId']>0){
return WSTReturn("该订单已进行了投诉,请勿重提提交投诉信息",-1);
}
Db::startTrans();
try{
$data['complainTargetId'] = $userId;
$data['respondTargetId'] = $order['shopId'];
$data['complainStatus'] = 0;
$data['complainType'] = (int)input('complainType');
$data['complainTime'] = date('Y-m-d H:i:s');
$data['complainAnnex'] = input('complainAnnex');
$data['complainContent'] = input('complainContent');
$rs = $this->validate('OrderComplains.add')->save($data);
if($rs !==false){
WSTUseImages(0, $this->complainId, $data['complainAnnex']);
//判断是否需要发送管理员短信
$tpl = WSTMsgTemplates('PHONE_ADMIN_COMPLAINT_ORDER');
if((int)WSTConf('CONF.smsOpen')==1 && (int)WSTConf('CONF.smsComplaintOrderTip')==1 && $tpl['tplContent']!='' && $tpl['status']=='1'){
$params = ['tpl'=>$tpl,'params'=>['ORDER_NO'=>$order['orderNo']]];
$staffs = Db::name('staffs')->where(['staffId'=>['in',explode(',',WSTConf('CONF.complaintOrderTipUsers'))],'staffStatus'=>1,'dataFlag'=>1])->field('staffPhone')->select();
for($i=0;$i<count($staffs);$i++){
if($staffs[$i]['staffPhone']=='')continue;
$m = new LogSms();
$rv = $m->sendAdminSMS(0,$staffs[$i]['staffPhone'],$params,'saveComplain','');
}
}
//微信消息
if((int)WSTConf('CONF.wxenabled')==1){
//判断是否需要发送给管理员消息
if((int)WSTConf('CONF.wxComplaintOrderTip')==1){
$remark = WSTDatas('ORDER_COMPLAINT',(int)input('complainType'));
$params = [];
$params['ORDER_NO'] = $order['orderNo'];
$params['REMARK'] = "".$remark['dataName']."".WSTMSubstr(input('complainContent'),0,20,'utf-8','...');
$params['LOGIN_NAME'] = session('WST_USER.loginName');
WSTWxBatchMessage(['CODE'=>'WX_ADMIN_ORDER_COMPLAINT','userType'=>3,'userId'=>explode(',',WSTConf('CONF.complaintOrderTipUsers')),'params'=>$params]);
}
}
Db::commit();
return WSTReturn('',1);
}else{
return WSTReturn($this->getError(),-1);
}
}catch (\Exception $e) {
Db::rollback();errLog($e);
}
return WSTReturn('投诉失败',-1);
}
/**
* 获取投诉详情
*/
public function getComplainDetail($userType = 0){
$userId = (int)session('WST_USER.userId');
$shopId = (int)session('WST_USER.shopId');
$id = (int)Input('id');
if($userType==0){
$where['complainTargetId']=$userId;
}else{
$where['needRespond'] = 1;
$where['respondTargetId'] = $shopId;
}
//获取订单信息
$where['complainId'] = $id;
$rs = $this->alias('oc')
->field('oc.*,o.realTotalMoney,o.orderNo,o.orderId,o.createTime,o.deliverMoney,s.shopName,s.shopId')
->join('__ORDERS__ o','oc.orderId=o.orderId','inner')
->join('__SHOPS__ s','o.shopId=s.shopId')
->where($where)->find();
if($rs){
if($rs['complainAnnex']!='')$rs['complainAnnex'] = explode(',',$rs['complainAnnex']);
if($rs['respondAnnex']!='')$rs['respondAnnex'] = explode(',',$rs['respondAnnex']);
//获取相关商品
$goods = $this->getOrderGoods($rs['orderId']);
$rs["goodsList"] = $goods;
}
return $rs;
}
/************************************* 商家 *********************************************/
/**
* 获取商家被投诉列表
*/
public function queryShopComplainByPage(){
$shopId = (int)session('WST_USER.shopId');
$orderNo = (int)Input('orderNo');
if($orderNo!=''){
$where['o.orderNo'] = ['like',"%$orderNo%"];
}
$where['oc.needRespond'] = 1;
$where['o.dataFlag'] = 1;
$where['oc.respondTargetId'] = $shopId;
$rs = $this->alias('oc')
->field('oc.complainId,o.orderId,o.orderNo,u.userName,u.loginName,oc.complainContent,oc.complainStatus,oc.complainTime,o.orderCode')
->join('__USERS__ u','oc.complainTargetId=u.userId','left')
->join('__ORDERS__ o','oc.orderId=o.orderId')
->where($where)
->order('oc.complainId desc')
->paginate()
->toArray();
foreach($rs['Rows'] as $k=>$v){
if($v['complainStatus']==0){
$rs['Rows'][$k]['complainStatus'] = '等待处理';
}elseif($v['complainStatus']==1){
$rs['Rows'][$k]['complainStatus'] = '等待被投诉方回应';
$rs['Rows'][$k]['needReply'] = 1;
}elseif($v['complainStatus']==2 || $v['complainStatus']==3 ){
$rs['Rows'][$k]['complainStatus'] = '等待仲裁';
}elseif($v['complainStatus']==4){
$rs['Rows'][$k]['complainStatus'] = '已仲裁';
}
$rs['Rows'][$k]['orderCodeTitle'] = WSTOrderCodeTitle($v['orderCode']);
}
if($rs!==false){
return WSTReturn('',1,$rs);
}else{
return WSTReturn($this->getError,-1);
}
}
/**
* 保存订单应诉信息
*/
public function saveRespond(){
$shopId = (int)session('WST_USER.shopId');
$complainId = (int)Input('complainId');
//判断是否提交过应诉和是否有效的投诉信息
$complainRs = $this->field('needRespond,complainStatus,orderId,complainType,complainContent')->where("complainId=$complainId AND respondTargetId=$shopId")->find();
if((int)$complainRs['needRespond']!=1){
return WSTReturn('无效的投诉信息',-1);
}
if((int)$complainRs['complainStatus']!=1){
return WSTReturn('该投诉订单已进行了应诉,请勿重复提交应诉信息',-1);
}
Db::startTrans();
try{
$data['complainStatus'] = 3;
$data['respondTime'] = date('Y-m-d H:i:s');
$data['respondAnnex'] = Input('respondAnnex');
$data['respondContent'] = Input('respondContent');
$rs = $this->validate('OrderComplains.respond')->where('complainId='.$complainId)->update($data);
if($rs !==false){
WSTUseImages(0, $complainId, $data['respondAnnex']);
$order = Db::name('orders')->alias('o')->join('__USERS__ u','u.userId=o.userId')
->where('orderId',$complainRs['orderId'])
->field('o.orderNo,u.loginName')->find();
//判断是否需要发送管理员短信
$tpl = WSTMsgTemplates('PHONE_ADMIN_COMPLAINT_ORDER');
if((int)WSTConf('CONF.smsOpen')==1 && (int)WSTConf('CONF.smsComplaintOrderTip')==1 && $tpl['tplContent']!='' && $tpl['status']=='1'){
$params = ['tpl'=>$tpl,'params'=>['ORDER_NO'=>$order['orderNo']]];
$staffs = Db::name('staffs')->where(['staffId'=>['in',explode(',',WSTConf('CONF.complaintOrderTipUsers'))],'staffStatus'=>1,'dataFlag'=>1])->field('staffPhone')->select();
for($i=0;$i<count($staffs);$i++){
if($staffs[$i]['staffPhone']=='')continue;
$m = new LogSms();
$rv = $m->sendAdminSMS(0,$staffs[$i]['staffPhone'],$params,'saveRespond','');
}
}
//微信消息
if((int)WSTConf('CONF.wxenabled')==1){
//判断是否需要发送给管理员消息
if((int)WSTConf('CONF.wxComplaintOrderTip')==1){
$remark = WSTDatas('ORDER_COMPLAINT',$complainRs['complainType']);
$params = [];
$params['ORDER_NO'] = $order['orderNo'];
$params['REMARK'] = "".$remark['dataName']."".WSTMSubstr($complainRs['complainContent'],0,20,'utf-8','...');
$params['LOGIN_NAME'] = $order['loginName'];
WSTWxBatchMessage(['CODE'=>'WX_ADMIN_ORDER_COMPLAINT','userType'=>3,'userId'=>explode(',',WSTConf('CONF.complaintOrderTipUsers')),'params'=>$params]);
}
}
Db::commit();
return WSTReturn('应诉成功',1);
}
}catch (\Exception $e) {
Db::rollback();errLog($e);
}
return WSTReturn('投诉失败',-1);
}
}

View File

@ -0,0 +1,297 @@
<?php
namespace wstmart\common\model;
use think\Db;
/**
* ============================================================================
* 退款业务处理类
*/
class OrderRefunds extends Base{
/**
* 用户申请退款
*/
public function refund($uId=0){
$orderId = (int)input('post.id');
$reason = (int)input('post.reason');
$content = input('post.content');
//$money = (float)input('post.money');
$userId = ($uId==0)?(int)session('WST_USER.userId'):$uId;
//if($money<=0)return WSTReturn("请填写退款金额");
$order = Db::name('orders')->alias('o')->join('__ORDER_REFUNDS__ orf','orf.orderId=o.orderId','left')->join('__SHOPS__ s','o.shopId=s.shopId','left')
->where(['o.userId'=>$userId,'o.orderId'=>$orderId,'o.orderStatus'=>['in',[-3,-1]]])
->field('o.orderId,s.userId,o.shopId,o.orderStatus,o.payFrom,o.orderNo,o.realTotalMoney,o.isPay,o.productNum,o.couponsNum,o.wangNum,o.payType,o.useScore,orf.id refundId')->find();
$productNum = (float)input('post.productNum');
$couponsNum = (float)input('post.couponsNum');
$wangNum = (float)input('post.wangNum');
if($productNum > $order['productNum']){
return WSTReturn("最多可退产品券:".$order['productNum']);
}
if($couponsNum > $order['couponsNum']){
return WSTReturn("最多可退优惠券:".$order['couponsNum']);
}
if($wangNum > $order['wangNum']){
return WSTReturn("最多可退旺旺券:".$order['wangNum']);
}
$money = $productNum + $couponsNum + $wangNum;
$reasonData = WSTDatas('REFUND_TYPE',$reason);
if(empty($reasonData))return WSTReturn("无效的退款原因");
if($reason==10000 && $content=='')return WSTReturn("请输入退款原因");
if(empty($order))return WSTReturn('操作失败,请检查订单状态是否已改变');
$allowRequest = false;
if($order['isPay']==1 || ($order['payType']==0 && $order['useScore']>0)){
$allowRequest = true;
}
if(!$allowRequest)return WSTReturn("您的退款申请已提交,请留意退款信息");
// if($money>$order['realTotalMoney'])return WSTReturn("申请退款金额不能大于实支付金额");
//查看退款申请是否已存在
$orfId = $this->where('orderId',$orderId)->value('id');
// orderStatus-3:用户拒收 -2:未付款的订单 -1用户取消 0:待发货 1:配送中 2:用户确认收货
Db::startTrans();
try{
$result = false;
//如果退款单存在就进行编辑
if($orfId>0){
$object = $this->get($orfId);
$object->refundReson = $reason;
if($reason==10000)$object->refundOtherReson = $content;
$object->backMoney = $money;
$object->backProductNum = $productNum;
$object->backCouponsNum = $couponsNum;
$object->backWangNum = $wangNum;
$object->refundStatus = 0;
$result = $object->save();
}else{
$data = [];
$data['orderId'] = $orderId;
$data['refundTo'] = 0;
$data['refundReson'] = $reason;
if($reason==10000)$data['refundOtherReson'] = $content;
$data['backMoney'] = $money;
$data['backProductNum'] = $productNum;
$data['backCouponsNum'] = $couponsNum;
$data['backWangNum'] = $wangNum;
$data['createTime'] = date('Y-m-d H:i:s');
$data['refundStatus'] = ($order['orderStatus']==-1)?1:0;
$result = $this->save($data);
}
if(false !== $result){
//拒收、取消申请退款的话要给商家发送信息
if($order['orderStatus']!=-1){
$tpl = WSTMsgTemplates('ORDER_REFUND_CONFER');
if( $tpl['tplContent']!='' && $tpl['status']=='1'){
$find = ['${ORDER_NO}'];
$replace = [$order['orderNo']];
$msg = array();
$msg["shopId"] = $order['shopId'];
$msg["tplCode"] = $tpl["tplCode"];
$msg["msgType"] = 1;
$msg["content"] = str_replace($find,$replace,$tpl['tplContent']);
$msg["msgJson"] = ['from'=>1,'dataId'=>$orderId];
model("common/MessageQueues")->add($msg);
}
//微信消息
if((int)WSTConf('CONF.wxenabled')==1){
$params = [];
$params['ORDER_NO'] = $order['orderNo'];
$params['REASON'] = $reasonData['dataName'].(($reason==10000)?" - ".$content:"");
$params['MONEY'] = $money.(($order['useScore']>0)?("【退回积分:".$order['useScore'].""):"");
$msg = array();
$tplCode = "WX_ORDER_REFUND_CONFER";
$msg["shopId"] = $order['shopId'];
$msg["tplCode"] = $tplCode;
$msg["msgType"] = 4;
$msg["paramJson"] = ['CODE'=>$tplCode,'URL'=>Url('wechat/orders/sellerorder','',true,true),'params'=>$params];
$msg["msgJson"] = "";
model("common/MessageQueues")->add($msg);
}
}else{
//判断是否需要发送管理员短信
$tpl = WSTMsgTemplates('PHONE_ADMIN_REFUND_ORDER');
if((int)WSTConf('CONF.smsOpen')==1 && (int)WSTConf('CONF.smsRefundOrderTip')==1 && $tpl['tplContent']!='' && $tpl['status']=='1'){
$params = ['tpl'=>$tpl,'params'=>['ORDER_NO'=>$order['orderNo']]];
$staffs = Db::name('staffs')->where(['staffId'=>['in',explode(',',WSTConf('CONF.refundOrderTipUsers'))],'staffStatus'=>1,'dataFlag'=>1])->field('staffPhone')->select();
for($i=0;$i<count($staffs);$i++){
if($staffs[$i]['staffPhone']=='')continue;
$m = new LogSms();
$rv = $m->sendAdminSMS(0,$staffs[$i]['staffPhone'],$params,'refund','');
}
}
//微信消息
if((int)WSTConf('CONF.wxenabled')==1){
//判断是否需要发送给管理员消息
if((int)WSTConf('CONF.wxRefundOrderTip')==1){
$params = [];
$params['ORDER_NO'] = $order['orderNo'];
$params['REASON'] = $reasonData['dataName'].(($reason==10000)?" - ".$content:"");
$params['MONEY'] = $money.(($order['useScore']>0)?("【退回积分:".$order['useScore'].""):"");
WSTWxBatchMessage(['CODE'=>'WX_ADMIN_ORDER_REFUND','userType'=>3,'userId'=>explode(',',WSTConf('CONF.refundOrderTipUsers')),'params'=>$params]);
}
}
}
Db::commit();
return WSTReturn('您的退款申请已提交,请留意退款信息',1);
}
}catch (\Exception $e) {
Db::rollback();errLog($e);
}
return WSTReturn('操作失败',-1);
}
/**
* 获取订单价格以及申请退款价格
*/
public function getRefundMoneyByOrder($orderId = 0){
$result= Db::name('orders')->alias('o')->join('__ORDER_REFUNDS__ orf','orf.orderId=o.orderId')->where('orf.id',$orderId)
->field('o.orderId,o.payFrom,orderNo,goodsMoney,deliverMoney,useScore,scoreMoney,totalMoney,realTotalMoney,orf.backMoney')->find();
if($result['payFrom']=="ect"){
$ectPrice=db('orders_ect')->where('orderId',$result['orderId'])->value('ectPrice');
$result['ectNum']=$result['backMoney']/$ectPrice;
}
$result['ectNum']=isset($result['ectNum'])?$result['ectNum']:"";
return $result;
}
/**
* 商家处理是否同意退款
*/
public function shopRefund(){
$id = (int)input('id');
$refundStatus = (int)input('refundStatus');
$content = input('content');
if($id==0)return WSTReturn('无效的操作');
if(!in_array($refundStatus,[1,-1]))return WSTReturn('无效的操作');
if($refundStatus==-1 && $content=='')return WSTReturn('请输入拒绝原因');
Db::startTrans();
try{
//返还商品库存
// $goods=db('order_goods')->alias('og')
// ->join('order_refunds or','or.orderId=og.orderId','left')
// ->join('orders o','o.orderId=og.orderId','left')
// ->join('goods g','g.goodsId=og.goodsId','left')
// ->where('or.id',$id)->field('g.goodsId,g.goodsStock,g.saleNum,og.goodsNum,g.isSpec,o.orderCode')
// ->select();
// //dump($goods);die;
// //返还商品库存
// foreach ($goods as $key => $v){
// //处理虚拟产品
// if($v['orderCode']=='order'){
// //修改库存
// // dump($v['isSpec']);die;
// if($v['isSpec']>0){
// Db::name('goods_specs')->where('id',$v['goodsSpecId'])->setInc('specStock',$v['goodsNum']);
// Db::name('goods_specs')->where('id',$v['goodsSpecId'])->setDec('saleNum',$v['goodsNum']);
// }
// Db::name('goods')->where('goodsId',$v['goodsId'])->setInc('goodsStock',$v['goodsNum']);
// Db::name('goods')->where('goodsId',$v['goodsId'])->setDec('saleNum',$v['goodsNum']);
// }
//
// }
$object = $this->get($id);
$order = Db::name('orders')->where('orderId',$object->orderId)->field('userId,shopId,orderNo,orderId,useScore')->find();
if(!$order || $order['shopId'] != input('post.shopId')){
return WSTReturn('未找到此订单');
}
$object->refundStatus = $refundStatus;
if($object->refundStatus==-1)$object->shopRejectReason = $content;
$result = $object->save();
if(false !== $result){
//如果是拒收话要给用户发信息
if($refundStatus==-1){
$tpl = WSTMsgTemplates('ORDER_REFUND_FAIL');
if( $tpl['tplContent']!='' && $tpl['status']=='1'){
$find = ['${ORDER_NO}','${REASON}'];
$replace = [$order['orderNo'],$content];
WSTSendMsg($order['userId'],str_replace($find,$replace,$tpl['tplContent']),['from'=>1,'dataId'=>$order['orderId']]);
}
//微信消息
if((int)WSTConf('CONF.wxenabled')==1){
$reasonData = WSTDatas('REFUND_TYPE',$object->refundReson);
$params = [];
$params['ORDER_NO'] = $order['orderNo'];
$params['REASON'] = $reasonData['dataName'].(($object->refundReson==10000)?" - ".$object->refundOtherReson:"");
$params['SHOP_REASON'] = $object->shopRejectReason;
$params['MONEY'] = $object->backMoney.(($order['useScore']>0)?("【退回积分:".$order['useScore'].""):"");
WSTWxMessage(['CODE'=>'WX_ORDER_REFUND_FAIL','userId'=>$order['userId'],'URL'=>Url('wechat/orders/index','',true,true),'params'=>$params]);
}
}else{
//判断是否需要发送管理员短信
$tpl = WSTMsgTemplates('PHONE_ADMIN_REFUND_ORDER');
if((int)WSTConf('CONF.smsOpen')==1 && (int)WSTConf('CONF.smsRefundOrderTip')==1 && $tpl['tplContent']!='' && $tpl['status']=='1'){
$params = ['tpl'=>$tpl,'params'=>['ORDER_NO'=>$order['orderNo']]];
$staffs = Db::name('staffs')->where(['staffId'=>['in',explode(',',WSTConf('CONF.refundOrderTipUsers'))],'staffStatus'=>1,'dataFlag'=>1])->field('staffPhone')->select();
for($i=0;$i<count($staffs);$i++){
if($staffs[$i]['staffPhone']=='')continue;
$m = new LogSms();
$rv = $m->sendAdminSMS(0,$staffs[$i]['staffPhone'],$params,'shoprefund','');
}
}
//微信消息
if((int)WSTConf('CONF.wxenabled')==1){
//判断是否需要发送给管理员消息
if((int)WSTConf('CONF.wxRefundOrderTip')==1){
$reasonData = WSTDatas('REFUND_TYPE',$object->refundReson);
$params = [];
$params['ORDER_NO'] = $order['orderNo'];
$params['REASON'] = $reasonData['dataName'].(($object->refundReson==10000)?" - ".$object->refundOtherReson:"");
$params['MONEY'] = $object->backMoney.(($order['useScore']>0)?("【退回积分:".$order['useScore'].""):"");
WSTWxBatchMessage(['CODE'=>'WX_ADMIN_ORDER_REFUND','userType'=>3,'userId'=>explode(',',WSTConf('CONF.refundOrderTipUsers')),'params'=>$params]);
}
}
}
Db::commit();
return WSTReturn('操作成功',1);
}
}catch (\Exception $e) {
Db::rollback();errLog($e);
}
return WSTReturn('操作失败',-1);
}
/**
* 临时申请退款接口
*/
public function byRefund($orderNo){
//$orderNo = input('orderNo');
$order = Db::name('orders o')->where(['o.orderNo'=>$orderNo,'o.orderStatus'=>['in',[0,1]]])
->field('o.orderId,o.shopId,o.orderStatus,o.orderNo,o.realTotalMoney,o.isPay,o.payType,o.useScore')->find();
if(empty($order))return WSTReturn('操作失败,请检查订单状态是否已改变',-1);
$allowRequest = false;
if($order['isPay']==1 || ($order['payType']==0 && $order['useScore']>0)){
$allowRequest = true;
}
$isfind = false;
if($this->where(['orderId'=>$order['orderId']])->find()){
$isfind = true;
}
if(!$allowRequest || $isfind)return WSTReturn("退款申请已提交,请不要重复提交",-1);
$money=$order['realTotalMoney'];
Db::startTrans();
try{
if($order['orderStatus']==0){
db('orders')->where('orderNo',$orderNo)->update(['orderStatus'=>-1]);
}
if($order['orderStatus']==1){
db('orders')->where('orderNo',$orderNo)->update(['orderStatus'=>-3]);
}
$result = false;
//退款单进行编辑
$data = [];
$data['orderId'] = $order['orderId'];
$data['refundTo'] = 0;
$data['refundReson'] = 5;
$data['backMoney'] = $money;
$data['createTime'] = date('Y-m-d H:i:s');
$data['refundStatus'] = 1;
$result = $this->insert($data);
if($result){
Db::commit();
return WSTReturn('您的退款申请已提交,请留意退款信息',1);
}
}catch (\Exception $e) {
Db::rollback();errLog($e);
}
return WSTReturn('操作失败',-1);
}
}

3087
hyhproject/common/model/Orders.php Executable file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,62 @@
<?php
namespace wstmart\common\model;
use think\Db;
/**
* ============================================================================
* 支付管理业务处理
*/
class Payments extends Base{
/**
* 获取支付方式种类
*
* $isApp 如果是接口请求,则不返回payConfig数据
*/
public function getByGroup($payfor = '', $onlineType = -1, $isApp = false){
$payments = ['0'=>[],'1'=>[]];
$where = ['enabled'=>1];
if(in_array($onlineType,[1,0]))$where['isOnline'] = $onlineType;
$rs = $this->where($where)->where("find_in_set ($payfor,payFor)")->order('payOrder asc')->select();
foreach ($rs as $key =>$v){
if($v['payConfig']!='')$v['payConfig'] = json_decode($v['payConfig'], true);
if($isApp)unset($v['payConfig']);
$payments[$v['isOnline']][] = $v;
}
return $payments;
}
/**
* 获取支付信息
*/
public function getPayment($payCode){
$payment = $this->where("enabled=1 AND payCode='$payCode' AND isOnline=1")->find();
$payConfig = json_decode($payment["payConfig"]) ;
foreach ($payConfig as $key => $value) {
$payment[$key] = $value;
}
return $payment;
}
public function getPaymentDiscount($payCode){
return $this->where('payCode',$payCode)->value('payRatio');
}
/**
* 获取在线支付方式
*/
public function getOnlinePayments(){
//获取支付信息
return $this->where(['isOnline'=>1,'enabled'=>1])->order('payOrder asc')->select();
}
/**
* 判断某种支付是否开启
*/
public function isEnablePayment($payCode){
//获取支付信息
return $this->where(['isOnline'=>1,'enabled'=>1,'payCode'=>$payCode])->Count();
}
public function recharePayments($payfor = ''){
$rs = $this->where(['isOnline'=>1,'enabled'=>1])->where("find_in_set ($payfor,payFor)")->where("payCode!='wallets'")
->field('id,payCode,payName,isOnline')->order('payOrder asc')->select();
return $rs;
}
}

View File

@ -0,0 +1,72 @@
<?php
namespace wstmart\common\model;
use think\Db;
/**
* ============================================================================
* 地区类
*/
class Position extends Base{
private $level = 1;
private $tagName = 'province';
private $pName = '';
public function __construct(){
parent::__construct();
$this->initData((int)input('post.level/d'));
}
function initData($level){
switch ($level) {
case 1:
$this->level = 1;
$this->tagName = 'province';
$this->pName = '';
break;
case 2:
$this->level = 2;
$this->tagName = 'city';
$this->pName = 'province';
break;
case 3:
$this->level = 3;
$this->tagName = 'county';
$this->pName = 'city';
break;
case 4:
$this->level = 4;
$this->tagName = 'town';
$this->pName = 'county';
break;
case 5:
$this->level = 5;
$this->tagName = 'village';
$this->pName = 'town';
break;
default:
$this->level = 1;
$this->tagName = 'province';
$this->pName = '';
break;
}
}
/**
* 获取区域名称
* @return [type] [description]
*/
public function getAreaName($areaId=0){
$where[$this->tagName.'_id']=empty($areaId) ? (int)input('post.id/d') : $areaId;
$field=$this->tagName.'_id areaId'.','.$this->tagName.'_name areaName';;
return Db::name('position_'.$this->tagName)->where($where)->cache(true)->field($field)->find();
}
/**
* 获取地区列表
*/
public function listQuery(){
$where=[];
if($this->level > 1){
$where[$this->pName.'_id']=(int)input('post.pid/d');
}
$field=$this->tagName.'_id areaId'.','.$this->tagName.'_name areaName';
return Db::name('position_'.$this->tagName)->where($where)->cache(true)->field($field)->select();
}
}

View File

@ -0,0 +1,321 @@
<?php
namespace wstmart\common\model;
use think\Db;
/**
* ============================================================================
* 结算类
*/
class Settlements extends Base
{
/**
* 即时计算
*/
public function speedySettlement($orderId)
{
$order = model('common/orders')->get($orderId);
$shops = model('common/shops')->get($order->shopId);
if (empty($shops)) return WSTReturn('结算失败,商家不存在');
//获取优惠款 价格*优惠率
$m = Model('common/Table');
$m->setTable('order_goods');
$orderGoodsList = $m->getList(['orderId'=>$orderId],'goodsPrice,goodsNum,freight,discountRate');
$discountMoney = 0;//优惠款
foreach ($orderGoodsList as &$v) {
//$discountMoney += ($v['goodsPrice']*$v['goodsNum'] + $v['freight']) * ($v['discountRate']*0.01);//优惠款
$discountMoney += ($v['goodsPrice']*$v['goodsNum']) * ($v['discountRate']*0.01);//优惠款
}
$discountMoney = round($discountMoney,2);
//加入快代付值
$fastScale = dataConf('fastPayInSaleScale');
$fastNum = round($discountMoney * ($fastScale*0.01),5);
Model('SysSummary')->addToPayFast($orderId,$fastNum,$fastScale);
//获取产品额
$totalMoney = $order->realTotalMoney;//产品额
if(2 != $order->goodsType){//助微吧商品不给购户券值
// 购户的所得分配
// 1购户获得预获产品券为产品额的100% buyerPreProductInProductScale
// 2购户获得预获优惠券为优惠款的50% buyerPreCoupousInSaleScale
// 3获得预获产品券为被扣手续费的100% buyerPreProductInHandlingFeeScale
// 4获得预获产品券为被扣税费的100% buyerPreProductInTaxFeeScale
// 5获得预获产品券为被扣手续费的100% buyerPreProductInProductHandlingFeeScale
// 6获得预获产品券为被扣税费的100% buyerPreProductInProductTaxFeeScale
$buyerPreProductNum = round(($totalMoney + $order->deliverMoney)* (dataConf('buyerPreProductInProductScale')*0.01),2);//1
$buyerPreCoupousNum = round($discountMoney * (dataConf('buyerPreCoupousInSaleScale')*0.01),2);//2
$buyerPreProductNum += round($order->productHandlingFee * (dataConf('buyerPreProductInHandlingFeeScale')*0.01),2);//3
$buyerPreProductNum += round($order->productTaxFee * (dataConf('buyerPreProductInTaxFeeScale')*0.01),2);//4
$buyerPreProductNum += round($order->couponsHandlingFee * (dataConf('buyerPreProductInProductHandlingFeeScale')*0.01),2);//5
$buyerPreProductNum += round($order->couponsTaxFee * (dataConf('buyerPreProductInProductTaxFeeScale')*0.01),2);//6
if($buyerPreProductNum >= 0.01 || $buyerPreCoupousNum>=0.01){
Model('common/UserVouchers')->insertVouchersNotice($order->userId,$orderId,$buyerPreProductNum,$buyerPreCoupousNum,'交易订单【'.$order->orderNo.'】购户购物所得');
}
}
// 商户的所得分配
// 1商户获得预获产品券占优惠款比例 100% sellerPreProductInProductScale
// 2商户获得预获优惠券占优惠款比例 100% sellerPreCoupousInSaleScale
// 3优惠款-产品-优惠券-旺旺券大于0是商户需付公司的钱,小于0是公司需付给商户的钱,即旺旺券
// $discountMoney-$order->productNum-$order->couponsNum-$order->wangNum-$order->moneyNum
$sellerPreProductNum = round($discountMoney * (dataConf('sellerPreProductInProductScale')*0.01),2);//1
$sellerPreCoupousNum = round($discountMoney * (dataConf('sellerPreCoupousInSaleScale')*0.01),2);//2
if($sellerPreProductNum >= 0.01 || $sellerPreCoupousNum>=0.01){
Model('common/UserVouchers')->insertVouchersNotice($shops['userId'],$orderId,$sellerPreProductNum,$sellerPreCoupousNum,'交易订单【'.$order->orderNo.'】商户售物所得');
}
//旺旺券结算
$payVouchersNum = ($order->productNum - $order->productHandlingFee - $order->productTaxFee) + ($order->couponsNum - $order->couponsHandlingFee - $order->couponsTaxFee) + $order->wangNum;////3个券的付款总额+$order->moneyNum;
$giveWangNum = round($payVouchersNum - $discountMoney,2);
$m->setTable('orders');
if($giveWangNum > 0){
$m->updateInfo(['orderId'=>$orderId],['certificateStatus'=>1,'payable'=>$giveWangNum]);
Model('common/LogMoneys')->addMoneyLog(1,$order->shopId,$order->orderId,1,'交易订单【'.$order->orderNo.'】结算收入¥'.$giveWangNum,1,$giveWangNum,'qlgpay',3);
}else{
$m->updateInfo(['orderId'=>$orderId],['certificateStatus'=>0,'payable'=>$giveWangNum]);
}
//商超,商厦,商都所得
// 1获得预获优惠券时限上日有消费≥100元为产品额的5%。
// shopPreCoupousYdGTMoney shopPreCoupousYesInProductScale
// 2获得预获优惠券时限上日有消费100元为产品额的2.5% shopPreCoupousNoInProductScale
$m->setTable('shops');
$positionInfo = $m->getInfo(['shopId'=>$order->shopId,'dataFlag'=>1],'villageId,townId,countyId');
if($positionInfo){
$m->setTable('user_update');
//村代理
$agentAreaId = 'villageId';
$agentUserId = $m->getField(['applyLevel'=>2,$agentAreaId=>$positionInfo[$agentAreaId],'status'=>1],'userId');
if($agentUserId && $vInfo = getUserInfo(['userId'=>$agentUserId,'dataFlag'=>1,'userStatus'=>1],'userId')){
$yesterdayBuyMoney = Model('common/Orders')->getYesterdayBuyMoney($agentUserId,'realTotalMoney');
$agentProductMoney = 0;
if($yesterdayBuyMoney >= dataConf('shopPreCoupousYdGTMoney')){//大于设定值
$agentProductMoney = round($totalMoney * (dataConf('shopPreCoupousYesInProductScale')*0.01),2);//1
}else{
$agentProductMoney = round($totalMoney * (dataConf('shopPreCoupousNoInProductScale')*0.01),2);//2
}
if($agentProductMoney >= 0.01){
Model('common/UserVouchers')->insertVouchersNotice($agentUserId,$orderId,0,$agentProductMoney,'交易订单【'.$order->orderNo.'】商超所得');
}
}
//乡镇代理
$m->setTable('user_update');
$agentAreaId = 'townId';
$agentUserId = $m->getField(['applyLevel'=>3,$agentAreaId=>$positionInfo[$agentAreaId],'status'=>1],'userId');
if($agentUserId && $vInfo = getUserInfo(['userId'=>$agentUserId,'dataFlag'=>1,'userStatus'=>1],'userId')){
$yesterdayBuyMoney = Model('common/Orders')->getYesterdayBuyMoney($agentUserId,'realTotalMoney');
$agentProductMoney = 0;
if($yesterdayBuyMoney >= dataConf('shopPreCoupousYdGTMoney')){//大于设定值
$agentProductMoney = round($totalMoney * (dataConf('shopPreCoupousYesInProductScale')*0.01),2);//1
}else{
$agentProductMoney = round($totalMoney * (dataConf('shopPreCoupousNoInProductScale')*0.01),2);//2
}
if($agentProductMoney >= 0.01){
Model('common/UserVouchers')->insertVouchersNotice($agentUserId,$orderId,0,$agentProductMoney,'交易订单【'.$order->orderNo.'】商厦所得');
}
}
//区县代理
$m->setTable('user_update');
$agentAreaId = 'countyId';
$agentUserId = $m->getField(['applyLevel'=>4,$agentAreaId=>$positionInfo[$agentAreaId],'status'=>1],'userId');
if($agentUserId && $vInfo = getUserInfo(['userId'=>$agentUserId,'dataFlag'=>1,'userStatus'=>1],'userId')){
$yesterdayBuyMoney = Model('common/Orders')->getYesterdayBuyMoney($agentUserId,'realTotalMoney');
$agentProductMoney = 0;
if($yesterdayBuyMoney >= dataConf('shopPreCoupousYdGTMoney')){//大于设定值
$agentProductMoney = round($totalMoney * (dataConf('shopPreCoupousYesInProductScale')*0.01),2);//1
}else{
$agentProductMoney = round($totalMoney * (dataConf('shopPreCoupousNoInProductScale')*0.01),2);//2
}
if($agentProductMoney >= 0.01){
Model('common/UserVouchers')->insertVouchersNotice($agentUserId,$orderId,0,$agentProductMoney,'交易订单【'.$order->orderNo.'】商都所得');
}
}
}
//推荐人所得
// 1推荐人获得预获产品券时限上日有消费≥10元为优惠款的50%。
// refPreProductYdGTMoney refPreProductYesInSaleScale
// 2推荐人获得预获产品券时限上日有消费10元为优惠款的25% refPreProductNoInSaleScale
$m->setTable('user_trees');
$pid = $m->getField(['uid'=>$shops['userId']],'pid');
if($pid && $pInfo = getUserInfo(['userId'=>$pid,'dataFlag'=>1,'userStatus'=>1],'userId')){//有推荐人并且推荐人状态正常
$yesterdayBuyMoney = Model('common/Orders')->getYesterdayBuyMoney($pid,'realTotalMoney');
$refProductMoney = 0;
if($yesterdayBuyMoney >= dataConf('refPreProductYdGTMoney')){//大于设定值
$refProductMoney = round($discountMoney * (dataConf('refPreProductYesInSaleScale')*0.01),2);//1
}else{
$refProductMoney = round($discountMoney * (dataConf('refPreProductNoInSaleScale')*0.01),2);//2
}
if($refProductMoney > 0){
Model('common/UserVouchers')->insertVouchersNotice($pid,$orderId,$refProductMoney,0,'交易订单【'.$order->orderNo.'】推荐所得');
}
}
return true;
}
/**
* 即时计算
*/
// public function speedySettlement($orderId)
// {
// $order = model('common/orders')->get($orderId);
// $shops = model('common/shops')->get($order->shopId);
// if (empty($shops)) return WSTReturn('结算失败,商家不存在');
// //$backMoney = 0;
// $sub_deposit = 0;
// $deposit_msg = '';
// $payFrom = $order->payFrom;
// if ($order->payType == 1) {
// //在线支付的返还金额=实付金额+惠宝抵扣金额-佣金
// // $backMoney = $order->realTotalMoney+$order->scoreMoney-$order->commissionFee;
// //修改为不加入惠宝的结算金额 mark hsf 20180308
// if ($payFrom == 'ect') {
// $ectInfo = db('orders_ect')->where('orderId', $order['orderId'])->field('orderEctNum,ectPrice')->find();
// $commissionFee = $order->commissionFee;//佣金
// $backMoney = round($ectInfo['orderEctNum'] - ($order->commissionFee / $ectInfo['ectPrice']), 2);
// } else {
// //订单业务员提成
// $comDeduct = Db::name('shop_commission')->where('shopId',$order->shopId)->field('comDeduct,userId,userName,deductMoney')->find();
// if($comDeduct && $comDeduct['comDeduct']>0){
// $deductMoney = $order->realTotalMoney * $comDeduct['comDeduct'] * 0.01;
// $deduct['userId'] = $comDeduct['userId'];
// $deduct['orderId'] = $order['orderId'];
// $deduct['deductMoney'] = $deductMoney;
// $deduct['createTime'] = time();
// // dump($deduct);die;
// Db::name('shop_commission_deduct')->insert($deduct);
// $manDeduct = $comDeduct['deductMoney'] + $deductMoney;
// Db::name('shop_commission')->where('userId',$comDeduct['userId'])->update(['deductMoney'=>$manDeduct]);
// }
// $commissionFee = $order->commissionFee;//佣金
// $backMoney = $order->realTotalMoney - $commissionFee;//返还金额
// //商家质保金未交齐则扣除在线支付返回金额的30%
// $deposit_info = Db::name('shops_deposit')->where('shopId', $order->shopId)->field('isFinish,payDeposit,cashDeposit')->find();
// if(!$deposit_info){
// $deposit_info['shopId']=$order->shopId;
// $deposit_info['isFinish']=2;
// $deposit_info['cashDeposit']=0;
// $deposit_info['payDeposit']=1000;//老商户1000质保金
// $deposit_info['passTime']=time();
// Db::name('shops_deposit')->insert($deposit_info);
// }
// if (2 == $deposit_info['isFinish']) {//未交齐质保金
// $no_money = $deposit_info['payDeposit'] - $deposit_info['cashDeposit'];
// if ($no_money > 0) {
// $sub_money = $backMoney * 0.3;//质保金不足,订单扣除30%质保金
// $data_deposit = [];
// if ($no_money > $sub_money) {//未完成
// $sub_deposit = $sub_money;
// } else {
// $sub_deposit = $no_money;
// $data_deposit['isFinish'] = 1;
// $data_deposit['completeTime'] = time();
// //记录店铺订单中扣除的质保金
// }
// //添加到质保金里
// $data_deposit['cashDeposit'] = $deposit_info['cashDeposit'] + $sub_deposit;
// Db::name('shops_deposit')->where('shopId', $order->shopId)->update($data_deposit);
// //添加到质保金记录
// $detail = [];
// $detail['shopId'] = $order->shopId;
// $detail['orderId'] = $order->orderId;
// $detail['cashDeposit'] = $sub_deposit;
// $detail['payType'] = 2;
// $detail['payTime'] = time();
// Db::name('shops_deposit_detail')->insert($detail);
// $backMoney -= $sub_deposit;
// $deposit_msg = ',质保金抵扣¥:'.$sub_deposit;
// }
// }
// }
// if ($backMoney < 0) {
// return true;
// }
// } else {
// //货到付款的返还金额=惠宝抵扣金额-佣金
// //$backMoney = $order->scoreMoney-$order->commissionFee;
// //修改为不加入惠宝的结算金额 mark hsf 20180308
// $backMoney = 0;
// }
// $data = [];
// $data['settlementType'] = 1;
// $data['shopId'] = $order->shopId;
// //修改为不加入惠宝的结算金额 mark hsf 20180308
// $data['settlementMoney'] = ($order->payType == 1) ? $order->realTotalMoney : 0;//$order->scoreMoney+(($order->payType==1)?$order->realTotalMoney:0);
// $data['commissionFee'] = $commissionFee;
// $data['backMoney'] = $backMoney;
// $data['settlementStatus'] = 1;
// $data['settlementTime'] = date('Y-m-d H:i:s');
// $data['createTime'] = date('Y-m-d H:i:s');
// $data['settlementNo'] = '';
// $settlementId = $this->insertGetId($data);
// if ($settlementId > 0) {
// $settlementNo = $settlementId . uniqid() . mt_rand(10, 99);//(fmod($this->settlementId,7));
// $this->where(['settlementId' => $settlementId])->update(['settlementNo' => $settlementNo]);
// $order->settlementId = $settlementId;
// $order->save();
// // dump($backMoney);
// // dump($payFrom);exit;
// if ($payFrom == "ect") {
// ectLog($shops['userId'], $backMoney, 12, '结算', ['userECT' => ['exp', 'userECT+' . $backMoney]], 1);
// } else {
// //修改商家钱包
// $shops->shopMoney = $shops['shopMoney'] + $backMoney;
// $shops->save();
// }
// //返还金额
// $lmarr = [];
// //如果是货到付款并且有惠宝支付的话,还要补上一个惠宝支付的资金流水记录,不然流水上金额不对。
// // if($order->payType==0 && $order->scoreMoney >0){
// // $lm = [];
// // $lm['targetType'] = 1;
// // $lm['targetId'] = $order->shopId;
// // $lm['dataId'] = $this->settlementId;
// // $lm['dataSrc'] = 2;
// // $lm['remark'] = '结算订单申请【'.$this->settlementNo.'】惠宝支付金额¥'.$order->scoreMoney;
// // $lm['moneyType'] = 1;
// // $lm['money'] =$order->scoreMoney;
// // $lm['payType'] = 0;
// // $lm['createTime'] = date('Y-m-d H:i:s');
// // $lmarr[] = $lm;
// // }
// //收取佣金
// if ($commissionFee > 0) {
// $lm = [];
// $lm['targetType'] = 1;
// $lm['targetId'] = $order->shopId;
// $lm['dataId'] = $settlementId;
// $lm['dataSrc'] = 2;
// $lm['remark'] = '结算订单申请【' . $settlementNo . '】收取订单佣金¥' . $commissionFee;
// $lm['moneyType'] = 0;
// $lm['money'] = $commissionFee;
// $lm['payType'] = 0;
// $lm['createTime'] = date('Y-m-d H:i:s');
// $lmarr[] = $lm;
// }
// if ($backMoney > 0) {
// $lm = [];
// $lm['targetType'] = 1;
// $lm['targetId'] = $order->shopId;
// $lm['dataId'] = $settlementId;
// $lm['dataSrc'] = 2;
// $lm['remark'] = '结算订单申请【' . $settlementNo . '】返还金额¥' . $backMoney.$deposit_msg;
// $lm['moneyType'] = 1;
// $lm['money'] = $backMoney;
// $lm['payType'] = 0;
// $lm['createTime'] = date('Y-m-d H:i:s');
// $lmarr[] = $lm;
// }
// model('common/LogMoneys')->saveAll($lmarr);
// return true;
// }
// return false;
// }
}

View File

@ -0,0 +1,275 @@
<?php
namespace wstmart\common\model;
use think\Db;
/**
* ============================================================================
* 门店分类
*/
class ShopCats extends Base{
/**
* 批量保存商品分类
*/
public function batchSaveCats(){
$shopId = (int)session('WST_USER.shopId');
$createTime = date("Y-m-d H:i:s");
//先保存了已经有父级的分类
$otherNo = input('post.otherNo/d');
for($i=0;$i<$otherNo;$i++){
$data = array();
$data['catName'] = input('post.catName_o_'.$i);
if($data['catName']=='')continue;
$data['shopId'] = $shopId;
$data['parentId'] = input('post.catId_o_'.$i."/d");
$data['catSort'] = input('post.catSort_o_'.$i."/d");
$data['isShow'] = input('post.catShow_o_'.$i."/d");
$data['createTime'] = $createTime;
$rs = $this->where(["dataFlag"=>1,"shopId"=>$shopId,"catId"=>$data['parentId']])->find();
if(empty($rs))continue;
$this->isUpdate(false)->allowField(["catName","shopId","parentId","catSort","isShow","createTime"])->save($data);
}
//保存没有父级分类的
$fristNo = input('post.fristNo/d');
for($i=0;$i<$fristNo;$i++){
$data = array();
$data['catName'] = input('post.catName_'.$i);
if($data['catName']=='')continue;
$data['parentId'] = 0;
$data['shopId'] = $shopId;
$data['catSort'] = input('post.catSort_'.$i."/d");
$data['isShow'] = input('post.catShow_'.$i."/d");
$data['createTime'] = $createTime;
$parentRs = $this->isUpdate(false)->allowField(["catName","shopId","parentId","catSort","isShow","createTime"])->save($data);
if(false !== $parentRs){
$parentId = $this->catId;
unset($this->catId);
//新增子类
$catSecondNo = (int)input('post.catSecondNo_'.$i."/d");
for($j=0;$j<$catSecondNo;$j++){
$data = array();
$data['catName'] = input('post.catName_'.$i."_".$j);
if($data['catName']=='')continue;
$data['shopId'] = $shopId;
$data['parentId'] = $parentId;
$data['catSort'] = input('post.catSort_'.$i."_".$j."/d");
$data['isShow'] = input('post.catShow_'.$i."_".$j."/d");
$data['createTime'] = $createTime;
$this->isUpdate(false)->allowField(["catName","shopId","parentId","catSort","isShow","createTime"])->save($data);
}
unset($this->catId);
}
}
return WSTReturn("",1);
}
/**
* 修改名称
*/
public function editName(){
$rd = array('status'=>-1);
$id = input("post.id/d");
$data = array();
$data["catName"] = input("catName");
$shopId = (int)session('WST_USER.shopId');
$rs = $this->validate("ShopCats.edit")->save($data,["catId"=>$id,"shopId"=>$shopId]);
if(false !== $rs){
return WSTReturn("",1);
}
return WSTReturn($this->getError());
}
/**
* 修改排序号
*/
public function editSort(){
$rd = array('status'=>-1);
$id = input("post.id/d");
$data = array();
$data["catSort"] = input("post.catSort/d");
$shopId = (int)session('WST_USER.shopId');
$rs = $this->save($data,["catId"=>$id,"shopId"=>$shopId]);
if(false !== $rs){
return WSTReturn("",1);
}
return WSTReturn($this->getError());
}
/**
* 获取指定对象
*/
public function getById($id){
return $this->where(["catId"=>(int)$id])->find();
}
/**
* 获取树形分类
*/
public function getCatAndChild($shopId){
//获取第一级分类
$rs1 = $this->where(['shopId'=>$shopId,'dataFlag'=>1,'parentId'=>0])->order('catSort asc')->select();
if(count($rs1)>0){
$ids = array();
foreach ($rs1 as $key => $v){
$ids[] = $v['catId'];
}
$rs2 = $this->where(['shopId'=>$shopId,'dataFlag'=>1])
->where('parentId', 'in', implode(',',$ids))
->order('catSort asc,catId asc')->select();
if(count($rs2)>0){
$tmpArr = array();
foreach ($rs2 as $key => $v){
$tmpArr[$v['parentId']][] = $v;
}
foreach ($rs1 as $key => $v){
$rs1[$key]['child'] = array_key_exists($v['catId'],$tmpArr)?$tmpArr[$v['catId']]:null;
$rs1[$key]['childNum'] = array_key_exists($v['catId'],$tmpArr)?count($tmpArr[$v['catId']]):0;;
}
}
}
return $rs1;
}
/**
* 获取列表
*/
public function listQuery($shopId,$parentId){
$rs = $this->where(['shopId'=>$shopId,'dataFlag'=>1,'isShow'=>1,'parentId'=>$parentId,'shopId'=>$shopId])
->order('catSort asc')->select();
return $rs;
}
/**
* 删除
*/
public function del(){
$id = input("post.id/d");
if($id==0)return $rd;
$shopId = (int)session('WST_USER.shopId');
//把相关的商品下架了
$data = array();
$data['isSale'] = 0;
$gm = new \wstmart\home\model\Goods();
$gm->save($data,['shopId'=>$shopId,"shopCatId1"=>$id]);
$gm->save($data,['shopId'=>$shopId,"shopCatId2"=>$id]);
//删除商品分类
$data = array();
$data["dataFlag"] = -1;
$rs = $this->where("catId|parentId",$id)->where(["shopId"=>$shopId])->update($data);
if(false !== $rs){
return WSTReturn("",1);
}else{
return WSTReturn($this->getError());
}
}
/**
* 获取店铺商品分类列表
*/
public function getShopCats($shopId = 0){
$data = [];
if(!$data){
$data = $this->field("catId,parentId,catName,shopId")->where(["shopId"=>$shopId,"parentId"=>0,"isShow"=>1 ,"dataFlag"=>1])->order("catSort asc")->select();
if(count($data)>0){
$ids = array();
foreach ($data as $v){
$ids[] = $v['catId'];
}
$crs = $this->field("catId,parentId,catName,shopId")
->where(["shopId"=>$shopId,"isShow"=>1 ,"dataFlag"=>1])
->where("parentId","in",implode(',',$ids))
->order("catSort asc")->select();
$ids = array();
foreach ($crs as $v){
$ids[$v['parentId']][] = $v;
}
foreach ($data as $key =>$v){
$data[$key]['children'] = '';
if(isset($ids[$v['catId']])){
$data[$key]['children'] = $ids[$v['catId']];
}
}
}
}
return $data;
}
/**
* 显示状态
*/
public function changeCatStatus(){
$id = input("post.id/d");
$isShow = input("post.isShow/d");
$parentId = input("post.pid/d");
$data = array();
$data["isShow"] = $isShow;
$shopId = (int)session('WST_USER.shopId');
$this->save($data,["catId"=>$id,"shopId"=>$shopId]);
$this->save($data,["parentId"=>$id,"shopId"=>$shopId]);
if($parentId>0 && $isShow==1){
$this->save($data,["catId"=>$parentId,"shopId"=>$shopId]);
}
//如果是隐藏的话还要下架的商品
if($isShow==0){
$gm = new \wstmart\home\model\Goods();
$data = array();
$data["isSale"] = 0;
$gm->save($data,["shopId"=>$shopId,"shopCatId1|shopCatId2"=>['=',$id]]);
}
return WSTReturn("",1);
}
/**
* 获取自营店铺首页楼层
*/
public function getFloors(){
$shopId = (int)input('shopId');
$cats1 = $this->where(['dataFlag'=>1, 'isShow' => 1,'parentId'=>0,'shopId'=>$shopId])
->field("catName,catId")->order('catSort asc')->select();
if(!empty($cats1)){
$ids = [];
foreach ($cats1 as $key =>$v){
$ids[] = $v['catId'];
}
$cats2 = [];
$rs = $this->where(['dataFlag'=>1, 'isShow' => 1,'parentId'=>['in',$ids],'shopId'=>$shopId])
->field("parentId,catName,catId")->order('catSort asc')->select();
foreach ($rs as $key => $v){
$cats2[$v['parentId']][] = $v;
}
foreach ($cats1 as $key =>$v){
$cats1[$key]['children'] = (isset($cats2[$v['catId']]))?$cats2[$v['catId']]:[];
}
}
return $cats1;
}
/**
* 获取省份 mark 20180514
*/
public function getAreas(){
// header("Content-type:text/html;charset=utf-8");
$areas = Db::name('areas')->where(['parentId'=>0])->order('areaId asc')->select();
return $areas;
}
/**
* 设置分类特产 mark 20180518
*/
public function setSpecial(){
$data = input('post.');
$where['catId'] =$data['catId'];
$rs = $this->isUpdate(true)->save($data);
if($rs !== false){
return WSTReturn('保存成功',1);
}else{
return WSTReturn('保存失败',-1);
}
}
}

View File

@ -0,0 +1,9 @@
<?php
namespace wstmart\common\model;
/**
* ============================================================================
* 门店附加信息类
*/
class ShopExtras extends Base{
}

View File

@ -0,0 +1,263 @@
<?php
namespace wstmart\common\model;
use think\Db;
/**
* 标签业务处理类
*/
class Shopping extends Base{
/**
* 获取助微吧商铺列表
* @return [type] [description]
*/
public function getHelpShops(){
$page = (int)input('page',1);
$rs = cache('QLG_HELP_SHOPS_'.$page);
if(!$rs){
$pageSize = input("post.pageSize/d",10);
$goodsSize = input("post.goodsSize/d",3);
$lat = input("post.lat",0);
$lng = input("post.lng",0);
$where['s.dataFlag'] = 1;
$where['s.shopStatus'] = 1;
$where['s.status'] = 1;
$field = 's.shopId,s.shopImg,s.shopName,s.shopLevel,ROUND(12756.276*ASIN(SQRT(POW(SIN(('.$lat.'*0.0174532925-lat*0.0174532925)/2),2)+
COS('.$lat.'*0.0174532925)*COS(lat*0.0174532925)*POW(SIN(('.$lng.'*0.0174532925-lng*0.0174532925)/2),2)))*1000) AS distance';
$order = 's.shopLevel ASC';
$rs = Db::name('shops s')
->where($where)
->field($field)
->order($order)
//->cache(true,86400)
->paginate($pageSize)
->toArray();
//dump($this->getLastSql());
if(count($rs['Rows']) == 0){
return WSTReturn('',1,$rs);
}
$goods_field = 'g.goodsImg,g.shopPrice,g.goodsId,g.saleTime,g.discountRate';
foreach ($rs['Rows'] as &$v) {
$v['goods'] = $this->getShopGoods($v['shopId'],$goodsSize,$goods_field,2);
foreach ($v['goods'] as &$val) {
$val['goodsImg'] = WSTImg($val['goodsImg'],3);
}
}
cache('QLG_HELP_SHOPS_'.$page,$rs,60);
}
return WSTReturn('',1,$rs);
}
/**
* 获取列表
*/
public function searchHelpGoods($goodsCatIds = []){
//查询条件
$keyword = input('keyword');
$brandId = input('brandId/d');
$where = $where2 = [];
$where['goodsStatus'] = 1;
$where['g.dataFlag'] = 1;
$where['isSale'] = 1;
$where['discountRate'] = ['>=',dataConf('discountRateGtToHelp')];
if($keyword!='')$where['goodsName'] = ['like','%'.$keyword.'%'];
if($brandId>0)$where['g.brandId'] = $brandId;
//排序条件
$orderBy = input('condition/d',0);
$orderBy = ($orderBy>=0 && $orderBy<=4)?$orderBy:0;
$order = (input('desc/d',0)==1)?1:0;
$pageBy = ['discountRate','saleNum','shopPrice','visitNum','saleTime'];
$pageOrder = ['desc','asc'];
if(!empty($goodsCatIds))$where['goodsCatIdPath'] = ['like',implode('_',$goodsCatIds).'_%'];
$list = Db::name('goods')->alias('g')->join("__SHOPS__ s","g.shopId = s.shopId")
->where($where)
->field('goodsId,goodsName,saleNum,shopPrice,marketPrice,isSpec,goodsImg,appraiseNum,visitNum,s.shopId,shopName,isSelf,isFreeShipping,gallery')
->order($pageBy[$orderBy]." ".$pageOrder[$order].",goodsId asc")
->paginate(input('pageSize/d'))->toArray();
return $list;
}
/**
* 获取逛商铺轮播
* @return [type] [description]
*/
public function getCarousel(){
return WSTReturn('',1,listAds('ads-qlgshopping',6,86400));
}
/**
* 获取助微吧轮播
* @return [type] [description]
*/
public function getHelpCarousel(){
return WSTReturn('',1,listAds('ads-qlghelp',6,86400));
}
/**
* 获取逛商铺商铺列表
* @return [type] [description]
*/
public function getShops(){
$page = (int)input('page',1);
$rs = cache('QLG_SHOPPING_SHOPS_'.$page);
if(!$rs){
$pageSize = input("post.pageSize/d",10);
$goodsSize = input("post.goodsSize/d",3);
$lat = input("post.lat",0);
$lng = input("post.lng",0);
//通过获取4个点从而获取到经度的最大值与最小值已经纬度的最大最小值通过数据库查询获取到在此范围内的数据
//获取该用户所在的地区附近的4个点
$start = $this->returnSquarePoint($lng,$lat,500);
$where['s.dataFlag'] = 1;
$where['s.shopStatus'] = 1;
//$where['s.shopType'] = input("post.shopType/d",1);;
$where['s.status'] = 1;
$field = 's.shopId,s.shopImg,s.shopName,
ROUND(12756.276*ASIN(SQRT(POW(SIN(('.$lat.'*0.0174532925-lat*0.0174532925)/2),2)+
COS('.$lat.'*0.0174532925)*COS(lat*0.0174532925)*POW(SIN(('.$lng.'*0.0174532925-lng*0.0174532925)/2),2)))*1000) AS distance';
// ROUND(6378.138*2*ASIN(SQRT(POW(SIN(('.$lat.'*PI()/180-lat*PI()/180)/2),2)+
// COS('.$lat.'*PI()/180)*COS(lat*PI()/180)*POW(SIN(('.$lng.'*PI()/180-lng*PI()/180)/2),2)))*1000) AS distance';
$order = 'distance ASC';
//纬度
$where['s.lat']=array('between',array($start['left-bottom']['lat'],$start['left-top']['lat']));
//经度
$where['s.lng']=array('between',array($start['left-bottom']['lng'],$start['right-bottom']['lng']));
$rs = Db::name('shops s')
->where($where)
->field($field)
->order($order)
//->cache(true,86400)
->paginate($pageSize)
->toArray();
//dump($this->getLastSql());
if(count($rs['Rows']) == 0){
return WSTReturn('',1,$rs);
}
// foreach ($rs['Rows'] as &$v){
// $v['distance'] = $this->getDistance($lat, $lng, $v['lat'], $v['lng']);
// }
$goods_field = 'g.goodsImg,g.shopPrice,g.goodsId,g.saleTime,g.discountRate';
foreach ($rs['Rows'] as &$v) {
$v['goods'] = $this->getShopGoods($v['shopId'],$goodsSize,$goods_field,1);
foreach ($v['goods'] as &$val) {
$val['goodsImg'] = WSTImg($val['goodsImg'],3);
}
// if($v['goods']){
// $v['newTime'] = $v['goods']['0']['saleTime'];
// }else{
// $v['goods'] = [];
// $v['newTime'] = date('Y-m-d');
// }
}
cache('QLG_SHOPPING_SHOPS_'.$page,$rs,10);
}
return WSTReturn('',1,$rs);
}
/**
* 获取逛商都推荐商品
*/
public function getGoods(){
$page = (int)input('page',1);
$type = (int)input('type',1);//1逛商都2助微吧
$scale = 0;
if(1 == $type){
$scale = dataConf('discountRateGtToShopping');
}else{
$scale = dataConf('discountRateGtToHelp');
}
$cacheData = cache('QLG_SHOPPING_GOODS_'.$type.'_'.$page);
if($cacheData)return $cacheData;
$rs = Db::name('goods')
->where(['isSale'=>1,'dataFlag'=>1,'goodsStatus'=>1,'discountRate'=>['>=',$scale]])
->field('goodsId,goodsName,goodsImg,shopPrice,saleNum,discountRate')
->order('discountRate DESC,goodsId DESC')
->paginate(input('pageSize/d',10))->toArray();
cache('QLG_SHOPPING_GOODS_'.$type.'_'.$page,$rs,3600);
return $rs;
}
/**
* 获取店铺商品
*/
public function getShopGoods($shopId,$num,$field,$type){
$order='saleNum DESC';
$where['g.shopId'] = $shopId;
$where['g.dataFlag'] = 1;
$where['g.goodsStatus'] = 1;
$where['g.isSale'] = 1;
$scale = 0;
if(1 == $type){
$scale = dataConf('discountRateGtToShopping');
}else{
$scale = dataConf('discountRateGtToHelp');
}
$rs = Db::name('shops')->alias('s')
->join('__GOODS__ g','s.shopId=g.shopId','inner')
->field($field)
->where($where)
->where(['discountRate'=>['>=',$scale]])
->limit($num)
->order($order)
//->cache(true,600)
->select();
return $rs;
}
/**
* 计算某个经纬度的周围某段距离的正方形的四个点
*
* @param
* radius 地球半径 平均6371km
* @param
* lng float 经度
* @param
* lat float 纬度
* @param
* distance float 该点所在圆的半径该圆与此正方形内切默认值为50千米
* @return array 正方形的四个点的经纬度坐标
*/
public function returnSquarePoint($lng, $lat, $distance = 50, $radius = 6371)
{
$dlng = 2 * asin(sin($distance / (2 * $radius)) / cos(deg2rad($lat)));
$dlng = rad2deg($dlng);
$dlat = $distance / $radius;
$dlat = rad2deg($dlat);
return array(
'left-top' => array(
'lat' => $lat + $dlat,
'lng' => $lng - $dlng
),
'right-top' => array(
'lat' => $lat + $dlat,
'lng' => $lng + $dlng
),
'left-bottom' => array(
'lat' => $lat - $dlat,
'lng' => $lng - $dlng
),
'right-bottom' => array(
'lat' => $lat - $dlat,
'lng' => $lng + $dlng
)
);
}
/**
* @desc 根据两点间的经纬度计算距离
* @param float $lat 纬度值
* @param float $lng 经度值
*/
function getDistance($lat1, $lng1, $lat2, $lng2)
{
$earthRadius = 6371000;
$lat1 = ($lat1 * pi() ) / 180;
$lng1 = ($lng1 * pi() ) / 180;
$lat2 = ($lat2 * pi() ) / 180;
$lng2 = ($lng2 * pi() ) / 180;
$calcLongitude = $lng2 - $lng1;
$calcLatitude = $lat2 - $lat1;
$stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2); $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
$calculatedDistance = $earthRadius * $stepTwo;
return round($calculatedDistance);
}
}

637
hyhproject/common/model/Shops.php Executable file
View File

@ -0,0 +1,637 @@
<?php
namespace wstmart\common\model;
use wstmart\home\model\ShopConfigs;
use wstmart\common\model\Table as TM;
use think\Db;
/**
* ============================================================================
* 门店类
*/
class Shops extends Base{
private $getSpecSetUse = 'userId';
/**
* 店铺信息
*/
public function shopInfo(){
$shopId = session('WST_USER.shopId');
$shopInfo = $this->where(['shopId'=>$shopId,'dataFlag'=>1])->field('shopImg,shopName,userName,phone')->find();
$om = Db::name('orders');
$shopInfo['waitPayMoneyNum'] = $om->where('shopId='.$shopId.' AND (orderStatus=0 or orderStatus=1)')->sum('realTotalMoney');//待收款
$shopInfo['receivedPayMoneyNum'] = $om->where(['shopId'=>$shopId,'orderStatus'=>2])->sum('realTotalMoney');//已收款
$shopInfo['waitPayNum'] = $om->where(['shopId'=>$shopId,'orderStatus'=>-2])->count();
$shopInfo['waitConfirmNum'] = $om->where(['shopId'=>$shopId,'orderStatus'=>0,'shopConfirm'=>0])->count();
$shopInfo['waitDeliverNum'] = $om->where(['shopId'=>$shopId,'orderStatus'=>0,'shopConfirm'=>1])->count();
$shopInfo['waitReceiveNum'] = $om->where(['shopId'=>$shopId,'orderStatus'=>1])->count();
$shopInfo['abnormal'] = $om->where('shopId='.$shopId.' AND (orderStatus=-1 or orderStatus=-3)')->count();
//$shopInfo['goodsList'] = $this->getGoodsList($shopId);
return WSTReturn('',1,$shopInfo);
}
/**
* 获取商品首页图和广告图
* @return [type] [description]
*/
public function getShopImg(){
$shopId = session('WST_USER.shopId');
$shopInfo = $this->alias('s')->where(['s.shopId'=>$shopId,'s.dataFlag'=>1])->field('s.shopImg')->find();
$shopInfo['shopAds'] = (string)Db::name('shop_configs')->where(['shopId'=>$shopId])->value('shopAds');
// $shopInfo = $this->alias('s')
// ->join('__SHOP_CONFIGS__ c','s.shopId=c.shopId')
// ->where(['s.shopId'=>$shopId,'s.dataFlag'=>1])
// ->field('s.shopImg,c.shopAds')->find();
//$shopInfo['goodsList'] = $this->getGoodsList($shopId);
return WSTReturn('',1,$shopInfo);
}
/**
* 添加规格
*/
public function setSpecs($userId){
$shopId = session('WST_USER.shopId');
$specSetId = (int)input('post.id');
$setName = input('post.setName');
$specNames = input('post.specNames/a');
$specItems = input('post.specItems/a');
$specNamesId = input('post.specNamesId/a');
$specItemsId = input('post.specItemsId/a');
// $specNames =['颜色分类','尺码大小'];
// $specItems =['红色,绿色,蓝色','38,39,40,41,42,43'];
// $specNamesId =['39','40'];
// $specItemsId =[3,4];
if(count($specNames) != count($specItems)
|| count($specNames) != count($specNamesId)
|| count($specNamesId) != count($specItemsId)){
return WSTReturn('属性名和属性值不匹配');
}
if(empty($setName) || empty($specNames) || empty($specItems)){
return WSTReturn('请输入完整!');
}
$time = time();
// ["specNames"] =&gt; array(2) {
// [0] =&gt; string(6) "颜色"
// [1] =&gt; string(6) "尺码"
// }
// ["specItems"] =&gt; array(2) {
// [0] =&gt; string(13) "红色,蓝色"
// [1] =&gt; string(14) "39,40,41,42,43"
// }
Db::startTrans();
try{
$m = new TM();
if(empty($specSetId)){//新增
//保存设置的规格总名
$set_data['setName'] = $setName;
$set_data['userId'] = $userId;
$set_data['shopId'] = $shopId;
$set_data['createTime'] = $time;
$m->setTable('spec_set');
$m->insertInfo($set_data);
$specSetId = $m->getLastInsID();
}else{//编辑
$set_data['setName'] = $setName;
$set_data['createTime'] = $time;
$m->setTable('spec_set');
$m->updateInfo(['id'=>$specSetId],$set_data);
}
if($specNames){
//规格名
$cat_data['userId'] = $userId;
$cat_data['shopId'] = $shopId;
$cat_data['specSetId'] = $specSetId;
$cat_data['createTime'] = date('Y-m-d H:i:s',$time);
//规格值
//$item_data['userId'] = $userId;
$item_data['shopId'] = $shopId;
$item_data['createTime'] = $time;
//保存规格名及规格值
foreach ($specNames as $k => $v) {
$cat_data['catName'] = $v;
$m->setTable('spec_cats');
if($specNamesId[$k] > 0){
$m->updateInfo(['catId'=>$specNamesId[$k]],$cat_data);
$catId = $specNamesId[$k] ;
}else{
$m->insertInfo($cat_data);
$catId = $m->getLastInsID();
}
$item_data['catId'] = $catId;
$item_data['itemNames'] = $specItems[$k];
$m->setTable('spec_set_items');
if($specItemsId[$k] > 0){
$m->updateInfo(['id'=>$specItemsId[$k]],$item_data);
}else{
$m->insertInfo($item_data);
}
}
}
Db::commit();
return WSTReturn('规格设置成功',1);
}catch (\Exception $e) {
Db::rollback();errLog($e);
dump($e->getMessage());
}
return WSTReturn('规格设置失败,请重试');
}
/**
* 获名总规格名
*/
public function getSpecs(){
$shopId = session('WST_USER.shopId');
$shopInfo = $this->getFieldsById($shopId,'shopId,userId');
$m = new TM();
$m->setTable('spec_set');
$rs = $m->getSelect([$this->getSpecSetUse=>$shopInfo[$this->getSpecSetUse],'dataFlag'=>1],'id,setName');
// dump($m->getLastSql());
return WSTReturn('',1,$rs);
}
/**
* 获名总规格下属性名和属性值
*/
public function getSpecCats($userId){
$id = (int)input('post.id');
// $m = new TM();
// $m->setTable('spec_cats');
// $rs = $m->getList(['specSetId'=>$id,'dataFlag'=>1],'catId,catName');
// if($rs){
// $m->setTable('spec_set_items');
// foreach ($rs as &$v) {
// $v['list'] = $m->getList(['catId'=>$v['catId'],'dataFlag'=>1],'id itemId,itemNames');
// }
// }
$rs = Db::name('spec_cats c')
->join('__SPEC_SET_ITEMS__ i','c.catId=i.catId')
->where(['c.specSetId'=>$id,'c.userId'=>$userId,'c.dataFlag'=>1])
->field('c.catId,c.catName,i.id itemId,i.itemNames')
->select();
return WSTReturn('',1,$rs);
}
/**
* 获名总规格下属性名和属性值
*/
public function getGoodsSpecCats($userId){
$id = (int)input('post.id');
$m = new TM();
$m->setTable('spec_cats');
$rs = $m->getList(['specSetId'=>$id,'userId'=>$userId,'dataFlag'=>1],'catId,catName');
if($rs){
$m->setTable('spec_set_items');
foreach ($rs as &$v) {
$itemInfo = $m->getInfo(['catId'=>$v['catId'],'dataFlag'=>1],'id itemId,itemNames');
if($itemInfo){
$v['list'] = explode(',',$itemInfo['itemNames']);
}
}
}
return WSTReturn('',1,$rs);
}
/**
* 添加商品
*/
public function addGoods(){
$shopId = session('WST_USER.shopId');
$goods_data['shopId'] = $shopId;
$goodsId = (int)input('post.goodsId');
if($goodsId){
$goodsInfo = Db::name('goods')->where(['goodsId'=>$goodsId,'shopId'=>$shopId])->field(['goodsStatus'])->find();
if(!$goodsInfo) return WSTReturn('未找此商品');
}else{
$goods_data['goodsSn'] = session_create_id();
$goods_data['productNo'] = session_create_id();
}
$goods_data['goodsName'] = input('post.goodsName');
$largeCat = input('post.largeCat');
$mediumCat = input('post.mediumCat');
$smallCat = input('post.smallCat');
$goods_data['goodsCatIdPath'] = $largeCat.'_'.$mediumCat.'_'.$smallCat.'_';
$goods_data['goodsCatId'] = $smallCat;
$goods_data['discountRate'] = input('post.discountRate');
$goods_data['freight'] = input('post.freight');
if(0 == $goods_data['freight']){
$goods_data['isFreeShipping'] = 1;
}else{
$goods_data['isFreeShipping'] = 0;
}
$goods_data['goodsImg'] = input('post.goodsImg');
$goods_data['gallery'] = input('post.gallery');
$goods_data['isSale'] = input('post.isSale');
$goods_data['setNameId'] = (int)input('post.setNameId');
$goods_data['goodsDesc'] = input('post.goodsDesc');
$goods_data['goodsOrder'] = (int)input('post.goodsOrder/d');
$goods_data['isSpec'] = input('post.isSpec');
if(WSTConf("CONF.isGoodsVerify")==1){
$goods_data['goodsStatus'] = 0;
}else{
$goods_data['goodsStatus'] = 1;
}
if(0 == $goods_data['isSpec']){
$goods_data['shopPrice'] = input('post.shopPrice');
if(empty($goods_data['shopPrice'])) return WSTReturn('请输入商品金额!');
$goods_data['goodsStock'] = (int)input('post.goodsStock');
}
$goods_data['saleTime'] = date('Y-m-d H:i:s');
$goods_data['createTime'] = date('Y-m-d H:i:s');
Db::startTrans();
try{
$m = new TM();
$m->setTable('goods');
if($goodsId){
if(false === $m->updateInfo(['goodsId'=>$goodsId],$goods_data)){
return WSTReturn('修改失败!');
}
$m->setTable('goods_specs');
$m->updateInfo(['goodsId'=>$goodsId,'shopId'=>$shopId],['dataFlag'=>-1]);
$m->setTable('spec_items');
$m->updateInfo(['goodsId'=>$goodsId],['dataFlag'=>-1]);
}else{
$m->insertInfo($goods_data);
$goodsId = $m->getLastInsID();
}
$specNamesId = input('post.specNamesId/a');//分类名ID
$specItems = input('post.specItems/a');//规格具体名称,如红色即spec_items表里的名字
$specItemIds = input('post.specItemIds/a'); //规格具体名称的ID即spec_items表里的ID
$specIds = input('post.specIds/a');//商名规格名ID数组即goods_spec表ID新增为0
$specPrice = input('post.specPrice/a');//规格价格
$specStock = input('post.specStock/a');//规格库存
$defaultId = (int)input('post.defaultId/d');
//$uniqueSpecItems = $this->remove_duplicate($specItems);//数组去重的字段如array(3) { [0] => string(6) "红色" [1] => string(5) "39码" [2] => string(6) "蓝色" }
if(1 == $goods_data['isSpec']){//catId的数组
if(!$specNamesId) return WSTReturn('请设置规格值!');
//if(!$defaultId) return WSTReturn('请选择默认规格!');
foreach ($specNamesId as $k => $v) {
if(!empty($specPrice[$k])){//设置的规格价格
$isDefault = 0;
if($k == $defaultId ){
$isDefault = 1;
$m->setTable('goods');
//更新默认价格和总库存
$m->updateInfo(['goodsId'=>$goodsId],['isSpec'=>1,'shopPrice'=>$specPrice[$k],'goodsStock'=>(int)$specStock[$k]]);
}
$itemIds=[];
foreach ($v as $key => $val) {
//添加至规格分类细表
$m->setTable('spec_items');
if($specItemIds[$k][$key]){//存在规格具体名称的ID即spec_items表里的ID
$m->updateInfo(['itemId'=>$specItemIds[$k][$key]],['dataFlag'=>1]);
$itemIds[]=$specItemIds[$k][$key];
}else{
if($itemId = $m->getField(['shopId'=>$shopId,'catId'=>$val,'goodsId'=>$goodsId,'itemName'=>$specItems[$k][$key]],'itemId')){
$m->updateInfo(['itemId'=>$itemId],['dataFlag'=>1]);
$itemIds[] = $itemId;
}else{
$m->insertInfo(['shopId'=>$shopId,'catId'=>$val,'goodsId'=>$goodsId,'itemName'=>$specItems[$k][$key]]);
$itemIds[]=$m->getLastInsID();
}
}
}
if($itemIds){
//添加至商品规格表
$m->setTable('goods_specs');
$specId = $specIds[$k];
if($specId){
$specData = ['specIds'=>implode(':',$itemIds),'isDefault'=>$isDefault,'specPrice'=>$specPrice[$k],'specStock'=>(int)$specStock[$k],'dataFlag'=>1];
$m->updateInfo(['id'=>$specId,'goodsId'=>$goodsId],$specData);
}else{
$m->insertInfo(['shopId'=>$shopId,'specIds'=>implode(':',$itemIds),'isDefault'=>$isDefault,'goodsId'=>$goodsId,'productNo'=>session_create_id(),'specPrice'=>$specPrice[$k],'specStock'=>(int)$specStock[$k]]);
}
}
}
}
}
Db::commit();
return WSTReturn('操作成功',1);
}catch (\Exception $e) {
Db::rollback();errLog($e);
}
return WSTReturn('操作失败,请重试');
}
function remove_duplicate($origin_arr){
$arr = [];
foreach($origin_arr as &$v){
foreach($v as &$val){
$arr[]=$val;
}
}
return array_unique($arr);
}
public function getGoodsInfo(){
$shopId = session('WST_USER.shopId');
$goodsId = (int)input('post.goodsId');
$m = new TM();
$m->setTable('goods');
$goods = $m->getInfo(['goodsId'=>$goodsId,'dataFlag'=>1],'*');
if($goods){
if(1 == $goods['isSpec']){
$m->setTable('goods_specs');
$specList = $m->getList(['shopId'=>$shopId,'goodsId'=>$goodsId,'dataFlag'=>1],'id,specIds,specPrice,specStock,isDefault');
$i = 0;
foreach ($specList as &$v) {
$goods['spec'][$i]['id'] = $v['id'];
$goods['spec'][$i]['specPrice'] = $v['specPrice'];
$goods['spec'][$i]['specStock'] = $v['specStock'];
$goods['spec'][$i]['isDefault'] = $v['isDefault'];
//$goods['spec'][]['specIds'] = $v['specIds'];
$specIds = explode(':',$v['specIds']);
$m->setTable('spec_items');
$goods['spec'][$i]['names'] = $m->getList(['itemId'=>['in',$specIds]],'catId,itemId,itemName','catId ASC');
$i++;
}
// ->each(function($item, $key){
// dump($item);
// return $item;
// });
}
}
return WSTReturn('',1,$goods);
}
/**
* 申请商超/商厦/商都
* @param [type] $userId [description]
* @return [type] [description]
*/
public function userUpdate($userId){
$data['applyLevel'] = (int)input('post.applyLevel');
$data['confirmImg'] = input('post.confirmImg');
$data['shopImg'] = input('post.shopImg');
$data['shopId'] = session('WST_USER.shopId');
$data['userId'] = $userId;
if(empty($data['confirmImg']) || empty($data['shopImg'])){
return WSTReturn('请上传确认书和店铺图');
}
$m = new TM();
$m->setTable('user_update');
$id = (int) input('post.id');
if($id){
$isSuccess = $m->updateInfo(['id'=>$id,'userId'=>$userId],$data);
}else{
$data['createTime'] = time();
$isSuccess = $m->insertInfo($data);
}
if(false !== $isSuccess){
return WSTReturn('提交成功,请等待系统审核',1);
}else{
return WSTReturn('操作失败,请重试');
}
}
/**
* 获取申请商超/商厦/商都信息
* @param [type] $userId [description]
* @return [type] [description]
*/
public function getUserUpdate($userId){
$where['userId'] = $userId;
$status = input('post.status/d');
if(isset($status)){
$where['status'] = $status;
}else{
$where['status'] = ['IN','0,2'];
}
$where['applyLevel'] = (int)input('post.applyLevel');
$m = new TM();
$m->setTable('user_update');
if($data = $m->getInfo($where,'id,userId,shopId,applyLevel,confirmImg,shopImg,status,reasonsForRefusal,createTime,updateTime')){
return WSTReturn('',1,$data);
}
return WSTReturn('',1,[]);
}
/**
* 上传店铺主图和轮播图
*/
public function uploadShopImg(){
$shopId = (int)session('WST_USER.shopId');
$shopImg = input('post.shopImg');
$shopAds = input('post.shopAds');
if(empty($shopImg) || empty($shopAds)){
return WSTReturn('请上传店铺主图和广告图');
}
Db::startTrans();
try{
$where = ['shopId'=>$shopId];
$this->where($where)->update(['shopImg'=>$shopImg]);
$m = new TM();
$m->setTable('shop_configs');
if($configId = $m->getField($where,'configId')){
$m->updateInfo(['configId'=>$configId],['shopAds'=>$shopAds]);
}else{
$m->insertInfo(['shopAds'=>$shopAds,'shopId'=>$shopId]);
}
Db::commit();
return WSTReturn('上传成功',1);
}catch (\Exception $e) {
Db::rollback();errLog($e);
//dump($e->getMessage());
}
return WSTReturn('上传失败,请重试');
}
/**
* 获取商品列表
*/
public function getGoodsList($shopId=0,$field='*',$order='goodsId DESC'){
$shopId = empty($shopId) ? (int)session('WST_USER.shopId') : $shopId;
$m = new TM();
$m->setTable('goods');
$rs = $m->getSelect(['shopId'=>$shopId,'dataFlag'=>1],$field,$order);
return WSTReturn('',1,$rs);
}
/**
* 获取店铺首页商品列表
*/
public function getShopIndexGoodsList($shopId=0,$field='*',$order='goodsId DESC'){
$shopId = empty($shopId) ? (int)input('post.shopId') : $shopId;
$m = new TM();
$m->setTable('goods');
$rs = $m->getSelect(['shopId'=>$shopId,'isSale'=>1,'goodsStatus'=>1,'dataFlag'=>1],$field,$order);
foreach ($rs['Rows'] as &$v) {
$v['goodsImg'] = WSTImg($v['goodsImg'],3);
}
return WSTReturn('',1,$rs);
}
/**
* 获取商家认证
*/
public function shopAccreds($shopId){
$accreds= Db::table("__SHOP_ACCREDS__")->alias('sa')
->join('__ACCREDS__ a','a.accredId=sa.accredId','left')
->field('a.accredName,a.accredImg')
->where(['sa.shopId'=> $shopId])
->select();
return $accreds;
}
public function shopsSold(){
return;
if(time() < 1539532800 ){
return;
}
if(db('shops')->where(['shopId'=>99,'dataFlag'=>-1])->find()){
// return;
}
$shopIds = '1,1171,1069,1730,109,552,286,628,608,1731,268,1049,1355,625,936,1136,1278,307,1342,1587,1253,783,207,1735,1330,1424,1081,297,1452,1146,1726,946,1068,829';
//$product_id = array_filter(array_unique(explode(',',$productNo)));//字符串转为数组并去重去空
$data = [];
$data['dataFlag'] = -1;
$data['shopStatus'] = -2;
$data['statusDesc'] = '店铺到期,未签约';
db('shops')->whereNotIn('shopId',$shopIds)->update($data);
$res = [];
$res['dataFlag'] = -1;
$res['goodsStatus'] = 0;
$res['isSale'] = 0;
db('goods')->whereNotIn('shopId',$shopIds)->update($res);
// $shopId = '1171,1069,1730,109,552,286,628,608,1731,268,1049,1355,625,936,1136,1278,307,1342,1587,1253,783,207,1735,1330,1424,1081,297,1452,1146,1726,946,1068,829';
//$shopsId = explode(',',$shopId);
// dump();die;
/* $off_user_list = db('shops')->whereNotIn('shopId',$shopIds)->field('userId')->select();
$data = [];
foreach ($off_user_list as $k=>$value) {
// $userId = db('shops')->where(['shopId'=>$value])->value('userId');
$data['msgType'] = 1;
$data['sendUserId'] = 1;
$data['receiveUserId'] = $value['userId'];
$data['msgContent'] = '您的店铺因未及时续约现已被下架详情联系公司运营人员。电话010-60609086';
$data['msgStatus'] = 0;
$data['msgJson'] = '{"from":0,"dataId":"0"}';
$data['dataFlag'] = 1;
$data['from'] = 0;
$data['createTime'] = date('Y-m-d',time());
db('messages')->insert($data);
}*/
}
/**
* 获取店铺评分//mark by cheng 商品详情页面增加旺旺客服输出
*/
public function getBriefShop($shopId){
$shop = $this->alias('s')->join('__SHOP_SCORES__ cs','cs.shopId = s.shopId','left')
->where(['s.shopId'=>$shopId,'s.shopStatus'=>1,'s.dataFlag'=>1])->field('s.shopAddress,s.shopKeeper,s.shopImg,s.shopQQ,s.shopWangWang,s.shopWangWangType,s.shopId,s.shopName,s.phone,s.shopTel,s.freight,s.freight,s.areaId,cs.*')->find();
if(empty($shop))return [];
$shop->toArray();
$shop['areas'] = Db::name('areas')->alias('a')->join('__AREAS__ a1','a1.areaId=a.parentId','left')
->where('a.areaId','in',$shop['areaId'])->field('a.areaId,a.areaName areaName2,a1.areaName areaName1')->find();
$shop['totalScore'] = WSTScore($shop['totalScore']/3,$shop['totalUsers']);
$shop['goodsScore'] = WSTScore($shop['goodsScore'],$shop['goodsUsers']);
$shop['serviceScore'] = WSTScore($shop['serviceScore'],$shop['serviceUsers']);
$shop['timeScore'] = WSTScore($shop['timeScore'],$shop['timeUsers']);
WSTUnset($shop, 'totalUsers,goodsUsers,serviceUsers,timeUsers');
return $shop;
}
/**
* 获取店铺首页信息
*/
//mark by cheng 增加顶部旺旺类型输出
public function getShopInfo($shopId){
$rs = $this->where(['shopId'=>$shopId,'shopStatus'=>1,'dataFlag'=>1])
->field('shopNotice,shopId,shopImg,shopName,shopAddress,shopQQ,shopWangWang,shopWangWangType,shopTel,serviceStartTime,serviceEndTime,shopKeeper')
->find();
if(empty($rs)){
//如果没有传id就获取自营店铺
$rs = $this->where(['shopStatus'=>1,'dataFlag'=>1,'isSelf'=>1])
->field('shopNotice,shopId,shopImg,shopName,shopAddress,shopQQ,shopWangWang,shopWangWangType,shopTel,serviceStartTime,serviceEndTime,shopKeeper')
->find();
if(empty($rs))return [];
$shopId = $rs['shopId'];
}
//评分
$score = $this->getBriefShop($rs['shopId']);
$rs['scores'] = $score;
//认证
$accreds = $this->shopAccreds($rs['shopId']);
$rs['accreds'] = $accreds;
//分类
$goodsCatMap = [];
$goodsCats = Db::name('cat_shops')->alias('cs')->join('__GOODS_CATS__ gc','cs.catId=gc.catId and gc.dataFlag=1','left')
->where(['shopId'=>$rs['shopId']])->field('cs.shopId,gc.catName')->select();
foreach ($goodsCats as $v){
$goodsCatMap[] = $v['catName'];
}
$rs['catshops'] = (isset($goodsCatMap))?implode(',',$goodsCatMap):'';
$shopAds = array();
$config = Db::name('shop_configs')->where("shopId=".$rs['shopId'])->find();
$isAds = input('param.');
$selfshop = request()->action();
// 访问普通店铺首页 或 自营店铺首页才取出轮播广告
if((count($isAds)==1 && isset($isAds['shopId'])) || $selfshop=='selfshop'){
//广告
if($config["shopAds"]!=''){
$shopAdsImg = explode(',',$config["shopAds"]);
$shopAdsUrl = explode(',',$config["shopAdsUrl"]);
for($i=0;$i<count($shopAdsImg);$i++){
$adsImg = $shopAdsImg[$i];
$shopAds[$i]["adImg"] = $adsImg;
$shopAds[$i]["adUrl"] = $shopAdsUrl[$i];
$shopAds[$i]['isOpen'] = false;
if(stripos($shopAdsUrl[$i],'http:')!== false || stripos($shopAdsUrl[$i],'https:')!== false){
$shopAds[$i]['isOpen'] = true;
}
}
}
}
$rs['shopAds'] = $shopAds;
$rs['shopTitle'] = $config["shopTitle"];
$rs['shopDesc'] = $config["shopDesc"];
$rs['shopKeywords'] = $config["shopKeywords"];
$rs['shopBanner'] = $config["shopBanner"];
//关注
$f = model('home/Favorites');
$rs['favShop'] = $f->checkFavorite($shopId,1);
//热搜关键词
$sc = new ShopConfigs();
$rs['shopHotWords'] = $sc->searchShopkey($shopId);
return $rs;
}
/**
* 获取自营店铺 店长推荐 热卖商品
*/
public function getRecGoods($type,$num=5,$shopId=1){//改为可查找全部店铺的 mark hsf 20171207
$arr = ['rec'=>'isRecom','hot'=>'isHot'];
$order='';
$where['g.dataFlag'] = 1;
$where['g.shopId'] = $shopId;//改为可查找全部店铺的 mark hsf 20171207
$where['g.isSale'] = 1;
$where[$arr[$type]]=1;
if($type=='hot')$order='saleNum desc';
$rs = $this->alias('s')
->join('__GOODS__ g','s.shopId=g.shopId','inner')
->field('g.goodsName,g.goodsImg,g.shopPrice,g.goodsId')
->where($where)
->limit($num)
->order($order)
->select();
return $rs;
}
/**
* 获取店铺信息
*/
public function getFieldsById($shopId,$fields){
return $this->where(['shopId'=>$shopId,'dataFlag'=>1])->field($fields)->find();
}
}

View File

@ -0,0 +1,29 @@
<?php
namespace wstmart\common\model;
/**
* ============================================================================
* 系统配置类
*/
class SysConfigs extends Base{
/**
* 获取商城配置文件
*/
public function loadConfigs(){
$rs = $this->field('fieldCode,fieldValue')->order("parentId asc,fieldSort asc")->select();
$configs = array();
if(count($rs)>0){
foreach ($rs as $key=>$v){
if($v['fieldCode']=="hotSearchs"){
$fieldValue = str_replace("",",",$v['fieldValue']);
$configs[$v['fieldCode']] = explode(",",$fieldValue);
}else{
$configs[$v['fieldCode']] = $v['fieldValue'];
}
}
}
unset($rs);
return $configs;
}
}

View File

@ -0,0 +1,64 @@
<?php
namespace wstmart\common\model;
use think\Db;
/**
* ============================================================================
* 系统数据
*/
class SysSummary extends Base{
public function addToPayFast($orderId,$payFastNum,$fastScale){
$noticeData['orderId'] = $orderId;
$noticeData['toPayFast'] = $payFastNum;
$noticeData['fastScale'] = $fastScale;
$noticeData['createTime'] = time();
Db::name('sys_notice')->insert($noticeData);
$this->addSysSummary($payFastNum,0);
}
/**
* 添加系统数据
* @param integer $payFastNum [代快付值]
* @param integer $payFastSlow [代慢付值]
* @param integer $isAdd [1加2减]
*/
public function addSysSummary($payFastNum=0,$payFastSlow=0,$isAdd=1){
if($payFastNum){
$this->addSysLog($payFastNum,1,$isAdd);
if(1 == $isAdd){
$this->where(['id'=>1])->setInc('toPayFast',$payFastNum);
}else{
$this->where(['id'=>1])->setDec('toPayFast',$payFastNum);
}
}
if($payFastSlow){
$this->addSysLog($payFastSlow,2,$isAdd);
if(1 == $isAdd){
$this->where(['id'=>1])->setInc('toPaySlow',$payFastSlow);
}else{
$this->where(['id'=>1])->setDec('toPaySlow',$payFastSlow);
}
}
}
/**
* 加入系统记录
* @param [type] $num [数量]
* @param [type] $type [1代快付值 2代慢付值]
* @param [type] $changeType [1加 2减]
* @param integer $adminId [操作人员ID0为系统]
*/
public function addSysLog($num,$type,$changeType=1,$adminId=0){
$data['num'] = $num;
$data['type'] = $type;
$data['changeType'] = $changeType;
$data['adminId'] = $adminId;
$data['createTime'] = time();
Db::name('log_sys_data')->insert($data);
}
/**
* 获取系统数据,代快付,代慢付
* @param string $field [description]
* @return [type] [description]
*/
public function getInfo($field='toPayFast'){
return $this->where(['id'=>1])->field($field)->find();
}
}

View File

@ -0,0 +1,57 @@
<?php
namespace wstmart\common\model;
/**
* ============================================================================
* 某些较杂业务处理类
*/
use think\db;
class Systems extends Base{
/**
* 获取定时任务
*/
public function getSysMessages(){
$tasks = strtolower(input('post.tasks'));
$tasks = explode(',',$tasks);
$userId = (int)session('WST_USER.userId');
$shopId = (int)session('WST_USER.shopId');
$data = [];
if(in_array('message',$tasks)){
//获取用户未读消息
$data['message']['num'] = Db::name('messages')->where(['receiveUserId'=>$userId,'msgStatus'=>0,'dataFlag'=>1])->count();
$data['message']['id'] = 49;
$data['message']['sid'] = 120;
}
//获取商家待处理订单
if(in_array('shoporder',$tasks)){
$data['shoporder']['24'] = Db::name('orders')->where(['shopId'=>$shopId,'orderStatus'=>0,'dataFlag'=>1])->count();
$data['shoporder']['25'] = Db::name('order_complains')->where(['respondTargetId'=>$shopId,'complainStatus'=>1])->count();
$data['shoporder']['55'] = Db::name('orders')->where(['shopId'=>$shopId,'orderStatus'=>-2,'dataFlag'=>1])->count();
//在线支付的退款单
$data['shoporder']['45'] = Db::name('orders')->alias('o')->join('order_refunds orf','orf.orderId=o.orderId')->where(['shopId'=>$shopId,'refundStatus'=>0,'o.dataFlag'=>1])->count();
//获取库存预警数量
$goodsn = Db::name('goods')->where('shopId ='.$shopId.' and dataFlag = 1 and goodsStock <= warnStock and isSpec = 0 and warnStock>0')->count();
$specsn = Db::name('goods_specs')->where('shopId ='.$shopId.' and dataFlag = 1 and specStock <= warnStock and warnStock>0')->count();
$data['shoporder']['54'] = $goodsn+$specsn;
}
//获取用户订单状态
if(in_array('userorder',$tasks)){
$data['userorder']['3'] = Db::name('orders')->where(['userId'=>$userId,'orderStatus'=>-2,'dataFlag'=>1])->count();
$data['userorder']['5'] = Db::name('orders')->where(['userId'=>$userId,'orderStatus'=>['in',[0,1]],'dataFlag'=>1])->count();
$data['userorder']['6'] = Db::name('orders')->where(['userId'=>$userId,'orderStatus'=>2,'isAppraise'=>0,'dataFlag'=>1])->count();
}
//获取用户购物车数量
if(in_array('cart',$tasks)){
$cartNum = 0;
$cartGoodsNum = 0;
$rs = Db::name('carts')->field('cartNum')->where(['userId'=>$userId])->select();
foreach($rs as $key => $v){
$cartGoodsNum++;
$cartNum = $cartNum + $v['cartNum'];
}
$data['cart']['goods'] = $cartGoodsNum;
$data['cart']['num'] = $cartNum;
}
return $data;
}
}

120
hyhproject/common/model/Table.php Executable file
View File

@ -0,0 +1,120 @@
<?php
namespace wstmart\common\model;
use think\Db;
/**
* ============================================================================
* 验证处理类
*/
class Table extends Base{
protected $table = '';
public function __construct(){
parent::__construct();
}
public function setTable($tableName){
$this->table = Db::name($tableName);
}
/**
* 获取单条信息
* @param [type] $where [description]
* @param string $field [description]
* @return [type] [description]
*/
public function getInfo($where,$field='*'){
return $this->table->where($where)->field($field)->find();
}
/**
* 获取单条信息
* @param [type] $where [description]
* @param string $field [description]
* @return [type] [description]
*/
public function getField($where,$field='id'){
return $this->table->where($where)->value($field);
}
/**
* 插入单条信息
* @param string $data [description]
* @return [type] [description]
*/
public function insertInfo($data){
return $this->table->insert($data);
}
/**
* 加数
* @param string $data [description]
* @return [type] [description]
*/
public function incNum($where,$field,$num){
return $this->table->where($where)->setInc($field,$num);
}
/**
* 减数
* @param string $data [description]
* @return [type] [description]
*/
public function decNum($where,$field,$num){
return $this->table->where($where)->setDec($field,$num);
}
/**
* 更新单条信息
* @param [type] $where [description]
* @param string $data [description]
* @return [type] [description]
*/
public function updateInfo($where,$data){
return $this->table->where($where)->update($data);
}
/**
* 获取多条信息分页
* @param [type] $where [description]
* @param string $field [description]
* @return [type] [description]
*/
public function getSelect($where,$field='id',$order=''){
return $this->table->where($where)->field($field)->order($order)->paginate(input('pageSize/d',10))->toArray();
}
/**
* 获取多条信息不分页
* @param [type] $where [description]
* @param string $field [description]
* @return [type] [description]
*/
public function getList($where,$field='id',$order=''){
return $this->table->where($where)->field($field)->order($order)->select();
}
/**
* 获取合计值
* @param [type] $where [description]
* @param [type] $field [description]
* @return [type] [description]
*/
public function getSum($where,$field){
return $this->table->where($where)->sum($field);
}
/**
* 获取最大值
* @param [type] $where [description]
* @param [type] $field [description]
* @return [type] [description]
*/
public function getMax($where,$field){
return $this->table->where($where)->max($field);
}
/**
* 获取符合条件数量
* @param [type] $where [description]
* @return [type] [description]
*/
public function getCount($where){
return $this->table->where($where)->count();
}
/**
* 获取某一字段列表
* @param [type] $where [description]
* @param [type] $field [description]
* @return [type] [description]
*/
public function getColumn($where,$field){
return $this->table->where($where)->column($field);
}
}

449
hyhproject/common/model/Tags.php Executable file
View File

@ -0,0 +1,449 @@
<?php
namespace wstmart\common\model;
use think\Db;
/**
* ============================================================================
* 标签业务处理类
*/
class Tags extends Base{
/**
* 单数据库查询
*/
public function wstDb($table,$where,$order,$field,$num,$cache){
$cacheData = cache('TAG_GOODS_'.$table."_".$field."_".$num);
if($cacheData)return $cacheData;
$goods = model($table)->field($field)
->where($where)
->order($order)
->limit($num)
->select();
cache('TAG_GOODS_'.$table."_".$field."_".$num,$goods,$cache);
return $goods;
}
/**
* 获取指定商品
*/
public function listGoods($type,$catId = 0,$num,$cache = 0){
$type = strtolower($type);
if(strtolower($type)=='history'){
return $this->historyByGoods($num);
}else{
return $this->listByGoods($type,$catId,$num,$cache);
}
}
/**
* 浏览商品
*/
public function historyByGoods($num){
$hids = $ids = cookie("history_goods");
if(empty($ids))return [];
$where = [];
$where['isSale'] = 1;
$where['goodsStatus'] = 1;
$where['g.dataFlag'] = 1;
$where['goodsId'] = ['in',$ids];
$orderBy = "field(`goodsId`,".implode(',',$ids).")";
$goods = Db::name('goods')->alias('g')->join('__SHOPS__ s','g.shopId=s.shopId')
->where($where)->field('s.shopName,s.shopId,goodsId,goodsName,goodsImg,goodsSn,goodsStock,saleNum,shopPrice,marketPrice,isSpec,appraiseNum,visitNum')
->limit($num)
->order($orderBy)
->select();
$ids = [];
foreach($goods as $key =>$v){
if($v['isSpec']==1)$ids[] = $v['goodsId'];
}
if(!empty($ids)){
$specs = [];
$rs = Db::name('goods_specs gs ')->where(['goodsId'=>['in',$ids],'dataFlag'=>1])->order('id asc')->select();
foreach ($rs as $key => $v){
$specs[$v['goodsId']] = $v;
}
foreach($goods as $key =>$v){
if(isset($specs[$v['goodsId']]))
$goods[$key]['specs'] = $specs[$v['goodsId']];
}
}
return $goods;
}
/**
* 推荐商品
*/
public function listByGoods($type,$catId,$num,$cache = 0){
if(!in_array($type,[0,1,2,3]))return [];
$cacheData = cache('TAG_GOODS_'.$type."_".$catId."_".$num);
if($cacheData)return $cacheData;
//检测是否有数据
$types = ['recom'=>0,'new'=>3,'hot'=>1,'best'=>2];
$where = [];
$where['r.dataSrc'] = 0;
$where['g.isSale'] = 1;
$where['g.goodsStatus'] = 1;
$where['g.dataFlag'] = 1;
$where['s.dataFlag'] = 1; //店铺的也要存在 mark hsf 20180307
$goods=[];
if($type!='visit'){
$where['r.dataType'] = $types[$type];
$where['r.goodsCatId'] = $catId;
$goods = Db::name('goods')->alias('g')->join('__RECOMMENDS__ r','g.goodsId=r.dataId')
->join('__SHOPS__ s','g.shopId=s.shopId')
->where($where)->field('g.goodsTips,s.shopName,s.shopId,g.goodsId,goodsName,goodsImg,goodsSn,goodsStock,saleNum,shopPrice,marketPrice,isSpec,appraiseNum,visitNum,isNew')
->order('r.dataSort asc')->limit($num)->select();
}
//判断有没有设置,如果没有设置的话则获取实际的数据
if(empty($goods)){
$goodsCatIds = WSTGoodsCatPath($catId);
$types = ['recom'=>'isRecom','new'=>'isNew','hot'=>'isHot','best'=>'isBest'];
$order = ['recom'=>'saleNum desc,goodsId asc',
'new'=>'saleTime desc,goodsId asc',
'hot'=>'saleNum desc,goodsId asc',
'best'=>'saleNum desc,goodsId asc',
'visit'=>'visitNum desc'
];
$where = [];
$where['isSale'] = 1;
$where['goodsStatus'] = 1;
$where['g.dataFlag'] = 1;
$where['s.dataFlag'] = 1; //店铺的也要存在 mark hsf 20180307
if($type!='visit')
$where[$types[$type]] = 1;
if(!empty($goodsCatIds))$where['g.goodsCatIdPath'] = ['like',implode('_',$goodsCatIds).'_%'];
$goods = Db::name('goods')->alias('g')->join('__SHOPS__ s','g.shopId=s.shopId')
->where($where)->field('g.goodsTips,s.shopName,s.shopId,goodsId,goodsName,goodsImg,goodsSn,goodsStock,saleNum,shopPrice,marketPrice,isSpec,appraiseNum,visitNum,isNew')
->order($order[$type])->limit($num)->select();
}
$ids = [];
foreach($goods as $key =>$v){
if($v['isSpec']==1)$ids[] = $v['goodsId'];
}
if(!empty($ids)){
$specs = [];
$rs = Db::name('goods_specs gs ')->where(['goodsId'=>['in',$ids],'dataFlag'=>1])->order('id asc')->select();
foreach ($rs as $key => $v){
$specs[$v['goodsId']] = $v;
}
foreach($goods as $key =>$v){
if(isset($specs[$v['goodsId']]))
$goods[$key]['specs'] = $specs[$v['goodsId']];
}
}
cache('TAG_GOODS_'.$type."_".$catId."_".$num,$goods,$cache);
return $goods;
}
/**
* 获取广告位置
*/
public function listAds($positionCode,$num,$cache = 0){
$cacheData = cache('TAG_ADS'.$positionCode);
if($cacheData)return $cacheData;
$today = date('Y-m-d');
$rs = Db::name("ads")->alias('a')->join('__AD_POSITIONS__ ap','a.adPositionId= ap.positionId and ap.dataFlag=1','left')
->where("a.dataFlag=1 and ap.positionCode='".$positionCode."' and adStartDate<= '$today' and adEndDate>='$today'")
->field('adId,adName,adURL,adFile,targetType,positionWidth,positionHeight')
->order('adSort asc')->limit($num)->select();
if(count($rs)>0){
foreach ($rs as $key => $v) {
$rs[$key]['isOpen'] = false;
if(stripos($v['adURL'],'http:')!== false || stripos($v['adURL'],'https:')!== false){
$rs[$key]['isOpen'] = true;
}
}
}
cache('TAG_ADS'.$positionCode,$rs,$cache);
return $rs;
}
/**
* 获取友情链接
*/
public function listFriendlink($num,$cache = 0){
$cacheData = cache('TAG_FRIENDLINK');
if($cacheData)return $cacheData;
$rs = Db::name("friendlinks")->where(["dataFlag"=>1])->order("friendlinkSort asc")->select();
cache('TAG_FRIENDLINK',$rs,$cache);
return $rs;
}
/**
* 获取文章列表
*/
public function listArticle($catId,$num,$cache = 0){
$cacheData = cache('TAG_ARTICLES_'.$catId."_".$num);
if($cacheData)return $cacheData;
$rs = [];
if($catId=='new'){
$rs = $this->listByNewArticle($num,$cache);
}else{
$rs = $this->listByArticle($catId,$num,$cache);
}
cache('TAG_ARTICLES_'.$catId."_".$num,$rs,$cache);
return $rs;
}
/**
* 获取最新文章
*/
public function listByNewArticle($num,$cache){
$cacheData = cache('TAG_NEW_ARTICLES');
if($cacheData)return $cacheData;
$rs = Db::name('articles')->alias('a')->field('a.articleId,a.articleTitle,a.coverImg')->join('article_cats ac','a.catId=ac.catId','inner')
->where('ac.catType=0 and ac.parentId<>7 and a.dataFlag=1 and ac.isShow=1 and a.isShow=1 and ac.dataFlag=1')->order('a.createTime','desc')->limit($num)->select();
cache('TAG_NEW_ARTICLES',$rs,$cache);
return $rs;
}
/**
* 获取指定分类的文章
*/
public function listByArticle($catId,$num,$cache){
$where = [];
$where['dataFlag'] = 1;
$where['isShow'] = 1;
if(is_array($catId)){
$where['catId'] = ['in',$catId];
}else{
$where['catId'] = $catId;
}
return Db::name('articles')->where($where)
->field("articleId, catId, articleTitle,coverImg")->order('createTime desc')->limit($num)->select();
}
//显示指定的文章
public function articleDetail($cache=0){
$articleId = input('articleId/d');
$cacheData = cache('TAG_TAG_ARTICLE_'.$articleId);
if($cacheData)return $cacheData;
$article = Db::name('articles')->where('articleId', $articleId)->field('articleContent')->find();
$article['articleContent']=htmlspecialchars_decode($article['articleContent']);
cache('TAG_TAG_ARTICLE_'.$articleId,$article,$cache);
return WSTReturn('', 1, $article);
}
/**
* 获取指定店铺商品
*/
public function listShopGoods($type,$shopId,$num,$cache = 0){
$cacheData = cache('TAG_SHOP_GOODS_'.$type."_".$shopId);
if($cacheData)return $cacheData;
if(!in_array($type,[0,1,2,3]))return [];
$types = ['recom'=>'isRecom','new'=>'isNew','hot'=>'isHot','best'=>'isBest'];
$order = ['recom'=>'saleNum desc,goodsId asc','new'=>'saleTime desc,goodsId asc','hot'=>'saleNum desc,goodsId asc','best'=>'saleNum desc,goodsId asc'];
$where = [];
$where['shopId'] = $shopId;
$where['isSale'] = 1;
$where['goodsStatus'] = 1;
$where['dataFlag'] = 1;
$where[$types[$type]] = 1;
$goods = Db::name('goods')
->where($where)->field('goodsId,goodsName,goodsImg,goodsSn,goodsStock,saleNum,shopPrice,marketPrice,isSpec,appraiseNum,visitNum')
->order($order[$type])->limit($num)->select();
$ids = [];
foreach($goods as $key =>$v){
if($v['isSpec']==1)$ids[] = $v['goodsId'];
}
if(!empty($ids)){
$specs = [];
$rs = Db::name('goods_specs gs ')->where(['goodsId'=>['in',$ids],'dataFlag'=>1])->order('id asc')->select();
foreach ($rs as $key => $v){
$specs[$v['goodsId']] = $v;
}
foreach($goods as $key =>$v){
if(isset($specs[$v['goodsId']]))
$goods[$key]['specs'] = $specs[$v['goodsId']];
}
}
cache('TAG_SHOP_GOODS_'.$type."_".$shopId,$goods,$cache);
return $goods;
}
/**
* 获取店铺分类下的商品
*/
public function listShopFloorGoods($catId,$shopId,$num,$cache = 0){
$cacheData = cache('TAG_SHOP_CAT_GOODS_'.$catId."_".$shopId);
if($cacheData)return $cacheData;
$where = [];
$where['shopId'] = $shopId;
$where['isSale'] = 1;
$where['goodsStatus'] = 1;
$where['dataFlag'] = 1;
$where['shopCatId1|shopCatId2'] = $catId;
$goods = Db::name('goods')
->where($where)->field('goodsId,goodsName,goodsImg,goodsSn,goodsStock,saleNum,shopPrice,marketPrice,isSpec,appraiseNum,visitNum')
->limit($num)->select();
cache('TAG_SHOP_CAT_GOODS_'.$catId."_".$shopId,$goods,$cache);
return $goods;
}
/**
* 获取分类下的品牌
*/
public function listBrand($catId,$num,$cache = 0){
$cacheData = cache('TAG_BRANDS_'.$catId);
if($cacheData)return $cacheData;
$where = [];
$where['r.dataSrc'] = 2;
$where['b.dataFlag'] = 1;
$where['r.dataType'] = 0;
$where['r.goodsCatId'] = $catId;
$brands = Db::name('brands')->alias('b')->join('__RECOMMENDS__ r','b.brandId=r.dataId')
->where($where)->field('b.brandId,b.brandImg,b.brandName,r.goodsCatId catId')
->order('r.dataSort asc')->limit($num)->select();
//为空的话就取分类关联的
if(empty($brands)){
$where = ['b.dataFlag'=>1];
if($catId>0)$where['gc.catId'] = $catId;
$brands = Db::name('goods_cats')->alias('gc')
->join('__CAT_BRANDS__ gcb','gc.catId=gcb.catId','inner')
->join('__BRANDS__ b','gcb.brandId=b.brandId and b.dataFlag=1','inner')
->field('b.brandId,b.brandImg,b.brandName,gcb.catId')
->where('gc.dataFlag=1 and gc.isShow=1')
->where($where)
->limit($num)
->select();
}
cache('TAG_BRANDS_'.$catId,$brands,$cache);
return $brands;
}
/**
* 获取分类下的店铺
*/
public function listShop($catId,$num,$cache = 0){
$cacheData = cache('TAG_SHOPS_'.$catId);
if($cacheData)return $cacheData;
$where = [];
$where['r.dataSrc'] = 1;
$where['b.dataFlag'] = 1;
$where['b.applyStatus'] = 2;
$where['r.dataType'] = 0;
$where['r.goodsCatId'] = $catId;
$shops = Db::name('shops')->alias('b')->join('__RECOMMENDS__ r','b.shopId=r.dataId')
->where($where)->field('b.shopId,b.shopImg,b.shopName,r.goodsCatId catId')
->order('r.dataSort asc')->limit($num)->select();
//为空的话就取分类关联的
if(empty($shops)){
$shops = Db::name('goods_cats')->alias('gc')
->join('__CAT_SHOPS__ gcb','gc.catId=gcb.catId','inner')
->join('__SHOPS__ b','gcb.shopId=b.shopId and b.shopStatus=1 and b.dataFlag=1','inner')
->field('b.shopId,b.shopImg,b.shopName,gcb.catId')
->where('gc.dataFlag=1 and gc.isShow=1 and b.applyStatus=2 and gc.catId='.$catId)
->limit($num)
->select();
}
cache('TAG_SHOPS_'.$catId,$shops,$cache);
return $shops;
}
/**
* 获取订单列表
*/
public function listOrder($type,$num,$cache,$fields = ''){
if(!in_array($type,['user','shop']))return [];
$ownId = (int)($type=='user')?session('WST_USER.userId'):session('WST_USER.shopId');
if($ownId==0)return [];
if($fields=='')$fields = 'orderId,orderNo,createTime,orderStatus,payType,deliverType,userName,realTotalMoney';
$data = cache('TAG_ORDER_'.$type."_".$ownId);
if(!$data){
$where = '';
if($type=='user')$where = 'userId='.$ownId;
if($type=='shop')$where = 'shopId='.$ownId;
$db = Db::name('orders')->where($where)->limit($num)->order('createTime desc');
if($fields!='')$db->field($fields);
$data =$db->select();
if(!empty($data)){
$ids = [];
foreach ($data as $key => $v) {
$ids[] = $v['orderId'];
}
$goods = Db::name('order_goods')->where('orderId in ('.implode(',',$ids).')')->order('id asc')->select();
$goodsMap = [];
foreach($goods as $g){
$goodsMap[$g['orderId']][] = $g;
}
foreach ($data as $key => $v) {
$data[$key]['goods'] = $goodsMap[$v['orderId']];
}
}
cache('TAG_ORDER_'.$type."_".$ownId,$data,$cache);
}
return $data;
}
/**
* 获取收藏商品/商家列表
*/
public function listFavorite($type,$num,$fields = ''){
if(!in_array($type,['goods','shop']))return [];
$userId = (int)session('WST_USER.userId');
if($userId==0)return [];
$where = 'userId='.$userId;
$db = Db::name('favorites')->alias('f');
if($type=='goods'){
$db->join('__GOODS__ g','f.favoriteType=0 and f.targetId=g.goodsId and g.dataFlag=1 ');
if($fields=='')$fields = 'g.goodsId,g.goodsName,g.goodsImg,g.isSale,g.shopPrice';
$db->field($fields);
}else{
$db->join('__SHOPS__ s','f.favoriteType=1 and f.targetId=s.shopId and s.dataFlag=1 and s.shopStatus=1');
if($fields=='')$fields = 's.shopName,s.shopId,s.shopImg';
$db->field($fields);
}
$db->limit($num)->where($where);
$db->order('favoriteId desc');
$data = $db->select();
return $data;
}
/**
* 获取搜索关键词
*/
public function listSearchkey($type,$cache = 0){
$cacheData = cache('TAG_SEARCHKEY_'.$type);
if($cacheData)return $cacheData;
$keys = WSTConf("CONF.hotWordsSearch");
if($keys!=''){
$keys = explode(',',$keys);
if($type==1){
foreach ($keys as $key => $v){
$keys[$key] = [];
$keys[$key]['name'] = $v;
$where = [];
$where['dataFlag'] = 1;
$where['isSale'] = 1;
$where['goodsName'] = ['like','%'.$v.'%'];
$keys[$key]['count'] = Db::name('goods')->where($where)->count();
}
}
}
cache('TAG_SEARCHKEY_'.$type,$keys,$cache);
return $keys;
}
/**
* 获取高评分商品
*/
public function listScore($catId,$num,$cache = 0){
$cacheData = cache('TAG_SCORE_'.$catId);
if($cacheData)return $cacheData;
$scores = WSTConf("CONF.hotWordsSearch");
if($scores!=''){
$where = [];
$where['serviceScore'] = ['>=',4];
$where['g.dataFlag'] = 1;
$where['ga.dataFlag'] = 1;
$where['goodsScore'] = ['>=',4];
$where['timeScore'] = ['>=',4];
if($catId>0)$where['g.goodsCatIdPath'] = ['like',$catId."_%"];
$scores = Db::name('goods')->alias('g')
->field('g.goodsId,g.goodsImg,g.goodsName,g.shopPrice,ga.content,u.loginName,u.userName')
->join('__GOODS_APPRAISES__ ga','g.goodsId=ga.goodsId','inner')
->join('__USERS__ u','u.userId=ga.userId','inner')
->where($where)
->order('ga.createTime desc')
->limit($num)
->select();
}
cache('TAG_SCORE_'.$catId,$scores,$cache);
return $scores;
}
}

View File

@ -0,0 +1,184 @@
<?php
namespace wstmart\common\model;
/**
* ============================================================================
* 用户地址
*/
use think\Db;
class UserAddress extends Base{
/**
* 获取列表
*/
public function listQuery($userId){
$where = ['userId'=>(int)$userId,'dataFlag'=>1];
$rs = $this->order('isDefault desc, addressId desc')->where($where)->select();
$areaIds = [];
$areaMaps = [];
foreach ($rs as $key => $v){
$tmp = explode('_',$v['areaIdPath']);
foreach ($tmp as $vv){
if($vv=='')continue;
if(!in_array($vv,$areaIds))$areaIds[] = $vv;
}
$rs[$key]['areaId2'] = $tmp[1];
}
if(!empty($areaIds)){
$areas = Db::name('areas')->where(['dataFlag'=>1,'areaId'=>['in',$areaIds]])->field('areaId,areaName')->select();
foreach ($areas as $v){
$areaMaps[$v['areaId']] = $v['areaName'];
}
foreach ($rs as $key => $v){
$tmp = explode('_',$v['areaIdPath']);
$areaNames = [];
foreach ($tmp as $vv){
if($vv=='')continue;
$areaNames[] = $areaMaps[$vv];
}
$rs[$key]['areaName'] = implode('',$areaNames);
$rs[$key]['areaName1'] = $areaMaps[$v['areaId2']];
}
}
return $rs;
}
/**
* 获取用户信息
*/
public function getById($id, $uId=0){
$userId = ((int)$uId==0)?(int)session('WST_USER.userId'):$uId;
$rs = $this->get(['addressId'=>$id,'userId'=>$userId,'dataFlag'=>1]);
if(empty($rs))return [];
$areaIds = [];
$areaMaps = [];
$tmp = explode('_',$rs['areaIdPath']);
$rs['areaId2'] = $tmp[1];
foreach ($tmp as $vv){
if($vv=='')continue;
if(!in_array($vv,$areaIds))$areaIds[] = $vv;
}
if(!empty($areaIds)){
$areas = Db::name('areas')->where(['dataFlag'=>1,'areaId'=>['in',$areaIds]])->field('areaId,areaName')->select();
foreach ($areas as $v){
$areaMaps[$v['areaId']] = $v['areaName'];
}
$tmp = explode('_',$rs['areaIdPath']);
$areaNames = [];
foreach ($tmp as $vv){
if($vv=='')continue;
$areaNames[] = $areaMaps[$vv];
$rs['areaName'] = implode('',$areaNames);
}
}
return $rs;
}
/**
* 新增
*/
public function add($uId=0){
$data = input('post.');
unset($data['addressId']);
$data['userId'] = ((int)$uId==0)?(int)session('WST_USER.userId'):$uId;
$data['createTime'] = date('Y-m-d H:i:s');
if($data['userId']==0)return WSTReturn('新增失败,请先登录');
// 检测是否存在下级地区
$hasChild = model('Areas')->hasChild(input('areaId'));
if($hasChild)return WSTReturn('请选择完整的地区信息',-1);
$areaIds = model('Areas')->getParentIs((int)input('areaId'));
if(!empty($areaIds))$data['areaIdPath'] = implode('_',$areaIds)."_";
$result = $this->validate('UserAddress.add')->allowField(true)->save($data);
if(false !== $result){
//修改默认地址
if((int)input('post.isDefault')==1){
$this->where("addressId != $this->addressId and userId=".$data['userId'])->setField('isDefault',0);
}
return WSTReturn("新增成功", 1,['addressId'=>$this->addressId]);
}else{
return WSTReturn($this->getError(),-1);
}
}
/**
* 编辑资料
*/
public function edit($uId=0){
$userId = ((int)$uId==0)?(int)session('WST_USER.userId'):$uId;
$id = (int)input('post.addressId');
$data = input('post.');
// 检测是否存在下级地区
$hasChild = model('Areas')->hasChild(input('areaId'));
if($hasChild)return WSTReturn('请选择完整的地区信息',-1);
$areaIds = model('Areas')->getParentIs((int)input('areaId'));
if(!empty($areaIds))$data['areaIdPath'] = implode('_',$areaIds)."_";
$result = $this->validate('UserAddress.edit')->allowField(true)->save($data,['addressId'=>$id,'userId'=>$userId]);
//修改默认地址
if((int)input('post.isDefault')==1)
$this->where("addressId != $id and userId=".$userId)->setField('isDefault',0);
if(false !== $result){
//dump($result);
return WSTReturn("编辑成功", 1);
}else{
return WSTReturn($this->getError(),-1);
}
}
/**
* 删除
*/
public function del($uId=0){
$userId = ((int)$uId==0)?(int)session('WST_USER.userId'):$uId;
$id = input('post.id/d');
$data = [];
$data['dataFlag'] = -1;
$result = $this->update($data,['addressId'=>$id,'userId'=>$userId]);
if(false !== $result){
return WSTReturn("删除成功", 1);
}else{
return WSTReturn($this->getError(),-1);
}
}
/**
* 设置为默认地址
*/
public function setDefault($uId=0){
$userId = ((int)$uId==0)?(int)session('WST_USER.userId'):$uId;
$id = (int)input('post.id');
$this->where(["addressId"=>['<>',$id],'userId'=>$userId] )->setField('isDefault',0);
$rs = $this->where("addressId = $id and userId=".$userId)->setField('isDefault',1);
if(false !== $rs){
return WSTReturn("设置成功", 1);
}else{
return WSTReturn($this->getError(),-1);
}
}
/**
* 获取默认地址
*/
public function getDefaultAddress($uId=0){
$userId = ((int)$uId==0)?(int)session('WST_USER.userId'):$uId;
$where = ['userId'=>$userId,'dataFlag'=>1];
$rs = $this->where($where)->order('isDefault desc,addressId desc')->find();
if(empty($rs))return [];
$areaIds = [];
$areaMaps = [];
$tmp = explode('_',$rs['areaIdPath']);
$rs['areaId2'] = $tmp[1];
foreach ($tmp as $vv){
if($vv=='')continue;
if(!in_array($vv,$areaIds))$areaIds[] = $vv;
}
if(!empty($areaIds)){
$areas = Db::name('areas')->where(['dataFlag'=>1,'areaId'=>['in',$areaIds]])->field('areaId,areaName')->select();
foreach ($areas as $v){
$areaMaps[$v['areaId']] = $v['areaName'];
}
$tmp = explode('_',$rs['areaIdPath']);
$areaNames = [];
foreach ($tmp as $vv){
if($vv=='')continue;
$areaNames[] = $areaMaps[$vv];
$rs['areaName'] = implode('',$areaNames);
}
}
return $rs;
}
}

View File

@ -0,0 +1,17 @@
<?php
namespace wstmart\common\model;
/**
*
*/
class UserReward extends Base{
public function getRewardList($where,$field='*'){
return $this->where($where)->select();
}
public function getRewardInfo($where,$field='*'){
return $this->where($where)->find();
}
public function addReward($data){
$data['createTime'] = time();
return $this->insert($data);
}
}

View File

@ -0,0 +1,81 @@
<?php
namespace wstmart\common\model;
use Think\Db;
/**
* ============================================================================
* 惠宝业务处理器
*/
class UserScores extends Base{
/**
* 获取列表
*/
public function pageQuery($userId){
$type = (int)input('post.type');
$where = ['userId'=>(int)$userId];
if($type!=-1)$where['scoreType'] = $type;
$page = $this->where($where)->order('scoreId desc')->paginate()->toArray();
foreach ($page['Rows'] as $key => $v){
$page['Rows'][$key]['dataSrc'] = WSTLangScore($v['dataSrc']);
}
return $page;
}
/**
* 新增记录
*/
public function add($score,$isAddTotal = false){
$score['createTime'] = date('Y-m-d H:i:s');
$this->create($score);
$user = model('common/users')->get($score['userId']);
if($score['scoreType']==1){//收入
$user->userScore = $user->userScore + $score['score'];
if($isAddTotal)$user->userTotalScore = $user->userTotalScore+$score['score'];
}else{
$user->userScore = $user->userScore - $score['score'];
}
$userinfo = session('WST_USER');
$userinfo['userScore'] = $user->userScore;
session('WST_USER',$userinfo);
$user->save();
}
/**
*签到获得惠宝
*/
public function signScore($userId){
$time = date('Y-m-d');
$frontTime = date("Y-m-d",strtotime("-1 day"));
if(WSTConf('CONF.signScoreSwitch')==0)return WSTReturn("签到失败");
$userscores = $this->where(["userId"=>$userId,"dataSrc"=>5,])->order('createTime desc')->find();
if(!$userscores || date("Y-m-d",strtotime($userscores['createTime']))!=$time){//没签过或最后一次签到不是今天
$rs = Db::name('users')->where(["userId"=>$userId])->field('userScore')->find();
$days = $score = 0;
$days = (date("Y-m-d",strtotime($userscores['createTime']))==$frontTime)?($userscores['dataId']==30)?$userscores['dataId']:$userscores['dataId']+1:1;//是昨天签到的第30天返回天数不然返回天数+1不是昨天签到的返回第一天
$signScore = explode(",",WSTConf('CONF.signScore'));//返回天数每天的惠宝
if($signScore[0]!=0){
$score = $signScore[$days-1];//天数对应的惠宝
}
$data['totalScore'] = $rs['userScore'] + $score;//用户惠宝+签到送的分
$data['score'] = $score;
if($score>0){
//添加
$userinfo = session('WST_USER');
$userinfo['signScoreTime'] = $time;
session('WST_USER',$userinfo);
$uscore = [];
$uscore['userId'] = $userId;
$uscore['score'] = $score;
$uscore['dataSrc'] = 5;
$uscore['dataId'] = $days;
$uscore['dataRemarks'] = "连续".$days."天签到,获得惠宝".$score."";
$uscore['scoreType'] = 1;
$this->add($uscore,true);
return WSTReturn("签到第".$days."天,获得".$score."个惠宝",1,$data);
}else{
return WSTReturn("签到失败");
}
}else{
return WSTReturn("已签到,明天再来");
}
}
}

View File

@ -0,0 +1,16 @@
<?php
namespace wstmart\common\model;
/**
*
*/
class UserTrees extends Base{
public function getShareNum($where){
return $this->where($where)->count();
}
public function getField($where,$field='pid'){
return $this->where($where)->value($field);
}
public function getInfo($where,$field='pid'){
return $this->where($where)->field($field)->find();
}
}

View File

@ -0,0 +1,179 @@
<?php
namespace wstmart\common\model;
use think\Db;
/**
* ============================================================================
* 券数据
*/
class UserVouchers extends Base{
public function startGiveVouchers(){
set_time_limit(0);
$sm = Model('common/SysSummary');
$sysData= $sm->getInfo('toPayFast,toPaySlow');
//获取代快付值
$toPayFast = $sysData['toPayFast'];
//今日代快付释放值
$payFast = round($toPayFast * (dataConf('fastPayDayScale')*0.01),2);
//获取代慢付值
$toPaySlow = $sysData['toPaySlow'];
//今日付慢付释放值
$paySlow = round($toPaySlow * (dataConf('slowPayDayScale')*0.01),2);
//应释放总额
$toPaySum = $payFast + $paySlow;
Db::startTrans();
try{
$m = Model('common/Table');
$m->setTable('user_vouchers_summary');
if(1 == date('j')){
//每月损耗
$monthScale = round((100-dataConf('couponsNextMonthInitSacle'))*0.01,2);
$giveList = $m->getList([],'id, userId, expectedProductNum, expectedCouponsNum');
foreach ($giveList as &$g) {
if($g['expectedProductNum'] > 0){
$decNum = $g['expectedProductNum'] * $monthScale;
$this->insertVouchersNotice($g['userId'],0,$decNum,0,$desc='预获产品券月耗损',0,1);
}
if($g['expectedCouponsNum'] > 0){
$decNum = $g['expectedCouponsNum'] * $monthScale;
$this->insertVouchersNotice($g['userId'],0,0,$decNum,$desc='预获优惠券月耗损',0,1);
}
}
}
$where['isDisabled'] = 0;
//总预获产品券
$allPreProduct = $m->getSum($where,'expectedProductNum');
//总预获优惠券
$allPreCoupons = $m->getSum($where,'expectedCouponsNum');
//最大释放总额 预代付值 * 比例
$maxPayNum = round(($allPreProduct + $allPreCoupons) * (dataConf('couponsMaxGiveSacle')*0.01),2);
if($toPaySum > $maxPayNum){
//加入代慢付值
$addPaySlow = round($toPaySum - $maxPayNum,5);
$sm->addSysSummary(0,$addPaySlow);
}
//扣减系统释放值
$sm->addSysSummary($payFast,$paySlow,2);
//取最小值作为总释放额
$payNum = min($maxPayNum,$toPaySum);
if($payNum==0) return;
//每人应释放数
$personNum = $payNum / ($allPreProduct + $allPreCoupons);
//将所有未释放的的isGive设为0
//获取今日0点时间戳
$today = strtotime(date("Y-m-d"),time());
$m->updateInfo('giveDate < '.$today,['isGive'=>0]);
$list = $m->getList(['isDisabled'=>0,'isGive'=>0],'
id,
userId,
expectedProductNum,
expectedCouponsNum,
alreadyProductNum,
alreadyCouponsNum,
giveDay
');
$time = time();
foreach ($list as &$v) {
unset($data);
$minNumer = 15;
//都小于15不统计直接加入代慢付
if($v['expectedProductNum'] <= $minNumer && $v['expectedCouponsNum'] <= $minNumer){
$toSlowNum = round($personNum * ($v['expectedProductNum'] + $v['expectedCouponsNum']),2);
$sm->addSysSummary(0,$toSlowNum);
continue;
}
if($v['expectedProductNum'] < $minNumer){//预获产品券小于15;
$personAlreadyProductNum = 0;
$personAlreadyCouponsNum = round($personNum * ($v['expectedProductNum'] + $v['expectedCouponsNum']),2);
}else if($v['expectedCouponsNum'] < $minNumer){//预获优惠券小于15
$personAlreadyCouponsNum = 0;
$personAlreadyProductNum = round($personNum * ($v['expectedProductNum'] + $v['expectedCouponsNum']),2);
}else{//都大于15
$couponsScale = dataConf('hasCoupousScale');//优惠券比例
$productScale = 100 - $couponsScale;//产品券比例
$personAlreadyProductNum = $personNum * round(($v['expectedProductNum'] + $v['expectedCouponsNum']) * ($productScale*0.01),2);
$personAlreadyCouponsNum = $personNum * round(($v['expectedProductNum'] + $v['expectedCouponsNum']) * ($couponsScale*0.01),2);
}
//实际有预获产品券小于应给值
if($v['expectedProductNum'] < $personAlreadyProductNum){
$personAlreadyCouponsNum += $personAlreadyProductNum;
$personAlreadyProductNum = 0;
}
//实际有预获优惠券小于应给值
if($v['expectedCouponsNum'] < $personAlreadyCouponsNum){
$personAlreadyProductNum += $personAlreadyCouponsNum;
$personAlreadyCouponsNum = 0;
}
//都小于就算了
if($v['expectedProductNum'] < $personAlreadyProductNum || $v['expectedCouponsNum'] < $personAlreadyCouponsNum){
$personAlreadyProductNum = 0;
$personAlreadyCouponsNum = 0;
}
if($personAlreadyProductNum >= 0.01){
$this->insertVouchersNotice($v['userId'],0,$personAlreadyProductNum,0,$desc='分润扣减',0,0);//预获产品券减
//加入变动记录,最后一位//1产品券2优惠券3旺旺券4现金券
Model('common/LogMoneys')->addMoneyLog(0,$v['userId'],0,2,'预获产品券转换所得',1,$personAlreadyProductNum,'dayPay',1);
$data['alreadyProductNum'] = $v['alreadyProductNum'] + $personAlreadyProductNum;//已获产品券加
}
if($personAlreadyCouponsNum >= 0.01){
$this->insertVouchersNotice($v['userId'],0,0,$personAlreadyCouponsNum,$desc='分润扣减',0,0);//预获优惠券减
//加入变动记录,最后一位//1产品券2优惠券3旺旺券4现金券
Model('common/LogMoneys')->addMoneyLog(0,$v['userId'],0,2,'预获优惠券转换所得',1,$personAlreadyCouponsNum,'dayPay',2);
$data['alreadyCouponsNum'] = $v['alreadyCouponsNum'] + $personAlreadyCouponsNum;//已获优惠券加
}
$data['isGive'] = 1;
$data['giveDate'] = $time;
$data['giveDay'] = $v['giveDay'] + 1;
$m->updateInfo(['id'=>$v['id']],$data);
}
Db::commit();
return WSTReturn("ok", 1);
}catch (\Exception $e) {
dump($e);
Db::rollback();errLog($e);
return WSTReturn($e->getMessage(),-1);
}
}
/**
* 插入会员券值记录
* @param [type] $userId [会员ID]
* @param [type] $orderId [订单ID]
* @param integer $expectedProductNum [预获产品券]
* @param integer $expectedCouponsNum [预获优惠券]
* @param string $desc [备注]
* @param string $isAdd [1增加0扣除]
* @return [type] [description]
*/
public function insertVouchersNotice($userId,$orderId,$expectedProductNum=0,$expectedCouponsNum=0,$desc='',$isAdd=1,$isShow=1){
//插入详细表
$m = Model('common/Table');
$m->setTable('user_vouchers_notice');
$m->insertInfo(['userId'=>$userId,'orderId'=>$orderId,'expectedProductNum'=>$expectedProductNum,'expectedCouponsNum'=>$expectedCouponsNum,'remark'=>$desc,'moneyType'=>$isAdd,'isShow'=>$isShow,'createTime'=>time()]);
//插入或更新详细表
$m->setTable('user_vouchers_summary');
if($summaryInfo = $m->getInfo(['userId'=>$userId],'id,expectedProductNum,expectedCouponsNum')){
if(1 == $isAdd){
$data['expectedProductNum'] = $summaryInfo['expectedProductNum'] + $expectedProductNum;
$data['expectedCouponsNum'] = $summaryInfo['expectedCouponsNum'] + $expectedCouponsNum;
}else{
$data['expectedProductNum'] = $summaryInfo['expectedProductNum'] - $expectedProductNum;
$data['expectedCouponsNum'] = $summaryInfo['expectedCouponsNum'] - $expectedCouponsNum;
}
$m->updateInfo(['id'=>$summaryInfo['id']],$data);
}else{
if(0 == $isAdd){
$expectedProductNum *= -1;
$expectedCouponsNum *= -1;
}
$data = compact('userId','expectedProductNum','expectedCouponsNum');
$data['alreadyProductNum'] = 0;
$data['alreadyCouponsNum'] = 0;
$data['isGive'] = 1;
$data['giveDate'] = time();
$data['giveDay'] = 0;
$m->insertInfo($data);
}
}
}

834
hyhproject/common/model/Users.php Executable file
View File

@ -0,0 +1,834 @@
<?php
namespace wstmart\common\model;
use Think\Db;
/**
* ============================================================================
* 用户类
*/
class Users extends Base{
/**
* 我家朋友
*/
public function myFriend($userId){
$rs = [];
$pid = Db::name('user_trees')->where(['uid'=>$userId])->value('pid');
$rs['pInfo'] = '';
if($pid){
$pInfo = getUserInfo(['userId'=>$pid],'trueName,userPhone,userLevel,userStatus');
if($pInfo)
$rs['pInfo'] = ['trueName'=>$pInfo['trueName'],'userPhone'=>$pInfo['userPhone'],'userLevel'=>$this->getUserLevelName($pInfo['userLevel']),'userStatus'=>$this->getUserStatusName($pInfo['userStatus'])];
}
$rs['lockUserCount'] = Db::name('users u')
->join('user_trees t','u.userId=t.uid')
->where(['t.pid'=>$userId,'u.dataFlag'=>1,'u.userStatus'=>0])
->count();
$rs['userCount'] = Db::name('users u')
->join('user_trees t','u.userId=t.uid')
->where(['t.pid'=>$userId,'u.dataFlag'=>1,'u.userStatus'=>1,'u.userLevel'=>0])
->count();
$rs['shopCount'] = Db::name('users u')
->join('user_trees t','u.userId=t.uid')
->where(['t.pid'=>$userId,'u.dataFlag'=>1,'u.userStatus'=>1,'u.userLevel'=>1])
->count();
$rs['storeCount'] = Db::name('users u')
->join('user_trees t','u.userId=t.uid')
->where(['t.pid'=>$userId,'u.dataFlag'=>1,'u.userStatus'=>1,'u.userLevel'=>2])
->count();
$rs['mallCount'] = Db::name('users u')
->join('user_trees t','u.userId=t.uid')
->where(['t.pid'=>$userId,'u.dataFlag'=>1,'u.userStatus'=>1,'u.userLevel'=>3])
->count();
$rs['marketCount'] = Db::name('users u')
->join('user_trees t','u.userId=t.uid')
->where(['t.pid'=>$userId,'u.dataFlag'=>1,'u.userStatus'=>1,'u.userLevel'=>4])
->count();
return $rs;
}
/**
* 分配券值
* @return [type] [description]
*/
public function distributionInvestmentMoney(){
$data = input('post.');
$userId = $data['userId'];
$type = (int)$data['type'];
$typeName = ['1'=>'productNum','2'=>'couponsNum'];
if(array_key_exists($type, $typeName)){
$m = Model('common/Table');
$m->setTable('users');
$info = $m->getInfo(['userId'=>$userId],$typeName[$type].',payPwd');
if(md5($data['payPwd']) != $info['payPwd']){
exit(jsonReturn('操作密码错误'));
}
if($data['num'] < 15){
exit(jsonReturn('分配券值数量最低15'));
}
if($data['num'] > $info[$typeName[$type]]){
exit(jsonReturn('超出最大可分配数量,最多可分配:'.$info[$typeName[$type]]));
}
Db::startTrans();
try{
// $isDec = $m->decNum(['userId'=>$userId],$typeName[$type],$data['num']);
// if($isDec){
$m->setTable('auth_company_partner');
$list = $m->getList(['userId'=>$userId,'dataFlag'=>1],'partnerId,stake');
$allNum = 0;
foreach ($list as &$v) {
$num = $data['num']*($v['stake']*0.01);
$allNum += $num;
Model('common/LogMoneys')->addMoneyLog(0,$v['partnerId'],0,2,'合作分配',1,$num,'invPay',$type);
}
Model('common/LogMoneys')->addMoneyLog(0,$userId,0,2,'合作分配',0,$allNum,'invPay',$type);
Db::commit();
exit(jsonReturn('操作成功',1));
//}
}catch (\Exception $e) {
Db::rollback();errLog($e);
}
exit(jsonReturn('操作超时,请重试'));
}
}
/**
* 我家朋友
*/
public function myFriendList($userId){
$userLevel = (int)input('post.userLevel/d');
$isLock = (int)input('post.isLock/d');
$rs = [];
if($isLock){
$rs = Db::name('users u')
->join('user_trees t','u.userId=t.uid')
->join('user_lock l','u.userId=l.userId')
->where(['t.pid'=>$userId,'u.userStatus'=>0,'u.userLevel'=>$userLevel])
->field('u.userId,u.trueName,u.userPhone,u.userLevel,l.lockReason,l.lockTime,from_unixtime(l.createTime) createTime')
->order('l.id DESC,u.userId DESC')
->paginate(input('pageSize/d'))->toArray();
}else{
$rs = Db::name('users u')
->join('user_trees t','u.userId=t.uid')
->where(['t.pid'=>$userId,'u.userStatus'=>1,'u.userLevel'=>$userLevel])
->field('u.userId,u.trueName,u.userPhone,u.userLevel,u.createTime')
->order('u.userId DESC')
->paginate(input('pageSize/d'))->toArray();
}
return $rs;
}
public function getHTTPS($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_REFERER, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
/**
* 用户登录验证
*/
public function checkLogin($loginSrc = 0){
$loginName = input("post.loginName");
$loginPwd = input("post.loginPwd");
$code = input("post.verifyCode");
$rememberPwd = input("post.rememberPwd",1);
// if(WSTVisitModule() == 'home'){//pc版的有验证码 mark 20170914
// if(!WSTVerifyCheck($code) && strpos(WSTConf("CONF.captcha_model"),"4")>=0){
// return WSTReturn('验证码错误!');
// }
// }
if(strlen($loginName) < 3 || strlen($loginPwd) < 3){
return WSTReturn('请输入用户名和密码!');
}
$ip = request()->ip();
if($loginSrc ==3 ){
$ticket = input('post.ticket');
$randstr = input('post.randstr');
if($ticket && $randstr){
try{
$url='https://ssl.captcha.qq.com/ticket/verify?aid=2089606583&AppSecretKey=02pqzvc15HUGyhYTAck38HQ**&Ticket='.$ticket.'&Randstr='.$randstr.'&UserIP='.$ip;
$check_captcha = $this->getHTTPS($url);
$check_captcha = json_decode($check_captcha);
if('1' !== $check_captcha->response){
if('fsdagsadfdsfsad3e3hg' != $ticket || 'hyjuoiyugsfae3fs887ts' != $randstr) return WSTReturn($check_captcha->err_msg);
}
} catch (\Exception $e) {
return WSTReturn($e->getMessage());
}
}else{
return WSTReturn('请先验证!');
}
}
$rs = $this->where("loginName|userPhone",$loginName)
->where(["dataFlag"=>1])
->find();
if(isset($rs['userStatus']) && 0 == $rs['userStatus']){//禁用状态
$lockInfo = Db::name('user_lock')->where(['userId'=>$rs['userId']])->field('lockReason,lockTime,createTime')->order('id DESC')->find();
if($lockInfo){
if(0 == $lockInfo['lockTime']){
return WSTReturn("账号已禁用,禁用原因:".$lockInfo['lockReason'].',禁用时间:永久');
}
$lockEndTime = $lockInfo['createTime']+($lockInfo['lockTime']*60);
if(time() >= $lockEndTime){//大于锁定时间
$this->where(['userId'=>$rs['userId']])->update(['userStatus'=>1]);
}else{
return WSTReturn("账号已禁用,禁用原因:".$lockInfo['lockReason'].',解禁日期:'.date('Y-m-d H:i:s',$lockEndTime));
}
}else{
return WSTReturn('账号已禁用,禁用原因:未知,禁用时间:永久');
}
}
//hook("beforeUserLogin",["user"=>&$rs]);
/**
* 添加整合登录插件 mark 20170829
*/
// if(empty($rs)){
// hook("beforeUserLogin",["user"=>&$rs]);
// }
/**
* end
*/
if(!empty($rs)){
if($rs['loginPwd']!=md5($loginPwd.$rs['loginSecret']))return WSTReturn("密码错误");
if($rs['userPhoto']=='')$rs['userPhoto'] = WSTConf('CONF.userLogo');
$userId = $rs['userId'];
//获取用户等级
$rrs = Db::name('user_ranks')->where(['dataFlag'=>1])->where('startScore','<=',$rs['userTotalScore'])->where('endScore','>=',$rs['userTotalScore'])->field('rankId,rankName,userrankImg')->find();
$rs['rankId'] = $rrs['rankId'];
$rs['rankName'] = $rrs['rankName'];
$rs['userrankImg'] = $rrs['userrankImg'];
if(input("post.typ")==2){
$shoprs=$this->where(["dataFlag"=>1, "userStatus"=>1,"userType"=>1,"userId"=>$userId])->find();
if(empty($shoprs)){
return WSTReturn('您还没申请店铺!');
}
}
$update = [];
$update = ["lastTime"=>date('Y-m-d H:i:s'),"lastIP"=>$ip];
$wxOpenId = session('WST_WX_OPENID');
if($wxOpenId){
$update['wxOpenId'] = $rs['wxOpenId'] = session('WST_WX_OPENID');
// 保存unionId【若存在】 详见 unionId说明 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140839
$userinfo = session('WST_WX_USERINFO');
$update['wxUnionId'] = isset($userinfo['unionid'])?$userinfo['unionid']:'';
}
$token='';
if($loginSrc ==3 ){//添加token mark hsf 20180212
$update['token'] = md5($userId.time().mt_rand(1,999));
$token = $update['token'] ;
}
$this->where(["userId"=>$userId])->update($update);
//如果是店铺则加载店铺信息
if($rs['userType']>=1){
// $shop = Db::name("shops s")
// ->join("__SHOP_USERS__ su","s.shopId=su.shopId")
// ->field("s.*,su.roleId")
// ->where(["su.userId"=>$userId,"s.dataFlag" =>1])->find();
// dump($shop);die;
/*---------修复商家登录不上 mark hsf 20180227 */
$shop = Db::name("shops s")
->join("__SHOP_USERS__ su","s.shopId=su.shopId")
->field("s.*,su.roleId")
->where(["su.userId"=>$userId,"s.dataFlag" =>1])->find();
if(empty($shop)){
$shop = Db::name("shops s")
->field("s.*")
->where(["s.userId"=>$userId,"s.dataFlag" =>1])->find();
}
if(!empty($shop))$rs = array_merge($shop,$rs->toArray());
/*---------end-------------*/
}
// //签到时间
// if(WSTConf('CONF.signScoreSwitch')==1){
// $rs['signScoreTime'] = 0;
// $userscores = Db::name('user_scores')->where(["userId"=>$userId,"dataSrc"=>5,])->order('createTime desc')->find();
// if($userscores)$rs['signScoreTime'] = date("Y-m-d",strtotime($userscores['createTime']));
// }
//记录登录日志
$data = array();
$data["userId"] = $userId;
$data["loginTime"] = date('Y-m-d H:i:s');
$data["loginIp"] = $ip;
$data['loginSrc'] = $loginSrc;
Db::name('log_user_logins')->insert($data);
$rd = $rs;
//记住密码
// $t = time();
// cookie("loginName", $loginName, $t+3600*24*90);
if($rememberPwd == "on"){
$datakey = md5($rs['loginName'])."_".md5($rs['loginPwd']);
$key = $rs['loginSecret'];
//加密
$base64 = new \org\Base64();
$loginKey = $base64->encrypt($datakey, $key);
//cookie("loginPwd", $loginKey, $t+3600*24*90);
}else{
// cookie("loginPwd", null);
}
session('WST_USER',$rs);
hook('afterUserLogin',['user'=>$rs]);
return WSTReturn("登录成功","1",['token'=>$token]);//添加返回token mark hsf 20170212
}
return WSTReturn("用户名或密码错误");
}
/**
* 会员注册
*/
public function regist($loginSrc = 0){
// return WSTReturn('注册频繁');
$data = array();
$data['loginName'] = input("post.loginName");
$data['loginPwd'] = input("post.loginPwd");
$data['reUserPwd'] = $data['loginPwd'] ;//input("post.reUserPwd");
$data['payPwd'] = input("post.payPwd");
$data['regConfirmImg'] = input("post.regConfirmImg");//注册确认书
$loginName = $data['loginName'];
if(!$data['regConfirmImg']){
return WSTReturn("请上传注册确认书!");
}
if($data['loginPwd']!=$data['reUserPwd']){
return WSTReturn("两次输入密码不一致!");
}
if(strlen($data['loginPwd']) < 6){
return WSTReturn("登录密码不可小于6位!");
}
if(strlen($data['payPwd']) < 6){
return WSTReturn("操作密码不可小于6位!");
}
foreach ($data as $v){
if($v ==''){
return WSTReturn("注册信息请填写完整!");
}
}
$nameType = (int)input("post.nameType");
$mobileCode = input("post.mobileCode");
// if(WSTVisitModule() !='home'){
// $code = input("post.verifyCode");
// if(!WSTVerifyCheck($code)){
// return WSTReturn("验证码错误!");
// }
// }
$pInfo['userId']=0;
//添加验证推荐人了 mark hsf 20171129
$pName = input('post.pName');
//if($pName){//写推荐人了
$pInfo = getUserByName($pName,'userId');
if(!$pInfo){
return WSTReturn("推荐人不存在!");
}
//}
$fp = fopen("reg.lock", "r");
if(flock($fp,LOCK_EX | LOCK_NB)) {//if(flock($fp,LOCK_EX))阻塞(等待)模式
//检测账号是否存在
$crs = WSTCheckLoginKey($loginName);
if($crs['status']!=1){
flock($fp,LOCK_UN);
fclose($fp);
return $crs;
}
//------end------//
// if($nameType==3 && WSTConf("CONF.smsOpen")==1){//手机号码
//if(WSTConf("CONF.smsOpen")==1){//手机号码
//$data['userPhone'] = $loginName;
$verify = session('VerifyCode_userPhone');
$startTime = (int)session('VerifyCode_userPhone_Time');
if((time()-$startTime)>120){
flock($fp,LOCK_UN);
fclose($fp);
return WSTReturn("验证码已超过有效期!");
}
if($mobileCode=="" || $verify != $mobileCode){
flock($fp,LOCK_UN);
fclose($fp);
return WSTReturn("短信验证码错误!");
}
//$loginName = WSTRandomLoginName($loginName);
// }else if($nameType==1){//邮箱注册
// $data['userEmail'] = $loginName;
// $unames = explode("@",$loginName);
// $loginName = WSTRandomLoginName($unames[0]);
// }else{
// flock($fp,LOCK_UN);
// fclose($fp);
// return WSTReturn("注册失败,请重试!");
// }
// if($loginName==''){
// flock($fp,LOCK_UN);
// fclose($fp);
// return WSTReturn("注册失败!");//分派不了登录名
// }
$data['loginName'] = $loginName;
unset($data['reUserPwd']);
unset($data['protocol']);
//检测账号,邮箱,手机是否存在
$data["loginSecret"] = '';//rand(1000,9999);
$data['loginPwd'] = md5($data['loginPwd'].$data['loginSecret']);
$data['payPwd'] = md5($data['payPwd'].$data['loginSecret']);
$data['userType'] = 0;
$data['userName'] = input("post.userName");
$data['userQQ'] = "";
$data['userScore'] = 0;
$data['userTotalScore'] = 0;
$data['createTime'] = date('Y-m-d H:i:s');
$data['dataFlag'] = 1;
$wxOpenId = session('WST_WX_OPENID');
if($wxOpenId){
$data['wxOpenId'] = session('WST_WX_OPENID');
$userinfo = session('WST_WX_USERINFO');
if($userinfo){
$data['userName'] = $userinfo['nickname'];
$data['userSex'] = $userinfo['sex'];
$data['userPhoto'] = $userinfo['headimgurl'];
// 保存unionId【若存在】 详见 unionId说明 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140839
$data['wxUnionId'] = isset($userinfo['unionid'])?$userinfo['unionid']:'';
}
}
Db::startTrans();
try{
$userId = $this->data($data)->save();
if(false !== $userId){
//保存注册信息
$userId = $this->userId;
$logData['userId']=$userId;
$logData['loginSrc']=$loginSrc;
$logData['createTime']=time();
$logResult = db('login_src')->insert($logData);
$data = array();
$ip = request()->ip();
$data['lastTime'] = date('Y-m-d H:i:s');
$data['lastIP'] = $ip;
$userId = $this->userId;
$this->where(["userId"=>$userId])->update($data);
//记录登录日志
// $data = array();
// $data["userId"] = $userId;
// $data["loginTime"] = date('Y-m-d H:i:s');
// $data["loginIp"] = $ip;
// $data['loginSrc'] = $loginSrc;
// Db::name('log_user_logins')->insert($data);
$user = $this->get($userId);
if($user['userPhoto']=='')$user['userPhoto'] = WSTConf('CONF.userLogo');
session('WST_USER',$user);
//注册成功后执行钩子
hook('afterUserRegist',['user'=>$user]);
//发送消息
$tpl = WSTMsgTemplates('USER_REGISTER');
if( $tpl['tplContent']!='' && $tpl['status']=='1'){
$find = ['${LOGIN_NAME}','${MALL_NAME}'];
$replace = [$user['loginName'],WSTConf('CONF.mallName')];
WSTSendMsg($userId,str_replace($find,$replace,$tpl['tplContent']),['from'=>0,'dataId'=>0]);
}
create_tree($userId,$pInfo['userId']);
Db::commit();
flock($fp,LOCK_UN);
fclose($fp);
return WSTReturn("注册成功",1);
}
}catch (\Exception $e) {
Db::rollback();errLog($e);
flock($fp,LOCK_UN);
fclose($fp);
}
return WSTReturn("注册失败!");
}else{
fclose($fp);
return WSTReturn('系统繁忙,请稍后再试');
}
}
/**
* 查询用户手机是否存在
*
*/
public function checkUserPhone($userPhone,$userId = 0,$field='userId'){
$dbo = Db::name('users')->where(["dataFlag"=>1, "userPhone"=>$userPhone]);
if($userId>0){
$dbo->where("userId","<>",$userId);
}
$rs = $dbo->field($field)->find();
if($rs){
return WSTReturn("手机号已存在!",-1,$rs);
}else{
/* 增加检测联盟手机号 mark 20170915*/
// if(getLMUserByName($userPhone)){
// return WSTReturn("手机号已存在!");
// }
/* end */
return WSTReturn("",1);
}
// $rs = $dbo->count();
// if($rs>0){
// return WSTReturn("手机号已存在!");
// }else{
// return WSTReturn("",1);
// }
}
/**
* 修改用户密码
*/
public function editPass($id){
$data = array();
$newPass = input("post.newPass");
$decrypt_data = WSTRSA($newPass);
if($decrypt_data['status']==1){
$newPass = $decrypt_data['data'];
}else{
return WSTReturn('修改失败');
}
if(!$newPass){
return WSTReturn('密码不能为空',-1);
}
$rs = $this->where('userId='.$id)->find();
//核对密码
if($rs['loginPwd']){
$oldPass = input("post.oldPass");
$decrypt_data2 = WSTRSA($oldPass);
if($decrypt_data2['status']==1){
$oldPass = $decrypt_data2['data'];
}else{
return WSTReturn('修改失败');
}
if($rs['loginPwd']==md5($oldPass.$rs['loginSecret'])){
$data["loginPwd"] = md5($newPass.$rs['loginSecret']);
$rs = $this->update($data,['userId'=>$id]);
if(false !== $rs){
hook("afterEditPass",["userId"=>$id]);
return WSTReturn("密码修改成功", 1);
}else{
return WSTReturn($this->getError(),-1);
}
}else{
return WSTReturn('原始密码错误',-1);
}
}else{
$data["loginPwd"] = md5($newPass.$rs['loginSecret']);
$rs = $this->update($data,['userId'=>$id]);
if(false !== $rs){
hook("afterEditPass",["userId"=>$id]);
return WSTReturn("密码修改成功", 1);
}else{
return WSTReturn($this->getError(),-1);
}
}
}
/**
* 修改用户支付密码
*/
public function editPayPass($id){
$data = array();
$newPass = input("post.newPass");
//添加二次密码验证 mark hsf 20180321
$reNewPass = input("post.reNewPass");
if($newPass != $reNewPass){
return WSTReturn('二次密码输入不一致,请重新输入!',-1);
}
//end
$decrypt_data = WSTRSA($newPass);
if($decrypt_data['status']==1){
$newPass = $decrypt_data['data'];
}else{
return WSTReturn('修改失败');
}
if(!$newPass){
return WSTReturn('支付密码不能为空',-1);
}
$rs = $this->where('userId='.$id)->find();
//核对密码
if($rs['payPwd']){
$oldPass = input("post.oldPass");
$decrypt_data2 = WSTRSA($oldPass);
if($decrypt_data2['status']==1){
$oldPass = $decrypt_data2['data'];
}else{
return WSTReturn('修改失败');
}
if($rs['payPwd']==md5($oldPass.$rs['loginSecret'])){
$data["payPwd"] = md5($newPass.$rs['loginSecret']);
$rs = $this->update($data,['userId'=>$id]);
if(false !== $rs){
return WSTReturn("支付密码修改成功", 1);
}else{
return WSTReturn("支付密码修改失败",-1);
}
}else{
return WSTReturn('原始支付密码错误',-1);
}
}else{
$data["payPwd"] = md5($newPass.$rs['loginSecret']);
$rs = $this->update($data,['userId'=>$id]);
if(false !== $rs){
return WSTReturn("支付密码设置成功", 1);
}else{
return WSTReturn("支付密码修改失败",-1);
}
}
}
/**
* 重置用户支付密码
*/
public function resetbackPay($uId=0){
$timeVerify = session('Verify_backPaypwd_Time');
if(time()>floatval($timeVerify)+10*60){
session('Type_backPaypwd',null);
return WSTReturn("校验码已失效,请重新验证!");
exit();
}
$data = array();
$data["payPwd"] = input("post.newPass");
$decrypt_data = WSTRSA($data["payPwd"]);
if($decrypt_data['status']==1){
$data["payPwd"] = $decrypt_data['data'];
}else{
return WSTReturn('修改失败');
}
if(!$data["payPwd"]){
return WSTReturn('支付密码不能为空',-1);
}
$userId = ($uId==0)?(int)session('WST_USER.userId'):$uId;
$rs = $this->where('userId='.$userId)->find();
$data["payPwd"] = md5($data["payPwd"].$rs['loginSecret']);
$rs = $this->update($data,['userId'=>$userId]);
if(false !== $rs){
session('Type_backPaypwd',null);
session('Verify_backPaypwd_info',null);
session('Verify_backPaypwd_Time',null);
return WSTReturn("支付密码设置成功", 1);
}else{
return WSTReturn("支付密码修改失败",-1);
}
}
/**
* 获取用户信息
*/
public function getById($id){
$rs = $this->get(['userId'=>(int)$id]);
$rs['ranks'] = WSTUserRank($rs['userTotalScore']);
return $rs;
}
/**
* 编辑资料
*/
public function edit(){
$Id = (int)session('WST_USER.userId');
$data = input('post.');
if(isset($data['brithday']))$data['brithday'] = ($data['brithday']=='')?date('Y-m-d'):$data['brithday'];
WSTAllow($data,'brithday,trueName,userName,userId,userPhoto,userQQ,userSex');
Db::startTrans();
try{
if(isset($data['userPhoto']) && $data['userPhoto']!='')
WSTUseImages(0, $Id, $data['userPhoto'],'users','userPhoto');
$result = $this->allowField(true)->save($data,['userId'=>$Id]);
if(false !== $result){
Db::commit();
return WSTReturn("编辑成功", 1);
}
}catch (\Exception $e) {
Db::rollback();errLog($e);
return WSTReturn('编辑失败',-1);
}
}
/**
* 绑定邮箱
*/
public function editEmail($userId,$userEmail){
$data = array();
$data["userEmail"] = $userEmail;
Db::startTrans();
try{
$user = Db::name('users')->where(["userId"=>$userId])->field(["userId","loginName,userEmail"])->find();
$rs = $this->update($data,['userId'=>$userId]);
if(false !== $rs){
hook("afterEditEmail",["user"=>$user]);
Db::commit();
return WSTReturn("绑定成功",1);
}else{
Db::rollback();errLog($e);
return WSTReturn("",-1);
}
}catch (\Exception $e) {
Db::rollback();errLog($e);
return WSTReturn('编辑失败',-1);
}
}
/**
* 绑定手机
*/
public function editPhone($userId,$userPhone){
$data = array();
$data["userPhone"] = $userPhone;
$rs = $this->update($data,['userId'=>$userId]);
if(false !== $rs){
return WSTReturn("绑定成功", 1);
}else{
return WSTReturn($this->getError(),-1);
}
}
/**
* 查询并加载用户资料
*/
public function checkAndGetLoginInfo($key){
if($key=='')return array();
$rs = $this->where(["loginName|userEmail|userPhone"=>['=',$key],'dataFlag'=>1])->find();
return $rs;
}
/**
* 重置用户密码
*/
public function resetPass($uId=0){
if(time()>floatval(session('REST_Time'))+30*60){
return WSTReturn("连接已失效!", -1);
}
$reset_userId = (int)session('REST_userId');
if($reset_userId==0){
return WSTReturn("无效的用户!", -1);
}
$user = $this->where(["dataFlag"=>1,"userStatus"=>1,"userId"=>$reset_userId])->find();
if(empty($user)){
return WSTReturn("无效的用户!", -1);
}
$loginPwd = input("post.loginPwd");
if($uId==0){// 大于0表示来自app端
$decrypt_data = WSTRSA($loginPwd);
if($decrypt_data['status']==1){
$loginPwd = $decrypt_data['data'];
}else{
return WSTReturn('修改失败');
}
}
if(trim($loginPwd)==''){
return WSTReturn("无效的密码!", -1);
}
$data['loginPwd'] = md5($loginPwd.$user["loginSecret"]);
$rc = $this->update($data,['userId'=>$reset_userId]);
if(false !== $rc){
hook("afterEditPass",["userId"=>$reset_userId]);//修改密码插件 mark 20170915
session('REST_userId',null);
session('REST_Time',null);
session('REST_success',null);
session('findPass',null);
return WSTReturn("修改成功", 1);
}
return $rs;
}
/**
* 获取用户可用惠宝
*/
public function getFieldsById($userId,$fields){
return $this->where(['userId'=>$userId,'dataFlag'=>1])->field($fields)->find();
}
/*获取用户分享列表*/
public function getShareList(){
$id=session('WST_USER.userId');
//普通用户分享列表
$userType=(int)input('userType');
//$userType=1;
if($userType=='0'){
$user_lists=Db::name('user_trees')->alias('a')->join('users b','b.userId=a.uid')
->where('a.pid',$id)->where('b.userType','0')->field('b.userId,b.loginName,b.createTime,b.userPhoto')->order('userId DESC')
->paginate(input('pagesize/d'))->toArray();
if(empty($user_lists)){
exit(jsonReturn('暂无分享用户',0));
}else{
foreach ($user_lists['Rows'] as &$v) {
if(!Db::name('log_user_logins')->where(['userId'=>$v['userId'],'loginSrc'=>3])->field('userId')->find()){
$v['isLogin'] = 0;
}else{
$v['isLogin'] = 1;
}
}
exit(json_encode($user_lists));
}
}elseif ($userType=='1') {
$merchants_lists=Db::name('user_trees')->alias('a')->join('users b','b.userId=a.uid')
->where('a.pid',$id)->where('b.userType','1')->field('b.userId,b.loginName,b.createTime,b.userPhoto')->order('userId DESC')
->paginate(input('pagesize/d'))->toArray();
if(empty($merchants_lists)){
exit(jsonReturn('暂无分享商家',0));
}else{
foreach ($merchants_lists['Rows'] as &$v) {
if(!Db::name('log_user_logins')->where(['userId'=>$v['userId'],'loginSrc'=>3])->field('userId')->find()){
$v['isLogin'] = 0;
}else{
$v['isLogin'] = 1;
}
}
exit(json_encode($merchants_lists));
}
}else{
exit(jsonReturn('请输入有效类型!',-1));
}
}
/*获取用户分享信息*/
public function getShareInfo(){
$userId=session('WST_USER.userId');
//普通用户分享列表
$userType=(int)input('userType');
if(in_array($userType, [0,1])){
$sid=(int)input('sid');
$data['ect']=Db::name('user_reward')->alias('r')
->join('__ORDERS__ o','o.orderId=r.orderId')
->where(['r.userId'=>$userId,'r.sid'=>$sid,'r.isSeller'=>$userType,'r.payType'=>1])
// ->group('r.orderId')
->field('SUM(o.realTotalMoney) order_num,SUM(r.rewardNum) reward_num')
->find();
$data['money']=Db::name('user_reward')->alias('r')
->join('__ORDERS__ o','o.orderId=r.orderId')
->where(['r.userId'=>$userId,'r.sid'=>$sid,'r.isSeller'=>$userType,'r.payType'=>2])
// ->group('r.orderId')
->field('SUM(o.realTotalMoney) order_num,SUM(r.rewardNum) reward_num')
->find();
exit(json_encode($data));
}else{
exit(jsonReturn('请输入有效类型!',-1));
}
}
function getUserStatusName($userStatus){
$statusName = '禁用';
switch($userStatus){
case 1:
$statusName = '正常';
break;
}
return $statusName;
}
function getUserLevelName($userLevel){
$levelName = '普通用户';
switch($userLevel){
case 1:
$levelName = '商户';
break;
case 2:
$levelName = '商超';
break;
case 3:
$levelName = '商厦';
break;
case 4:
$levelName = '商都';
break;
}
return $levelName;
}
function addUserVouchersSummary($expectedProductNum,$expectedCouponsNum){
}
}

393
hyhproject/common/taglib/Wst.php Executable file
View File

@ -0,0 +1,393 @@
<?php
/**
* ============================================================================
*/
namespace wstmart\common\taglib;
use think\template\TagLib;
class Wst extends TagLib{
/**
* 定义标签列表
*/
protected $tags = [
'friendlink' => ['attr' => 'num,key,id,cache'],
'ads' => ['attr' => 'code,num,key,id,cache'],
'article' => ['attr' => 'cat,num,key,id,cache'],
'goods' => ['attr' => 'type,cat,num,key,id,cache'],
'brand' => ['attr' => 'cat,num,key,id,cache'],
'shop' => ['attr' => 'cat,num,key,id,cache'],
'shopgoods' => ['attr' => 'type,shop,num,key,id,cache'],
'shopfloorgoods' => ['attr' => 'cat,shop,num,key,id,cache'],
'table'=>['table','where','num','order','field','id','key'],
'order' =>['attr'=>'type,num,key,id,cache,field'],
'favorite' =>['attr'=>'type,num,key,id,cache,field'],
'searchkey' => ['attr' => 'type,key,id,cache'],
'score' => ['attr'=>'cat,num,key,id,cache']
];
/**
* 单表查询操作标签
* table:表名
* where:查询条件
* num:limit
* order:排序条件
* field:需要取哪些字段
* key:序号
* id:循环中定义的元素变量
* {wst:table table="goods" field="goodsId,goodsName" num='6'}{/wst:table}
*/
public function tagTable($tag, $content){
$table = $tag['table'];
$where = isset($tag['where'])?$tag['where']:'0';
$order = isset($tag['order'])?$tag['order']:'0';
$field = isset($tag['field'])?$tag['field']:'*';
/*$catId = isset($tag['cat'])?$tag['cat']:0;
$flag = substr($catId, 0, 1);
if (':' == $flag) {
$catId = $this->autoBuildVar($catId);
$parseStr .= '$_result=' . $catId . ';';
$catId = '$_result';
} else {
$catId = $this->autoBuildVar($catId);
}*/
$id = isset($tag['id'])?$tag['id']:'vo';
$num = isset($tag['num'])?(int)$tag['num']:0;
$cache = isset($tag['cache'])?$tag['cache']:0;
$key = isset($tag['key'])?$tag['key']:'key';
$parse = '<?php ';
$parse .= '$wstTagGoods = model("common/Tags")->wstDb("'.$table.'","'.$where.'","'.$order.'","'.$field.'",'.$num.','.$cache.'); ';
$parse .= 'foreach($wstTagGoods as $'.$key.'=>$'.$id.'){';
$parse .= '?>';
$parse .= $content;
$parse .= '<?php } ?>';
return $parse;
}
/**
* 商品数据调用
* type:推荐/新品/热销/精品/浏览历史/看了又看 - recom/new/hot/best/history/visit
* cat:商品分类
* num:获取记录数量
* cache:缓存时间
* key:序号
* id:循环中定义的元素变量
* {wst:goods type='hot' cat='1' num='6'}{/wst:goods}
*/
public function tagGoods($tag, $content){
$type = $tag['type'];
$catId = isset($tag['cat'])?$tag['cat']:0;
$flag = substr($catId, 0, 1);
if (':' == $flag) {
$catId = $this->autoBuildVar($catId);
$parseStr .= '$_result=' . $catId . ';';
$catId = '$_result';
} else {
$catId = $this->autoBuildVar($catId);
}
$id = isset($tag['id'])?$tag['id']:'vo';
$num = isset($tag['num'])?(int)$tag['num']:0;
$cache = isset($tag['cache'])?$tag['cache']:0;
$key = isset($tag['key'])?$tag['key']:'key';
$parse = '<?php ';
$parse .= '$wstTagGoods = model("common/Tags")->listGoods("'.$type.'",'.$catId.','.$num.','.$cache.'); ';
$parse .= 'foreach($wstTagGoods as $'.$key.'=>$'.$id.'){';
$parse .= '?>';
$parse .= $content;
$parse .= '<?php } ?>';
return $parse;
}
/**
* 广告数据调用
* num:获取记录数量
* cache:缓存时间
* key:序号
* id:循环中定义的元素变量
* {wst:friendlink num='6'}{/wst:ads}
*/
public function tagFriendlink($tag, $content){
$id = isset($tag['id'])?$tag['id']:'vo';
$num = isset($tag['num'])?(int)$tag['num']:99;
$cache = isset($tag['cache'])?$tag['cache']:0;
$key = isset($tag['key'])?$tag['key']:'key';
$parse = '<?php ';
$parse .= '$wstTagFriendlink = model("common/Tags")->listFriendlink('.$num.','.$cache.'); ';
$parse .= 'foreach($wstTagFriendlink as $'.$key.'=>$'.$id.'){';
$parse .= '?>';
$parse .= $content;
$parse .= '<?php } ?>';
return $parse;
}
/**
* 广告数据调用
* code:广告代码
* num:获取记录数量
* cache:缓存时间
* key:序号
* id:循环中定义的元素变量
* {wst:ads code='1' cat='1' num='6'}{/wst:ads}
*/
public function tagAds($tag, $content){
$code = $tag['code'];
$id = isset($tag['id'])?$tag['id']:'vo';
$num = isset($tag['num'])?(int)$tag['num']:99;
$cache = isset($tag['cache'])?$tag['cache']:0;
$key = isset($tag['key'])?$tag['key']:'key';
$parse = '<?php ';
$parse .= '$wstTagAds = model("common/Tags")->listAds("'.$code.'",'.$num.','.$cache.'); ';
$parse .= 'foreach($wstTagAds as $'.$key.'=>$'.$id.'){';
$parse .= '?>';
$parse .= $content;
$parse .= '<?php } ?>';
return $parse;
}
/**
* 文章数据调用
* cat:文章分类ID 或者 'new'
* num:获取记录数量
* cache:缓存时间
* key:序号
* id:循环中定义的元素变量
* {wst:article cat='1' num='6'}{/wst:article}
*/
public function tagArticle($tag, $content){
$cat = $tag['cat'];
$id = isset($tag['id'])?$tag['id']:'vo';
$num = isset($tag['num'])?(int)$tag['num']:99;
$cache = isset($tag['cache'])?$tag['cache']:0;
$key = isset($tag['key'])?$tag['key']:'key';
$parse = '<?php ';
$parse .= '$wstTagArticle = model("common/Tags")->listArticle("'.$cat.'",'.$num.','.$cache.'); ';
$parse .= 'foreach($wstTagArticle as $'.$key.'=>$'.$id.'){';
$parse .= '?>';
$parse .= $content;
$parse .= '<?php } ?>';
return $parse;
}
/**
* 店铺商品数据调用
* type:推荐/新品/热销/精品 - recom/new/hot/best
* shop:店铺ID
* num:获取记录数量
* cache:缓存时间
* key:序号
* id:循环中定义的元素变量
* {wst:shopgoods name='hot' cat='1' num='6'}{/wst:goods}
*/
public function tagShopGoods($tag, $content){
$type = $tag['type'];
$shopId = isset($tag['shop'])?$tag['shop']:0;
$flag = substr($shopId, 0, 1);
if (':' == $flag) {
$shopId = $this->autoBuildVar($shopId);
$parseStr .= '$_result=' . $shopId . ';';
$shopId = '$_result';
} else {
$shopId = $this->autoBuildVar($shopId);
}
$id = isset($tag['id'])?$tag['id']:'vo';
$num = isset($tag['num'])?(int)$tag['num']:0;
$cache = isset($tag['cache'])?$tag['cache']:0;
$key = isset($tag['key'])?$tag['key']:'key';
$parse = '<?php ';
$parse .= '$wstTagShopGoods = model("common/Tags")->listShopGoods("'.$type.'",'.$shopId.','.$num.','.$cache.'); ';
$parse .= 'foreach($wstTagShopGoods as $'.$key.'=>$'.$id.'){';
$parse .= '?>';
$parse .= $content;
$parse .= '<?php } ?>';
return $parse;
}
/**
* 自营店铺楼层商品数据调用
* shop:店铺ID
* num:获取记录数量
* cache:缓存时间
* key:序号
* id:循环中定义的元素变量
* {wst:shopfloorgoods cat='1' num='6'}{/wst:shopfloorgoods}
*/
public function tagShopFloorGoods($tag, $content){
$catId = isset($tag['cat'])?$tag['cat']:0;
$flag = substr($catId, 0, 1);
if (':' == $flag) {
$catId = $this->autoBuildVar($catId);
$parseStr .= '$_result=' . $catId . ';';
$catId = '$_result';
} else {
$catId = $this->autoBuildVar($catId);
}
$shopId = isset($tag['shop'])?$tag['shop']:0;
$flag = substr($shopId, 0, 1);
if (':' == $flag) {
$shopId = $this->autoBuildVar($shopId);
$parseStr .= '$_result=' . $shopId . ';';
$shopId = '$_result';
} else {
$shopId = $this->autoBuildVar($shopId);
}
$id = isset($tag['id'])?$tag['id']:'vo';
$num = isset($tag['num'])?(int)$tag['num']:0;
$cache = isset($tag['cache'])?$tag['cache']:0;
$key = isset($tag['key'])?$tag['key']:'key';
$parse = '<?php ';
$parse .= '$wstTagShopFloorGoods = model("common/Tags")->listShopFloorGoods('.$catId.','.$shopId.','.$num.','.$cache.'); ';
$parse .= 'foreach($wstTagShopFloorGoods as $'.$key.'=>$'.$id.'){';
$parse .= '?>';
$parse .= $content;
$parse .= '<?php } ?>';
return $parse;
}
/**
* 品牌数据调用
* cat:分类ID
* num:获取记录数量
* cache:缓存时间
* key:序号
* id:循环中定义的元素变量
* {wst:brand cat='1' num='6'}{/wst:brand}
*/
public function tagBrand($tag, $content){
$cat = $tag['cat'];
$id = isset($tag['id'])?$tag['id']:'vo';
$num = isset($tag['num'])?(int)$tag['num']:99;
$cache = isset($tag['cache'])?$tag['cache']:0;
$key = isset($tag['key'])?$tag['key']:'key';
$parse = '<?php ';
$parse .= '$wstTagBrand = model("common/Tags")->listBrand('.$cat.','.$num.','.$cache.'); ';
$parse .= 'foreach($wstTagBrand as $'.$key.'=>$'.$id.'){';
$parse .= '?>';
$parse .= $content;
$parse .= '<?php } ?>';
return $parse;
}
/**
* 店铺数据调用
* cat:分类ID
* num:获取记录数量
* cache:缓存时间
* key:序号
* id:循环中定义的元素变量
* {wst:shop cat='1' num='6'}{/wst:shop}
*/
public function tagShop($tag, $content){
$cat = $tag['cat'];
$id = isset($tag['id'])?$tag['id']:'vo';
$num = isset($tag['num'])?(int)$tag['num']:99;
$cache = isset($tag['cache'])?$tag['cache']:0;
$key = isset($tag['key'])?$tag['key']:'key';
$parse = '<?php ';
$parse .= '$wstTagShop = model("common/Tags")->listShop('.$cat.','.$num.','.$cache.'); ';
$parse .= 'foreach($wstTagShop as $'.$key.'=>$'.$id.'){';
$parse .= '?>';
$parse .= $content;
$parse .= '<?php } ?>';
return $parse;
}
/**
* 订单数据调用
* type:订单访问者类型可选值为user或者shop
* num:获取记录数量
* cache:缓存时间
* key:序号
* id:循环中定义的元素变量
*fields:需要读取的订单字段
* {wst:order type='user' ownId='1' num='6'}{/wst:order}
*/
public function tagOrder($tag, $content){
$type = isset($tag['type'])?$tag['type']:'';
$id = isset($tag['id'])?$tag['id']:'vo';
$num = isset($tag['num'])?(int)$tag['num']:99;
$cache = isset($tag['cache'])?$tag['cache']:0;
$key = isset($tag['key'])?$tag['key']:'key';
$fields = isset($tag['field'])?$tag['field']:'';
$parse = '<?php ';
$parse .= '$wstTagOrder = model("common/Tags")->listOrder("'.$type.'",'.$num.','.$cache.',"'.$fields.'"); ';
$parse .= 'foreach($wstTagOrder as $'.$key.'=>$'.$id.'){';
$parse .= '?>';
$parse .= $content;
$parse .= '<?php } ?>';
return $parse;
}
/**
* 搜索关键词数据调用
* type:0只获取关键词1获取关键词和搜索关键词的搜索数
* cache:缓存时间
* key:序号
* id:循环中定义的元素变量
* {wst:searchkey type='0' num='6'}{/wst:searchkey}
*/
public function tagSearchkey($tag, $content){
$type = $tag['type'];
$id = isset($tag['id'])?$tag['id']:'vo';
$cache = isset($tag['cache'])?$tag['cache']:0;
$key = isset($tag['key'])?$tag['key']:'key';
$parse = '<?php ';
$parse .= '$wstTagSearchkey = model("common/Tags")->listSearchkey('.$type.','.$cache.'); ';
$parse .= 'foreach($wstTagSearchkey as $'.$key.'=>$'.$id.'){';
$parse .= '?>';
$parse .= $content;
$parse .= '<?php } ?>';
return $parse;
}
/**
* 收藏商品/商家数据调用
* type:收藏类型可选值为goods或者shop
* num:获取记录数量
* cache:缓存时间
* key:序号
* id:循环中定义的元素变量
*fields:需要读取的记录字段
* {wst:favorite type='user' ownId='1' num='6'}{/wst:order}
*/
public function tagFavorite($tag, $content){
$type = isset($tag['type'])?$tag['type']:'';
$id = isset($tag['id'])?$tag['id']:'vo';
$num = isset($tag['num'])?(int)$tag['num']:99;
$key = isset($tag['key'])?$tag['key']:'key';
$fields = isset($tag['field'])?$tag['field']:'';
$parse = '<?php ';
$parse .= '$wstTagFavorite = model("common/Tags")->listFavorite("'.$type.'",'.$num.',"'.$fields.'"); ';
$parse .= 'foreach($wstTagFavorite as $'.$key.'=>$'.$id.'){';
$parse .= '?>';
$parse .= $content;
$parse .= '<?php } ?>';
return $parse;
}
/**
* 高评分商品数据调用
* cat:分类ID
* num:获取记录数量
* cache:缓存时间
* key:序号
* id:循环中定义的元素变量
* {wst:score type='0' num='6'}{/wst:score}
*/
public function tagScore($tag, $content){
$cat = $tag['cat'];
$id = isset($tag['id'])?$tag['id']:'vo';
$num = isset($tag['num'])?(int)$tag['num']:99;
$cache = isset($tag['cache'])?$tag['cache']:0;
$key = isset($tag['key'])?$tag['key']:'key';
$parse = '<?php ';
$parse .= '$wstTagScore = model("common/Tags")->listScore('.$cat.','.$num.','.$cache.'); ';
$parse .= 'foreach($wstTagScore as $'.$key.'=>$'.$id.'){';
$parse .= '?>';
$parse .= $content;
$parse .= '<?php } ?>';
return $parse;
}
}

View File

@ -0,0 +1,115 @@
<?php
namespace wstmart\common\validate;
use think\Validate;
/**
* ============================================================================
* 认证验证器
*/
class Auth extends Validate{
protected $rule = [
['headImg' ,'require','请上传头像'],
['householdName' ,'require|chs','请输入户主名|请输入汉字'],
['householdIdCard' ,'require|validation_filter_id_card','请输入身份证号|身份证号错误'],
['houseAddress' ,'require','请输入居住地址'],
['accountBookImg' ,'require','请上传手持户口簿主页照片'],
['payPwd' ,'require','请输入操作密码'],
['companyName' ,'require|chs','请输入合作名|请输入汉字'],
['trueName' ,'require|chs','请输入姓名|请输入汉字'],
['idCard' ,'require|validation_filter_id_card','请输入身份证号|身份证号错误'],
['companyAddress' ,'require','请输入公司地址'],
['familyName' ,'require|chs','请输入姓名|请输入汉字'],
['familyIdCard' ,'require|validation_filter_id_card','请输入身份证号|身份证号错误'],
['familyRelations' ,'require','请输入与户主关系'],
['familyRelationsImg' ,'require','请上传户主关系证明照'],
['idCardFrontImg' ,'require','请上传身份证正面照'],
['idCardBackImg' ,'require','请上传身份证反面照'],
['mobileCode' ,'require|length:4','请输入验证码'],
['bankName' ,'require|chs','请输入银行名|请输入汉字'],
['accountName' ,'require|chs','请输入开户名|请输入汉字'],
['bankNo' ,'require','请输入银行卡号'],
['uName' ,'require|chs','请输入姓名|请输入汉字'],
['positionName' ,'require|chs','请输入职位名|请输入汉字'],
['businessImg' ,'require','请上传手执营业执照照片'],
['stake' ,'require|between:1,100','请输入持股比例|持股比例范围为1-100']
];
protected $scene = [
'personal' => ['headImg','householdName','householdIdCard','houseAddress','accountBookImg'],//个人实名认证
'company' => ['headImg','companyName','trueName','idCard','companyAddress'],//合作实名认证
'report' => ['familyName','familyIdCard','familyRelations','familyRelationsImg'],//亲人报备
'family' => ['familyRelations','familyRelationsImg','idCardFrontImg','idCardBackImg'],//亲人认证
'bank' => ['bankName','accountName','bankNo'],//添加银行卡
'partner' => ['positionName','stake','businessImg','idCardFrontImg','idCardBackImg'],//合作人认证
];
// 自定义验证规则
// protected function checkName($value,$rule,$data)
// {
// return $rule == $value ? true : '名称错误';
// }
/**
* 身份证验证 start
*/
function validation_filter_id_card($id_card){
if(strlen($id_card)==18){
return $this->idcard_checksum18($id_card);
}elseif((strlen($id_card)==15)){
$id_card=$this->idcard_15to18($id_card);
return $this->idcard_checksum18($id_card);
}else{
return false;
}
}
// 计算身份证校验码根据国家标准GB 11643-1999
function idcard_verify_number($idcard_base){
if(strlen($idcard_base)!=17){
return false;
}
//加权因子
$factor=array(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2);
//校验码对应值
$verify_number_list=array('1','0','X','9','8','7','6','5','4','3','2');
$checksum=0;
for($i=0;$i<strlen($idcard_base);$i++){
$checksum += substr($idcard_base,$i,1) * $factor[$i];
}
$mod=$checksum % 11;
$verify_number=$verify_number_list[$mod];
return $verify_number;
}
// 将15位身份证升级到18位
function idcard_15to18($idcard){
if(strlen($idcard)!=15){
return false;
}else{
// 如果身份证顺序码是996 997 998 999这些是为百岁以上老人的特殊编码
if(array_search(substr($idcard,12,3),array('996','997','998','999')) !== false){
$idcard=substr($idcard,0,6).'18'.substr($idcard,6,9);
}else{
$idcard=substr($idcard,0,6).'19'.substr($idcard,6,9);
}
}
$idcard=$idcard.$this->idcard_verify_number($idcard);
return $idcard;
}
// 18位身份证校验码有效性检查
function idcard_checksum18($idcard){
if(strlen($idcard)!=18){
return false;
}
$idcard_base=substr($idcard,0,17);
if($this->idcard_verify_number($idcard_base)!=strtoupper(substr($idcard,17,1))){
return false;
return $user;
}else{
return true;
}
}
/***身份证验证 end */
}

View File

@ -0,0 +1,20 @@
<?php
namespace wstmart\common\validate;
use think\Validate;
/**
* ============================================================================
* 提现账号验证器
*/
class CashConfigs extends Validate{
protected $rule = [
['accTargetId' ,'require','请选择开卡银行'],
['accAreaId' ,'require','请选择开卡地区'],
['accNo' ,'require','请输入银行卡号'],
['accUser' ,'require','请输入持卡人']
];
protected $scene = [
'add' => ['accTargetId','accNo','accUser'],
'edit' => ['accTargetId','accNo','accUser']
];
}

View File

@ -0,0 +1,16 @@
<?php
namespace wstmart\common\validate;
use think\Validate;
/**
* ============================================================================
* 用户电子钱包地址验证器
*/
class EctWallet extends Validate{
protected $rule= [
['eAddress','require|length:42','地址不能为空|长度不符合']
];
protected $scene = [
'add' => ['eAddress'],
'edit'=> ['eAddress']
];
}

View File

@ -0,0 +1,19 @@
<?php
namespace wstmart\common\validate;
use think\Validate;
/**
* ============================================================================
* 评价验证器
*/
class GoodsAppraises extends Validate{
protected $rule = [
['goodsScore' ,'between:1,5','评分必须在1-5之间'],
['serviceScore' ,'between:1,5','评分必须在1-5之间'],
['timeScore' ,'between:1,5','评分必须在1-5之间'],
['content' ,'require|length:3,600','点评内容不能为空|点评内容应为3-200个字'],
];
protected $scene = [
'add' => ['goodsScore','serviceScore','timeScore','content'],
];
}

View File

@ -0,0 +1,19 @@
<?php
namespace wstmart\common\validate;
use think\Validate;
/**
* ============================================================================
* 商品咨询验证器
*/
class GoodsConsult extends Validate{
protected $rule = [
['consultContent' ,'require|length:3,600','请输入咨询内容|咨询内容应为3-200个字'],
['consultType' ,'in:1,2,3,4','请选择咨询类别'],
['reply' ,'require|length:3,600','请输入回复内容|回复内容应为3-200个字']
];
protected $scene = [
'add' => ['consultContent','consultType'],
'edit' => ['reply']
];
}

View File

@ -0,0 +1,20 @@
<?php
namespace wstmart\common\validate;
use think\Validate;
/**
* ============================================================================
* 订单投诉验证器
*/
class Informs extends Validate{
protected $rule = [
['informType' ,'in:1,2,3,4','无效的投诉类型!'],
['informContent' ,'require|length:3,600','投诉内容不能为空|投诉内容应为3-200个字'],
['respondContent' ,'require|length:3,600','应诉内容不能为空|应诉内容应为3-200个字'],
];
protected $scene = [
'add' => ['informType','informContent'],
'edit' => ['informType','informContent'],
'respond' =>['respondContent'],
];
}

View File

@ -0,0 +1,17 @@
<?php
namespace wstmart\common\validate;
use think\Validate;
/**
* ============================================================================
* 发票信息验证器
*/
class Invoices extends Validate{
protected $rule = [
['invoiceHead' ,'require','请输入发票抬头'],
];
protected $scene = [
'add' => ['invoiceHead'],
'edit' => ['invoiceHead'],
];
}

View File

@ -0,0 +1,20 @@
<?php
namespace wstmart\common\validate;
use think\Validate;
/**
* ============================================================================
* 订单投诉验证器
*/
class OrderComplains extends Validate{
protected $rule = [
['complainType' ,'in:1,2,3,4','无效的投诉类型!'],
['complainContent' ,'require|length:3,600','投诉内容不能为空|投诉内容应为3-200个字'],
['respondContent' ,'require|length:3,600','应诉内容不能为空|应诉内容应为3-200个字'],
];
protected $scene = [
'add' => ['complainType','complainContent'],
'edit' => ['complainType','complainContent'],
'respond' =>['respondContent'],
];
}

View File

@ -0,0 +1,18 @@
<?php
namespace wstmart\common\validate;
use think\Validate;
/**
* ============================================================================
* 门店分类验证器
*/
class ShopCats extends Validate{
protected $rule = [
['catName' ,'require|max:60','请输入分类名称|分类名称不能超过20个字符'],
['parentId' ,'number','无效的父级分类']
];
protected $scene = [
'add' => ['catName','parentId'],
'edit' => ['catName'],
];
}

View File

@ -0,0 +1,112 @@
<?php
namespace wstmart\common\validate;
use think\Validate;
/**
* ============================================================================
* 店铺验证器
*/
class Shops extends Validate{
protected $rule = [
//申请入驻
['shopName' ,'require','请输入店铺名'],
['userName' ,'require|chs','请输入直营人姓名|直营人姓名请输入汉字'],
['phone' ,'require','请输入联系电话'],
['provinceId' ,'require','请选择省'],
['cityId' ,'require','请选择市'],
['countyId' ,'require','请选择区县'],
['townId' ,'require','请选择乡镇'],
['villageId' ,'require','请选择村社区'],
['shopAddress' ,'require','请输入店铺地址'],
['lng' ,'require','请在地图点击坐标'],
['lat' ,'require','请在地图点击坐标'],
['bankName' ,'require|chs','请输入银行名|银行名请输入汉字'],
['accountName' ,'require|chs','请输入开户名|开户名请输入汉字'],
['bankNo' ,'require','请输入银行卡号'],
['idCardFrontImg' ,'require','请上传身份证正面照'],
['idCardBackImg' ,'require','请上传身份证反面照'],
['commissionImg' ,'require','请上传直营人委托书照片'],
['businessLicenceImg' ,'require','请上传手持身份证和营业执照,背影为店铺照片'],
['confirmationImg' ,'require','请上传确认书照片'],
//上传产品
['goodsName' ,'require','请输入产品名'],
['largeCat' ,'require|number','请选择一级分类|请选择一级分类!'],
['mediumCat' ,'require|number','请选择二级分类|请选择二级分类!'],
['smallCat' ,'require|number','请选择三级分类|请选择三级分类!'],
['discountRate' ,'require|float|between:0,100','请输入优惠率|请输入优惠率!|优惠率范围0%-100%'],
['freight' ,'require|float','请输入运费|请输入运费!'],
['goodsImg' ,'require','请上传商品主图'],
['gallery' ,'require','请上传商品相册'],
['isSale' ,'require|in:0,1','请选择商品通过审核后上下架|请选择商品通过审核后上下架!'],
];
protected $scene = [
'join' => ['shopName','userName','phone','provinceId','cityId','countyId','townId','villageId','shopAddress','lng','lat','bankName','accountName','bankNo','idCardFrontImg','idCardBackImg','commissionImg','businessLicenceImg','confirmationImg'],//商家入驻人认证
'addGoods'=>['goodsName' ,'largeCat','mediumCat' ,'smallCat', 'discountRate' ,'freight' ,'goodsImg' ,'gallery' ,'isSale'],
];
// 自定义验证规则
// protected function checkName($value,$rule,$data)
// {
// return $rule == $value ? true : '名称错误';
// }
/**
* 身份证验证 start
*/
function validation_filter_id_card($id_card){
if(strlen($id_card)==18){
return $this->idcard_checksum18($id_card);
}elseif((strlen($id_card)==15)){
$id_card=$this->idcard_15to18($id_card);
return $this->idcard_checksum18($id_card);
}else{
return false;
}
}
// 计算身份证校验码根据国家标准GB 11643-1999
function idcard_verify_number($idcard_base){
if(strlen($idcard_base)!=17){
return false;
}
//加权因子
$factor=array(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2);
//校验码对应值
$verify_number_list=array('1','0','X','9','8','7','6','5','4','3','2');
$checksum=0;
for($i=0;$i<strlen($idcard_base);$i++){
$checksum += substr($idcard_base,$i,1) * $factor[$i];
}
$mod=$checksum % 11;
$verify_number=$verify_number_list[$mod];
return $verify_number;
}
// 将15位身份证升级到18位
function idcard_15to18($idcard){
if(strlen($idcard)!=15){
return false;
}else{
// 如果身份证顺序码是996 997 998 999这些是为百岁以上老人的特殊编码
if(array_search(substr($idcard,12,3),array('996','997','998','999')) !== false){
$idcard=substr($idcard,0,6).'18'.substr($idcard,6,9);
}else{
$idcard=substr($idcard,0,6).'19'.substr($idcard,6,9);
}
}
$idcard=$idcard.$this->idcard_verify_number($idcard);
return $idcard;
}
// 18位身份证校验码有效性检查
function idcard_checksum18($idcard){
if(strlen($idcard)!=18){
return false;
}
$idcard_base=substr($idcard,0,17);
if($this->idcard_verify_number($idcard_base)!=strtoupper(substr($idcard,17,1))){
return false;
return $user;
}else{
return true;
}
}
/***身份证验证 end */
}

View File

@ -0,0 +1,21 @@
<?php
namespace wstmart\common\validate;
use think\Validate;
/**
* ============================================================================
* 用户地址验证器
*/
class UserAddress extends Validate{
protected $rule = [
['areaId' ,'require','请选择地址'],
['userAddress' ,'require','请输入详细地址'],
['userName' ,'require','请输入联系名称'],
['isDefault' ,'in:0,1','请选择是否默认地址'],
['userPhone' ,'require','请输入联系电话'],
];
protected $scene = [
'add' => ['areaId','userAddress','userName','isDefault','userPhone'],
'edit' => ['areaId','userAddress','userName','isDefault','userPhone'],
];
}