-
@@ -124,6 +124,7 @@
+{/block}
+
\ No newline at end of file
diff --git a/app/common/model/merchant/common.php b/app/common/model/merchant/common.php
new file mode 100644
index 0000000..b61090b
--- /dev/null
+++ b/app/common/model/merchant/common.php
@@ -0,0 +1,899 @@
+
+// +----------------------------------------------------------------------
+
+// 应用公共文件
+
+use app\common\model\merchant\system\config\SystemConfigValue;
+// use app\common\model\merchant\system\groupData\GroupData;
+// use crmeb\services\UploadService;
+// use Swoole\Lock;
+use think\db\BaseQuery;
+
+if (!function_exists('isDebug')) {
+ function isDebug(): bool
+ {
+ return !!env('APP_DEBUG');
+ }
+}
+
+if (!function_exists('formToData')) {
+ function formToData($form): array
+ {
+ $rule = $form->formRule();
+ $action = $form->getAction();
+ $method = $form->getMethod();
+ $title = $form->getTitle();
+ $config = (object)$form->formConfig();
+ $admin = config('admin.api_admin_prefix');
+ $merchant = config('admin.api_merchant_prefix');
+ $api = $action;
+ if (strpos($api, '/' . $admin) === 0) {
+ $api = substr($api, strlen($admin) + 1);
+ } else if (strpos($api, '/' . $merchant) === 0) {
+ $api = substr($api, strlen($merchant) + 1);
+ }
+ $api = str_replace('.html', '', $api);
+ return compact('rule', 'action', 'method', 'title', 'config', 'api');
+ }
+}
+
+if (!function_exists('getDistance')) {
+
+ function getDistance($lat1, $lng1, $lat2, $lng2)
+ {
+ //将角度转为狐度
+ $radLat1 = deg2rad($lat1); //deg2rad()函数将角度转换为弧度
+ $radLat2 = deg2rad($lat2);
+ $radLng1 = deg2rad($lng1);
+ $radLng2 = deg2rad($lng2);
+ $a = $radLat1 - $radLat2;
+ $b = $radLng1 - $radLng2;
+ $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6371;
+ return round($s, 1);
+ }
+}
+
+/**
+ * 无线级分类处理
+ *
+ * @param array $data 数据源
+ * @param string $idName 主键
+ * @param string $fieldName 父级字段
+ * @param string $childrenKey 子级字段名
+ * @return array
+ * @author 张先生
+ * @date 2020-03-27
+ */
+if (!function_exists('formatCategory')) {
+ function formatCategory(array $data, string $idName = "id", string $fieldName = 'pid', $childrenKey = 'children')
+ {
+ $items = [];
+ foreach ($data as $item) {
+ $items[$item[$idName]] = $item;
+ }
+ $result = array();
+ foreach ($items as $item) {
+ if (isset($items[$item[$fieldName]])) {
+ $items[$item[$fieldName]][$childrenKey][] = &$items[$item[$idName]];
+ } else if ($item[$fieldName] == 0) {
+ $result[] = &$items[$item[$idName]];
+ }
+ }
+ return $result;
+ }
+}
+
+if (!function_exists('formatTreeList')) {
+ function formatTreeList(&$options, $name, $pidName = 'pid', $pid = 0, $level = 0, &$data = []): array
+ {
+ $_options = $options;
+ foreach ($_options as $k => $option) {
+ if ($option[$pidName] == $pid) {
+ $data[] = ['value' => $k, 'label' => str_repeat('|---', $level + 1) . $option[$name]];
+ unset($options[$k]);
+ formatTreeList($options, $name, $pidName, $k, $level + 1, $data);
+ }
+ }
+ return $data;
+ }
+}
+
+if (!function_exists('formatTree')) {
+ function formatTree(&$options, $name, $pidName = 'pid', $pid = 0, $level = 0, $data = []): array
+ {
+ $_options = $options;
+ foreach ($_options as $k => $option) {
+ if ($option[$pidName] == $pid) {
+ $value = ['id' => $k, 'title' => $option[$name]];
+ unset($options[$k]);
+ $value['children'] = formatTree($options, $name, $pidName, $k, $level + 1);
+ $data[] = $value;
+ }
+ }
+ return $data;
+ }
+}
+
+if (!function_exists('formatCascaderData')) {
+ function formatCascaderData(&$options, $name, $baseLevel = 0, $pidName = 'pid', $pid = 0, $level = 0, $data = []): array
+ {
+ $_options = $options;
+ foreach ($_options as $k => $option) {
+ if ($option[$pidName] == $pid) {
+ $value = ['value' => $k, 'label' => $option[$name]];
+ unset($options[$k]);
+ $value['children'] = formatCascaderData($options, $name, $baseLevel, $pidName, $k, $level + 1);
+ if (!count($value['children'])) unset($value['children']);
+ $data[] = $value;
+ }
+ }
+ return $data;
+ }
+}
+
+
+/**
+ * @function toMap 数组重新组装
+ * @param array $data 数据
+ * @param string $field key
+ * @param string $value value default null
+ * @return array
+ * @author 张先生
+ * @date 2020-04-01
+ */
+if (!function_exists('toMap')) {
+ function toMap(array $data, $field = 'id', $value = '')
+ {
+ $result = array();
+
+ if (empty($data)) {
+ return $result;
+ }
+
+ //开始处理数据
+ foreach ($data as $item) {
+ $val = $item;
+ if (!empty($value)) {
+ $val = $item[$value];
+ }
+ $result[$item[$field]] = $val;
+ }
+
+ return $result;
+ }
+}
+
+/**
+ * @function getUniqueListByArray 从数组中获取某个字段的值,重新拼装成新的一维数组
+ * @param array $data 数据
+ * @param string $field key
+ * @return array
+ * @author 张先生
+ * @date 2020-04-01
+ */
+if (!function_exists('getUniqueListByArray')) {
+ function getUniqueListByArray(array $data, $field = 'id')
+ {
+ return array_unique(array_values(array_column($data, $field)));
+ }
+}
+
+
+if (!function_exists('isPhone')) {
+ function isPhone($test)
+ {
+ return !preg_match("/^1[3456789]{1}\d{9}$/", $test);
+ }
+}
+
+if (!function_exists('getMonth')) {
+ /**
+ * 获取本季度 time
+ * @param int|string $time
+ * @param $ceil
+ * @return array
+ */
+ function getMonth($time = '', $ceil = 0)
+ {
+ if ($ceil != 0)
+ $season = ceil(date('n') / 3) - $ceil;
+ else
+ $season = ceil(date('n') / 3);
+ $firstday = date('Y-m-01', mktime(0, 0, 0, ($season - 1) * 3 + 1, 1, date('Y')));
+ $lastday = date('Y-m-t', mktime(0, 0, 0, $season * 3, 1, date('Y')));
+ return array($firstday, $lastday);
+ }
+}
+
+
+if (!function_exists('getModelTime')) {
+ /**
+ * @param BaseQuery $model
+ * @param string $section
+ * @param string $prefix
+ * @param string $field
+ * @return mixed
+ * @author xaboy
+ * @day 2020-04-29
+ */
+ function getModelTime(BaseQuery $model, string $section, $prefix = 'create_time', $field = '-',$time = '')
+ {
+ if (!isset($section)) return $model;
+ switch ($section) {
+ case 'today':
+ $model->whereBetween($prefix, [date('Y-m-d H:i:s', strtotime('today')), date('Y-m-d H:i:s', strtotime('tomorrow -1second'))]);
+ break;
+ case 'week':
+ $model->whereBetween($prefix, [date('Y-m-d H:i:s', strtotime('this week 00:00:00')), date('Y-m-d H:i:s', strtotime('next week 00:00:00 -1second'))]);
+ break;
+ case 'month':
+ $model->whereBetween($prefix, [date('Y-m-d H:i:s', strtotime('first Day of this month 00:00:00')), date('Y-m-d H:i:s', strtotime('first Day of next month 00:00:00 -1second'))]);
+ break;
+ case 'year':
+ $model->whereBetween($prefix, [date('Y-m-d H:i:s', strtotime('this year 1/1')), date('Y-m-d H:i:s', strtotime('next year 1/1 -1second'))]);
+ break;
+ case 'yesterday':
+ $model->whereBetween($prefix, [date('Y-m-d H:i:s', strtotime('yesterday')), date('Y-m-d H:i:s', strtotime('today -1second'))]);
+ break;
+ case 'quarter':
+ list($startTime, $endTime) = getMonth();
+ $model = $model->where($prefix, '>', $startTime);
+ $model = $model->where($prefix, '<', $endTime);
+ break;
+ case 'lately7':
+ $model = $model->where($prefix, 'between', [date('Y-m-d', strtotime("-7 day")), date('Y-m-d H:i:s')]);
+ break;
+ case 'lately30':
+ $model = $model->where($prefix, 'between', [date('Y-m-d', strtotime("-30 day")), date('Y-m-d H:i:s')]);
+ break;
+ default:
+ if (strstr($section, $field) !== false) {
+ list($startTime, $endTime) = explode($field, $section);
+ if (strlen($startTime) == 4) {
+ $model->whereBetweenTime($prefix, date('Y-m-d H:i:s', strtotime($section)), date('Y-m-d H:i:s', strtotime($section . ' +1day -1second')));
+ } else {
+ if ($startTime == $endTime) {
+ $model = $model->whereBetweenTime($prefix, date('Y-m-d 0:0:0', strtotime($startTime)), date('Y-m-d 23:59:59', strtotime($endTime)));
+ } else if(strpos($startTime, ':')) {
+ $model = $model->whereBetweenTime($prefix, $startTime, $endTime);
+ } else {
+ $model = $model->whereBetweenTime($prefix, date('Y-m-d H:i:s', strtotime($startTime)), date('Y-m-d H:i:s', strtotime($endTime . ' +1day -1second')));
+ }
+ }
+ }
+ break;
+ }
+ return $model;
+ }
+}
+
+if (!function_exists('hasMany')) {
+ function hasMany($collection, $field, $model, $searchKey, $insertKey, $where = [] ,$select = '*')
+ {
+ $ids = [];
+ $link = [];
+
+ if (!$collection) return [];
+ $collection = $collection->toArray();
+ foreach ($collection as $k => $item) {
+ if (is_array($item[$field])) {
+ $link[$k] = array_unique($item[$field]);
+ $ids = array_merge($item[$field], $ids);
+ } else {
+ $link[$k] = array_unique(explode(',', $item[$field]));
+ }
+ $ids = array_merge($link[$k], $ids);
+ if (isset($collection[$k][$insertKey])) unset($collection[$k][$insertKey]);
+ }
+ $ids = array_filter(array_unique($ids));
+ if (!count($ids)) {
+ return $collection;
+ }
+ $many = $model::whereIn($searchKey, array_unique($ids))->where($where)->field($select)->select();
+
+ if (!$many) return $collection;
+ $many = $many->toArray();
+ foreach ($link as $k => $val) {
+ foreach ($many as $item) {
+ if (in_array($item[$searchKey], $val)) {
+
+ if (!isset($collection[$k][$insertKey])) $collection[$k][$insertKey] = [];
+
+ $collection[$k][$insertKey][] = $item;
+ }
+ }
+ }
+
+ return $collection;
+ }
+}
+
+if (!function_exists('activeProductSku')) {
+ //格式活动商品SKU
+ function activeProductSku($activeData, $type = null)
+ {
+ $make = app()->make(\app\common\model\merchant\store\product\Product::class);
+ $price = 0;
+ $data = [];
+ foreach($activeData as $key => $value) {
+ $maxPrice = 0;
+ $must_price = 0;
+ $attrValue = [];
+ if(is_null($value['product'])) continue;
+ $productSku = $value['productSku'];
+ $productAttr = $value['product']['attr'];
+ $productAttrValue = $value['product']['attrValue'];
+ unset($value['productSku'], $value['product']['attrValue'], $value['product']['attr']);
+ foreach ($productAttrValue as $attr_value) {
+ if (!empty($productSku)){
+ foreach ($productSku as $sk => $sv) {
+ if ( $sv['unique'] == $attr_value['unique']) {
+ if ($type == 'discounts') {
+ unset($attr_value['ot_price'], $attr_value['price']);
+ $attr_value['ot_price'] = $sv['price'];
+ $attr_value['price'] = $sv['active_price'];
+ $_price = bcsub($sv['price'], $sv['active_price'], 2);
+ if ($value['type']){
+ $must_price = $must_price > $_price ? $must_price : $_price;
+ } else {
+ $maxPrice = $maxPrice > $_price ? $maxPrice : $_price;
+ }
+ } else {
+ $attr_value['productSku'] = $sv;
+ }
+ $attrValue[] = $attr_value;
+ }
+ }
+ }
+ }
+ $attr = $make->detailAttr($productAttr);
+ if ($type == 'discounts') {
+ $sku = $make->detailAttrValue($attrValue, null);
+ $value['product']['sku'] = $sku;
+
+ } else {
+ $value['product']['attrValue'] = $attrValue;
+ }
+ $value['product']['attr'] = $attr;
+ $price = bcadd($price, bcadd($must_price,$maxPrice,2), 2);
+ if ($value['type'] == 1) {
+ array_unshift($data,$value);
+ }else {
+ $data[] = $value;
+ }
+ }
+ return compact('data', 'price');
+ }
+}
+
+
+if (!function_exists('systemConfig')) {
+ /**
+ * 获取系统配置
+ *
+ * @param string|string[] $key
+ * @return mixed
+ * @author xaboy
+ * @day 2020-05-08
+ */
+ function systemConfig($key)
+ {
+ return merchantConfig(0, $key);
+ }
+}
+
+if (!function_exists('getDatesBetweenTwoDays')) {
+ function getDatesBetweenTwoDays($startDate, $endDate)
+ {
+ $dates = [];
+ if (strtotime($startDate) > strtotime($endDate)) {
+ //如果开始日期大于结束日期,直接return 防止下面的循环出现死循环
+ return $dates;
+ } elseif ($startDate == $endDate) {
+ //开始日期与结束日期是同一天时
+ array_push($dates, date('m-d', strtotime($startDate)));
+ return $dates;
+ } else {
+ array_push($dates, date('m-d', strtotime($startDate)));
+ $currentDate = $startDate;
+ do {
+ $nextDate = date('Y-m-d', strtotime($currentDate . ' +1 days'));
+ array_push($dates, date('m-d', strtotime($currentDate . ' +1 days')));
+ $currentDate = $nextDate;
+ } while ($endDate != $currentDate);
+ return $dates;
+ }
+ }
+}
+
+if (!function_exists('getStartModelTime')) {
+ function getStartModelTime(string $section)
+ {
+ switch ($section) {
+ case 'today':
+ case 'yesterday':
+ return date('Y-m-d', strtotime($section));
+ case 'week':
+ return date('Y-m-d', strtotime('this week'));
+ case 'month':
+ return date('Y-m-d', strtotime('first Day of this month'));
+ case 'year':
+ return date('Y-m-d', strtotime('this year 1/1'));
+ case 'quarter':
+ list($startTime, $endTime) = getMonth();
+ return $startTime;
+ case 'lately7':
+ return date('Y-m-d', strtotime("-7 day"));
+ case 'lately30':
+ return date('Y-m-d', strtotime("-30 day"));
+ default:
+ if (strstr($section, '-') !== false) {
+ list($startTime, $endTime) = explode('-', $section);
+ return date('Y-m-d H:i:s', strtotime($startTime));
+ }
+ return date('Y-m-d H:i:s');
+ }
+ }
+}
+
+if (!function_exists('merchantConfig')) {
+ /**
+ * 获取商户配置
+ *
+ * @param int $merId
+ * @param string|string[] $key
+ * @return mixed
+ * @author xaboy
+ * @day 2020-05-08
+ */
+ function merchantConfig(int $merId, $key)
+ {
+ $request = request();
+ $make = app()->make(SystemConfigValue::class);
+ if (is_array($key)) {
+ $_key = [];
+ $cacheData = [];
+ foreach ($key as $v) {
+ if ($request->hasCache($merId, $v)) {
+ $cacheData[$v] = $request->getCache($merId, $v);
+ } else {
+ $_key[] = $v;
+ }
+ }
+ if (!count($_key)) return $cacheData;
+ $data = $make->more($_key, $merId);
+ $request->setCache($merId, $data);
+ $data += $cacheData;
+ } else {
+ if ($request->hasCache($merId, $key)) {
+ $data = $request->getCache($merId, $key);
+ } else {
+ $data = $make->get($key, $merId);
+ $request->setCache($merId, $key, $data);
+ }
+ }
+ return $data;
+ }
+}
+
+if (!function_exists('filter_emoji')) {
+
+ // 过滤掉emoji表情
+ function filter_emoji($str)
+ {
+ $str = preg_replace_callback( //执行一个正则表达式搜索并且使用一个回调进行替换
+ '/./u',
+ function (array $match) {
+ return strlen($match[0]) >= 4 ? '' : $match[0];
+ },
+ $str
+ );
+ return $str;
+ }
+}
+
+if (!function_exists('setHttpType')) {
+
+ /**
+ * TODO 修改 https 和 http 移动到common
+ * @param $url $url 域名
+ * @param int $type 0 返回https 1 返回 http
+ * @return string
+ */
+ function setHttpType($url, $type = 0)
+ {
+ $domainTop = substr($url, 0, 5);
+ if ($type) {
+ if ($domainTop == 'https') $url = 'http' . substr($url, 5, strlen($url));
+ } else {
+ if ($domainTop != 'https') $url = 'https:' . substr($url, 5, strlen($url));
+ }
+ return $url;
+ }
+}
+
+if (!function_exists('remoteImage')) {
+
+ /**
+ * TODO 获取小程序二维码是否生成
+ * @param $url
+ * @return array
+ */
+ function remoteImage($url)
+ {
+ $curl = curl_init();
+ curl_setopt($curl, CURLOPT_URL, $url);
+ curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
+ $result = curl_exec($curl);
+ $result = json_decode($result, true);
+ if (is_array($result)) return ['status' => false, 'msg' => $result['errcode'] . '---' . $result['errmsg']];
+ return ['status' => true];
+ }
+}
+
+if (!function_exists('image_to_base64')) {
+ /**
+ * 获取图片转为base64
+ * @param string $avatar
+ * @return bool|string
+ */
+ function image_to_base64($avatar = '', $timeout = 9)
+ {
+ try {
+ $url = parse_url($avatar);
+ $url = $url['host'];
+ $header = [
+ 'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:45.0) Gecko/20100101 Firefox/45.0',
+ 'Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
+ 'Accept-Encoding: gzip, deflate, br',
+ 'accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
+ 'Host:' . $url
+ ];
+ $dir = pathinfo($url);
+ $host = $dir['dirname'];
+ $refer = $host . '/';
+ $curl = curl_init();
+ curl_setopt($curl, CURLOPT_REFERER, $refer);
+ curl_setopt($curl, CURLOPT_URL, $avatar);
+ curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
+ curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
+ curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
+ curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
+ curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
+ curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
+ $data = curl_exec($curl);
+ $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
+ curl_close($curl);
+ if ($code == 200) {
+ return "data:image/jpeg;base64," . base64_encode($data);
+ } else {
+ return false;
+ }
+ } catch (Exception $e) {
+ return false;
+ }
+ }
+}
+
+
+if (!function_exists('put_image')) {
+ /**
+ * 获取图片转为base64
+ * @param string $avatar
+ * @return bool|string
+ */
+ function put_image($url, $filename = '')
+ {
+
+ if ($url == '') {
+ return false;
+ }
+ try {
+ if ($filename == '') {
+
+ $ext = pathinfo($url);
+ if ($ext['extension'] != "jpg" && $ext['extension'] != "png" && $ext['extension'] != "jpeg") {
+ return false;
+ }
+ $filename = time() . "." . $ext['extension'];
+ }
+
+ //文件保存路径
+ ob_start();
+ readfile($url);
+ $img = ob_get_contents();
+ ob_end_clean();
+ $path = 'public/uploads/qrcode';
+ $fp2 = fopen($path . '/' . $filename, 'a');
+ fwrite($fp2, $img);
+ fclose($fp2);
+ return $path . '/' . $filename;
+ } catch (Exception $e) {
+ return false;
+ }
+ }
+}
+
+if (!function_exists('path_to_url')) {
+ /**
+ * 路径转url路径
+ * @param $path
+ * @return string
+ */
+ function path_to_url($path)
+ {
+ return trim(str_replace(DIRECTORY_SEPARATOR, '/', $path), '.');
+ }
+}
+
+if (!function_exists('tidy_url')) {
+ /**
+ * 路径转url路径
+ * @param $url
+ * @param int $http
+ * @param string $site
+ * @return string
+ */
+ function tidy_url($url, $http = null, $site = null)
+ {
+ if (!$site) {
+ $site = systemConfig('site_url');
+ }
+ $url = path_to_url($url);
+ if (strpos($url, 'http') === false)
+ $url = rtrim($site, '/') . '/' . ltrim($url, '/');
+
+ if (is_null($http)) {
+ $http = (parse_url($site)['scheme'] ?? '') == 'https' ? 0 : 1;
+ }
+ $url = set_http_type($url, $http);
+ return $url;
+ }
+}
+
+
+if (!function_exists('curl_file_exist')) {
+ /**
+ * CURL 检测远程文件是否在
+ * @param $url
+ * @return bool
+ */
+ function curl_file_exist($url)
+ {
+ $ch = curl_init();
+ try {
+ curl_setopt($ch, CURLOPT_URL, $url);
+ curl_setopt($ch, CURLOPT_HEADER, 1);
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
+ curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
+ $contents = curl_exec($ch);
+ if (preg_match("/404/", $contents)) return false;
+ if (preg_match("/403/", $contents)) return false;
+ return true;
+ } catch (Exception $e) {
+ return false;
+ }
+ }
+}
+
+
+if (!function_exists('set_http_type')) {
+ /**
+ * 修改 https 和 http
+ * @param $url $url 域名
+ * @param int $type 0 返回https 1 返回 http
+ * @return string
+ */
+ function set_http_type($url, $type = 0)
+ {
+ $domainTop = substr($url, 0, 5);
+ if ($type) {
+ if ($domainTop == 'https') $url = 'http' . substr($url, 5, strlen($url));
+ } else {
+ if ($domainTop != 'https') $url = 'https:' . substr($url, 5, strlen($url));
+ }
+ return $url;
+ }
+}
+
+
+if (!function_exists('getTimes')) {
+ function getTimes()
+ {
+ $dates = [];
+ for ($i = 0; $i <= 24; $i++) {
+ for ($j = 0; $j < 60; $j++) {
+ $dates[] = sprintf('%02.d', $i) . ':' . sprintf('%02.d', $j);
+ }
+ }
+ return $dates;
+ }
+}
+
+if (!function_exists('monday')) {
+ /**
+ * 获取周一
+ *
+ * @param null $time
+ * @return false|string
+ * @author xaboy
+ * @day 2020/6/22
+ */
+ function monday($time = null)
+ {
+ return date('Y-m-d', strtotime('Sunday -6 day', $time ?: time()));
+ }
+}
+
+
+if (!function_exists('attr_format')) {
+ /**
+ * 格式化属性
+ * @param $arr
+ * @return array
+ */
+ function attr_format($arr)
+ {
+ $data = [];
+ $res = [];
+ $count = count($arr);
+ if ($count > 1) {
+ for ($i = 0; $i < $count - 1; $i++) {
+ if ($i == 0) $data = $arr[$i]['detail'];
+ //替代变量1
+ $rep1 = [];
+ foreach ($data as $v) {
+ foreach ($arr[$i + 1]['detail'] as $g) {
+ //替代变量2
+ $rep2 = ($i != 0 ? '' : $arr[$i]['value'] . '_$_') . $v . '-$-' . $arr[$i + 1]['value'] . '_$_' . $g;
+ $tmp[] = $rep2;
+ if ($i == $count - 2) {
+ foreach (explode('-$-', $rep2) as $k => $h) {
+ //替代变量3
+ $rep3 = explode('_$_', $h);
+ //替代变量4
+ $rep4['detail'][$rep3[0]] = isset($rep3[1]) ? $rep3[1] : '';
+ }
+ if ($count == count($rep4['detail']))
+ $res[] = $rep4;
+ }
+ }
+ }
+ $data = isset($tmp) ? $tmp : [];
+ }
+ } else {
+ $dataArr = [];
+ foreach ($arr as $k => $v) {
+ foreach ($v['detail'] as $kk => $vv) {
+ $dataArr[$kk] = $v['value'] . '_' . $vv;
+ $res[$kk]['detail'][$v['value']] = $vv;
+ }
+ }
+ $data[] = implode('-', $dataArr);
+ }
+ return [$data, $res];
+ }
+}
+
+if (!function_exists('filter_emoji')) {
+ //过滤掉emoji表情
+ function filter_emoji($str)
+ {
+ $str = preg_replace_callback('/./u', function (array $match) {
+ return strlen($match[0]) >= 4 ? '' : $match[0];
+ }, $str);
+ return $str;
+ }
+}
+
+/**
+ * 高德经纬度改百度经纬度
+ * @param $lng 经度
+ * @param $lat 纬度
+ * @return mixed
+ */
+if (!function_exists('bd_encrypt')) {
+ function bd_encrypt($lng, $lat)
+ {
+ $x_pi = 3.14159265358979324 * 3000.0 / 180.0;
+ $x = $lng;
+ $y = $lat;
+ $z = sqrt($x * $x + $y * $y) - 0.00002 * sin($y * $x_pi);
+ $theta = atan2($y, $x) - 0.000003 * cos($x * $x_pi);
+
+ $data['lng'] = $z * cos($theta) + 0.0065;
+ $data['lat'] = $z * sin($theta) + 0.006;
+ return $data;
+ }
+}
+
+
+if (!function_exists('aj_captcha_check_one')) {
+ /**
+ * 验证滑块1次验证
+ * @param string $token
+ * @param string $pointJson
+ * @return bool
+ */
+ function aj_captcha_check_one(string $captchaType, string $token, string $pointJson)
+ {
+ aj_get_serevice($captchaType)->check($token, $pointJson);
+ return true;
+ }
+}
+
+if (!function_exists('aj_captcha_check_two')) {
+ /**
+ * 验证滑块2次验证
+ * @param string $token
+ * @param string $pointJson
+ * @return bool
+ */
+ function aj_captcha_check_two(string $captchaType, string $captchaVerification )
+ {
+ aj_get_serevice($captchaType)->verificationByEncryptCode($captchaVerification);
+ return true;
+ }
+}
+
+
+if (!function_exists('validateIDCard')) {
+
+ function validateIDCard(string $idcard)
+ {
+ if(empty($idcard)){
+ return false;
+ }else{
+ $idcard = strtoupper($idcard); # 如果是小写x,转化为大写X
+ if(strlen($idcard) != 18 && strlen($idcard) != 15){
+ return false;
+ }
+ # 如果是15位身份证,则转化为18位
+ if(strlen($idcard) == 15){
+ # 如果身份证顺序码是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);
+ }
+ # 加权因子
+ $factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
+ # 校验码对应值
+ $code = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
+ $checksum = 0;
+ for ($i = 0; $i < strlen($idcard); $i++) {
+ $checksum += substr($idcard, $i, 1) * $factor[$i];
+ }
+ $idcard = $idcard . $code[$checksum % 11];
+ }
+ # 验证身份证开始
+ $IDCardBody = substr($idcard, 0, 17); # 身份证主体
+ $IDCardCode = strtoupper(substr($idcard, 17, 1)); # 身份证最后一位的验证码
+
+ # 加权因子
+ $factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
+ # 校验码对应值
+ $code = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
+ $checksum = 0;
+ for ($i = 0; $i < strlen($IDCardBody); $i++) {
+ $checksum += substr($IDCardBody, $i, 1) * $factor[$i];
+ }
+ $validateIdcard = $code[$checksum % 11]; # 判断身份证是否合理
+ if($validateIdcard != $IDCardCode){
+ return false;
+ }else{
+ return true;
+ }
+ }
+ }
+}
+
+
diff --git a/app/common/model/merchant/store/ShippingTemplate.php b/app/common/model/merchant/store/ShippingTemplate.php
new file mode 100644
index 0000000..6fdd5b3
--- /dev/null
+++ b/app/common/model/merchant/store/ShippingTemplate.php
@@ -0,0 +1,118 @@
+ "默认模板",
+ "type" => 1,
+ "appoint" => 0,
+ "undelivery" => 0,
+ 'mer_id' => $merId,
+ "region" => [[
+ "first" => 0,
+ "first_price" => 0,
+ "continue" => 0,
+ "continue_price" => 0,
+ "city_id" => 0
+ ]]
+ ];
+ return $this->createTemp($data);
+ }
+
+ /**
+ * @Author:Qinii
+ * @Date: 2020/5/13
+ * @param array $data
+ */
+ public function createTemp(array $data)
+ {
+ Db::transaction(function()use ($data) {
+ $region = $data['region'];
+ $free = $data['free'] ?? '';
+ $undelives = $data['undelives'] ?? '';
+ unset($data['region'],$data['free'],$data['undelives'],$data['city_ids']);
+ $temp = self::create($data);
+ if($data['appoint']) {
+ $settlefree = $this->settleFree($free, $temp['shipping_template_id']);
+ (new ShippingTemplateFree)->insertAll($settlefree);
+ }
+ $settleRegion = $this->settleRegion($region, $temp['shipping_template_id']);
+ (new ShippingTemplateRegion)->insertAll($settleRegion);
+ if($data['undelivery'] == 1){
+ $settleUndelives = $this->settleUndelives($undelives,$temp['shipping_template_id']);
+ (new ShippingTemplateUndelive)->create($settleUndelives);
+ }
+ });
+ }
+
+ /**
+ * @param $data
+ * @param $id
+ * @return array
+ * @author Qinii
+ */
+ public function settleFree($data,$id)
+ {
+ foreach ($data as $v){
+ if (isset($v['city_id']) && !is_array($v['city_id'])) throw new ValidateException('包邮参数类型错误');
+ $city = '/'.implode('/',$v['city_id']).'/';
+ $free[] = [
+ 'temp_id' => $id,
+ 'city_id' => $city,
+ 'number' => $v['number'],
+ 'price' => $v['price']
+ ];
+ }
+ return $free;
+ }
+
+ /**
+ * @Author:Qinii
+ * @Date: 2020/5/13
+ * @param $data
+ * @param $id
+ * @return array
+ */
+ public function settleRegion($data,$id)
+ {
+ $result = [];
+ foreach ($data as $k => $v){
+ $result[] = [
+ 'city_id' => ($k > 0 ) ? '/'.implode('/',$v['city_id']).'/' : 0,
+ 'temp_id' => $id,
+ 'first' => $v['first'],
+ 'first_price'=> $v['first_price'],
+ 'continue' => $v['continue'],
+ 'continue_price'=> $v['continue_price'],
+ ];
+ }
+ return $result;
+ }
+
+ /**
+ * @param $data
+ * @param $id
+ * @return array
+ * @author Qinii
+ */
+ public function settleUndelives($data,$id)
+ {
+ if (isset($v['city_id']) && !is_array($data['city_id'])) throw new ValidateException('指定不配送参数类型错误');
+ return ['temp_id' => $id, 'city_id' => $data['city_id']];
+ }
+}
\ No newline at end of file
diff --git a/app/common/model/merchant/store/ShippingTemplateFree.php b/app/common/model/merchant/store/ShippingTemplateFree.php
new file mode 100644
index 0000000..e03f882
--- /dev/null
+++ b/app/common/model/merchant/store/ShippingTemplateFree.php
@@ -0,0 +1,23 @@
+ 'sys',
+ 'num' => systemConfig('copy_product_defaul'),
+ 'message' => '赠送次数',
+ ];
+ $this->add($data,$merId);
+ }
+ }
+
+
+ /**
+ * TODO 添加记录并修改数据
+ * @param $data
+ * @param $merId
+ * @author Qinii
+ * @day 2020-08-06
+ */
+ public function add($data,$merId)
+ {
+ $make = app()->make(Merchant::class);
+ $getOne = $make->get($merId);
+
+ switch ($data['type']) {
+ case 'mer_dump':
+ //nobreak;
+ case 'pay_dump':
+ $field = 'export_dump_num';
+ break;
+ case 'sys':
+ //nobreak;
+ //nobreak;
+ case 'pay_copy':
+ //nobreak;
+ case 'copy':
+ //nobreak;
+ $field = 'copy_product_num';
+ break;
+ default:
+ $field = 'copy_product_num';
+ break;
+ }
+
+
+ $number = $getOne[$field] + $data['num'];
+ $arr = [
+ 'type' => $data['type'],
+ 'num' => $data['num'],
+ 'info' => $data['info']??'' ,
+ 'mer_id'=> $merId,
+ 'message' => $data['message'] ?? '',
+ 'number' => ($number < 0) ? 0 : $number,
+ ];
+ Db::transaction(function()use($arr,$make,$field){
+ self::create($arr);
+ if ($arr['num'] < 0) {
+ $make->sumFieldNum($arr['mer_id'],$arr['num'],$field);
+ } else {
+ $make->addFieldNum($arr['mer_id'],$arr['num'],$field);
+ }
+ });
+ }
+}
diff --git a/app/common/model/merchant/system/config/SystemConfig.php b/app/common/model/merchant/system/config/SystemConfig.php
new file mode 100644
index 0000000..96c08ff
--- /dev/null
+++ b/app/common/model/merchant/system/config/SystemConfig.php
@@ -0,0 +1,15 @@
+make(ConfigRepository::class)->intersectionKey($cid, $keys);
+ if (!count($keys)) return;
+ foreach ($keys as $key => $info) {
+ if (!isset($formData[$key]))
+ unset($formData[$key]);
+ else {
+ if ($info['config_type'] == 'number') {
+ if ($formData[$key] === '' || $formData[$key] < 0)
+ throw new ValidateException($info['config_name'] . '不能小于0');
+ $formData[$key] = floatval($formData[$key]);
+ }
+ $this->separate($key,$formData[$key],$merId);
+ }
+ }
+ $this->setFormData($formData, $merId);
+ }
+
+ /**
+ * TODO 需要做特殊处理的配置参数
+ * @param $key
+ * @author Qinii
+ * @day 2022/11/17
+ */
+ public function separate($key,$value,$merId)
+ {
+ switch($key) {
+ case 'mer_svip_status':
+ //修改商户的会员状态
+ app()->make(ProductRepository::class)->getSearch([])->where(['mer_id' => $merId,'product_type' => 0])->update([$key => $value]);
+ break;
+
+ //热卖排行
+ case 'hot_ranking_switch':
+ if ($value) {
+ Queue::push(SyncProductTopJob::class, []);
+ }
+ break;
+ case 'svip_switch_status':
+ if ($value == 1) {
+ $groupDataRepository = app()->make(GroupDataRepository::class);
+ $groupRepository = app()->make(GroupRepository::class);
+ $group_id = $groupRepository->getSearch(['group_key' => 'svip_pay'])->value('group_id');
+ $where['group_id'] = $group_id;
+ $where['status'] = 1;
+ $count = $groupDataRepository->getSearch($where)->field('group_data_id,value,sort,status')->count();
+ if (!$count)
+ throw new ValidateException('请先添加会员类型');
+ }
+ break;
+ default:
+ break;
+ }
+ return ;
+ }
+
+ public function setFormData(array $formData, int $merId)
+ {
+ Db::transaction(function () use ($merId, $formData) {
+ foreach ($formData as $key => $value) {
+ if ($this->dao->merExists($key, $merId))
+ $this->dao->merUpdate($merId, $key, ['value' => $value]);
+ else
+ $this->dao->create([
+ 'mer_id' => $merId,
+ 'value' => $value,
+ 'config_key' => $key
+ ]);
+ }
+ });
+ }
+
+
+
+ // -------------------------------------------------
+
+ /**
+ * @param array $keys
+ * @param int $merId
+ * @return array
+ */
+ protected function fields(array $keys, int $merId)
+ {
+ $result = SystemConfigValue::whereIn('config_key', $keys)->where('mer_id', $merId)->withAttr('value', function ($val, $data) {
+ return json_decode($val, true);
+ })->column('value', 'config_key');
+ foreach ($result as $k => $val) {
+ $result[$k] = json_decode($val, true);
+ }
+ return $result;
+ }
+
+ /**
+ * @param string $key
+ * @param int $merId
+ * @return mixed|null
+ */
+ protected function value(string $key, int $merId)
+ {
+ $value = SystemConfigValue::where('config_key', $key)->where('mer_id', $merId)->value('value');
+ $value = is_null($value) ? null : json_decode($value, true);
+ return $value;
+ }
+}
diff --git a/app/common/model/merchant/system/merchant/Merchant.php b/app/common/model/merchant/system/merchant/Merchant.php
index 11d6f3e..1e1e2aa 100644
--- a/app/common/model/merchant/system/merchant/Merchant.php
+++ b/app/common/model/merchant/system/merchant/Merchant.php
@@ -12,7 +12,9 @@ namespace app\common\model\merchant\system\merchant;
use think\Model;
use app\common\model\merchant\user\UserBill as UserBillModel;
+use app\common\model\merchant\store\ShippingTemplate;
use think\exception\ValidateException;
+use think\facade\Db;
/**
* @mixin \think\Model
@@ -32,6 +34,49 @@ class Merchant extends Model
return $this->merchantType()->bind(['type_name']);
}
+ /**
+ * @param array $data
+ * @author xaboy
+ * @day 2020-04-17
+ */
+ public function createMerchant(array $data)
+ {
+ if ($this->fieldExists('mer_name', $data['mer_name']))
+ throw new ValidateException('商户名已存在');
+ if ($data['mer_phone'] && isPhone($data['mer_phone']))
+ throw new ValidateException('请输入正确的手机号');
+ $merchantCategory = app()->make(MerchantCategory::class);
+ $admin = app()->make(MerchantAdmin::class);
+
+ if (!$data['category_id'] || !$merchantCategory->idIsExists($data['category_id']))
+ throw new ValidateException('商户分类不存在');
+ if ($admin->fieldExists('account', $data['mer_account']))
+ throw new ValidateException('账号已存在');
+
+ /** @var MerchantAdmin $make */
+ $make = app()->make(MerchantAdmin::class);
+
+ $margin = app()->make(MerchantType::class)->get($data['type_id']);
+ $data['is_margin'] = $margin['is_margin'] ?? -1;
+ $data['margin'] = $margin['margin'] ?? 0;
+
+ return Db::transaction(function () use ($data, $make) {
+ $account = $data['mer_account'];
+ $password = $data['mer_password'];
+ unset($data['mer_account'], $data['mer_password']);
+
+ $merchant = $this->dao->create($data);
+ $make->createMerchantAccount($merchant, $account, $password);
+ $address_id = Db::name('merchant_address')->insertGetId(['mer_id'=>$merchant->mer_id,'street_id'=>$data['geo_street']]);
+ if($data['area_id'] && $data['village_id']){
+ Db::name('merchant_address')->where('id',$address_id)->update(['area_id'=>$data['area_id'],'village_id'=>$data['village_id']]);
+ }
+ app()->make(ShippingTemplate::class)->createDefault($merchant->mer_id);
+ app()->make(ProductCopy::class)->defaulCopyNum($merchant->mer_id);
+ return $merchant;
+ });
+ }
+
/**
* 扣除保证金
*@param array $data [mer_id] => 75
@@ -79,4 +124,26 @@ class Merchant extends Model
return $merchant;
}
+
+
+ //------------------------------------------------
+
+ public function addFieldNum(int $merId, int $num, string $field)
+ {
+ if ($num < 0) $num = -$num;
+ $merchant = $this->getModel()::getDB()->where('mer_id', $merId)->find();
+ $number = $merchant[$field] + $num;
+ $merchant[$field] = $number;
+ $merchant->save();
+ }
+
+ public function sumFieldNum(int $merId, int $num, string $field)
+ {
+ if ($num < 0) $num = -$num;
+ $merchant = $this->getModel()::getDB()->where('mer_id', $merId)->find();
+ $number = $merchant[$field] - $num;
+ $merchant[$field] = $number;
+ $merchant->save();
+ }
+
}
diff --git a/app/common/model/merchant/system/merchant/MerchantAdmin.php b/app/common/model/merchant/system/merchant/MerchantAdmin.php
index 03ec84b..684f09b 100644
--- a/app/common/model/merchant/system/merchant/MerchantAdmin.php
+++ b/app/common/model/merchant/system/merchant/MerchantAdmin.php
@@ -11,4 +11,55 @@ use think\Model;
class MerchantAdmin extends Model
{
//
+ protected $connection = 'shop';
+ protected $table = 'eb_merchant_admin';
+
+ const PASSWORD_TYPE_ADMIN = 1;
+ const PASSWORD_TYPE_MERCHANT = 2;
+ const PASSWORD_TYPE_SELF = 3;
+
+
+ /**
+ * @param $field
+ * @param $value
+ * @param int|null $except
+ * @return bool
+ */
+ public function fieldExists($field, $value, ?int $except = null): bool
+ {
+ $query = self::where($field, $value);
+ if (!is_null($except)) $query->where($this->getPk(), '<>', $except);
+ return $query->count() > 0;
+ }
+
+ /**
+ * @param Merchant $merchant
+ * @param $account
+ * @param $pwd
+ * @return BaseDao|Model
+ * @author xaboy
+ * @day 2020-04-17
+ */
+ public function createMerchantAccount(Merchant $merchant, $account, $pwd)
+ {
+ $pwd = $this->passwordEncode($pwd);
+ $data = compact('pwd', 'account') + [
+ 'mer_id' => $merchant->mer_id,
+ 'real_name' => $merchant->real_name,
+ 'phone' => $merchant->mer_phone,
+ 'level' => 0
+ ];
+ return $this->create($data);
+ }
+
+ /**
+ * @param $password
+ * @return bool|string
+ * @author xaboy
+ * @day 2020-04-17
+ */
+ public function passwordEncode($password)
+ {
+ return password_hash($password, PASSWORD_BCRYPT);
+ }
}
diff --git a/app/common/model/merchant/system/merchant/MerchantCategory.php b/app/common/model/merchant/system/merchant/MerchantCategory.php
index aece970..29a9865 100644
--- a/app/common/model/merchant/system/merchant/MerchantCategory.php
+++ b/app/common/model/merchant/system/merchant/MerchantCategory.php
@@ -12,4 +12,31 @@ class MerchantCategory extends Model
{
protected $connection = 'shop';
protected $table = 'eb_merchant_category';
+
+
+ /**
+ * @param int $id
+ * @return bool
+ * @author xaboy
+ * @day 2020-03-27
+ */
+ public function idIsExists(int $id)
+ {
+ return $this->fieldExists($this->getPk(), $id);
+ }
+
+ /**
+ * @param $field
+ * @param $value
+ * @param int|null $except
+ * @return bool
+ * @author xaboy
+ * @day 2020-03-30
+ */
+ public function fieldExists($field, $value, ?int $except = null): bool
+ {
+ $query = self::where($field, $value);
+ if (!is_null($except)) $query->where($this->getPk(), '<>', $except);
+ return $query->count() > 0;
+ }
}
diff --git a/app/common/model/merchant/system/merchant/MerchantIntention.php b/app/common/model/merchant/system/merchant/MerchantIntention.php
index aaba01c..d4a4d67 100644
--- a/app/common/model/merchant/system/merchant/MerchantIntention.php
+++ b/app/common/model/merchant/system/merchant/MerchantIntention.php
@@ -12,6 +12,8 @@ namespace app\common\model\merchant\system\merchant;
use app\common\model\merchant\system\merchant\MerchantCategory;
use think\Model;
+use think\facade\Db;
+use think\exception\ValidateException;
/**
* @mixin \think\Model
@@ -38,7 +40,6 @@ class MerchantIntention extends Model
public function GetList(array $where, $page, $limit)
{
$query = self::search($where);
-
$count = $query->count();
$list = $query->page($page, $limit)->order('create_time DESC , status ASC')->with(['merchantCategory', 'merchantType'])->select();
@@ -91,6 +92,17 @@ class MerchantIntention extends Model
return $query;
}
+ /**
+ * 修改审核状态
+ */
+ public function getStatusAttr($value)
+ {
+ $status = [0=>'待审核', 1=>'审核已通过',2=>'审核未通过'];
+ return $status[$value];
+ }
+
+
+
public function Edit($id, $data)
{
$rows = self::where('mer_intention_id',$id)->update($data);
@@ -102,10 +114,141 @@ class MerchantIntention extends Model
$this->getModel()::getDB()->where($this->getPk(), $id)->update(['status' => $data['status'], 'mark' => $data['mark']]);
}
+ /**
+ * 数据是否存在
+ */
public function GetWhereCount($mer_intention_id)
{
- $count = self::where(['mer_intention_id' => $mer_intention_id, 'is_del' => 0])->fetchSql()->count();
+ $count = self::where(['mer_intention_id' => $mer_intention_id, 'is_del' => 0])->count();
return $count;
}
+
+ /**
+ * 审核
+ * TODO: 未完全
+ */
+ public function updateStatus($id, $data)
+ {
+ $create = $data['create_mer'] == 1;
+ unset($data['create_mer']);
+ $intention = $this->search(['mer_intention_id' => $id])->find();
+ // $smsData = [];
+ if (!$intention)
+ throw new ValidateException('信息不存在');
+ if ($intention->status)
+ throw new ValidateException('状态有误,修改失败');
+
+ //TODO: 此处需开发为可配置字段
+ $config = systemConfig(['broadcast_room_type', 'broadcast_goods_type']);
+
+ $margin = app()->make(MerchantType::class)->get($intention['mer_type_id']);
+ $data['is_margin'] = $margin['is_margin'] ?? -1;
+ $data['margin'] = $margin['margin'] ?? 0;
+ $merData = [];
+ if ($create) {
+ $password = substr($intention['phone'], -6);
+ $merData = [
+ 'mer_name' => $intention['mer_name'],
+ 'mer_phone' => $intention['phone'],
+ 'mer_account' => $intention['phone'],
+ 'category_id' => $intention['merchant_category_id'],
+ 'type_id' => $intention['mer_type_id'],
+ 'real_name' => $intention['name'],
+ 'status' => 1,
+ 'is_audit' => 1,
+ 'is_bro_room' => $config['broadcast_room_type'] == 1 ? 0 : 1,
+ 'is_bro_goods' => $config['broadcast_goods_type'] == 1 ? 0 : 1,
+ 'mer_password' => $password,
+ 'is_margin' => $margin['is_margin'] ?? -1,
+ 'margin' => $margin['margin'] ?? 0,
+ 'area_id' => $intention['area_id'] ?? 0,
+ 'geo_street' => $intention['street_id'] ?? 0,
+ 'village_id' => $intention['village_id'] ?? 0,
+ 'is_nmsc' => $intention['is_nmsc'] ?? 0,
+ ];
+ if ($data['status'] == 1) {
+ $data['fail_msg'] = '';
+ $smsData = [
+ 'date' => date('m月d日', strtotime($intention->create_time)),
+ 'mer' => $intention['mer_name'],
+ 'phone' => $intention['phone'],
+ 'pwd' => $password ?? '',
+ // 'site_name' => systemConfig('site_name'),
+ ];
+ }
+ }
+ if ($data['status'] == 2) {
+ $smsData = [
+ 'phone' => $intention['phone'],
+ 'date' => date('m月d日', strtotime($intention->create_time)),
+ 'mer' => $intention['mer_name'],
+ // 'site' => systemConfig('site_name'),
+ ];
+ }
+
+ self::transaction(function () use ($config, $intention, $data, $create,$margin,$merData,$smsData) {
+ if ($data['status'] == 1) {
+ if ($create) {
+ $merchant = app()->make(Merchant::class)->createMerchant($merData);
+ $data['mer_id'] = $merchant->mer_id;
+ // 暂不开通通知
+ // Queue::push(SendSmsJob::class, ['tempId' => 'APPLY_MER_SUCCESS', 'id' => $smsData]);
+ }
+ } else {
+ // Queue::push(SendSmsJob::class, ['tempId' => 'APPLY_MER_FAIL', 'id' => $smsData]);
+ }
+ $intention->save($data);
+ });
+ }
+
+ protected function isPhone($test)
+ {
+ return !preg_match("/^1[3456789]{1}\d{9}$/", $test);
+ }
+
+
+ /**
+ * @param array $data
+ * @author xaboy
+ * @day 2020-04-17
+ */
+ protected function createMerchant(array $data)
+ {
+ if ($this->fieldExists('mer_name', $data['mer_name']))
+ throw new ValidateException('商户名已存在');
+ if ($data['mer_phone'] && self::isPhone($data['mer_phone']))
+ throw new ValidateException('请输入正确的手机号');
+ $merchantCategory = new MerchantCategory;
+ $merchantAdmin = new MerchantAdmin;
+
+ if (!$data['category_id'] || !$merchantCategory->exists($data['category_id']))
+ throw new ValidateException('商户分类不存在');
+ if ($merchantAdmin->fieldExists('account', $data['mer_account']))
+ throw new ValidateException('账号已存在');
+
+ /** @var MerchantAdmin $make */
+ $make = new MerchantCategory;
+
+ $margin = (new MerchantType)->get($data['type_id']);
+ $data['is_margin'] = $margin['is_margin'] ?? -1;
+ $data['margin'] = $margin['margin'] ?? 0;
+
+ return Db::transaction(function () use ($data, $make) {
+ $account = $data['mer_account'];
+ $password = $data['mer_password'];
+ unset($data['mer_account'], $data['mer_password']);
+
+ $merchant = $this->dao->create($data);
+ $make->createMerchantAccount($merchant, $account, $password);
+ $address_id = Db::name('merchant_address')->insertGetId(['mer_id'=>$merchant->mer_id,'street_id'=>$data['geo_street']]);
+ if($data['area_id'] && $data['village_id']){
+ Db::name('merchant_address')->where('id',$address_id)->update(['area_id'=>$data['area_id'],'village_id'=>$data['village_id']]);
+ }
+ app()->make(ShippingTemplateRepository::class)->createDefault($merchant->mer_id);
+ app()->make(ProductCopyRepository::class)->defaulCopyNum($merchant->mer_id);
+ return $merchant;
+ });
+ }
+
}